repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
AutoCO
AutoCO-main/exp_public/adult/data/process.py
import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score data1 = pd.read_csv("./adult.data",header=None) data2 = pd.read_csv("./adult.test",header=None) data = pd.concat([data1, data2], axis=0) data.columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "income"] data_category = data[["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country", "income"]] data_category["income"] = data_category["income"].map({' <=50K': '<=50k', ' >50K': '>50k', ' <=50K.': '<=50k', ' >50K.': '>50k'}) def encode(data, column): label = sorted(data[column].unique(), key=lambda x:x) label_indices = list(range(len(label))) label_dict = dict(zip(label, label_indices)) data[column] = data[column].map(label_dict) for name in data_category.columns: encode(data_category, name) train_X = data_category.iloc[:,:-1].values train_y = data_category.iloc[:,-1].values clf = LogisticRegression(random_state=0).fit(train_X, train_y) predicted = clf.predict_proba(train_X) # reward: 36925 print("AUC score: ", roc_auc_score(train_y,predicted[:,1])) # data_category["eat_reward"] = data_category["income"].map(lambda x: 1 if x==0 else 0) # data_category["noteat_reward"] = data_category["income"].map(lambda x: 1 if x==1 else 0) # data_category.to_csv("./data.csv", index=False) # # N = 100000 # sample_indices = np.random.randint(0, data_category.shape[0], size=N) # data_sample = data_category.loc[sample_indices] # data_sample.to_csv("./data_sample.csv", index=False) #AUC: 0.7279
1,767
44.333333
154
py
AutoCO
AutoCO-main/exp_public/adult/simulate/utils.py
import numpy as np import pandas as pd import os import os.path import sys import shutil import torch import torch.nn as nn import torch.utils from sklearn.preprocessing import StandardScaler from sklearn.feature_extraction import DictVectorizer from sklearn.utils import shuffle from torch.utils.data import Dataset, DataLoader from models import PRIMITIVES_BINARY def create_exp_dir(path, scripts_to_save=None): if not os.path.exists(path): os.makedirs(path) print('Experiment dir : {}'.format(path)) if scripts_to_save is not None: os.mkdir(os.path.join(path, 'scripts')) for script in scripts_to_save: dst_file = os.path.join(path, 'scripts', os.path.basename(script)) shutil.copyfile(script, dst_file) def sample_arch(): arch = {} arch['mlp'] = {} arch['mlp']['p'] = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) arch['mlp']['q'] = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) arch['binary'] = PRIMITIVES_BINARY[np.random.randint(len(PRIMITIVES_BINARY))] return arch class Adult(Dataset): def __init__(self, root_dir, dummpy): self.data = pd.read_csv(root_dir) self.dummpy = dummpy def __len__(self): return self.data.shape[0] def one_hot(self, df, cols): res = [] for col in cols: dummies = pd.get_dummies(df[col], prefix=col, drop_first=False) res.append(dummies) df = pd.concat(res, axis=1) return df def __getitem__(self, index): sample = {} if not self.dummpy: sample["workclass"] = self.data.iloc[index]["workclass"] sample["education"] = self.data.iloc[index]["education"] sample["marital-status"] = self.data.iloc[index]["marital-status"] sample["occupation"] = self.data.iloc[index]["occupation"] sample["relationship"] = self.data.iloc[index]["relationship"] sample["race"] = self.data.iloc[index]["race"] sample["sex"] = self.data.iloc[index]["sex"] sample["native-country"] = self.data.iloc[index]["native-country"] eat_reward = self.data.iloc[index]["eat_reward"] noteat_reward = self.data.iloc[index]["noteat_reward"] sample["label"] = torch.Tensor([eat_reward, noteat_reward]) else: cols = ["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country"] data2 = self.one_hot(self.data, cols) sample["feature"] = torch.Tensor(data2.iloc[index][:]) eat_reward = self.data.iloc[index]["eat_reward"] noteat_reward = self.data.iloc[index]["noteat_reward"] sample["label"] = torch.Tensor([eat_reward, noteat_reward]) return sample def get_data_queue(args, dummpy): print(args.dataset) if args.dataset == 'Adult': train_data = "../data/data.csv" train_dataset = Adult(train_data, dummpy) train_queue = DataLoader(train_dataset, batch_size=args.batch_size, pin_memory=True) return train_queue else: return None class Adult2(Dataset): def __init__(self, contexts, pos_weights): self.data = contexts self.pos_weights = pos_weights def __len__(self): return self.data["label"].shape[0] def __getitem__(self, index): sample = {} sample["workclass"] = self.data["workclass"][index] sample["education"] = self.data["education"][index] sample["marital-status"] = self.data["marital-status"][index] sample["occupation"] = self.data["occupation"][index] sample["relationship"] = self.data["relationship"][index] sample["race"] = self.data["race"][index] sample["sex"] = self.data["sex"][index] sample["native-country"] = self.data["native-country"][index] sample["label"] = self.data["label"][index] sample["pos_weights"] = self.pos_weights[index] return sample def get_data_queue_bandit(args, contexts, pos_weights): train_dataset = Adult2(contexts, pos_weights) train_queue = DataLoader(train_dataset, batch_size=args.batch_size,pin_memory=True) return train_queue
4,315
36.206897
126
py
AutoCO
AutoCO-main/exp_public/adult/simulate/models.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable import utils import time PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat'] PRIMITIVES_NAS = [0, 2, 4, 8, 16] SPACE_NAS = pow(len(PRIMITIVES_NAS), 5) OPS = { 'plus': lambda p, q: p + q, 'multiply': lambda p, q: p * q, 'max': lambda p, q: torch.max(torch.stack((p, q)), dim=0)[0], 'min': lambda p, q: torch.min(torch.stack((p, q)), dim=0)[0], 'concat': lambda p, q: torch.cat([p, q], dim=-1), 'norm_0': lambda p: torch.ones_like(p), 'norm_0.5': lambda p: torch.sqrt(torch.abs(p) + 1e-7), 'norm_1': lambda p: torch.abs(p), 'norm_2': lambda p: p ** 2, 'I': lambda p: torch.ones_like(p), '-I': lambda p: -torch.ones_like(p), 'sign': lambda p: torch.sign(p), } def constrain(p): c = torch.norm(p, p=2, dim=1, keepdim=True) c[c < 1] = 1.0 p.data.div_(c) def MixedBinary(embedding_p, embedding_q, weights, FC): return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ for w,primitive,fc in zip(weights,PRIMITIVES_BINARY,FC)]), 0) class Virtue(nn.Module): def __init__(self, embedding_dim, reg, embedding_num=12, ofm=False): super(Virtue, self).__init__() self.embedding_dim = embedding_dim self.reg = reg self.embedding_all = nn.ModuleDict({}) self.columns = ["cap-shape", "cap-surface", "cap-color", "bruises", "odor", "gill-attachment", "gill-spacing", "gill-size", "gill-color", "stalk-shape", "stalk-root", "stalk-surface-above-ring", "stalk-surface-below-ring", "stalk-color-above-ring", "stalk-color-below-ring", "veil-type", "veil-color", "ring-number", "ring-type", "spore-print-color", "population", "habitat"] if not ofm: for name in self.columns: self.embedding_all[name] = nn.Embedding(embedding_num, embedding_dim) else: for name in self.columns: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: temp.append(nn.Embedding(embedding_num, embedding_dim)) self.embedding_all[name] = temp def compute_loss(self, inferences, labels, regs): labels = torch.reshape(labels, [-1,1]) loss = F.binary_cross_entropy_with_logits(inferences, labels.float()) #loss = F.mse_loss(inferences, labels) return loss + regs class Network(Virtue): def __init__(self, embedding_dim, arch, reg): super(Network, self).__init__(embedding_dim, reg) self.arch = arch self.mlp_p = arch['mlp']['p'] self.mlp_q = arch['mlp']['q'] self.FC = nn.ModuleDict({}) for name1 in self.columns: for name2 in self.columns: if arch['binary'] == 'concat': self.FC[name1+ ":" + name2] = nn.Linear(2*embedding_dim, 1, bias=False) else: self.FC[name1 + ":" + name2] = nn.Linear(embedding_dim, 1, bias=False) def forward(self, features): for value in self.FC.values(): constrain(next(value.parameters())) inferences = 0 regs = 0 for name1 in self.columns: for name2 in self.columns: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) regs += self.reg * (torch.norm(name1_embedding) + torch.norm(name2_embedding)) name1_embedding_trans = self.mlp_p(name1_embedding.view(-1,1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) inferences += self.FC[name1 + ":" + name2](OPS[self.arch['binary']](name1_embedding_trans, name2_embedding_trans)) return inferences, regs class Network_Search(Virtue): def __init__(self, embedding_dim, reg): super(Network_Search, self).__init__(embedding_dim, reg) self.FC = nn.ModuleDict({}) for name1 in self.columns: for name2 in self.columns: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self._initialize_alphas() def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self._arch_parameters = {} self._arch_parameters['mlp'] = {} self._arch_parameters['mlp']['p'] = self.mlp_p self._arch_parameters['mlp']['q'] = self.mlp_q self._arch_parameters['binary'] = Variable(torch.ones(len(PRIMITIVES_BINARY), dtype=torch.float, device='cpu') / 2, requires_grad=True) #self._arch_parameters['binary'] = Variable(torch.Tensor([1.0,1.0,1.0,1.0,1.0]), requires_grad=True) self._arch_parameters['binary'].data.add_( torch.randn_like(self._arch_parameters['binary'])*1e-3) def arch_parameters(self): return list(self._arch_parameters['mlp']['p'].parameters()) + \ list(self._arch_parameters['mlp']['q'].parameters()) + [self._arch_parameters['binary']] def new(self): model_new = Network_Search(self.num_users, self.num_items, self.embedding_dim, self.reg) for x, y in zip(model_new.arch_parameters(), self.arch_parameters()): x.data = y.data.clone() return model_new def clip(self): m = nn.Hardtanh(0, 1) self._arch_parameters['binary'].data = m(self._arch_parameters['binary']) def binarize(self): self._cache = self._arch_parameters['binary'].clone() max_index = self._arch_parameters['binary'].argmax().item() for i in range(self._arch_parameters['binary'].size(0)): if i == max_index: self._arch_parameters['binary'].data[i] = 1.0 else: self._arch_parameters['binary'].data[i] = 0.0 def recover(self): self._arch_parameters['binary'].data = self._cache del self._cache def forward(self, features): # for i in range(len(PRIMITIVES_BINARY)): # constrain(next(self._FC[i].parameters())) inferences = 0 regs = 0 for name1 in self.columns: for name2 in self.columns: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) regs += self.reg * (torch.norm(name1_embedding) + torch.norm(name2_embedding)) name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, self._arch_parameters['binary'], self.FC[name1 + ":" + name2]) return inferences, regs def genotype(self): genotype = PRIMITIVES_BINARY[self._arch_parameters['binary'].argmax().cpu().numpy()] genotype_p = F.softmax(self._arch_parameters['binary'], dim=-1) return genotype, genotype_p.cpu().detach() def step(self, features, features_valid, lr, arch_optimizer, unrolled): self.zero_grad() arch_optimizer.zero_grad() # binarize before forward propagation self.binarize() loss = self._backward_step(features_valid) # restore weight before updating self.recover() arch_optimizer.step() return loss def _backward_step(self, features_valid): inferences, regs = self(features_valid) loss = self.compute_loss(inferences, features_valid["label"], regs) loss.backward() return loss class DSNAS(Virtue): def __init__(self, embedding_dim, reg, args): super(DSNAS, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for name1 in self.columns: for name2 in self.columns: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) if self.args.multi_operation: num_op = len(self.columns) self.log_alpha = torch.nn.Parameter(torch.zeros((num_op*num_op, len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) else: self.log_alpha = torch.nn.Parameter(torch.zeros((1, len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) self._arch_parameters = [self.log_alpha] self.weights = Variable(torch.zeros_like(self.log_alpha)) if self.args.early_fix_arch: self.fix_arch_index = {} def recommend(self, features): self.eval() self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) if self.args.early_fix_arch: if len(self.fix_arch_index.keys()) > 0: for key, value_lst in self.fix_arch_index.items(): self.weights[key, :].zero_() self.weights[key, value_lst[0]] = 1 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for name1 in self.columns: for name2 in self.columns: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding = self.embedding_all[name1][max_index](features[name1]) name2_embedding = self.embedding_all[name2][max_index](features[name2]) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) name1_embedding_trans = name1_embedding#self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = name2_embedding#self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) #ipdb.set_trace() pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) simulate_index = [] for i in range(len(max_index)): if np.random.random() < self.args.epsion: simulate_index.append(np.random.randint(0, 2)) else: simulate_index.append(max_index[i]) a_ind = np.array([(i, val) for i, val in enumerate(simulate_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) cnt = 0 time_data = 0 time_forward = 0 time_update = 0 end = -1 for step, features in enumerate(train_bandit): if end!=-1: time_data += time.time() - end begin = time.time() optimizer.zero_grad() arch_optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) time_forward += time.time() - begin losses.append(error_loss.cpu().detach().item()) begin2 = time.time() optimizer.step() arch_optimizer.step() time_update += time.time() - begin2 cnt += 1 end = time.time() print("time_data: ", time_data) print("time_forward: ", time_forward) print("time_update: ", time_update) print("cnt: ", cnt) return np.mean(losses) def revised_arch_index(self): if self.args.early_fix_arch: sort_log_alpha = torch.topk(F.softmax(self.log_alpha.data, dim=-1), 2) argmax_index = (sort_log_alpha[0][:, 0] - sort_log_alpha[0][:, 1] >= 0.01) for id in range(argmax_index.size(0)): if argmax_index[id] == 1 and id not in self.fix_arch_index.keys(): self.fix_arch_index[id] = [sort_log_alpha[1][id, 0].item(), self.log_alpha.detach().clone()[id, :]] for key, value_lst in self.fix_arch_index.items(): self.log_alpha.data[key, :] = value_lst[1] def forward(self, features): regs = 0 self.weights = self._get_weights(self.log_alpha) self.revised_arch_index() if self.args.early_fix_arch: if len(self.fix_arch_index.keys()) > 0: for key, value_lst in self.fix_arch_index.items(): self.weights[key, :].zero_() self.weights[key, value_lst[0]] = 1 cate_prob = F.softmax(self.log_alpha, dim=-1) self.cate_prob = cate_prob.clone().detach() loss_alpha = torch.log( (self.weights * F.softmax(self.log_alpha, dim=-1)).sum(-1)).sum() self.weights.requires_grad_() inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 from sklearn.externals.joblib import Parallel, delayed names_all = [] for name1 in self.columns: for name2 in self.columns: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding = self.embedding_all[name1][max_index](features[name1]) name2_embedding = self.embedding_all[name2][max_index](features[name2]) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) names_all.append([name1_embedding, name2_embedding, cur_weights.view(-1,), self.FC[name1 + ":" + name2]]) res = Parallel(n_jobs=8, backend="threading")(delayed(MixedBinary)(para1, para2, para3, para4) for para1,para2,para3,para4 in names_all) inferences = sum(res) # for name1 in self.columns: # for name2 in self.columns: # if self.args.multi_operation: # cur_weights = self.weights[cur_index] # max_index = cur_weights.argmax().item() # cur_index += 1 # if self.args.ofm: # name1_embedding = self.embedding_all[name1][max_index](features[name1]) # name2_embedding = self.embedding_all[name2][max_index](features[name2]) # else: # name1_embedding = self.embedding_all[name1](features[name1]) # name2_embedding = self.embedding_all[name2](features[name2]) # regs += self.reg * (torch.norm(name1_embedding) + torch.norm(name2_embedding)) # name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) # name2_embedding_trans = self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) # inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) self.weights.grad = torch.zeros_like(self.weights) (weighted_loss + loss_alpha).backward() self.block_reward = self.weights.grad.data.sum(-1) self.log_alpha.grad.data.mul_(self.block_reward.view(-1, 1)) return inferences, weighted_loss, loss_alpha def _get_weights(self, log_alpha): if self.args.random_sample: uni = torch.ones_like(log_alpha) m = torch.distributions.one_hot_categorical.OneHotCategorical(uni) else: m = torch.distributions.one_hot_categorical.OneHotCategorical(probs=F.softmax(log_alpha, dim=-1)) return m.sample() def arch_parameters(self): return self._arch_parameters def genotype(self): if not self.args.multi_operation: genotype = PRIMITIVES_BINARY[self.log_alpha.argmax().cpu().numpy()] genotype_p = F.softmax(self.log_alpha, dim=-1) else: genotype = [] for index in self.log_alpha.argmax(axis=1).cpu().numpy(): genotype.append(PRIMITIVES_BINARY[index]) genotype = ":".join(genotype[:10]) genotype_p = F.softmax(self.log_alpha, dim=-1)[:10] return genotype, genotype_p.cpu().detach() class Uniform: def __init__(self, embedding_dim, reg, args): self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) def recommend(self, features): pos_weights = torch.zeros_like(features["label"]) max_index = np.random.randint(0, 2, features["label"].shape[0]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() return reward def step(self, optimizer, arch_optimizer): return 0 def genotype(self): return "uniform", 0 class Egreedy: def __init__(self, embedding_dim, reg, args): self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) self.epsion = 0.2 self.action_rewards = {0:[0,1.0], 1:[0,1.0]}#total reward, action_num self.max_action = 0 def recommend(self, features): max_reward = np.float("-inf") for key in self.action_rewards: if self.action_rewards[key][0]/self.action_rewards[key][1] > max_reward: max_reward = self.action_rewards[key][0]/self.action_rewards[key][1] self.max_action = key pos_weights = torch.zeros_like(features["label"]) max_index = np.random.randint(0, 2, features["label"].shape[0]) simulate_index = [] for i in range(len(max_index)): if np.random.random()<self.epsion: simulate_index.append(max_index[i]) else: simulate_index.append(self.max_action) a_ind = np.array([(i, val) for i, val in enumerate(simulate_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() action_rewards = torch.sum(torch.mul(features["label"], pos_weights), dim=0) action_nums = torch.sum(pos_weights, dim=0) for key in self.action_rewards: temp = self.action_rewards[key] temp[0] += action_rewards[key].cpu().detach().item() temp[1] += action_nums[key].cpu().detach().item() self.action_rewards[key] = temp return reward def step(self, optimizer, arch_optimizer): return 0 def genotype(self): return "uniform", 0 class FM(Virtue): def __init__(self, embedding_dim, reg, args): super(FM, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for name1 in self.columns: for name2 in self.columns: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([1, 1, 1, 1, 1.0]) self.weights = Variable(torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0])) def recommend(self, features): self.eval() inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for name1 in self.columns: for name2 in self.columns: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding = self.embedding_all[name1][max_index](features[name1]) name2_embedding = self.embedding_all[name2][max_index](features[name2]) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) name1_embedding_trans = name1_embedding#self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = name2_embedding#self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) cnt = 0 for step, features in enumerate(train_bandit): optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) losses.append(error_loss.cpu().detach().item()) optimizer.step() cnt += 1 print("cnt: ", cnt) return np.mean(losses) def forward(self, features): regs = 0 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for name1 in self.columns: for name2 in self.columns: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding = self.embedding_all[name1][max_index](features[name1]) name2_embedding = self.embedding_all[name2][max_index](features[name2]) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) regs += self.reg * (torch.norm(name1_embedding) + torch.norm(name2_embedding)) name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_p(name2_embedding.view(-1, 1)).view(name2_embedding.size()) inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) weighted_loss.backward() return inferences, weighted_loss, 0 def genotype(self): return "FM", 0 class Plus(FM): def __init__(self, embedding_dim, reg, args): super(Plus, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self._initialize_alphas() def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.weights = Variable(torch.Tensor([1.0, 0.0, 0.0, 0.0, 0.0])) def genotype(self): return "Plus", 0 class Max(FM): def __init__(self, embedding_dim, reg, args): super(Max, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self._initialize_alphas() def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.weights = Variable(torch.Tensor([0.0, 0.0, 1.0, 0.0, 0.0])) def genotype(self): return "Max", 0 class Min(FM): def __init__(self, embedding_dim, reg, args): super(Min, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self._initialize_alphas() def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.weights = Variable(torch.Tensor([0.0, 0.0, 0.0, 1.0, 0.0])) def genotype(self): return "Min", 0 class Concat(FM): def __init__(self, embedding_dim, reg, args): super(FM, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self._initialize_alphas() def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.weights = Variable(torch.Tensor([0.0, 0.0, 0.0, 0.0, 1.0])) def genotype(self): return "Concat", 0
29,058
42.962179
165
py
AutoCO
AutoCO-main/exp_public/adult/simulate/__init__.py
0
0
0
py
AutoCO
AutoCO-main/exp_public/adult/simulate/baseline.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable import utils from collections import Counter from torch.distributions.multivariate_normal import MultivariateNormal PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat'] PRIMITIVES_NAS = [0, 2, 4, 8, 16] SPACE_NAS = pow(len(PRIMITIVES_NAS), 5) OPS = { 'plus': lambda p, q: p + q, 'multiply': lambda p, q: p * q, 'max': lambda p, q: torch.max(torch.stack((p, q)), dim=0)[0], 'min': lambda p, q: torch.min(torch.stack((p, q)), dim=0)[0], 'concat': lambda p, q: torch.cat([p, q], dim=-1), 'norm_0': lambda p: torch.ones_like(p), 'norm_0.5': lambda p: torch.sqrt(torch.abs(p) + 1e-7), 'norm_1': lambda p: torch.abs(p), 'norm_2': lambda p: p ** 2, 'I': lambda p: torch.ones_like(p), '-I': lambda p: -torch.ones_like(p), 'sign': lambda p: torch.sign(p), } class Virtue_v(nn.Module): def __init__(self, embedding_dim, reg, embedding_num=12, ofm=False, first_order=False): super(Virtue_v, self).__init__() self.embedding_dim = embedding_dim self.reg = reg self.embedding_mean = nn.ModuleDict({}) self.embedding_std = nn.ModuleDict({}) if first_order: self.embedding_first_order = nn.ModuleDict({}) self.columns = ["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country"] for name in self.columns: self.embedding_mean[name] = nn.Embedding(embedding_num, embedding_dim) self.embedding_std[name] = nn.Embedding(embedding_num, embedding_dim) if first_order: self.embedding_first_order[name] = nn.Embedding(embedding_num, 1) self.embedding_action = nn.Embedding(2, embedding_dim) if first_order: self.embedding_action_first_order = nn.Embedding(2, 1) class Virtue(nn.Module): def __init__(self, embedding_dim, reg, embedding_num=12, ofm=False, first_order=False): super(Virtue, self).__init__() self.embedding_dim = embedding_dim self.reg = reg self.embedding_all = nn.ModuleDict({}) if first_order: self.embedding_first_order = nn.ModuleDict({}) self.columns = ["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country"] for name in self.columns: self.embedding_all[name] = nn.Embedding(embedding_num, embedding_dim) if first_order: self.embedding_first_order[name] = nn.Embedding(embedding_num, 1) self.embedding_action = nn.Embedding(2, embedding_dim) if first_order: self.embedding_action_first_order = nn.Embedding(2, 1) class FM_v(Virtue_v): """ FM with EE """ def __init__(self, embedding_dim, reg, args): super(FM_v, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num, first_order=args.first_order) self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.log_alpha = torch.Tensor([1, 1, 1, 1, 1.0]) self.weights = Variable(torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def reparameterize(self, mu, std): std = torch.log(1 + torch.exp(std)) v = self.rand_array[:std.numel()].reshape(std.shape) return (mu + std * v * 0.01) def KL_distance(self, mean1, mean2, std1, std2): a = torch.log(std2 / std1) + (std1 * std1 + (mean1 - mean2) * (mean1 - mean2)) / 2 / std2 / std2 - 1.0 / 2.0 return torch.sum(a) def recommend(self, features): self.eval() inferences = 0 inferences_0 = 0 inferences_1 = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) #inferences_0 += torch.sum(name1_embedding*name2_embedding, dim=1, keepdim=True) #inferences_1 += torch.sum(name1_embedding*name2_embedding, dim=1, keepdim=True) inferences += torch.sum(name1_embedding*name2_embedding, dim=1, keepdim=True) inferences_0 = 0 # inferences.clone() # action 0 inferences_1 = 0 # inferences.clone() # action_1 #features with action for name1 in self.columns: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) if epoch < self.args.search_epoch: train_epoch = (epoch+1)*5 else: train_epoch = 1 for k in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) losses.append(error_loss.cpu().detach().item()) optimizer.step() print(self.embedding_mean["workclass"](torch.LongTensor([[1]]))) return np.mean(losses) def forward(self, features): regs = 0 inferences = 0 inferences_0 = 0 inferences_1 = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) #inferences_0 += torch.sum(name1_embedding * name2_embedding, dim=1, keepdim=True) #inferences_1 += torch.sum(name1_embedding * name2_embedding, dim=1, keepdim=True) inferences += torch.sum(name1_embedding * name2_embedding, dim=1, keepdim=True) # features with action inferences_0 = 0 # inferences.clone() # action 0 inferences_1 = 0 # inferences.clone() # action_1 for name1 in self.columns: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) kl = 0 for name in self.columns: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) (weighted_loss + kl/features["label"].shape[0]).backward() return inferences, weighted_loss, 0 def genotype(self): return "FM_v", 0 class FM(Virtue): """ FM without EE """ def __init__(self, embedding_dim, reg, args): super(FM, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num, first_order=args.first_order) self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.log_alpha = torch.Tensor([1, 1, 1, 1, 1.0]) self.weights = Variable(torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def recommend(self, features): self.eval() inferences = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) inferences += torch.sum(name1_embedding*name2_embedding, dim=1, keepdim=True) inferences_0 = 0 #inferences.clone() # action 0 inferences_1 = 0 #inferences.clone() # action_1 #features with action for name1 in self.columns: name1_embedding = self.embedding_all[name1](features[name1]) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) if epoch < self.args.search_epoch: train_epoch = (epoch+1)*5 else: train_epoch = 1 for k in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) losses.append(error_loss.cpu().detach().item()) optimizer.step() print(self.embedding_all["workclass"](torch.LongTensor([[1]]))) return np.mean(losses) def forward(self, features): regs = 0 inferences = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) inferences += torch.sum(name1_embedding * name2_embedding, dim=1, keepdim=True) # features with action inferences_0 = 0 #inferences.clone() # action 0 inferences_1 = 0 #inferences.clone() # action_1 for name1 in self.columns: name1_embedding = self.embedding_all[name1](features[name1]) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) weighted_loss.backward() return inferences, weighted_loss, 0 def genotype(self): return "FM", 0 class FM_v2(Virtue_v): """ FM with EE and FC layer """ def __init__(self, embedding_dim, reg, args): super(FM_v2, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num, first_order=args.first_order) self.args = args self._initialize_alphas() self.FC = nn.ModuleDict({}) for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: self.FC[name1 + ":" + name2] = nn.Linear(embedding_dim, 1, bias=False) #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.log_alpha = torch.Tensor([1, 1, 1, 1, 1.0]) self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.weights = Variable(torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def reparameterize(self, mu, std): std = torch.log(1 + torch.exp(std)) v = self.rand_array[:std.numel()].reshape(std.shape) return (mu + std * v * 0.01) def KL_distance(self, mean1, mean2, std1, std2): a = torch.log(std2 / std1) + (std1 * std1 + (mean1 - mean2) * (mean1 - mean2)) / 2 / std2 / std2 - 1.0 / 2.0 return torch.sum(a) def recommend(self, features): self.eval() inferences = 0 inferences_0 = 0 inferences_1 = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) inferences += self.FC[name1 + ":" + name2](name1_embedding * name2_embedding) inferences_0 = inferences.clone() # action 0 inferences_1 = inferences.clone() # action_1 #features with action for name1 in self.columns: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer, step): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) cnt = 0 for step, features in enumerate(train_bandit): cnt += 1 optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) losses.append(error_loss.cpu().detach().item()) optimizer.step() print("cnt: ", cnt) return np.mean(losses) def forward(self, features): regs = 0 inferences = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) inferences += self.FC[name1 + ":" + name2](name1_embedding * name2_embedding) # features with action inferences_0 = inferences.clone() # action 0 inferences_1 = inferences.clone() # action_1 for name1 in self.columns: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) inferences_0 += torch.sum(name1_embedding * self.embedding_action(torch.zeros_like(features[name1]).long()), dim=1, keepdim=True) inferences_1 += torch.sum(name1_embedding * self.embedding_action(torch.ones_like(features[name1]).long()), dim=1, keepdim=True) if self.args.first_order: name1_embedding_first_order = self.embedding_first_order[name1](features[name1]) inferences_0 += name1_embedding_first_order inferences_1 += name1_embedding_first_order if self.args.first_order: inferences_0 += self.embedding_action_first_order(torch.zeros_like(features[name1]).long()) inferences_1 += self.embedding_action_first_order(torch.ones_like(features[name1]).long()) inferences = torch.cat([inferences_0, inferences_1], dim=1) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) kl = 0 for name in self.columns: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) (weighted_loss + kl/features["label"].shape[0]).backward() return inferences, weighted_loss, 0 def genotype(self): return "FM_v2", 0 class Random: def __init__(self, embedding_dim, reg, args): self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) def recommend(self, features): pos_weights = torch.zeros_like(features["label"]) max_index = np.random.randint(0, 2, features["label"].shape[0]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "Random", 0 class Egreedy: def __init__(self, embedding_dim, reg, args): self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) self.epsion = 0.2 self.action_rewards = {0:[0,1.0], 1:[0.1,1.0]}#total reward, action_num self.max_action = 0 def recommend(self, features): max_reward = np.float("-inf") for key in self.action_rewards: if self.action_rewards[key][0]/self.action_rewards[key][1] > max_reward: max_reward = self.action_rewards[key][0]/self.action_rewards[key][1] self.max_action = key pos_weights = torch.zeros_like(features["label"]) max_index = np.random.randint(0, 2, features["label"].shape[0]) simulate_index = [] for i in range(len(max_index)): if np.random.random()<self.epsion: simulate_index.append(max_index[i]) else: simulate_index.append(self.max_action) a_ind = np.array([(i, val) for i, val in enumerate(simulate_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() action_rewards = torch.sum(torch.mul(features["label"], pos_weights), dim=0) action_nums = torch.sum(pos_weights, dim=0) for key in self.action_rewards: temp = self.action_rewards[key] temp[0] += action_rewards[key].cpu().detach().item() temp[1] += action_nums[key].cpu().detach().item() self.action_rewards[key] = temp return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "Egreedy", 0 class Thompson: def __init__(self, embedding_dim, reg, args): self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) self.epsion = 0.2 self.action_rewards = {0:[0,0], 1:[0,0]}#total reward, action_num self.max_action = 0 def recommend(self, features): #Thompson sampling values = [] num = 2 N = 10000 for index in range(num): pos = np.random.beta(1+int(self.action_rewards[index][0]), 2+int(self.action_rewards[index][1]), N) values.append(pos) action_pos = np.vstack(values) action_num = Counter(action_pos.argmax(axis=0)) action_percentage = [] for index in range(num): action_percentage.append(action_num[index]/N) simulate_index = [] for i in range(features["label"].shape[0]): simulate_index.append(np.random.choice(range(num), p=action_percentage)) pos_weights = torch.zeros_like(features["label"]) a_ind = np.array([(i, val) for i, val in enumerate(simulate_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() action_rewards = torch.sum(torch.mul(features["label"], pos_weights), dim=0) action_nums = torch.sum(pos_weights, dim=0) for key in self.action_rewards: temp = self.action_rewards[key] temp[0] += action_rewards[key].cpu().detach().item() temp[1] += action_nums[key].cpu().detach().item() self.action_rewards[key] = temp return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "Thompson", 0 class LinUCB2: def __init__(self, embedding_dim, reg, args): self.Aa = torch.eye(104) self.ba = torch.zeros(104).view(-1,1) self.alpha = 0.05 self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) def recommend(self, features): action1_features = torch.zeros((features["label"].shape[0], 2)) action1_features[:, 0] = 1.0 action2_features = torch.zeros((features["label"].shape[0], 2)) action2_features[:, 1] = 1.0 action1_input = torch.cat([features["feature"], action1_features], dim=1) action2_input = torch.cat([features["feature"], action2_features], dim=1) inputs_all = [action1_input, action2_input] theta = torch.matmul(torch.inverse(self.Aa), self.ba) action1_score = torch.matmul(action1_input, theta) + self.alpha * torch.sqrt( torch.sum(torch.mul(torch.matmul(action1_input, torch.inverse(self.Aa)), action1_input), dim=-1)).view(-1,1) action2_score = torch.matmul(action2_input, theta) + self.alpha * torch.sqrt( torch.sum(torch.mul(torch.matmul(action2_input, torch.inverse(self.Aa)), action2_input), dim=-1)).view(-1, 1) score_all = torch.cat([action1_score, action2_score], dim=1) max_index = score_all.argmax(dim=1) print(Counter(max_index.numpy())) pos_weights = torch.zeros_like(features["label"]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() #update Aa and ba for i in range(max_index.shape[0]): cur_action = max_index[i].item() cur_reward = features["label"][i, cur_action].item() cur_feature = inputs_all[cur_action][i] self.Aa += torch.matmul(cur_feature.view(-1,1), cur_feature.view(1,-1)) self.ba += cur_reward * cur_feature.view(-1,1) return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "LinUCB2", 0 # class LinUCB: def __init__(self, embedding_dim, reg, args): self.action_num = 2 self.feature_dim = 102 self.Aa = [] self.ba = [] for i in range(self.action_num): self.Aa.append(torch.eye(self.feature_dim)) self.ba.append(torch.zeros(self.feature_dim).view(-1,1)) self.alpha = 1.0 self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) def recommend(self, features): score_all = [] for i in range(self.action_num): Aa = self.Aa[i] ba = self.ba[i] theta = torch.matmul(torch.inverse(Aa), ba) score = torch.matmul(features["feature"], theta) + self.alpha * torch.sqrt( torch.sum(torch.mul(torch.matmul(features["feature"], torch.inverse(Aa)), features["feature"]), dim=-1) ).view(-1,1) score_all.append(score) score_all = torch.cat(score_all, dim=1) max_index = score_all.argmax(dim=1) print(Counter(max_index.numpy())) pos_weights = torch.zeros_like(features["label"]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() #update Aa and ba for i in range(max_index.shape[0]): cur_action = max_index[i].item() cur_reward = features["label"][i, cur_action].item() cur_feature = features["feature"][i] Aa = self.Aa[cur_action] ba = self.ba[cur_action] Aa += torch.matmul(cur_feature.view(-1,1), cur_feature.view(1,-1)) ba += cur_reward * cur_feature.view(-1,1) self.Aa[cur_action] = Aa self.ba[cur_action] = ba return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "LinUCB", 0 class LinThompson: def __init__(self, embedding_dim, reg, args): self.action_num = 2 self.feature_dim = 102 self.Aa = [] self.ba = [] for i in range(self.action_num): self.Aa.append(torch.eye(self.feature_dim)) self.ba.append(torch.zeros(self.feature_dim).view(-1, 1)) self.alpha = 1.0 self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) def recommend(self, features): score_all = [] for i in range(self.action_num): Aa = self.Aa[i] ba = self.ba[i] mu = torch.matmul(torch.inverse(Aa), ba) variance = torch.inverse(Aa) try: theta = MultivariateNormal(loc=mu.view(-1), covariance_matrix=self.alpha * variance).sample().view(-1,1) except: print("Error here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") theta = mu.view(-1,1) score = torch.matmul(features["feature"], theta) + self.alpha * torch.sqrt( torch.sum(torch.mul(torch.matmul(features["feature"], torch.inverse(Aa)), features["feature"]), dim=-1) ).view(-1, 1) score_all.append(score) score_all = torch.cat(score_all, dim=1) max_index = score_all.argmax(dim=1) print(Counter(max_index.numpy())) pos_weights = torch.zeros_like(features["label"]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() # update Aa and ba for i in range(max_index.shape[0]): cur_action = max_index[i].item() cur_reward = features["label"][i, cur_action].item() cur_feature = features["feature"][i] Aa = self.Aa[cur_action] ba = self.ba[cur_action] Aa += torch.matmul(cur_feature.view(-1, 1), cur_feature.view(1, -1)) ba += cur_reward * cur_feature.view(-1, 1) self.Aa[cur_action] = Aa self.ba[cur_action] = ba return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "LinThompson", 0 class LinEGreedy: def __init__(self, embedding_dim, reg, args): self.Aa = torch.eye(104) self.ba = torch.zeros(104).view(-1,1) self.log_alpha = torch.Tensor([1.0, 2.0, 3.0, 4.0]) self.epsion = 0.2 self.turn = True def recommend(self, features): action1_features = torch.zeros((features["label"].shape[0], 2)) action1_features[:, 0] = 1.0 action2_features = torch.zeros((features["label"].shape[0], 2)) action2_features[:, 1] = 1.0 action1_input = torch.cat([features["feature"], action1_features], dim=1) action2_input = torch.cat([features["feature"], action2_features], dim=1) inputs_all = [action1_input, action2_input] theta = torch.matmul(torch.inverse(self.Aa), self.ba) action1_score = torch.matmul(action1_input, theta) action2_score = torch.matmul(action2_input, theta) score_all = torch.cat([action1_score, action2_score], dim=1) max_index = score_all.argmax(dim=1) if self.turn: simulate_index = [] for i in range(len(max_index)): if np.random.random() < self.epsion: simulate_index.append(max_index[i].item()) else: simulate_index.append(np.random.randint(0, 2)) max_index = simulate_index self.turn = False print(Counter(max_index)) pos_weights = torch.zeros_like(features["label"]) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() #update Aa and ba for i in range(len(max_index)): cur_action = max_index[i] cur_reward = features["label"][i, cur_action].item() cur_feature = inputs_all[cur_action][i] self.Aa += torch.matmul(cur_feature.view(-1,1), cur_feature.view(1,-1)) self.ba += cur_reward * cur_feature.view(-1,1) return reward def step(self, optimizer, arch_optimizer, epoch): return 0 def genotype(self): return "LinEGreedy", 0
37,292
45.909434
141
py
AutoCO
AutoCO-main/exp_public/adult/simulate/vartional_model.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable import utils import ipdb PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat'] PRIMITIVES_NAS = [0, 2, 4, 8, 16] SPACE_NAS = pow(len(PRIMITIVES_NAS), 5) OPS = { 'plus': lambda p, q: p + q, 'multiply': lambda p, q: p * q, 'max': lambda p, q: torch.max(torch.stack((p, q)), dim=0)[0], 'min': lambda p, q: torch.min(torch.stack((p, q)), dim=0)[0], 'concat': lambda p, q: torch.cat([p, q], dim=-1), 'norm_0': lambda p: torch.ones_like(p), 'norm_0.5': lambda p: torch.sqrt(torch.abs(p) + 1e-7), 'norm_1': lambda p: torch.abs(p), 'norm_2': lambda p: p ** 2, 'I': lambda p: torch.ones_like(p), '-I': lambda p: -torch.ones_like(p), 'sign': lambda p: torch.sign(p), } def constrain(p): c = torch.norm(p, p=2, dim=1, keepdim=True) c[c < 1] = 1.0 p.data.div_(c) def MixedBinary(embedding_p, embedding_q, weights, FC): # return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ # for w, primitive, fc in zip(weights, PRIMITIVES_BINARY, FC)]), 0) pos = weights.argmax().item() return weights[pos] * FC[pos](OPS[PRIMITIVES_BINARY[pos]](embedding_p, embedding_q)) class Virtue(nn.Module): def __init__(self, embedding_dim, reg, embedding_num=12, ofm=False): super(Virtue, self).__init__() self.embedding_dim = embedding_dim self.reg = reg self.embedding_mean = nn.ModuleDict({}) self.embedding_std = nn.ModuleDict({}) #self.embedding_first_order = nn.ModuleDict({}) self.columns = ["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country"] # for name in self.columns: # self.embedding_first_order[name] = nn.Embedding(embedding_num, 2) if not ofm: for name in self.columns: self.embedding_mean[name] = nn.Embedding(embedding_num, embedding_dim) self.embedding_std[name] = nn.Embedding(embedding_num, embedding_dim) else: for name in self.columns: temp_mean = nn.ModuleList() temp_std = nn.ModuleList() for primitive in PRIMITIVES_BINARY: temp_mean.append(nn.Embedding(embedding_num, embedding_dim)) temp_std.append(nn.Embedding(embedding_num, embedding_dim)) self.embedding_mean[name] = temp_mean self.embedding_std[name] = temp_std class Virtue2(nn.Module): def __init__(self, embedding_dim, reg, embedding_num=12, ofm=False): super(Virtue2, self).__init__() self.embedding_dim = embedding_dim self.reg = reg self.embedding_all = nn.ModuleDict({}) self.columns = ["workclass", "education", "marital-status", "occupation", "relationship", "race", "sex", "native-country"] if not ofm: for name in self.columns: self.embedding_all[name] = nn.Embedding(embedding_num, embedding_dim) else: for name in self.columns: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: temp.append(nn.Embedding(embedding_num, embedding_dim)) self.embedding_all[name] = temp class DSNAS_v(Virtue): def __init__(self, embedding_dim, reg, args): super(DSNAS_v, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) if self.args.multi_operation: num_op = len(self.columns) self.log_alpha = torch.nn.Parameter(torch.zeros((int(num_op*(num_op-1)/2), len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) else: self.log_alpha = torch.nn.Parameter(torch.zeros((1, len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) self._arch_parameters = [self.log_alpha] self.weights = Variable(torch.zeros_like(self.log_alpha)) if self.args.early_fix_arch: self.fix_arch_index = {} self.rand_array = torch.randn(3000000) def reparameterize(self, mu, std): std = torch.log(1 + torch.exp(std)) #v = self.rand_array[:std.numel()].reshape(std.shape) v = torch.randn(3000000)[:std.numel()].reshape(std.shape) return (mu + std * v * 0.01) # def KL_distance(self, mean1, mean2, std1, std2): # a = torch.log(std2 / std1) + (std1 * std1 + (mean1 - mean2) * (mean1 - mean2)) / 2 / std2 / std2 - 1.0 / 2.0 # return torch.sum(a) def KL_distance(self, mean1, mean2, std1, std2): a = 1/2 * (torch.log(torch.det(std2)/torch.det(std1)) - std1.numel() + (mean1 - mean2)*(mean1 - mean2)/torch.square(std2) + torch.sum(torch.square(std1)/torch.square(std2))) return a def recommend(self, features): self.eval() self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) if self.args.early_fix_arch: if len(self.fix_arch_index.keys()) > 0: for key, value_lst in self.fix_arch_index.items(): self.weights[key, :].zero_() self.weights[key, value_lst[0]] = 1 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding_mean = self.embedding_mean[name1][max_index](features[name1]) name1_embedding_std = self.embedding_std[name1][max_index](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2][max_index](features[name2]) name2_embedding_std = self.embedding_std[name2][max_index](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) #if epoch < self.args.search_epoch: # train_epoch = (epoch+1)*5 #else: train_epoch = 5 for k in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() if epoch < self.args.search_epoch: arch_optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features, epoch, search=True) else: output, error_loss, loss_alpha = self.forward(features, epoch, search=False) losses.append(error_loss.cpu().detach().item()) optimizer.step() if epoch < self.args.search_epoch: arch_optimizer.step() return np.mean(losses) def revised_arch_index(self, epoch): if self.args.early_fix_arch: if epoch < self.args.search_epoch: sort_log_alpha = torch.topk(F.softmax(self.log_alpha.data, dim=-1), 2) argmax_index = (sort_log_alpha[0][:, 0] - sort_log_alpha[0][:, 1] >= 0.10) for id in range(argmax_index.size(0)): if argmax_index[id] == 1 and id not in self.fix_arch_index.keys(): self.fix_arch_index[id] = [sort_log_alpha[1][id, 0].item(), self.log_alpha.detach().clone()[id, :]] if epoch >= self.args.search_epoch: #fix the arch。 max_index = torch.argmax(self.log_alpha, dim=-1) for id in range(max_index.size(0)): if id not in self.fix_arch_index.keys(): self.fix_arch_index[id] = [max_index[id].item(), self.log_alpha.detach().clone()[id, :]] for key, value_lst in self.fix_arch_index.items(): self.log_alpha.data[key, :] = value_lst[1] def forward(self, features, epoch, search): #self.weights = self._get_weights(self.log_alpha) self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) # self.revised_arch_index(epoch) # if self.args.early_fix_arch: # if len(self.fix_arch_index.keys()) > 0: # for key, value_lst in self.fix_arch_index.items(): # self.weights[key, :].zero_() # self.weights[key, value_lst[0]] = 1 if search: cate_prob = F.softmax(self.log_alpha, dim=-1) self.cate_prob = cate_prob.clone().detach() loss_alpha = torch.log( (self.weights * F.softmax(self.log_alpha, dim=-1)).sum(-1)).sum() self.weights.requires_grad_() max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 from sklearn.externals.joblib import Parallel, delayed names_all = [] for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding_mean = self.embedding_mean[name1][max_index](features[name1]) name1_embedding_std = self.embedding_std[name1][max_index](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2][max_index](features[name2]) name2_embedding_std = self.embedding_std[name2][max_index](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding names_all.append( [name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) res = Parallel(n_jobs=8, backend="threading")( delayed(MixedBinary)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) inferences = sum(res) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) kl = 0 for name in self.columns: if not self.args.ofm: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) else: for index in range(len(PRIMITIVES_BINARY)): kl += self.KL_distance(self.embedding_mean[name][index].weight, 0 * torch.ones_like(self.embedding_mean[name][index].weight), torch.log(1 + torch.exp(self.embedding_std[name][index].weight)), 0.1 * torch.ones_like(self.embedding_std[name][index].weight)) if search: self.weights.grad = torch.zeros_like(self.weights) (weighted_loss + loss_alpha + kl/features["label"].shape[0]).backward() self.block_reward = self.weights.grad.data.sum(-1) self.log_alpha.grad.data.mul_(self.block_reward.view(-1, 1)) return inferences, weighted_loss, loss_alpha else: (weighted_loss + kl/features["label"].shape[0]).backward() return inferences, weighted_loss, 0 def _get_weights(self, log_alpha): if self.args.random_sample: uni = torch.ones_like(log_alpha) m = torch.distributions.one_hot_categorical.OneHotCategorical(uni) else: m = torch.distributions.one_hot_categorical.OneHotCategorical(probs=F.softmax(log_alpha, dim=-1)) return m.sample() def arch_parameters(self): return self._arch_parameters def genotype(self): if not self.args.multi_operation: genotype = PRIMITIVES_BINARY[self.log_alpha.argmax().cpu().numpy()] genotype_p = F.softmax(self.log_alpha, dim=-1) else: genotype = [] for index in self.log_alpha.argmax(axis=1).cpu().numpy(): genotype.append(PRIMITIVES_BINARY[index]) genotype = ":".join(genotype[:10]) genotype_p = F.softmax(self.log_alpha, dim=-1)[:10] return genotype, genotype_p.cpu().detach() class NASP(Virtue2): def __init__(self, embedding_dim, reg, args): super(NASP, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) if self.args.multi_operation: num_op = len(self.columns) self.log_alpha = torch.nn.Parameter(torch.zeros((int(num_op*(num_op-1)/2), len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) else: self.log_alpha = torch.nn.Parameter(torch.zeros((1, len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) self._arch_parameters = [self.log_alpha] self.weights = Variable(torch.zeros_like(self.log_alpha)) if self.args.early_fix_arch: self.fix_arch_index = {} self.rand_array = torch.randn(3000000) def recommend(self, features): self.eval() self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) if self.args.early_fix_arch: if len(self.fix_arch_index.keys()) > 0: for key, value_lst in self.fix_arch_index.items(): self.weights[key, :].zero_() self.weights[key, value_lst[0]] = 1 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding = self.embedding_all[name1][max_index](features[name1]) name2_embedding = self.embedding_all[name2][max_index](features[name2]) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def MixedBinary_ofm(self, embedding_p_all, embedding_q_all, weights, FC): return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ for w, primitive, fc, embedding_p, embedding_q in zip(weights, PRIMITIVES_BINARY, FC, embedding_p_all, embedding_q_all)]), 0) def MixedBinary_all(self, embedding_p, embedding_q, weights, FC): return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ for w, primitive, fc in zip(weights, PRIMITIVES_BINARY, FC)]), 0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) if epoch < self.args.search_epoch: train_epoch = (epoch+1)*5 else: train_epoch = 1 for k in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() arch_optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features, epoch, search=True) losses.append(error_loss.cpu().detach().item()) optimizer.step() arch_optimizer.step() return np.mean(losses) def forward(self, features, epoch, search): self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) self.weights.requires_grad_() max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 from sklearn.externals.joblib import Parallel, delayed names_all = [] for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: embedding_name1_all = [] embedding_name2_all = [] for index_name in range(len(PRIMITIVES_BINARY)): name1_embedding = self.embedding_all[name1][index_name](features[name1]) embedding_name1_all.append(name1_embedding) name2_embedding = self.embedding_all[name2][index_name](features[name2]) embedding_name2_all.append(name2_embedding) else: name1_embedding = self.embedding_all[name1](features[name1]) name2_embedding = self.embedding_all[name2](features[name2]) if self.args.trans: if self.args.ofm: embedding_name1_all_temp = [] embedding_name2_all_temp = [] for index_temp in range(len(embedding_name1_all)): embedding_name1_all_temp.append(self.mlp_p(embedding_name1_all[index_temp].view(-1, 1)).view(embedding_name1_all[index_temp].size())) embedding_name2_all_temp.append(self.mlp_p(embedding_name2_all[index_temp].view(-1, 1)).view(embedding_name2_all[index_temp].size())) embedding_name1_all = embedding_name1_all_temp embedding_name2_all = embedding_name2_all_temp else: name1_embedding = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) if self.args.ofm: names_all.append([embedding_name1_all, embedding_name2_all, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) else: names_all.append( [name1_embedding, name2_embedding, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) if self.args.ofm: res = Parallel(n_jobs=8, backend="threading")( delayed(self.MixedBinary_ofm)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) else: res = Parallel(n_jobs=8, backend="threading")( delayed(self.MixedBinary_all)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) inferences = sum(res) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) weighted_loss.backward() self.log_alpha.grad = self.weights.grad return inferences, weighted_loss, 0 def arch_parameters(self): return self._arch_parameters def genotype(self): if not self.args.multi_operation: genotype = PRIMITIVES_BINARY[self.log_alpha.argmax().cpu().numpy()] genotype_p = F.softmax(self.log_alpha, dim=-1) else: genotype = [] for index in self.log_alpha.argmax(axis=1).cpu().numpy(): genotype.append(PRIMITIVES_BINARY[index]) genotype = ":".join(genotype[:10]) genotype_p = F.softmax(self.log_alpha, dim=-1)[:10] return genotype, genotype_p.cpu().detach() class NASP_v(Virtue): def __init__(self, embedding_dim, reg, args): super(NASP_v, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2*embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) if self.args.multi_operation: num_op = len(self.columns) self.log_alpha = torch.nn.Parameter(torch.zeros((int(num_op*(num_op-1)/2), len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) else: self.log_alpha = torch.nn.Parameter(torch.zeros((1, len(PRIMITIVES_BINARY))).normal_(self.args.loc_mean, self.args.loc_std).requires_grad_()) self._arch_parameters = [self.log_alpha] self.weights = Variable(torch.zeros_like(self.log_alpha)) if self.args.early_fix_arch: self.fix_arch_index = {} self.rand_array = torch.randn(3000000) def reparameterize(self, mu, std): std = torch.log(1 + torch.exp(std)) v = self.rand_array[:std.numel()].reshape(std.shape) return (mu + std * v * 0.01) def KL_distance(self, mean1, mean2, std1, std2): a = torch.log(std2 / std1) + (std1 * std1 + (mean1 - mean2) * (mean1 - mean2)) / 2 / std2 / std2 - 1.0 / 2.0 return torch.sum(a) def recommend(self, features): self.eval() self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) if self.args.early_fix_arch: if len(self.fix_arch_index.keys()) > 0: for key, value_lst in self.fix_arch_index.items(): self.weights[key, :].zero_() self.weights[key, value_lst[0]] = 1 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding_mean = self.embedding_mean[name1][max_index](features[name1]) name1_embedding_std = self.embedding_std[name1][max_index](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2][max_index](features[name2]) name2_embedding_std = self.embedding_std[name2][max_index](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def MixedBinary_ofm(self, embedding_p_all, embedding_q_all, weights, FC): return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ for w, primitive, fc, embedding_p, embedding_q in zip(weights, PRIMITIVES_BINARY, FC, embedding_p_all, embedding_q_all)]), 0) def MixedBinary_all(self, embedding_p, embedding_q, weights, FC): return torch.sum(torch.stack([w * fc(OPS[primitive](embedding_p, embedding_q)) \ for w, primitive, fc in zip(weights, PRIMITIVES_BINARY, FC)]), 0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) if epoch < self.args.search_epoch: train_epoch = (epoch+1)*5 else: train_epoch = 1 for k in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() arch_optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features, epoch, search=True) # if epoch < self.args.search_epoch: # arch_optimizer.zero_grad() # output, error_loss, loss_alpha = self.forward(features, epoch, search=True) # else: # output, error_loss, loss_alpha = self.forward(features, epoch, search=False) losses.append(error_loss.cpu().detach().item()) optimizer.step() arch_optimizer.step() # if epoch < self.args.search_epoch: # arch_optimizer.step() return np.mean(losses) def revised_arch_index(self, epoch): if self.args.early_fix_arch: if epoch < self.args.search_epoch: sort_log_alpha = torch.topk(F.softmax(self.log_alpha.data, dim=-1), 2) argmax_index = (sort_log_alpha[0][:, 0] - sort_log_alpha[0][:, 1] >= 0.10) for id in range(argmax_index.size(0)): if argmax_index[id] == 1 and id not in self.fix_arch_index.keys(): self.fix_arch_index[id] = [sort_log_alpha[1][id, 0].item(), self.log_alpha.detach().clone()[id, :]] if epoch >= self.args.search_epoch: #fix the arch。 max_index = torch.argmax(self.log_alpha, dim=-1) for id in range(max_index.size(0)): if id not in self.fix_arch_index.keys(): self.fix_arch_index[id] = [max_index[id].item(), self.log_alpha.detach().clone()[id, :]] for key, value_lst in self.fix_arch_index.items(): self.log_alpha.data[key, :] = value_lst[1] def forward(self, features, epoch, search): self.weights = torch.zeros_like(self.log_alpha).scatter_(1, torch.argmax(self.log_alpha, dim=-1).view(-1, 1), 1) self.weights.requires_grad_() regs = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 from sklearn.externals.joblib import Parallel, delayed names_all = [] for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: embedding_name1_all = [] embedding_name2_all = [] for index_name in range(len(PRIMITIVES_BINARY)): name1_embedding_mean = self.embedding_mean[name1][index_name](features[name1]) name1_embedding_std = self.embedding_std[name1][index_name](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) embedding_name1_all.append(name1_embedding) name2_embedding_mean = self.embedding_mean[name2][index_name](features[name2]) name2_embedding_std = self.embedding_std[name2][index_name](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) embedding_name2_all.append(name2_embedding) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) regs += 1e-5 * (torch.norm(name1_embedding) + torch.norm(name2_embedding)) if self.args.trans: if self.args.ofm: embedding_name1_all_temp = [] embedding_name2_all_temp = [] for index_temp in range(len(embedding_name1_all)): embedding_name1_all_temp.append(self.mlp_p(embedding_name1_all[index_temp].view(-1, 1)).view(embedding_name1_all[index_temp].size())) embedding_name2_all_temp.append(self.mlp_p(embedding_name2_all[index_temp].view(-1, 1)).view(embedding_name2_all[index_temp].size())) embedding_name1_all = embedding_name1_all_temp embedding_name2_all = embedding_name2_all_temp else: name1_embedding = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) if self.args.ofm: names_all.append([embedding_name1_all, embedding_name2_all, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) else: names_all.append( [name1_embedding, name2_embedding, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) if self.args.ofm: res = Parallel(n_jobs=8, backend="threading")( delayed(self.MixedBinary_ofm)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) else: res = Parallel(n_jobs=8, backend="threading")( delayed(self.MixedBinary_all)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) inferences = sum(res) if self.args.first_order: for name in self.columns: inferences += self.embedding_first_order[name](features[name]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) kl = 0 for name in self.columns: if not self.args.ofm: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) else: for index in range(len(PRIMITIVES_BINARY)): kl += self.KL_distance(self.embedding_mean[name][index].weight, 0 * torch.ones_like(self.embedding_mean[name][index].weight), torch.log(1 + torch.exp(self.embedding_std[name][index].weight)), 0.1 * torch.ones_like(self.embedding_std[name][index].weight)) (weighted_loss + regs + kl/features["label"].shape[0]).backward() self.log_alpha.grad = self.weights.grad return inferences, weighted_loss, 0 def arch_parameters(self): return self._arch_parameters def genotype(self): if not self.args.multi_operation: genotype = PRIMITIVES_BINARY[self.log_alpha.argmax().cpu().numpy()] genotype_p = F.softmax(self.log_alpha, dim=-1) else: genotype = [] for index in self.log_alpha.argmax(axis=1).cpu().numpy(): genotype.append(PRIMITIVES_BINARY[index]) genotype = ":".join(genotype[:10]) genotype_p = F.softmax(self.log_alpha, dim=-1)[:10] return genotype, genotype_p.cpu().detach() class MULTIPLY_v(Virtue): def __init__(self, embedding_dim, reg, args): super(MULTIPLY_v, self).__init__(embedding_dim, reg, ofm=args.ofm, embedding_num=args.embedding_num) self.FC = nn.ModuleDict({}) for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: temp = nn.ModuleList() for primitive in PRIMITIVES_BINARY: if primitive == 'concat': temp.append(nn.Linear(2 * embedding_dim, 2, bias=False)) else: temp.append(nn.Linear(embedding_dim, 2, bias=False)) self.FC[name1 + ":" + name2] = temp self.args = args self._initialize_alphas() #initialize contextual infos self.contexts = {} self.pos_weights = torch.Tensor() self.rewards = [] def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0]) self.weights = Variable(torch.Tensor([0.0, 1.0, 0.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def reparameterize(self, mu, std): std = torch.log(1 + torch.exp(std)) v = self.rand_array[:std.numel()].reshape(std.shape) return (mu + std * v * 0.01) def KL_distance(self, mean1, mean2, std1, std2): a = torch.log(std2 / std1) + (std1 * std1 + (mean1 - mean2) * (mean1 - mean2)) / 2 / std2 / std2 - 1.0 / 2.0 return torch.sum(a) def recommend(self, features): self.eval() inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding_mean = self.embedding_mean[name1][max_index](features[name1]) name1_embedding_std = self.embedding_std[name1][max_index](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2][max_index](features[name2]) name2_embedding_std = self.embedding_std[name2][max_index](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding inferences += MixedBinary(name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1,), self.FC[name1 + ":" + name2]) # if self.args.first_order: # for name in self.columns: # inferences += self.embedding_first_order[name](features[name]) pos_weights = torch.zeros_like(features["label"]) max_index = torch.argmax(inferences, dim=1) a_ind = np.array([(i, val) for i, val in enumerate(max_index)]) pos_weights[a_ind[:, 0], a_ind[:, 1]] = 1.0 reward = torch.sum(torch.mul(features["label"], pos_weights)).cpu().detach().item() self.add_batch(features, pos_weights) return reward def add_batch(self, features, pos_weights): for index in features: if index in self.contexts: temp = self.contexts[index] self.contexts[index] = torch.cat([temp, features[index]], dim=0) else: self.contexts[index] = features[index] self.pos_weights = torch.cat([self.pos_weights, pos_weights], dim=0) def step(self, optimizer, arch_optimizer, epoch): self.train() losses = [] train_bandit = utils.get_data_queue_bandit(self.args, self.contexts, self.pos_weights) if epoch < 10: train_epoch = (epoch+1)*5 else: train_epoch = 1 for i in range(train_epoch): for step, features in enumerate(train_bandit): optimizer.zero_grad() output, error_loss, loss_alpha = self.forward(features) losses.append(error_loss.cpu().detach().item()) optimizer.step() return np.mean(losses) def forward(self, features): regs = 0 inferences = 0 max_index = self.weights.argmax().item() cur_weights = self.weights cur_index = 0 from sklearn.externals.joblib import Parallel, delayed names_all = [] for index1, name1 in enumerate(self.columns): for index2, name2 in enumerate(self.columns): if index1 < index2: if self.args.multi_operation: cur_weights = self.weights[cur_index] max_index = cur_weights.argmax().item() cur_index += 1 if self.args.ofm: name1_embedding_mean = self.embedding_mean[name1][max_index](features[name1]) name1_embedding_std = self.embedding_std[name1][max_index](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2][max_index](features[name2]) name2_embedding_std = self.embedding_std[name2][max_index](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) else: name1_embedding_mean = self.embedding_mean[name1](features[name1]) name1_embedding_std = self.embedding_std[name1](features[name1]) name1_embedding = self.reparameterize(name1_embedding_mean, name1_embedding_std) name2_embedding_mean = self.embedding_mean[name2](features[name2]) name2_embedding_std = self.embedding_std[name2](features[name2]) name2_embedding = self.reparameterize(name2_embedding_mean, name2_embedding_std) if self.args.trans: name1_embedding_trans = self.mlp_p(name1_embedding.view(-1, 1)).view(name1_embedding.size()) name2_embedding_trans = self.mlp_q(name2_embedding.view(-1, 1)).view(name2_embedding.size()) else: name1_embedding_trans = name1_embedding name2_embedding_trans = name2_embedding names_all.append( [name1_embedding_trans, name2_embedding_trans, cur_weights.view(-1, ), self.FC[name1 + ":" + name2]]) res = Parallel(n_jobs=8, backend="threading")( delayed(MixedBinary)(para1, para2, para3, para4) for para1, para2, para3, para4 in names_all) inferences = sum(res) # if self.args.first_order: # for name in self.columns: # inferences += self.embedding_first_order[name](features[name]) loss = (inferences - features["label"])**2 weighted_loss = torch.mean(torch.sum(torch.mul(features["pos_weights"], loss), dim=1)) kl = 0 for name in self.columns: if not self.args.ofm: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) else: kl += self.KL_distance(self.embedding_mean[name].weight, 0 * torch.ones_like(self.embedding_mean[name].weight), torch.log(1 + torch.exp(self.embedding_std[name].weight)), 0.1 * torch.ones_like(self.embedding_std[name].weight)) (weighted_loss + kl/features["label"].shape[0]).backward() return inferences, weighted_loss, 0 def genotype(self): return "FM_v", 0 class MAX_v(MULTIPLY_v): def __init__(self, embedding_dim, reg, args): super(MAX_v, self).__init__(embedding_dim, reg, args) def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([1, 1, 1, 1, 1.0]) self.weights = Variable(torch.Tensor([0.0, 0.0, 1.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def genotype(self): return "MAX", 0 class PLUS_v(MULTIPLY_v): def __init__(self, embedding_dim, reg, args): super(PLUS_v, self).__init__(embedding_dim, reg, args) def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([1, 0, 0, 0, 0.0]) self.weights = Variable(torch.Tensor([1.0, 0.0, 0.0, 0.0, 0.0])) self.rand_array = torch.randn(3000000) def genotype(self): return "PLUS", 0 class MIN_v(MULTIPLY_v): def __init__(self, embedding_dim, reg, args): super(MIN_v, self).__init__(embedding_dim, reg, args) def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([0, 0, 0, 1, 0.0]) self.weights = Variable(torch.Tensor([0.0, 0.0, 0.0, 1.0, 0.0])) self.rand_array = torch.randn(3000000) def genotype(self): return "MIN", 0 class CONCAT_v(MULTIPLY_v): def __init__(self, embedding_dim, reg, args): super(CONCAT_v, self).__init__(embedding_dim, reg, args) def _initialize_alphas(self): self.mlp_p = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.mlp_q = nn.Sequential( nn.Linear(1, 8), nn.Tanh(), nn.Linear(8, 1)) self.log_alpha = torch.Tensor([0, 0, 0, 0, 1.0]) self.weights = Variable(torch.Tensor([0.0, 0.0, 0.0, 0.0, 1.0])) self.rand_array = torch.randn(3000000) def genotype(self): return "CONCAT", 0
55,609
50.730233
176
py
AutoCO
AutoCO-main/exp_public/adult/simulate/train.py
import numpy as np import time def train(train_queue, model, optimizer, arch_optimizer, logging): rewards_all = [] losses_all = [] for step, features in enumerate(train_queue): rewards = model.recommend(features) rewards_all.append(rewards) losses = model.step(optimizer, arch_optimizer, step) losses_all.append(losses) print("losses: ", losses, "rewards: ", rewards) print("model's log_alpha", model.log_alpha) logging.info("step: %s, rewards: %s"%(step, rewards)) logging.info("step: %s, total_reward: %s" % (step, sum(rewards_all))) g, gp = model.genotype() return g, gp, np.mean(losses_all), sum(rewards_all)
635
34.333333
71
py
gae
gae-master/setup.py
from setuptools import setup from setuptools import find_packages setup(name='gae', version='0.0.1', description='Implementation of (Variational) Graph Auto-Encoders in Tensorflow', author='Thomas Kipf', author_email='[email protected]', url='https://tkipf.github.io', download_url='https://github.com/tkipf/gae', license='MIT', install_requires=['numpy', 'tensorflow', 'networkx', 'scikit-learn', 'scipy', ], extras_require={ 'visualization': ['matplotlib'], }, package_data={'gae': ['README.md']}, packages=find_packages())
733
30.913043
86
py
gae
gae-master/gae/initializations.py
import tensorflow as tf import numpy as np def weight_variable_glorot(input_dim, output_dim, name=""): """Create a weight variable with Glorot & Bengio (AISTATS 2010) initialization. """ init_range = np.sqrt(6.0 / (input_dim + output_dim)) initial = tf.random_uniform([input_dim, output_dim], minval=-init_range, maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
446
36.25
76
py
gae
gae-master/gae/preprocessing.py
import numpy as np import scipy.sparse as sp def sparse_to_tuple(sparse_mx): if not sp.isspmatrix_coo(sparse_mx): sparse_mx = sparse_mx.tocoo() coords = np.vstack((sparse_mx.row, sparse_mx.col)).transpose() values = sparse_mx.data shape = sparse_mx.shape return coords, values, shape def preprocess_graph(adj): adj = sp.coo_matrix(adj) adj_ = adj + sp.eye(adj.shape[0]) rowsum = np.array(adj_.sum(1)) degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5).flatten()) adj_normalized = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo() return sparse_to_tuple(adj_normalized) def construct_feed_dict(adj_normalized, adj, features, placeholders): # construct feed dictionary feed_dict = dict() feed_dict.update({placeholders['features']: features}) feed_dict.update({placeholders['adj']: adj_normalized}) feed_dict.update({placeholders['adj_orig']: adj}) return feed_dict def mask_test_edges(adj): # Function to build test set with 10% positive links # NOTE: Splits are randomized and results might slightly deviate from reported numbers in the paper. # TODO: Clean up. # Remove diagonal elements adj = adj - sp.dia_matrix((adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape) adj.eliminate_zeros() # Check that diag is zero: assert np.diag(adj.todense()).sum() == 0 adj_triu = sp.triu(adj) adj_tuple = sparse_to_tuple(adj_triu) edges = adj_tuple[0] edges_all = sparse_to_tuple(adj)[0] num_test = int(np.floor(edges.shape[0] / 10.)) num_val = int(np.floor(edges.shape[0] / 20.)) all_edge_idx = list(range(edges.shape[0])) np.random.shuffle(all_edge_idx) val_edge_idx = all_edge_idx[:num_val] test_edge_idx = all_edge_idx[num_val:(num_val + num_test)] test_edges = edges[test_edge_idx] val_edges = edges[val_edge_idx] train_edges = np.delete(edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0) def ismember(a, b, tol=5): rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1) return np.any(rows_close) test_edges_false = [] while len(test_edges_false) < len(test_edges): idx_i = np.random.randint(0, adj.shape[0]) idx_j = np.random.randint(0, adj.shape[0]) if idx_i == idx_j: continue if ismember([idx_i, idx_j], edges_all): continue if test_edges_false: if ismember([idx_j, idx_i], np.array(test_edges_false)): continue if ismember([idx_i, idx_j], np.array(test_edges_false)): continue test_edges_false.append([idx_i, idx_j]) val_edges_false = [] while len(val_edges_false) < len(val_edges): idx_i = np.random.randint(0, adj.shape[0]) idx_j = np.random.randint(0, adj.shape[0]) if idx_i == idx_j: continue if ismember([idx_i, idx_j], train_edges): continue if ismember([idx_j, idx_i], train_edges): continue if ismember([idx_i, idx_j], val_edges): continue if ismember([idx_j, idx_i], val_edges): continue if val_edges_false: if ismember([idx_j, idx_i], np.array(val_edges_false)): continue if ismember([idx_i, idx_j], np.array(val_edges_false)): continue val_edges_false.append([idx_i, idx_j]) assert ~ismember(test_edges_false, edges_all) assert ~ismember(val_edges_false, edges_all) assert ~ismember(val_edges, train_edges) assert ~ismember(test_edges, train_edges) assert ~ismember(val_edges, test_edges) data = np.ones(train_edges.shape[0]) # Re-build adj matrix adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])), shape=adj.shape) adj_train = adj_train + adj_train.T # NOTE: these edge lists only contain single direction of edge! return adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false
4,057
35.232143
104
py
gae
gae-master/gae/input_data.py
import numpy as np import sys import pickle as pkl import networkx as nx import scipy.sparse as sp def parse_index_file(filename): index = [] for line in open(filename): index.append(int(line.strip())) return index def load_data(dataset): # load the data: x, tx, allx, graph names = ['x', 'tx', 'allx', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.append(pkl.load(f, encoding='latin1')) else: objects.append(pkl.load(f)) x, tx, allx, graph = tuple(objects) test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset)) test_idx_range = np.sort(test_idx_reorder) if dataset == 'citeseer': # Fix citeseer dataset (there are some isolated nodes in the graph) # Find isolated nodes, add them as zero-vecs into the right position test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1) tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1])) tx_extended[test_idx_range-min(test_idx_range), :] = tx tx = tx_extended features = sp.vstack((allx, tx)).tolil() features[test_idx_reorder, :] = features[test_idx_range, :] adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph)) return adj, features
1,432
33.119048
83
py
gae
gae-master/gae/model.py
from gae.layers import GraphConvolution, GraphConvolutionSparse, InnerProductDecoder import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS class Model(object): def __init__(self, **kwargs): allowed_kwargs = {'name', 'logging'} for kwarg in kwargs.keys(): assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg for kwarg in kwargs.keys(): assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg name = kwargs.get('name') if not name: name = self.__class__.__name__.lower() self.name = name logging = kwargs.get('logging', False) self.logging = logging self.vars = {} def _build(self): raise NotImplementedError def build(self): """ Wrapper for _build() """ with tf.variable_scope(self.name): self._build() variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name) self.vars = {var.name: var for var in variables} def fit(self): pass def predict(self): pass class GCNModelAE(Model): def __init__(self, placeholders, num_features, features_nonzero, **kwargs): super(GCNModelAE, self).__init__(**kwargs) self.inputs = placeholders['features'] self.input_dim = num_features self.features_nonzero = features_nonzero self.adj = placeholders['adj'] self.dropout = placeholders['dropout'] self.build() def _build(self): self.hidden1 = GraphConvolutionSparse(input_dim=self.input_dim, output_dim=FLAGS.hidden1, adj=self.adj, features_nonzero=self.features_nonzero, act=tf.nn.relu, dropout=self.dropout, logging=self.logging)(self.inputs) self.embeddings = GraphConvolution(input_dim=FLAGS.hidden1, output_dim=FLAGS.hidden2, adj=self.adj, act=lambda x: x, dropout=self.dropout, logging=self.logging)(self.hidden1) self.z_mean = self.embeddings self.reconstructions = InnerProductDecoder(input_dim=FLAGS.hidden2, act=lambda x: x, logging=self.logging)(self.embeddings) class GCNModelVAE(Model): def __init__(self, placeholders, num_features, num_nodes, features_nonzero, **kwargs): super(GCNModelVAE, self).__init__(**kwargs) self.inputs = placeholders['features'] self.input_dim = num_features self.features_nonzero = features_nonzero self.n_samples = num_nodes self.adj = placeholders['adj'] self.dropout = placeholders['dropout'] self.build() def _build(self): self.hidden1 = GraphConvolutionSparse(input_dim=self.input_dim, output_dim=FLAGS.hidden1, adj=self.adj, features_nonzero=self.features_nonzero, act=tf.nn.relu, dropout=self.dropout, logging=self.logging)(self.inputs) self.z_mean = GraphConvolution(input_dim=FLAGS.hidden1, output_dim=FLAGS.hidden2, adj=self.adj, act=lambda x: x, dropout=self.dropout, logging=self.logging)(self.hidden1) self.z_log_std = GraphConvolution(input_dim=FLAGS.hidden1, output_dim=FLAGS.hidden2, adj=self.adj, act=lambda x: x, dropout=self.dropout, logging=self.logging)(self.hidden1) self.z = self.z_mean + tf.random_normal([self.n_samples, FLAGS.hidden2]) * tf.exp(self.z_log_std) self.reconstructions = InnerProductDecoder(input_dim=FLAGS.hidden2, act=lambda x: x, logging=self.logging)(self.z)
4,738
39.504274
105
py
gae
gae-master/gae/layers.py
from gae.initializations import * import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS # global unique layer ID dictionary for layer name assignment _LAYER_UIDS = {} def get_layer_uid(layer_name=''): """Helper function, assigns unique layer IDs """ if layer_name not in _LAYER_UIDS: _LAYER_UIDS[layer_name] = 1 return 1 else: _LAYER_UIDS[layer_name] += 1 return _LAYER_UIDS[layer_name] def dropout_sparse(x, keep_prob, num_nonzero_elems): """Dropout for sparse tensors. Currently fails for very large sparse tensors (>1M elements) """ noise_shape = [num_nonzero_elems] random_tensor = keep_prob random_tensor += tf.random_uniform(noise_shape) dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool) pre_out = tf.sparse_retain(x, dropout_mask) return pre_out * (1./keep_prob) class Layer(object): """Base layer class. Defines basic API for all layer objects. # Properties name: String, defines the variable scope of the layer. # Methods _call(inputs): Defines computation graph of layer (i.e. takes input, returns output) __call__(inputs): Wrapper for _call() """ def __init__(self, **kwargs): allowed_kwargs = {'name', 'logging'} for kwarg in kwargs.keys(): assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg name = kwargs.get('name') if not name: layer = self.__class__.__name__.lower() name = layer + '_' + str(get_layer_uid(layer)) self.name = name self.vars = {} logging = kwargs.get('logging', False) self.logging = logging self.issparse = False def _call(self, inputs): return inputs def __call__(self, inputs): with tf.name_scope(self.name): outputs = self._call(inputs) return outputs class GraphConvolution(Layer): """Basic graph convolution layer for undirected graph without edge labels.""" def __init__(self, input_dim, output_dim, adj, dropout=0., act=tf.nn.relu, **kwargs): super(GraphConvolution, self).__init__(**kwargs) with tf.variable_scope(self.name + '_vars'): self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name="weights") self.dropout = dropout self.adj = adj self.act = act def _call(self, inputs): x = inputs x = tf.nn.dropout(x, 1-self.dropout) x = tf.matmul(x, self.vars['weights']) x = tf.sparse_tensor_dense_matmul(self.adj, x) outputs = self.act(x) return outputs class GraphConvolutionSparse(Layer): """Graph convolution layer for sparse inputs.""" def __init__(self, input_dim, output_dim, adj, features_nonzero, dropout=0., act=tf.nn.relu, **kwargs): super(GraphConvolutionSparse, self).__init__(**kwargs) with tf.variable_scope(self.name + '_vars'): self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name="weights") self.dropout = dropout self.adj = adj self.act = act self.issparse = True self.features_nonzero = features_nonzero def _call(self, inputs): x = inputs x = dropout_sparse(x, 1-self.dropout, self.features_nonzero) x = tf.sparse_tensor_dense_matmul(x, self.vars['weights']) x = tf.sparse_tensor_dense_matmul(self.adj, x) outputs = self.act(x) return outputs class InnerProductDecoder(Layer): """Decoder model layer for link prediction.""" def __init__(self, input_dim, dropout=0., act=tf.nn.sigmoid, **kwargs): super(InnerProductDecoder, self).__init__(**kwargs) self.dropout = dropout self.act = act def _call(self, inputs): inputs = tf.nn.dropout(inputs, 1-self.dropout) x = tf.transpose(inputs) x = tf.matmul(inputs, x) x = tf.reshape(x, [-1]) outputs = self.act(x) return outputs
4,046
32.446281
107
py
gae
gae-master/gae/__init__.py
from __future__ import print_function from __future__ import division
70
22.666667
37
py
gae
gae-master/gae/train.py
from __future__ import division from __future__ import print_function import time import os # Train on CPU (hide GPU) due to memory constraints os.environ['CUDA_VISIBLE_DEVICES'] = "" import tensorflow as tf import numpy as np import scipy.sparse as sp from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score from gae.optimizer import OptimizerAE, OptimizerVAE from gae.input_data import load_data from gae.model import GCNModelAE, GCNModelVAE from gae.preprocessing import preprocess_graph, construct_feed_dict, sparse_to_tuple, mask_test_edges # Settings flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.') flags.DEFINE_integer('epochs', 200, 'Number of epochs to train.') flags.DEFINE_integer('hidden1', 32, 'Number of units in hidden layer 1.') flags.DEFINE_integer('hidden2', 16, 'Number of units in hidden layer 2.') flags.DEFINE_float('weight_decay', 0., 'Weight for L2 loss on embedding matrix.') flags.DEFINE_float('dropout', 0., 'Dropout rate (1 - keep probability).') flags.DEFINE_string('model', 'gcn_ae', 'Model string.') flags.DEFINE_string('dataset', 'cora', 'Dataset string.') flags.DEFINE_integer('features', 1, 'Whether to use features (1) or not (0).') model_str = FLAGS.model dataset_str = FLAGS.dataset # Load data adj, features = load_data(dataset_str) # Store original adjacency matrix (without diagonal entries) for later adj_orig = adj adj_orig = adj_orig - sp.dia_matrix((adj_orig.diagonal()[np.newaxis, :], [0]), shape=adj_orig.shape) adj_orig.eliminate_zeros() adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false = mask_test_edges(adj) adj = adj_train if FLAGS.features == 0: features = sp.identity(features.shape[0]) # featureless # Some preprocessing adj_norm = preprocess_graph(adj) # Define placeholders placeholders = { 'features': tf.sparse_placeholder(tf.float32), 'adj': tf.sparse_placeholder(tf.float32), 'adj_orig': tf.sparse_placeholder(tf.float32), 'dropout': tf.placeholder_with_default(0., shape=()) } num_nodes = adj.shape[0] features = sparse_to_tuple(features.tocoo()) num_features = features[2][1] features_nonzero = features[1].shape[0] # Create model model = None if model_str == 'gcn_ae': model = GCNModelAE(placeholders, num_features, features_nonzero) elif model_str == 'gcn_vae': model = GCNModelVAE(placeholders, num_features, num_nodes, features_nonzero) pos_weight = float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum() norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2) # Optimizer with tf.name_scope('optimizer'): if model_str == 'gcn_ae': opt = OptimizerAE(preds=model.reconstructions, labels=tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'], validate_indices=False), [-1]), pos_weight=pos_weight, norm=norm) elif model_str == 'gcn_vae': opt = OptimizerVAE(preds=model.reconstructions, labels=tf.reshape(tf.sparse_tensor_to_dense(placeholders['adj_orig'], validate_indices=False), [-1]), model=model, num_nodes=num_nodes, pos_weight=pos_weight, norm=norm) # Initialize session sess = tf.Session() sess.run(tf.global_variables_initializer()) cost_val = [] acc_val = [] def get_roc_score(edges_pos, edges_neg, emb=None): if emb is None: feed_dict.update({placeholders['dropout']: 0}) emb = sess.run(model.z_mean, feed_dict=feed_dict) def sigmoid(x): return 1 / (1 + np.exp(-x)) # Predict on test set of edges adj_rec = np.dot(emb, emb.T) preds = [] pos = [] for e in edges_pos: preds.append(sigmoid(adj_rec[e[0], e[1]])) pos.append(adj_orig[e[0], e[1]]) preds_neg = [] neg = [] for e in edges_neg: preds_neg.append(sigmoid(adj_rec[e[0], e[1]])) neg.append(adj_orig[e[0], e[1]]) preds_all = np.hstack([preds, preds_neg]) labels_all = np.hstack([np.ones(len(preds)), np.zeros(len(preds_neg))]) roc_score = roc_auc_score(labels_all, preds_all) ap_score = average_precision_score(labels_all, preds_all) return roc_score, ap_score cost_val = [] acc_val = [] val_roc_score = [] adj_label = adj_train + sp.eye(adj_train.shape[0]) adj_label = sparse_to_tuple(adj_label) # Train model for epoch in range(FLAGS.epochs): t = time.time() # Construct feed dictionary feed_dict = construct_feed_dict(adj_norm, adj_label, features, placeholders) feed_dict.update({placeholders['dropout']: FLAGS.dropout}) # Run single weight update outs = sess.run([opt.opt_op, opt.cost, opt.accuracy], feed_dict=feed_dict) # Compute average loss avg_cost = outs[1] avg_accuracy = outs[2] roc_curr, ap_curr = get_roc_score(val_edges, val_edges_false) val_roc_score.append(roc_curr) print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(avg_cost), "train_acc=", "{:.5f}".format(avg_accuracy), "val_roc=", "{:.5f}".format(val_roc_score[-1]), "val_ap=", "{:.5f}".format(ap_curr), "time=", "{:.5f}".format(time.time() - t)) print("Optimization Finished!") roc_score, ap_score = get_roc_score(test_edges, test_edges_false) print('Test ROC score: ' + str(roc_score)) print('Test AP score: ' + str(ap_score))
5,635
32.547619
103
py
gae
gae-master/gae/optimizer.py
import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS class OptimizerAE(object): def __init__(self, preds, labels, pos_weight, norm): preds_sub = preds labels_sub = labels self.cost = norm * tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(logits=preds_sub, targets=labels_sub, pos_weight=pos_weight)) self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) # Adam Optimizer self.opt_op = self.optimizer.minimize(self.cost) self.grads_vars = self.optimizer.compute_gradients(self.cost) self.correct_prediction = tf.equal(tf.cast(tf.greater_equal(tf.sigmoid(preds_sub), 0.5), tf.int32), tf.cast(labels_sub, tf.int32)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) class OptimizerVAE(object): def __init__(self, preds, labels, model, num_nodes, pos_weight, norm): preds_sub = preds labels_sub = labels self.cost = norm * tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(logits=preds_sub, targets=labels_sub, pos_weight=pos_weight)) self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) # Adam Optimizer # Latent loss self.log_lik = self.cost self.kl = (0.5 / num_nodes) * tf.reduce_mean(tf.reduce_sum(1 + 2 * model.z_log_std - tf.square(model.z_mean) - tf.square(tf.exp(model.z_log_std)), 1)) self.cost -= self.kl self.opt_op = self.optimizer.minimize(self.cost) self.grads_vars = self.optimizer.compute_gradients(self.cost) self.correct_prediction = tf.equal(tf.cast(tf.greater_equal(tf.sigmoid(preds_sub), 0.5), tf.int32), tf.cast(labels_sub, tf.int32)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))
1,962
44.651163
144
py
malfoy
malfoy-master/setup.py
from setuptools import setup, find_packages setup( name='v2x', version='0.1', author='j80055002', packages=find_packages(), install_requires=[ 'numpy', 'mesa' ] )
203
16
43
py
malfoy
malfoy-master/run.py
# -*- coding: utf-8 -*- from v2x.config.config import (PSTATS_FILE,LOGS_DIR, RESOURCE_SITE_PARAMS as rsp) from v2x.utils.common_utils import openFiles,closeFiles from v2x.solutions.v2x import V2XModel from v2x.utils.graphic_utils import Graphics import cProfile import pstats import os,sys,re import numpy as np import warnings warnings.filterwarnings("ignore") def runProfiler(): cProfile.run('runStandAloneModel()', PSTATS_FILE) p = pstats.Stats(PSTATS_FILE) p.strip_dirs().sort_stats('cumulative').print_stats(30) def runStandAloneModel(nrSites=2,train=True,evaluation=False, loadModel=False,steps=8000,rebid=True,curious=False, interval=None,cumstep=0,endOfGame=5000, sumoDataOffset=0,ca=True): nrRsu = 1 if interval is not None: filedict = openFiles(additional=[interval,nrSites,str(train)], trainable=(train and not evaluation)) else: filedict = openFiles(additional=[nrSites,str(train)], trainable=(train and not evaluation)) mdl = V2XModel(filedict,nrSites=nrSites,nrRsu=nrRsu,train=train, evaluation=evaluation,loadModel=loadModel,rebid=rebid, curious=curious,extRewardInterval=interval, cumstep=cumstep,endOfGame=endOfGame, sumoDataOffset=sumoDataOffset,ca=ca) iterations = len(rsp.resourceCapa) chpt = list(np.arange(start=steps/iterations,stop=steps, step=steps/iterations,dtype=int))[0:iterations-1] for i in range(steps): mdl.step() if i in chpt: actor_learning_rate = [] for v in mdl.vehicles.values(): actor_learning_rate.append(v.priceMdl.actor_learning_rate) print('actor learning rate: {},{}.'.format( min(actor_learning_rate),max(actor_learning_rate))) closeFiles(filedict) del mdl.trace.context return mdl #%% if __name__ == '__main__': train = True nrSites = 2 evaluation = False loadModel = True steps = 200000 sumoDataOffset = 50000 path = LOGS_DIR curious = True rebid = True interval = 1 outputThres = 1000 repetition = 1 ca = True # if true: run attention model (credit assignment) if sys.argv[1]=='draw': path = LOGS_DIR try: path = os.path.join(path,sys.argv[2]) except: pass graph = Graphics(path) res = graph.drawPerformance(drawPerformanceOnly=True, target='totalSuccessRatio',textOutput=True, outputThres=outputThres,endOfGame=steps, legends='best',stepRange=(2000,200000), decimals=2,yaxisTick='right',orderHue='by algorithm', density=1,ci='sd') else: if 'rial' in sys.argv[1]: train = False if 'eval' in sys.argv[1]: evaluation = True if 'sameInput' in sys.argv[1]: sumoDataOffset += steps if 'rebid' not in sys.argv[1]: rebid = False if 'noAttention' in sys.argv[1]: ca = False try: if 'interval' in sys.argv[1]: location = re.search('=',sys.argv[1]).span()[1] try: end = location + re.search('_',sys.argv[1][location:]).span()[1] interval = int(sys.argv[1][location:end-1]) except: interval = int(sys.argv[1][location:]) except: pass try: path = os.path.join(path,sys.argv[3]) except: pass if interval==1: curious = False for i in range(repetition): runStandAloneModel(nrSites=nrSites, train=train,evaluation=evaluation, loadModel=loadModel,steps=steps,rebid=rebid, curious=curious,interval=interval,cumstep=i*steps, endOfGame=steps,sumoDataOffset=sumoDataOffset,ca=ca)
4,206
34.957265
84
py
malfoy
malfoy-master/output.py
# -*- coding: utf-8 -*- from v2x.config.config import (LOGS_DIR, PRICE_MODEL_PARAMS as pmp, CURIOUS_MODEL_PARAMS as cmp) from v2x.utils.graphic_utils import Graphics from v2x.utils.name_utils import ColumnHead as ch import numpy as np import pandas as pd pd.set_option('display.max_columns', None) from scipy.stats import t as tDistr import re,sys,os import warnings warnings.filterwarnings("ignore") #LEARNED = c.LEARNED #RANDOM = c.RANDOM def _changeColumnName(data,oldName,newName): cols = list(data.columns) if oldName in cols: cols[cols.index(oldName)] = newName data.columns = cols return data def outputBackOffCharts(subdir=['25-25-60-rebid=1'],minStaging=1, outputGraph=True,path=LOGS_DIR,size=(5,4)): name='finishedBids' target = ch.BIDPRICE folder = subdir[0] capa = int(folder[0:re.search('-',folder).span()[0]]) * 2 rebid = folder[-7:] data = pd.DataFrame() for filepath in subdir: path = os.path.join(path,filepath) graph = Graphics(path) data0 = graph._collectData(name) if len(data)==0: data = data0 else: data = pd.concat([data,data0],axis=0) if len(data)==0: return None col = [ch.STEP,ch.TOTALACTIVEBIDS,ch.SORTIDX,ch.BATCHCREATE,ch.CREATETIME] for c in col: try: data[c] = data[c].astype(int) except: continue col = [target,ch.BIDPAYMENT,ch.CARBUDGET,ch.BIDVALUE] for c in col: try: data[c] = data[c].astype(float) except: continue nrSites = '2sites' df = data.loc[data[ch.NRSITES]==nrSites] df[ch.VEHICLE] = df[ch.BIDID].apply(lambda x: x[0:re.search('_',x).span()[0]]) maxStep = max(df[ch.STEP]) df1 = df[df[ch.STEP]>maxStep-5000] # average staging time df1[ch.BACKOFFTIME] = df1.apply(lambda row: row[ch.CREATETIME]-row[ch.BATCHCREATE],axis=1) df1 = df1[df1[ch.BACKOFFTIME]> minStaging] try: df1[ch.ADMITTED] = np.where(df1[ch.DECISION]=='admitted', 'admitted','failed') except: df1[ch.ADMITTED] = np.where(df1[ch.SUCCESS]==1,'admitted','failed') ttl = df1.groupby([ch.VEHICLE,ch.BIDQOS,ch.CARBUDGET],as_index=False)\ .agg({ch.BIDID:'size'}).rename(columns={ch.BIDID:ch.TOTALBYQOS}) df1 = pd.merge(df1,ttl,on=[ch.VEHICLE,ch.BIDQOS,ch.CARBUDGET],copy=False) df2 = df1[[ch.VEHICLE,ch.TRAINED,ch.BIDQOS,ch.BIDID,ch.BIDPRICE, ch.BACKOFFTIME,ch.TOTALBYQOS,ch.CARBUDGET]].groupby( [ch.VEHICLE,ch.TRAINED,ch.BIDQOS,ch.CARBUDGET], as_index=False).agg({ch.BIDID:'size',ch.BIDPRICE:'mean', ch.BACKOFFTIME:'mean',ch.TOTALBYQOS:'mean'}) df2 = _changeColumnName(df2,ch.BIDQOS,ch.DEADLINE) df2[ch.DEADLINE] = np.where(df2[ch.DEADLINE]=='low quality', 'long deadline','short deadline') df2 = _changeColumnName(df2,ch.CARBUDGET,ch.BUDGET) df2[ch.BUDGET] = np.where(df2[ch.BUDGET]==min(df2[ch.BUDGET]), 'low budget','high budget') df2[ch.CAPACITY] = capa df2.sort_values(by=[ch.DEADLINE,ch.BUDGET,ch.TRAINED,ch.BIDPRICE], ascending=[True,True,True,True],inplace=True) df2_1 = df2[df2[ch.TRAINED]==ch.LEARNED] if outputGraph: graph._drawBoxplot(df=df2_1,x=ch.DEADLINE,y=ch.BACKOFFTIME, title='backoff_'+'capa='+str(capa)+'_'+rebid+'_budget', hue=ch.BUDGET,legends=1,ylabel=None, legendFontsize=8,figsize=size, myPalette = {'low budget':'C1','high budget':'C0'}) df2_1[ch.PRICERANGE] = np.where( df2_1[ch.BIDPRICE]>np.mean(df2_1[ch.BIDPRICE]), 'high price','low price') if outputGraph: graph._drawBoxplot(df=df2_1,x=ch.DEADLINE,y=ch.BACKOFFTIME, title='backoff_'+'capa='+str(capa)+'_'+rebid+'_priceRange', hue=ch.PRICERANGE,legends=None,ylabel=None, legendFontsize=12,figsize=size, myPalette = {'low price':'C1','high price':'C0'}) return df2_1 def getServiceLevelData(filename='servicelevel_rebid_1.csv', stepRange=(300,7999),decimals=2,path=LOGS_DIR): filepath = os.path.join(path,filename) # newname = ch.MP try: servicedata = pd.read_csv(filepath,sep=';') # servicedata = _changeColumnName(servicedata,oldname,newname) # servicedata[ch.TYPE] = servicedata.apply(lambda row: # row[ch.ALGORITHMTYPE]+','+newname+'='+str(row[ch.MP]),axis=1) return servicedata except: pass folders = [] rebids = ['1','5'] for i in np.arange(25,120,step=5): for rebid in rebids: folders.append( '-'.join([str(int(i)),str(int(i)),'60','rebid='])+rebid) servicedata = pd.DataFrame() for folder in folders: path0 = os.path.join(path,folder) graph = Graphics(path0) idx = ['_'] + [str(int(x)) for x in list(range(1,10))] for j in idx: name = 'performance' + j try: df0 = graph._getPerformanceData(name=name,stepRange=stepRange, sites=['2sites']) except: print(folder) print(j) if df0 is None: continue values = graph._outputFailureComparison(data=df0,textOutput=False, graphicOutput=False,stepRange=stepRange,legends=2) df = pd.DataFrame(columns=[ch.CAPACITY,ch.STANDARD,ch.CLOUD, ch.SUCCESSRATE,ch.ALGORITHMTYPE,ch.MP, ch.TYPE,ch.SELECTED,ch.VERSION]) listOfValues = [np.round(x,decimals=decimals) for x in list(values.iloc[0])] df[ch.SUCCESSRATE] = listOfValues df[ch.ALGORITHMTYPE] = [ch.RANDOM,ch.LEARNED] df[ch.MP] = int(folder[-1]) df[ch.TYPE] = df[ch.ALGORITHMTYPE].apply( lambda x:x+','+ch.MP+'='+folder[-1]) capa = int(folder[0:re.search('-',folder).span()[0]]) df[ch.CAPACITY] = capa * 2 df[ch.STANDARD] = capa df[ch.CLOUD] = capa df[ch.SELECTED] = 'Y' df[ch.VERSION] = 'v2' df = df.loc[~df[ch.SUCCESSRATE].isnull()] if len(servicedata)==0: servicedata = df else: servicedata = pd.concat([servicedata,df],axis=0) servicedata[ch.FAILEDRATE] = 1 - servicedata[ch.SUCCESSRATE] servicedata.to_csv(filepath,sep=';',index=None) return servicedata def outputServiceLevel(filename='servicelevel_rebid.csv', separate=None,size=(8,4),ci=None,vertical=True, legendFontsize=None,tickFontsize=None,path=LOGS_DIR): graph = Graphics(path) dataAll = pd.read_csv(os.path.join(path,filename),sep=';') dataAll = dataAll[dataAll[ch.SELECTED]=='Y'] dataAll = _changeColumnName(dataAll,ch.MAXREBIDOLD,ch.MP) if separate is None: hue = ch.TYPE data = dataAll[[ch.CAPACITY,ch.SUCCESSRATE,hue]] data1 = dataAll[[ch.CAPACITY,ch.FAILEDRATE,hue]] else: hue = ch.TYPE if separate==ch.MAXREBIDOLD: separate = ch.MP data = dataAll[[ch.CAPACITY,ch.SUCCESSRATE,separate,hue]] data1 = dataAll[[ch.CAPACITY,ch.FAILEDRATE,separate,hue]] if ci is None: data = data.groupby([ch.CAPACITY,separate,hue], as_index=False).mean().round(3) data1 = data1.groupby([ch.CAPACITY,separate,hue], as_index=False).mean().round(3) graph._drawLineplot(data,x=ch.CAPACITY,y=ch.SUCCESSRATE, title='Success rate with different resource capacity', hue=hue,style=hue,order='sorted',legends=4, legendFontsize=legendFontsize,tickFontsize=tickFontsize, size=size,separate=separate,ci=ci, vertical=vertical)#,showTable=True) graph._drawLineplot(data1,x=ch.CAPACITY,y=ch.FAILEDRATE, title='Failure rate with different resource capacity', hue=hue,style=hue,order='sorted',legends='best', legendFontsize=legendFontsize,tickFontsize=tickFontsize, size=size,separate=separate,ci=ci, vertical=vertical,yscale='log',yaxisTick='right')#,showTable=True) def outputUtilizationOverTimeLowResCapa(path=LOGS_DIR,nrSites='2sites', site='site0',service='service2', legends=None,stepRange=None,avgTime=1, avgMax=False,ci=None): if path is None: path = os.path.join(path,'logs_multipleService',nrSites) graph = Graphics(path) data = graph._collectData('performance') data = data.loc[data[ch.NRSITES]==nrSites] if stepRange is None: stepRange = (min(data[ch.STEP]),max(data[ch.STEP])) data = data.loc[(data[ch.STEP]<=stepRange[1]) & (data[ch.STEP]>=stepRange[0])] if avgTime>1: data[ch.STEP] = data[ch.STEP].apply(lambda x: int(x/avgTime)*avgTime) data[ch.TRAINED] = np.where(data[ch.TRAINED]==ch.RANDOM,ch.RANDOM, ch.LEARNED) data[ch.MODELTYPE] = np.where(data[ch.MODELTYPE]=='ConvCritic_ConvActor', 'CNN-HW','MLP') data[ch.MODELTYPE] = np.where(data[ch.TRAINED]==ch.RANDOM, '',data[ch.MODELTYPE]) data = data[data[ch.MODELTYPE]!='MLP'] pattern = re.compile('cloud|standard|slow') sitetype = pattern.findall(data[ch.SITETYPE].iloc[0]) sitetype = dict([('site'+str(i),x) for i,x in enumerate(sitetype)]) utilized = graph._parseColumn(data,ch.UTILIZATION,sitetype) df = pd.concat([data,utilized],axis=1) analyzeCols = [x for x in utilized.columns if site in x and service in x] try: df[ch.CAT] = df[ch.TRAINED]+' '+df[ch.INTERVAL] except: df[ch.CAT] = df[ch.TRAINED] hue = ch.CAT hue_order = list(set(df[ch.CAT])) hue_order.sort(reverse=False) if avgMax and ci is None: charttype = 'max' else: charttype = 'mean' for t in analyzeCols: if ci is None: if avgMax: tmp = df[[ch.STEP,hue,t]].groupby( [ch.STEP,hue],as_index=False).max() else: tmp = df[[ch.STEP,hue,t]].groupby( [ch.STEP,hue],as_index=False).mean() else: tmp = df[[ch.STEP,hue,t]] tmp.columns = [ch.STEP,hue,ch.UTILIZATION] graph._drawLineplot(df=tmp,x=ch.STEP,y=ch.UTILIZATION, title=t+'_'+charttype, style=hue,hue=hue, hue_order=hue_order,legends=legends, tickFontsize=12,ci=ci,ylim=(0,1)) def outputNrRebidData(subfolder,resource,name,path=LOGS_DIR): path = os.path.join(path,subfolder) graph = Graphics(path) data = graph._collectData(name) if data.shape[0]<=1: return col = [ch.STEP,ch.BATCHCREATE,ch.CREATETIME,ch.FINISHTIME,ch.NRREBID] for c in col: data[c] = data[c].astype(int) col = [ch.BIDPRICE,ch.BIDPAYMENT,ch.CARBUDGET] for c in col: data[c] = data[c].astype(float) df = data.copy() df[ch.VEHICLE] = df[ch.BIDID].apply(lambda x: x[0:re.search('_',x).span()[0]]) maxStep = max(df[ch.STEP]) df1 = df[df[ch.STEP]>maxStep-5000] # average staging time df1[ch.BACKOFFTIME] = df1.apply(lambda row: row[ch.CREATETIME]-row[ch.BATCHCREATE],axis=1) # correlation admission rate vs. price vs. staging time, by qos df1[ch.ADMITTED] = np.where(df1[ch.STATUS]=='finished',True,False) df1 = _changeColumnName(df1,ch.NRSITES,ch.MAXREBIDOLD2) df1[ch.MAXREBIDOLD2] = df1[ch.MAXREBIDOLD2].apply(lambda x: int(x[0])) df1[ch.TRAINED] = np.where(df1[ch.TRAINED]==ch.RANDOM,ch.RANDOM, df1[ch.TRAINED]) ttl = df1.groupby([ch.MAXREBIDOLD2,ch.TRAINED,ch.VEHICLE,ch.BIDQOS, ch.CARBUDGET],as_index=False)\ .agg({ch.BIDID:'size'}).rename(columns={ch.BIDID:ch.TOTALBYQOS}) df1 = pd.merge(df1,ttl,on=[ch.MAXREBIDOLD2,ch.TRAINED,ch.VEHICLE,ch.BIDQOS, ch.CARBUDGET],copy=False) df2 = df1[[ch.MAXREBIDOLD2,ch.TRAINED,ch.VEHICLE,ch.ADMITTED,ch.BIDQOS, ch.BIDID,ch.BIDPRICE,ch.BACKOFFTIME,ch.TOTALBYQOS, ch.CARBUDGET,ch.NRREBID]].groupby([ch.MAXREBIDOLD2,ch.TRAINED, ch.VEHICLE,ch.ADMITTED,ch.BIDQOS,ch.CARBUDGET], as_index=False).agg({ch.BIDID:'size',ch.BIDPRICE:'mean', ch.BACKOFFTIME:'mean',ch.TOTALBYQOS:'mean',ch.NRREBID:'mean'}) df2.sort_values(ch.TRAINED,ascending=False,inplace=True) df2[ch.CAPACITY] = resource return df2 def outputNrRebidComparisonBoxplot(subfolder='25-25-60',path=LOGS_DIR): name = 'finishedBids' resource = int(subfolder[0:2]) * 2 df2 = outputNrRebidData(subfolder=subfolder,resource=resource,name=name, path=path) title = (name+'_distr-nrRebid_all_byAlgorithm') graph = Graphics(path) graph._drawBoxplot(df=df2,x=ch.MAXREBIDOLD2,y=ch.NRREBID,title=title, hue=ch.TRAINED,ylabel='rebidding overhead',legends=2, legendFontsize=8,figsize=(2,4)) def _drawHistLine(path,data_learned,data_random,note, col=None,xlim=(0,1),loc=4,size=(10,4)): if col is None: vehicleSuccess = data_learned.groupby(ch.VEHICLE).agg( {ch.BIDID:'size',ch.SUCCESS:'sum'}) tmp = data_random.groupby(ch.VEHICLE).agg( {ch.BIDID:'size',ch.SUCCESS:'sum'}) else: vehicleSuccess = data_learned.groupby([ch.VEHICLE,col], as_index=False).agg({ch.BIDID:'size',ch.SUCCESS:'sum'}) tmp = data_random.groupby([ch.VEHICLE,col],as_index=False).agg( {ch.BIDID:'size',ch.SUCCESS:'sum'}) vehicleSuccess[ch.SUCCESSRATE] = (vehicleSuccess[ch.SUCCESS] / vehicleSuccess[ch.BIDID]) vehicleSuccess[ch.TRAINED] = ch.LEARNED tmp[ch.SUCCESSRATE] = tmp[ch.SUCCESS] / tmp[ch.BIDID] tmp[ch.TRAINED] = ch.RANDOM vehicleSuccess = pd.concat([vehicleSuccess,tmp]) style = {ch.LEARNED:'-',ch.RANDOM:'--'} graph = Graphics(path) graph._drawCdfFromKde(df=vehicleSuccess,hue=ch.TRAINED, target=ch.SUCCESSRATE,style=style, title='allocation_'+note+'_vehicleSuccessRateCdf', xlim=xlim,col=col,loc=loc,size=size) vehicleFailure = vehicleSuccess vehicleFailure[ch.FAILEDRATE] = 1 - vehicleFailure[ch.SUCCESSRATE] graph._drawCdfFromKde(df=vehicleFailure,hue=ch.TRAINED, target=ch.FAILEDRATE,style=style, title='allocation_'+note+'_vehicleFailureRateCdf', xlim=(1-xlim[1],1-xlim[0]),col=col,loc=loc,size=size) def outputIndividualSuccessRateWithHighResCapa(path=LOGS_DIR, folder='35-35-60-rebid=1',size=(10,4)): path = os.path.join(path,folder) graph = Graphics(path) name = 'finishedBids' data = graph._collectData(name) data[ch.MODELTYPE] = 'CNN-HW' data = data[data[ch.STEP]>7000] col = [ch.STEP,ch.SUCCESS,ch.BATCHCREATE,ch.CREATETIME,ch.FINISHTIME, ch.NRREBID] for c in col: try: data[c] = data[c].astype(int) except: pass target = ch.BIDPRICE col = [target,ch.BIDPAYMENT,ch.CARBUDGET] for c in col: data[c] = data[c].astype(float) data[ch.VEHICLE] = data[ch.BIDID].apply( lambda x:x[0:re.search('_',x).span()[0]]) data[ch.CARBUDGET] = np.where(data[ch.CARBUDGET]<2000,'low','high') data = _changeColumnName(data,ch.CARBUDGET,ch.BUDGET) data_learned = data[data[ch.TRAINED]==ch.LEARNED] data_random = data[data[ch.TRAINED]==ch.RANDOM] _drawHistLine(path,data_learned,data_random, 'highResCapa_budgets',col=ch.BUDGET,xlim=(0.6,1),loc=4, size=size) def _outputUtilizationMeanAndStdHighResCapa_perCapa(path=LOGS_DIR, folder='35-35-60-rebid=1',capa=35): path = os.path.join(path,folder) graph = Graphics(path) name = 'performance' data = graph._collectData(name) if len(data)==0: return None,None data[ch.TRAINED] = np.where(data[ch.TRAINED]==ch.RANDOM, ch.RANDOM,data[ch.TRAINED]) pattern = re.compile('cloud|standard|slow') sitetype = pattern.findall(data[ch.SITETYPE].iloc[0]) sitetype = dict([('site'+str(i),x) for i,x in enumerate(sitetype)]) utilized = graph._parseColumn(data,ch.UTILIZATION,sitetype) occupied = graph._parseColumn(data,ch.OCCUPIED,sitetype) maxAmount = graph._parseColumn(data,ch.MAXAMOUNT,sitetype) data = pd.concat([data,utilized,occupied,maxAmount],axis=1) df0 = data[data[ch.STEP]>5000] df0.fillna(0,inplace=True) targets = [] for s in sitetype.keys(): targets.append(s) occupiedColn = [x for x in df0.columns if ch.OCCUPIED in x and s in x and 'resource' not in x] maxAmountColn = [x for x in df0.columns if ch.MAXAMOUNT in x and s in x and 'resource' not in x] df0[s] = df0.apply(lambda row: sum(row[occupiedColn])/sum(row[maxAmountColn]),axis=1) colname = 'allsites' targets.append(colname) occupiedColn = list(occupied.columns) maxAmountColn = [x for x in maxAmount.columns if 'resource' not in x] df0[colname] = df0.apply(lambda row: sum(row[occupiedColn])/sum(row[maxAmountColn]),axis=1) def myFunc(data): results = [] colnames = [] for c in targets: results += [np.mean(data[c]),np.std(data[c])] colnames += [c+'_mean', c+'_std'] return pd.Series(data=results,index=colnames) tmp = df0[[ch.TRAINED]+targets].groupby(ch.TRAINED).apply(myFunc) tmp.sort_index(inplace=True,ascending=False) tmp = tmp.transpose() tmp.reset_index(inplace=True) tmp.columns = [ch.SITE,ch.LEARNED,ch.RANDOM] tmp[ch.REBID] = int(path[-1]) tmp[ch.CAPACITY] = capa df0[ch.REBID] = int(path[-1]) df0[ch.CAPACITY] = capa * 2 return df0,tmp def outputUtilizationMeanAndStdHighResCapa(boxchart=None,path=LOGS_DIR, rebid='5',target='site0'): if boxchart is None: folders = [] for i in np.arange(25,120,step=5): folders.append( '-'.join([str(int(i)),str(int(i)),'60','rebid='])+rebid) boxchart = pd.DataFrame() for folder in folders: capa = int(folder[0:re.search('-',folder).span()[0]]) df0,tmp = _outputUtilizationMeanAndStdHighResCapa_perCapa( path=path,folder=folder,capa=capa) if df0 is None: continue if len(boxchart)==0: boxchart = df0 else: boxchart = pd.concat([boxchart,df0],axis=0) # boxchart = _changeColumnName(boxchart,'resource',ch.CAPACITY) graph = Graphics(path) graph._drawBoxplot(df=boxchart,x=ch.CAPACITY, y=target,ylabel='utilization',hue=ch.TRAINED, title='utilization_boxplot_'+target+'_rebid='+rebid, legendFontsize=12,figsize=(6,4),legends=1) return boxchart def outputReliability(path=LOGS_DIR,rebid=['1','5'],stepRange=(0,8000)): name = 'finishedBids' folders = [] capas = [] for r in rebid: for i in np.arange(25,120,step=5): folders.append( '-'.join([str(int(i)),str(int(i)),'60','rebid='])+r) capas.append((int(i),r)) colnames = [ch.TRAINED,ch.CAPACITY,ch.MP,ch.ADMITTED,ch.RELIABILITY] result = [] for i,folder in enumerate(folders): path0 = os.path.join(path,folder) graph = Graphics(path0) data = graph._collectData(name) if len(data)==0: continue data = data[(data[ch.STEP]>=stepRange[0]) & (data[ch.STEP]<stepRange[1])] for alg in set(data[ch.TRAINED]): admitted = data[(data[ch.STATUS]=='finished') & (data[ch.TRAINED]==alg)] successful = admitted[admitted[ch.SUCCESS]==1] reliability = successful.shape[0] / admitted.shape[0] result.append(dict(zip(colnames,[alg,capas[i][0],capas[i][1], admitted.shape[0],reliability]))) return pd.DataFrame(result) def outputRebidBoxplotMeanAndStd(boxchart=None,path=LOGS_DIR,rebid='5'): if boxchart is None: name = 'finishedBids' folders = [] for i in np.arange(25,120,step=5): folders.append( '-'.join([str(int(i)),str(int(i)),'60','rebid='])+rebid) boxchart = pd.DataFrame() for folder in folders: resource = int(folder[0:re.search('-',folder).span()[0]]) * 2 df0 = outputNrRebidData(subfolder=folder,resource=resource, name=name,path=path) if df0 is None: continue if len(boxchart)==0: boxchart = df0 else: boxchart = pd.concat([boxchart,df0],axis=0) graph = Graphics(path) graph._drawBoxplot(df=boxchart,x=ch.CAPACITY,y=ch.NRREBID, ylabel='rebidding overhead',hue=ch.TRAINED, title='rebid='+rebid+'_boxplot', legendFontsize=8,figsize=(6,4),legends=None) boxchart[ch.MAXREBIDOLD2] = rebid return boxchart def getInterval(tbl,targetCol,rebidCol,algorithmCol, capaCol=ch.CAPACITY): interval = pd.DataFrame() tbl[rebidCol] = tbl[rebidCol].apply(str) for rebid in ['1','5']: for capa in set(tbl[capaCol]): x1 = list(tbl[(tbl[rebidCol]==rebid) & (tbl[capaCol]==capa) & (tbl[algorithmCol]==ch.LEARNED)][targetCol]) x2 = list(tbl[(tbl[rebidCol]==rebid) & (tbl[capaCol]==capa) & (tbl[algorithmCol]==ch.RANDOM)][targetCol]) if len(x1)==0: continue meanDiff,interval_ttest,interval_welch = welch_ttest(x1,x2) tmp = pd.DataFrame( [[rebid,capa,meanDiff,interval_ttest,interval_welch]], columns=[ch.MP,ch.CAPACITY,'mean difference', 'confidence interval ttest','confidence interval welch']) if len(interval)==0: interval = tmp else: interval = pd.concat([interval,tmp],axis=0) interval.sort_values(by=[ch.MP,ch.CAPACITY],inplace=True) return interval def outputComparisonTbl(tbl,targetCol,rebidCol=ch.MP, capaCol=ch.CAPACITY,algorithmCol=ch.TRAINED): tbl_1 = tbl[[algorithmCol,capaCol,targetCol]].groupby( [algorithmCol,capaCol],as_index=False).mean() tbl_2 = tbl_1.pivot_table(values=targetCol,index=capaCol, columns=algorithmCol) tbl_2[ch.DIFFERENCE] = (tbl_2[ch.RANDOM] - tbl_2[ch.LEARNED]) / tbl_2[ch.RANDOM] interval = getInterval(tbl,targetCol=targetCol,rebidCol=rebidCol, algorithmCol=algorithmCol,capaCol=capaCol) return tbl_2, interval def findOffloadRate(tbl,target,rebid=1,minRate=None,maxRate=None, rebidCol=ch.MP): result = None try: if minRate is not None: result = min(tbl.loc[(tbl[rebidCol]==rebid) & (tbl[target]>=minRate),ch.CAPACITY]) elif maxRate is not None: result = max(tbl.loc[(tbl[rebidCol]==rebid) & (tbl[target]<=maxRate),ch.CAPACITY]) return result except: return result def outputServiceCmpTbl(servicedata): serviceComp = servicedata[[ch.ALGORITHMTYPE,ch.MP, ch.CAPACITY,ch.SUCCESSRATE]].pivot_table( index=[ch.MP,ch.CAPACITY], columns=ch.ALGORITHMTYPE,values=ch.SUCCESSRATE) serviceComp[ch.DIFFERENCE] = (serviceComp[ch.RANDOM] - serviceComp[ch.LEARNED]) / serviceComp[ch.RANDOM] for c in serviceComp.columns: serviceComp[c] = serviceComp[c].apply(lambda x: np.round(x,2)) serviceComp.reset_index(inplace=True) offloadRate = {} for rebid in [1,5]: for minRate in [0.98,0.99]: for target in [ch.LEARNED,ch.RANDOM]: offloadRate[(rebid,minRate,target)] = findOffloadRate( serviceComp,target=target,rebid=rebid,minRate=minRate) interval = getInterval(servicedata,targetCol=ch.SUCCESSRATE, rebidCol=ch.MP,algorithmCol=ch.ALGORITHMTYPE) return serviceComp, offloadRate, interval def outputBackoffChartsComparison(rebid='1',contention=None,figsize=(10,4), path=LOGS_DIR): if contention=='high': folders = [] for i in np.arange(25,50,step=5): folders.append('-'.join([str(int(i)),str(int(i)), '60','rebid='])+rebid) elif contention=='low': folders = [] for i in np.arange(55,120,step=5): folders.append('-'.join([str(int(i)),str(int(i)), '60','rebid='])+rebid) else: contention = 'all' folders = [] for i in np.arange(25,120,step=5): folders.append('-'.join([str(int(i)),str(int(i)), '60','rebid='])+rebid) backoffBudget = pd.DataFrame() for folder in folders: backoffData = outputBackOffCharts(subdir=[folder],outputGraph=False, path=path) if len(backoffBudget)==0: backoffBudget = backoffData else: backoffBudget = pd.concat([backoffBudget,backoffData],axis=0) for dl in ['long deadline','short deadline']: tmp = backoffBudget.loc[backoffBudget[ch.DEADLINE]==dl] graph = Graphics(path) graph._drawBoxplot(df=tmp,x=ch.CAPACITY,y=ch.BACKOFFTIME, ylabel=ch.BACKOFFTIME,hue=ch.PRICERANGE, title='backoffBudget_'+contention+'Contention_'+dl +'_rebid='+rebid, legendFontsize=14,figsize=figsize,legends=1, myPalette={'low price':'C1','high price':'C0'}) return backoffBudget def welch_ttest(x1,x2,ci=0.95,tail='one'): if tail=='two': ci = 1 - (1-ci)/2 n1 = len(x1) n2 = len(x2) mu1 = np.mean(x1) mu2 = np.mean(x2) dof1 = n1-1 dof2 = n2-1 var1 = np.var(x1,ddof=1) var2 = np.var(x2,ddof=1) pooled_samplevar = (dof1 * var1 + dof2 * var2) / (dof1 + dof2) pooled_sd = np.sqrt(pooled_samplevar) t1 = tDistr.ppf(ci,dof1+dof2) interval_ttest = t1 * pooled_sd * np.sqrt(1/n1 + 1/n2) welch_dof = (var1/n1 + var2/n2)**2 / ( (var1/n1)**2 / dof1 + (var2/n2)**2 / dof2 ) t2 = tDistr.ppf(ci,welch_dof) interval_welch = t2 * np.sqrt(var1/n1 + var2/n2) meanDiff = mu1 - mu2 return meanDiff,interval_ttest,interval_welch def _collectRewardData(folder,filename,columnName,dataRange, targetCol=ch.AVGREWARD,path=LOGS_DIR): if folder is None or folder=='': filepath = os.path.join(path,filename) else: filepath = os.path.join(path,folder,filename) try: data = pd.read_csv(filepath,sep=';') except: return data1 = data[[ch.STEP,targetCol]].groupby( ch.STEP,as_index=False).mean() data1 = data1[(data1[ch.STEP]<=dataRange[1]) & (data1[ch.STEP]>dataRange[0])] data1.columns = [ch.STEP,columnName] return data1 def outputCuriosityReward(filepath=LOGS_DIR,folder='',dataRange=(100,2000), interval=None): if interval is None: interval = '' else: interval = '_' + str(interval) filename = 'invModel' + interval + '_2_True.txt' dataInv = _collectRewardData(folder=folder,filename=filename, targetCol=ch.AVGINVLOSS, columnName=ch.AVERAGELOSS, dataRange=dataRange) filename = 'forwardModel' + interval + '_2_True.txt' dataFwd = _collectRewardData(folder=folder,filename=filename, targetCol=ch.AVGFWDLOSS, columnName=ch.AVERAGELOSS, dataRange=dataRange) dataInv_out = dataInv.copy() dataFwd_out = dataFwd.copy() dataInv_out.columns = [ch.STEP,ch.AVERAGELOSSINVERSE] dataFwd_out.columns = [ch.STEP,ch.AVERAGELOSSFORWARD] avgStep = 100 dataInv[ch.STEP] = dataInv[ch.STEP].apply(lambda x: int(x/avgStep)*avgStep) dataFwd[ch.STEP] = dataFwd[ch.STEP].apply(lambda x: int(x/avgStep)*avgStep) graph = Graphics(filepath) graph._drawLineplot(df=dataInv,x=ch.STEP,y=ch.AVERAGELOSS, title='avgLoss_inverse'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False, ylim=(0,None)) graph._drawLineplot(df=dataFwd,x=ch.STEP,y=ch.AVERAGELOSS, title='avgLoss_forward'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False, ylim=(0,None)) return (dataInv_out,dataFwd_out) def outputFspReward(filepath=LOGS_DIR,folder='30-30-60-rebid=1', dataRange=(100,1500),interval=None,const=None): graph = Graphics(filepath) if interval is None: interval = '' else: interval = '_' + str(interval) dataSL = pd.DataFrame() filelist = [''] + list(np.arange(0,10)) for i in filelist: filename = 'supervisedLearningModel'+str(i)+interval+'_2_True.txt' data_sl = _collectRewardData(folder=folder,filename=filename, columnName=ch.AVERAGELOSSSL, dataRange=dataRange) if data_sl is None: continue if len(dataSL)==0: dataSL = data_sl else: dataSL = pd.concat([dataSL,data_sl],axis=0) avgStepAtt = 1000 avgStepExt = 1000 avgStepInt = 500 dataInt = pd.DataFrame() dataExt = pd.DataFrame() dataAtt = pd.DataFrame() for i in filelist: try: filename = 'reward'+str(i)+interval+'_2_True.txt' data_int = _collectRewardData(folder=folder,filename=filename, columnName=ch.INTRINSICREWARD, targetCol=ch.INTREWARD, dataRange=dataRange) data_ext = _collectRewardData(folder=folder,filename=filename, columnName=ch.EXTRINSICREWARD, targetCol=ch.EXTREWARD, dataRange=dataRange) if data_int is not None: if len(dataInt)==0: dataInt = data_int else: dataInt = pd.concat([dataInt,data_int],axis=0) if data_ext is not None: if len(dataExt)==0: dataExt = data_ext else: dataExt = pd.concat([dataExt,data_ext],axis=0) except: pass filename = 'priceLearningModel'+str(i)+interval+'_2_True.txt' try: data_att = _collectRewardData(folder=folder,filename=filename, columnName=ch.AVERAGEATTENTIONLOSS, targetCol=ch.ATTENTIONLOSS, dataRange=(dataRange[0],1000000)) except: continue if data_att is not None: if len(dataAtt)==0: dataAtt = data_att else: dataAtt =pd.concat([dataAtt,data_att],axis=0) if len(dataAtt)>0: dataAtt[ch.STEP] = dataAtt[ch.STEP].apply(lambda x: int(x/avgStepAtt)*avgStepAtt) graph._drawLineplot(df=dataAtt,x=ch.STEP,y=ch.AVERAGEATTENTIONLOSS, title='avgAttentionLoss'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) try: data = dataSL.merge(dataInt,on=ch.STEP,how='outer') except: filename = 'priceLearningModel'+interval+'_2_True.txt' dataRL = _collectRewardData(folder=folder,filename=filename, columnName=ch.AVERAGEREWARDRL, dataRange=dataRange) data = dataSL.merge(dataRL,on=ch.STEP,how='outer') return data,dataAtt data = data.merge(dataExt,on=ch.STEP,how='outer') data.fillna(0,inplace=True) data_out = data.copy() if len(dataAtt>0): dataAtt = dataAtt[~dataAtt[ch.AVERAGEATTENTIONLOSS].isnull()] if const is None: const = pmp.fsp_rl_weight_constant data[ch.WEIGHTEDINTRINSICREWARD] = ( (1-data[ch.AVERAGELOSSSL]) * (1-const/(data[ch.STEP]+const)) + const/(data[ch.STEP]+const) * data[ch.INTRINSICREWARD]) data1 = data.copy() data[ch.STEP] = data[ch.STEP].apply(lambda x: int(x/avgStepInt)*avgStepInt) graph._drawLineplot(df=data,x=ch.STEP,y=ch.WEIGHTEDINTRINSICREWARD, title='weightIntReward'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) graph._drawLineplot(df=data,x=ch.STEP,y=ch.INTRINSICREWARD, title='avgIntReward'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) graph._drawLineplot(df=data,x=ch.STEP,y=ch.AVERAGELOSSSL, title='avgLoss_sl'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) data1[ch.STEP] = data1[ch.STEP].apply( lambda x:int(x/avgStepExt)*avgStepExt) graph._drawLineplot(df=data1,x=ch.STEP,y=ch.EXTRINSICREWARD, title='avgExtReward'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) return (data_out,dataAtt) def addRows(tbl,dataRange,valueCol,dataCol,filler): exist = set(tbl[dataCol]) diff = list(set(dataRange)-exist) exist = list(exist) exist.sort() for i in diff: oneSmaller = exist[0] oneBigger = i for j in exist: if j < i and j > oneSmaller: oneSmaller = j if j > i: oneBigger = j break resBefore = tbl[tbl[dataCol]==oneSmaller][valueCol].tolist()[-1] resAfter = tbl[tbl[dataCol]==oneBigger][valueCol].tolist()[0] newRes = int(np.round((resAfter - resBefore) * (i - oneSmaller) / (oneBigger - oneSmaller) + resBefore,decimals=0)) tmpPd = pd.DataFrame([filler + [newRes,i]],columns=tbl.columns) tbl = pd.concat([tbl,tmpPd],axis=0) return tbl def outputServiceTable(serviceComp,size=None, legendFontsize=None,tickFontsize=None,path=LOGS_DIR, output='success'): if isinstance(serviceComp[ch.MP][0],str): serviceComp[ch.MP]=serviceComp[ch.MP].apply(int) dra = serviceComp[[ch.MP, ch.CAPACITY, ch.LEARNED]] ria = serviceComp[[ch.MP, ch.CAPACITY, ch.RANDOM]] perfRange = np.arange(0.90,0.985,step=0.01) perfRange = [np.round(x,decimals=2) for x in perfRange] target = ch.SUCCESSRATE if output=='failure': target = ch.FAILEDRATE draco = pd.DataFrame() rial = pd.DataFrame() for rebid in [1,5]: tmp = dra[dra[ch.MP]==rebid] tmp = addRows(tbl=tmp,dataRange=perfRange, valueCol=ch.CAPACITY,dataCol=ch.LEARNED, filler=[rebid]) if len(draco)==0: draco = tmp else: draco = pd.concat([draco,tmp],axis=0) tmp0 = ria[ria[ch.MP]==rebid] tmp0 = addRows(tbl=tmp0,dataRange=perfRange, valueCol=ch.CAPACITY,dataCol=ch.RANDOM, filler=[rebid]) if len(rial)==0: rial = tmp0 else: rial = pd.concat([rial,tmp0],axis=0) col = [ch.MP,ch.CAPACITY,target,ch.TYPE] draco[ch.TYPE] = ch.LEARNED draco.columns = col rial[ch.TYPE] = ch.RANDOM rial.columns = col data = pd.concat([draco,rial],axis=0) data = data[(data[target]>=perfRange[0])] data1 = data.groupby([ch.MP,target,ch.TYPE],as_index=False).agg('min') dataRange = perfRange+[0.99] xticklabel = None if output=='failure': xticklabel = np.array([np.round(1-x,decimals=2) for x in dataRange]) graph = Graphics(path) graph.drawRegplot(df=data1,x=target,y=ch.CAPACITY, title='capacityUse_'+target,hue=ch.TYPE,order='fixed',size=size, legendFontsize=legendFontsize,tickFontsize=tickFontsize,legends='best', separate=ch.MP,x_decimals=2,y_decimals=0, dataRange=dataRange,xticklabel=xticklabel) data = data.pivot_table(values=ch.CAPACITY, index=[ch.MP,target], columns=ch.TYPE,aggfunc='min') data.reset_index(inplace=True) data[ch.SAVING] = (data[ch.RANDOM] - data[ch.LEARNED]) / data[ch.RANDOM] data[ch.SAVING] = data[ch.SAVING].apply( lambda x: np.round(x,decimals=2) if not np.isnan(x) else '') for col in [ch.LEARNED,ch.RANDOM]: data[col] = data[col].apply( lambda x: int(x) if not np.isnan(x) else '') return data,data1 def outputSumoTrace(filepath=LOGS_DIR,folder='', file='',gridRangeX=(1,401),gridRangeY=(1,307), sumoDataOffset=50000,nrRecord=200000): graph = Graphics(os.path.join(filepath,folder)) df = graph.drawTraceDataDistr( file=file,gridRangeX=gridRangeX,gridRangeY=gridRangeY, sumoDataOffset=sumoDataOffset,nrRecord=nrRecord) return df def outputAttentionReward(filepath,dataInv,dataFwd,dataRL,dataAtt, dataRange=(0,50000),interval=None): if interval is None: interval = '' else: interval = '_' + str(interval) invLoss_weight = cmp.invLoss_weight rl_weight = pmp.fsp_rl_weight_constant curiosity_weight = 0 data = pd.merge(dataInv,dataFwd,how='outer',on=ch.STEP) data = data.merge(dataRL,how='outer',on=ch.STEP) data.fillna(0,inplace=True) data = data[(data[ch.STEP]>dataRange[0]) & (data[ch.STEP]<=dataRange[1])] data[ch.CURIOSITYLOSS] = (invLoss_weight * data[ch.AVERAGELOSSINVERSE] + (1-invLoss_weight) * data[ch.AVERAGELOSSFORWARD]) data[ch.AVERAGEINTRINSICREWARD] = ( (1-data[ch.AVERAGELOSSSL]) * (1-rl_weight/(data[ch.STEP]+rl_weight)) + rl_weight/(data[ch.STEP]+rl_weight) * ((1-curiosity_weight)*data[ch.INTRINSICREWARD] +curiosity_weight*(1-data[ch.CURIOSITYLOSS])) ) avgStep = 50 data[ch.STEP] = data[ch.STEP].apply(lambda x: int(x/avgStep)*avgStep) graph = Graphics(filepath) graph._drawLineplot(df=data,x=ch.STEP,y=ch.AVERAGEINTRINSICREWARD, title='avgIntReward'+interval,legends=None, legendFontsize=None,tickFontsize=12, size=None,decimals=2,ci='sd',showTable=False) if len(dataAtt)>0: avgStep = 100 dataAtt[ch.STEP] = dataAtt[ch.STEP].apply(lambda x: int(x/avgStep)*avgStep) #%% if __name__ == '__main__': path = LOGS_DIR try: path = os.path.join(path,sys.argv[3]) except: pass if sys.argv[1]=='curious': # testDf = outputSumoTrace(file='test', # nrRecord=100000,sumoDataOffset=75000) # evalDf = outputSumoTrace(file='eval', # nrRecord=100000,sumoDataOffset=100000) # trainNewDf = outputSumoTrace(file='trainNew', # nrRecord=200000,sumoDataOffset=52000) interval = int(sys.argv[2]) if interval>0: # folder = os.path.join('conext', # 'attentionRNNsupervised_capa=30_train') # folder = os.path.join('conext', # 'intrinsicRewardWithFwdloss+payoff_ascent_capa=30_train') folder = '' dataInv,dataFwd = outputCuriosityReward(filepath=path, folder=folder,dataRange=(0,50000),interval=interval) dataRL,dataAtt = outputFspReward(filepath=path,folder=folder, dataRange=(0,50000),interval=interval) # outputAttentionReward(filepath=path, # dataInv=dataInv,dataFwd=dataFwd,dataRL=dataRL, # dataAtt=dataAtt,dataRange=(2000,50000),interval=interval) # outputUtilizationOverTimeLowResCapa(path=path,nrSites='2sites', # site='site',service='service', # stepRange=(60000,130000), # avgTime=1000,ci='sd', # legends='best') else: # general setup path = os.path.join(path,'general') folder = '30-30-60-rebid=1' graph = Graphics(os.path.join(path,folder)) # graph.drawPerformance(drawPerformanceOnly=True,textOutput=False, # sites='2sites',target=ch.TOTALSUCCESSRATIO, # legends=4,stepRange=(300,7999), # decimals=2,ci='sd') graph.drawPerformance(drawPerformanceOnly=True,textOutput=False, sites='2sites',target=ch.TOTALSUCCESSRATIO, legends='best',stepRange=(300,7999), yaxisTick='right', decimals=2,ci='sd') outputUtilizationOverTimeLowResCapa( path=os.path.join(path,folder), nrSites='2sites',site='site0',service='service2', stepRange=(7700,7999)) # outputFspReward(filepath=path,folder=folder,dataRange=(150,7999)) decimals = 3 filename = 'servicelevel_rebid_decimals='+str(decimals)+'.csv' servicedata = getServiceLevelData(filename=filename,decimals=decimals, path=path) size = (5, 4) legendFontsize = 10 tickFontsize = 10 outputServiceLevel(filename=filename,separate=ch.MP,ci='sd', size=size,legendFontsize=legendFontsize, tickFontsize=tickFontsize,vertical=True,path=path) serviceComp,offloadRate,serviceCi = outputServiceCmpTbl(servicedata) serviceTbl,tbl = outputServiceTable(serviceComp,size=size, legendFontsize=legendFontsize, tickFontsize=tickFontsize,path=path) serviceTbl,tbl = outputServiceTable(serviceComp,size=size, legendFontsize=legendFontsize, tickFontsize=tickFontsize,path=path, output='failure') try: rebidTbl5 = pd.read_csv( os.path.join(path,'rebid=5_Tbl.csv'),sep=';') rebidTbl5 = outputRebidBoxplotMeanAndStd( boxchart=rebidTbl5,path=path,rebid='5') except: rebidTbl5 = outputRebidBoxplotMeanAndStd(path=path,rebid='5') rebidTbl5.to_csv(os.path.join(path,'rebid=5_Tbl.csv'), sep=';',index=None) rebidComp, rebidCi = outputComparisonTbl(tbl=rebidTbl5, targetCol=ch.NRREBID,rebidCol=ch.MAXREBIDOLD2, capaCol=ch.CAPACITY,algorithmCol=ch.TRAINED) try: utilTbl1 = pd.read_csv(os.path.join(path,'rebid=1_utilTbl.csv'), sep=';') utilTbl1 = outputUtilizationMeanAndStdHighResCapa( boxchart=utilTbl1,path=path,rebid='1') except: utilTbl1 = outputUtilizationMeanAndStdHighResCapa(path=path, rebid='1') utilTbl1.to_csv(os.path.join(path,'rebid=1_utilTbl.csv'), sep=';',index=None) utilComparison, utilCi = outputComparisonTbl(tbl=utilTbl1, targetCol='site0',rebidCol=ch.REBID,capaCol=ch.CAPACITY, algorithmCol=ch.TRAINED) outputIndividualSuccessRateWithHighResCapa(path=path,size=(14,4)) _ = outputBackOffCharts(subdir=['25-25-60-rebid=5'],path=path, size=(7,4)) backoffBudget5 = outputBackoffChartsComparison( rebid='5',contention='high',figsize=(7,4),path=path) testDf = outputSumoTrace(file='test', nrRecord=100000,sumoDataOffset=75000) # testGraph = graph.drawPerformance(drawPerformanceOnly=True, # target='totalSuccessRatio',textOutput=True, # outputThres=1000,endOfGame=200000, # legends='best',stepRange=(25000,125000), # decimals=2,yaxisTick='right',orderHue='by algorithm', # density=100,ci='sd') evalDf = outputSumoTrace(file='eval', nrRecord=100000,sumoDataOffset=100000) # evalGraph = graph.drawPerformance(drawPerformanceOnly=True, # target='totalSuccessRatio',textOutput=True, # outputThres=1000,endOfGame=200000, # legends='best',stepRange=(50000,150000), # decimals=2,yaxisTick='right',orderHue='by algorithm', # density=100,ci='sd') trainNewDf = outputSumoTrace(file='trainNew', nrRecord=200000,sumoDataOffset=52000) # trainGraph = graph.drawPerformance(drawPerformanceOnly=True, # target='totalSuccessRatio',textOutput=True, # outputThres=1000,endOfGame=200000, # legends='best',stepRange=(2000,200000), # decimals=2,yaxisTick='right',orderHue='by algorithm', # density=300,ci='sd') result = outputReliability(path=path)
48,341
41.59207
92
py
malfoy
malfoy-master/v2x/__init__.py
0
0
0
py
malfoy
malfoy-master/v2x/config/config.py
# -*- coding: utf-8 -*- import os import sys import torch torch.set_num_threads(1) ROOT_DIR = os.path.normpath(os.path.join( os.path.dirname(os.path.realpath(__file__)), '../..')) LOGS_DIR = os.path.join(ROOT_DIR, 'logs') RESOURCES_DIR = os.path.join(ROOT_DIR, 'resources') MODEL_DIR = os.path.join(ROOT_DIR, 'models') GRAPH_DIR = os.path.join(ROOT_DIR, 'graphs') PSTATS_FILE = os.path.join(LOGS_DIR, 'profile.stats') COUNTDOWN_FILE = os.path.join(MODEL_DIR, 'countdownHistory') BATCHCREATE_FILE = os.path.join(MODEL_DIR, 'batchCreateHistory') DEVICE = torch.device('cpu') DTYPE = torch.FloatTensor class FILES(): ALLOC_FILE = ('allocfile',os.path.join(LOGS_DIR,'allocation')) PERF_FILE =('perfile',os.path.join(LOGS_DIR,'performance')) PLM_FILE = ('plmfile',os.path.join(LOGS_DIR,'priceLearningModel')) BID_FILE = ('bidfile',os.path.join(LOGS_DIR,'finishedBids')) SL_FILE = ('supervisefile',os.path.join(LOGS_DIR,'supervisedLearningModel')) INVMDL_FILE = ('invmodelfile',os.path.join(LOGS_DIR,'invModel')) FWDMDL_FILE = ('forwardmodelfile',os.path.join(LOGS_DIR,'forwardModel')) REWARD_FILE = ('rewardfile',os.path.join(LOGS_DIR,'reward')) class RESOURCE_SITE_PARAMS(): serviceCapa = [(15,16),(15,16), (15,16)] # Range of random service capacity. # when services are created. items. # for different types of services. resourceCapa = [[(0,1),(0,1),(0,1)], [(100,101),(100,101),(250,251)], [(200,201),(200,201),(250,251)], [(500,501),(500,501),(1000,1001)], [(1000,1001),(1000,1001),(2000,2001)]] # Range of random resource capacity # when resources are created. # Items are for different types of # resources. transCost = 0.01 # Transmission cost between sites. burnIn = 4000 # Frozen period for capacity # adjustment. lowerCapaLimit = 0.4 # For capacity adjustment. upperCapaLimit = 0.8 # For capacity adjustment. resProfileSelectionThreshold = 2 # Before collecting this much # of data, take user's resource # profile. After that trust # the service's estimated profile. randomizeQueueTimeThres = 10 # Min sample size for getting # queue length distribution class SERVICE_PARAMS(): avgCapacityPeriod = 50 # For calculation of average # capacity. avgCostPeriod = 10 # For calculation of average cost. discount = 0.8 # Price discount of slower servers. utilPredictionWeights = [1/50] * 50 capacityBuffer = 0.1 # Buffer in capacity adjustment. resProfileUpdateThreshold = 20 # At least to collect so many data # points before curve fitting # for resNeedsEstim. null = 1E-7 # Anything below is null. class RSU_PARAMS(): secondPriceThres = 3 # Least number of failed bids # record for regression overload = 0.1 # % overload allowed on resource # sites at time of allocation. class VEHICLE_PARAMS(): totalBudget = (2000,1500) # Total budget at time of creation. minNrBids = 5 # Minimum number of simultaneous # bids a vehicle can activate. # Whenever active nr. bids drops # below this, new bids are # created. maxNrBids = 100 # Maximum nr of simultaneous bids # a vehicle can activate. totalNrBids = sys.maxsize # Maxixmum total nr. bids a # vehicle can create. maxSensingDist = 1000 # Distance for sensing the RSU. # Can be useful when there are # multiple RSUs. budgetRenewal = 1 # Number of bids to share the # available budget. maxLifespan = 50000 # Vehicle lifespan range envCategory = 5 # Discretize nr. bids as env. input priceCategory = 5 # Discretize price competitorDataThres = 0 # Nr bids to collect before # creating transitionTbl plmTrainingThres = 5 # Interval (in terms of new # priceLearningModel inputs) lamMax = 0.6 # Max. lambda of the exponential # distribution for # generating new bids # e.g. 0.2 means 1 batch every 5 # time steps. lamChangeInterval = 30 # Interval of changing lambda. lamMin = 0.02 # Min. lambda. ph = 1 # transition prob. high to low pl = 1 # transition prob. low to high lamCategory = 5 # Nr. of lambda categories. # the higher the number, the more # extreme the lambdas. stagingMaxsize = 50 # Maxsize for staged batches. stagingMaxtime = 250 # Longest time to be staged. stagingThreshold = [0.6] # An indicator of higher than # threshold will be submitted. stagingPeriod = 10 # Max time to wait until next # evaluation. curiosityTrainingThres = 3 # curiosityExtRewardThres = 1 # external reward interval class BID_PARAMS(): QoS1 = 100 # High performance E2E processing time. QoS2 = 500 # Low performance E2E processing time. servAmount1 = 1 # Low service amount servAmount2 = 3 # High service amount minDataSize = 0.4 # Min data size in mbit. maxDataSize = 4 # Max data size in mbit. maxlength = 1 # Maximum chain length. nrRebid = 1 # Max number of rebids. requestCountdown1 = 100 # request creation interval for service1 requestCountdown2 = 500 # for service2 class MDL_PARAMS(): width = 402 # Visual param height = 308 # Visual param rsuPos = (int(width/2),int(height/2)) # Visual param rsuInterval = 20 # Visual param resSitePos = (80,150) # Visual param resSiteInterval = 20 # Visual param vehicleYposChoice = (50,65) # Visual param vehicleInterval = 1 # Visual param lam = 0 # Lambda of the poisson distribution for # generating new vehicles. totalSimTime = 1000000 # Simulation time timeForNewVehicles = 1000000 # Latest time to create new vehicles nrSites = 2 # Default number of sites to create initVehicles = 27 # Initial number of vehicles to create. # When lam==0, no new vehicles will be # created after initialization, to give # the vehicles the chance to learn. nrRsu = 1 # Default number of RSUs to create. recent = 350 # Performance indicator for only # the recent periods class RESOURCE_PARAMS(): defaultMaxAmount = 200 # default maximum resource amount unitCost = [(2,2),(20,5)] # cost per resource unit per time unit class TRANSITION_PARAMS(): trainingThres = 3 # Interval (in terms of new nr. inputs) # to train the competitorLearnModel. historyPeriods = 1 # Number of historical states to use # for forecast of next state. class COMP_MODEL_PARAMS(): hidden_size1 = 64 hidden_size2 = 64 batch_size = 10 hitory_record = 10 epoch = 10 learning_rate = 0.3 pretrain_nr_record = 2 # No training until this nr. inputs. # Afterwards train on the most recent # history_record number of records # every TRANSITION_PARAMS.trainingThres class PRICE_MODEL_PARAMS(): evaluation_start = 1000000 batch_size = 30 history_record = 62 # total size of input epoch = 1 epoch_supervise = 5 train_all_records = 62 # Before this nr. inputs, train on all # records. after this, train on the # most recent history_record number of # records every # VEHICLE_PARAMS.plmTrainingThres critic_type = 'ConvCritic' # 'ConvCritic' or 'Critic' class critic_num_filter = 32 critic_hidden_size1 = 128 critic_hidden_size2 = 128 critic_lr_min = 0.1 critic_lr_reduce_rate = 0.99 critic_learning_rate = 0.9 critic_dropout_rate = 0.0 reward_rate = 0.99 # Continuing tasks with function estimator # should not use discount. # Use average reward instead. reward_min = 0.01 reward_reduce_rate = 1 critic_pretrain_nr_record = 62 # no training until this nr. inputs actor_type = 'ConvActor' # 'ConvActor' or 'Actor' class actor_num_filter = 64 actor_hidden_size1 = 128 actor_hidden_size2 = 128 actor_lr_min = 0.1 actor_lr_reduce_rate = 0.99 actor_learning_rate = 0.9 actor_dropout_rate = 0.0 actor_pretrain_nr_record = 32 # No training until this nr. inputs. sharedlayer_output_dim = 128 # If no compression in sharedLayers, # set the value to -1. add_randomness = 0 # Valued between 0 and 1. if greater # than zero, then in inference function, # action is randomly chosen # when generated random number is smaller # than add_randomness * learning rate exploration = 128 # Before the model accumulated this # number of records, the # learning rate does not reduce. supervise_learning_rate = 0.1 # learning rate for supervised learning supervise_hidden_size1 = 64 # MLP hidden layer supervise_hidden_size2 = 128 # MLP hidden layer fsp_rl_weight_constant = exploration * 2 reward_ext_weight = 0 # Balance between ext. and int. reward. # Higher weight means more important ex. reward. reward_int_weight = 0.9 # Balance between utility and curiosity prediction # loss in intrinsic reward. # Higher weight means more important utility. class CURIOUS_MODEL_PARAMS(): feature_hidden_size1 = 64 feature_hidden_size2 = 128 feature_outputDim = 32 inv_hidden_size1 = 64 inv_hidden_size2 = 128 inv_learning_rate = 0.1 forward_hidden_size1 = 64 forward_hidden_size2 = 128 forward_learning_rate = 0.1 batch_size = 30 epoch = 5 invLoss_weight = 0.5
13,031
50.920319
80
py
malfoy
malfoy-master/v2x/config/__init__.py
0
0
0
py
malfoy
malfoy-master/v2x/solutions/price_model_curious.py
# -*- coding: utf-8 -*- import os import numpy as np import torch from torch import tensor,nn from torch.autograd import Variable torch.autograd.set_detect_anomaly(True) from torch.nn import functional as F from torch.distributions.multivariate_normal import MultivariateNormal from ..config.config import (PRICE_MODEL_PARAMS as pmp, VEHICLE_PARAMS as vp, CURIOUS_MODEL_PARAMS as cmp, DEVICE,DTYPE,MODEL_DIR) from ..solutions.attention import Attention class Model(): train_all_records = pmp.train_all_records history_record = pmp.history_record critic_pretrain_nr_record = pmp.critic_pretrain_nr_record batch_size = pmp.batch_size epoch = pmp.epoch epoch_supervise = pmp.epoch_supervise def __init__(self,evaluation=False,loadModel=False,curiosity=False, maxReward=1): self.unique_id = None self.evaluation = evaluation self.loadModel = loadModel self.curiosity = curiosity self.reward = dict() self.reward_normalized = dict() self.reward_curious = dict() self.inputVec = dict() self.nextStateVec = dict() # price model output: first digit is whether to delay. # rest of output is proportion of allocated budget to each bid self.output = dict() self.maxReward = maxReward self.inputCounter = 0 self.firstInput = 0 def _prepInput(self,inputVec,pos=None,var=True): if pos is None: pos = list(range(len(inputVec))) x = [] if isinstance(inputVec,dict): for k in pos: x.append(inputVec[str(k)]) x = np.array(x) else: x = np.array([x for i,x in enumerate(inputVec) if i in pos]) if var: return Variable(tensor(x,device=DEVICE).type(DTYPE)) else: return tensor(x,device=DEVICE).type(DTYPE) def _removeRecord(self,number=1,model='priceLearningModel'): pos = self.firstInput for i in range(number): try: _ = self.inputVec.pop(str(pos)) except KeyError: pass try: _ = self.output.pop(str(pos)) except KeyError: pass if model=='priceLearningModel': try: _ = self.reward.pop(str(pos)) except KeyError: pass try: _ = self.nextStateVec.pop(str(pos)) except KeyError: pass if self.curiosity: for j in range(pos+1): try: _ = self.reward_curious.pop(str(j)) except KeyError: continue try: _ = self.reward_normalized.pop(str(j)) except KeyError: continue pos += 1 self.firstInput += number def _prep_reward(self,rewardVec,randomize=True,normalize=True, curiosity=False): extraPos = 0 if curiosity: # add one more position for reward from previous round # state vector of curiosity model is the concatenation # of current state and previous reward extraPos = 1 try: length = len([v for k,v in rewardVec.items() if v is not None and not np.isnan(v)]) except ValueError: length = len([v for k,v in rewardVec.items() if v[0] is not None and not np.isnan(v[0])]) if length>=self.train_all_records: length = min(length,self.history_record+extraPos) try: pos = [int(k) for k,v in rewardVec.items() if v is not None and not np.isnan(v)] except ValueError: pos = [int(k) for k,v in rewardVec.items() if v[0] is not None and not np.isnan(v[0])] pos.sort() r = [] for k in pos: r.append(rewardVec[str(k)]) # reward from curiosity model r = tensor(r[-length+extraPos:],device=DEVICE).type(DTYPE) if randomize: r = (r + (torch.abs(r+1E-7)/100)**0.5 * torch.randn(len(r)) ).type(DTYPE) if normalize: try: maxReward = torch.max(torch.abs(r)) except: maxReward = self.maxReward if maxReward > self.maxReward: self.maxReward = maxReward else: maxReward = self.maxReward r = r / maxReward # position for previous reward from MEC, to be concatenated to # the state vector of curiosity model pos_tm1 = pos[-length:-extraPos] # position for input and output vectors pos = pos[-length+extraPos:] return r,pos,pos_tm1 def prep_data(self,time,plmfile,reward=None,reward_curious=None, inputVec=None,nextStateVec=None,output=None, curious=False,model='priceLearningModel'): if reward is None: reward = self.reward.copy() if reward_curious is None: if model=='priceLearningModel': reward_curious = self.reward_curious else: reward_curious = reward if inputVec is None: inputVec = self.inputVec if nextStateVec is None: nextStateVec = self.nextStateVec if output is None: output = self.output try: if not curious: currentIdx = max([int(k) for k in reward.keys()]) else: currentIdx = max([int(k) for k in reward_curious.keys()]) except: # if no reward is recorded yet return if (currentIdx<max(self.critic_pretrain_nr_record,self.batch_size)): plmfile.write('{};{};{};too few data points.\n'.format( time,self.unique_id,0)) plmfile.flush() return if not curious: # prepare data for RL without curiosity model r,pos,_ = self._prep_reward(rewardVec=reward) if model=='supervisedModel': r = r.repeat_interleave(2) pos = [y for z in [[x*2,x*2+1] for x in pos] for y in z] r = r.view(-1,1) x = self._prepInput(inputVec,pos,var=True) y = self._prepInput(nextStateVec,pos,var=False) a = self._prepInput(output,pos,var=False) assert len(x)==len(y)==len(r) if model=='supervisedModel': return (currentIdx,x,y,r,a,pos) r_batch = r[self.batch_size-1:] a_batch = a[self.batch_size-1:] pos_batch = pos[self.batch_size-1:] x_batch = self._create_batch(x) y_batch = self._create_batch(y) return (currentIdx,x_batch,y_batch,r_batch,a_batch,pos_batch) # prepare data for curiosity model interval = 1 r_curious,pos,pos_tm1 = self._prep_reward( rewardVec=reward_curious,curiosity=True) if model=='curiosity': r_copy = r_curious.detach().numpy() for i,k in enumerate(pos): # to be added to interval reward in update_curiousReward() self.reward_normalized[str(k)] = r_copy[i] if model=='supervisedModel': # supervised model has two positions for each round, one is # from behavior strategy, the other one from best response r_curious = r_curious.repeat_interleave(2) pos = [y for z in [[x*2,x*2+1] for x in pos] for y in z] interval = 2 r_curious = r_curious[:-interval].view(-1,1) r = self._prepInput(reward,pos_tm1,var=True) if model=='supervisedModel': r = r.repeat_interleave(2) r_x = r.view(-1,1) r_y = r[interval:].view(-1,1) x = self._prepInput(inputVec,pos,var=True) y = self._prepInput(nextStateVec,pos[:-interval],var=True) x = torch.cat([x,r_x],dim=1) y = torch.cat([y,r_y],dim=1) a_inv = self._prepInput(output,pos,var=False) a_fwd = self._prepInput(output,pos,var=True) assert len(x)==len(y)+interval==len(r_curious)+interval==len(a_inv) # create data batches of batchsize x_batch = [] y_batch = [] r_curious_batch = r_curious[self.batch_size-1:] a_inv_batch = a_inv[self.batch_size-1:] a_fwd_batch = a_fwd[self.batch_size-1:] pos_batch = pos[self.batch_size-1:] for idx in np.arange(self.batch_size,len(x)+1): x_batch.append(x[idx-self.batch_size:idx]) for idx in np.arange(self.batch_size,len(y)+1): y_batch.append(y[idx-self.batch_size:idx]) if len(y_batch)==0: # not enough data for one batch plmfile.write('{};{};{};too few data points.\n'.format( time,self.unique_id,0)) plmfile.flush() return x_batch = torch.stack(x_batch,dim=0) y_batch = torch.stack(y_batch,dim=0) return (currentIdx,x_batch,y_batch,r_curious_batch,a_inv_batch, a_fwd_batch,pos_batch) def _create_batch(self,x): x_batch = [] for idx in np.arange(self.batch_size,len(x)+1): x_batch.append(x[idx-self.batch_size:idx]) try: x_batch = torch.stack(x_batch,dim=0) return x_batch except: return def collectInput(self,inputVec,model='priceLearningModel', buffer=None): if buffer is None: buffer = self.history_record * 2 self.inputVec[str(self.inputCounter)] = inputVec self.inputCounter += 1 if len(self.inputVec)>max(self.history_record+buffer, self.train_all_records+buffer): self._removeRecord(model=model) return str(self.inputCounter-1) # id for matching output and reward def collectOutput(self,output,idx): self.output[idx] = output class PriceLearningModel(Model): ''' vehicle price learning model, A2C. input is competitor state, new bid info and environment variables. output is whether to hold bids for the current round, and budget allocation to each bid. number of bids sharing the same budget pool is currently fixed. inputs, outputs and rewards are all normalized. ''' actor_learning_rate = pmp.actor_learning_rate actor_lr_min = pmp.actor_lr_min actor_lr_reduce_rate = pmp.actor_lr_reduce_rate critic_learning_rate = pmp.critic_learning_rate critic_lr_min = pmp.critic_lr_min critic_lr_reduce_rate = pmp.critic_lr_reduce_rate actor_pretrain_nr_record = pmp.actor_pretrain_nr_record reward_rate = pmp.reward_rate reward_min = pmp.reward_min reward_reduce_rate = pmp.reward_reduce_rate add_randomness = pmp.add_randomness exploration = pmp.exploration actor_type = pmp.actor_type critic_type = pmp.critic_type def __init__(self,uniqueId,dimOutput=1,evaluation=False,loadModel=False, curiosity=False,cumstep=0,endOfGame=5000,ca=True, maxReward=1): super().__init__(evaluation,loadModel,curiosity,maxReward) self.unique_id = uniqueId + '_plm' self.dimOutput = dimOutput self.actor = None self.critic = None self.actor_optimizer = None self.critic_optimizer = None self.attention = None self.ca = ca # ignore attention net(aka credit assignment) if False. if self.ca: self.attentionpath = os.path.join(MODEL_DIR, self.unique_id+'_attention.pkl') self.avg_reward = 0 self.avg_reward_ext = 0 # fictitious self play fsp self.criticpath = os.path.join(MODEL_DIR, self.unique_id+'_critic_train_fsp.pkl') self.actorpath = os.path.join(MODEL_DIR, self.unique_id+'_actor_train_fsp.pkl') self.trainingdata = None # vectors of state, next state, reward, action self.reward_ext = dict() # external reward for curiosity model # control training of atttention net: # (to train, to save attention.trainingdata) self.trainWeightvector = (False,False) self.exploration = max( int(self.exploration / 2**(cumstep / endOfGame)),16) def _initBudget(self): ''' random budget split if model is not available ''' return list(np.random.rand(self.dimOutput)) #return np.random.rand(self.dimOutput) def _initActor(self,inputDim,outputDim,sharedLayers=None): paramDim = int(outputDim + outputDim + (outputDim**2 - outputDim) / 2) if self.actor_type=='Actor': self.actor = MLP_Wrapper(inputDim,paramDim, pmp.actor_hidden_size1,pmp.actor_hidden_size2) else: self.actor = CNNHighway(inputDim,paramDim,pmp.actor_num_filter, pmp.actor_dropout_rate,pmp.actor_hidden_size1, pmp.actor_hidden_size2,pmp.sharedlayer_output_dim, sharedLayers) if DEVICE!=torch.device('cpu'): self.actor = nn.DataParallel(self.actor) self.actor.to(DEVICE) self.actor_params = list(filter(lambda p: p.requires_grad, self.actor.parameters())) self.actor_optimizer = torch.optim.SGD(self.actor_params, lr=self.actor_learning_rate) if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload(self.actorpath) def _initCritic(self,inputDim,outputDim,sharedLayers=None): if self.critic_type=='Critic': self.critic = MLP_Wrapper(inputDim,outputDim, pmp.critic_hidden_size1,pmp.critic_hidden_size2) else: self.critic = CNNHighway(inputDim,outputDim,pmp.critic_num_filter, pmp.critic_dropout_rate,pmp.critic_hidden_size1, pmp.critic_hidden_size2,pmp.sharedlayer_output_dim, sharedLayers) if DEVICE!=torch.device('cpu'): self.critic = nn.DataParallel(self.critic) self.critic.to(DEVICE) self.critic_params = list(filter(lambda p: p.requires_grad, self.critic.parameters())) self.critic_optimizer = torch.optim.SGD(self.critic_params, lr=self.critic_learning_rate) if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload(self.criticpath) def _initAttention(self,inputDim,outputDim): self.attention = Attention(self.unique_id,input_size=inputDim, output_size=outputDim,maxReward=1) if DEVICE!=torch.device('cpu'): self.attention = nn.DataParallel(self.attention) self.attention.to(DEVICE) self.attention.setOptim(lr=0.01) if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload(self.attentionpath) def _reload(self,path): try: checkpoint = torch.load(path) if path==self.criticpath: self.critic.load_state_dict(checkpoint) elif path==self.actorpath: self.actor.load_state_dict(checkpoint) elif path==self.attentionpath: self.attention.load_state_dict(checkpoint) else: pass except: pass def _updateLearningRate(self): currentIdx = max([int(k) for k in self.reward.keys()]) if currentIdx < self.exploration: critic_lr_reduce_rate = 1 actor_lr_reduce_rate = 1 reward_reduce_rate = 1 else: critic_lr_reduce_rate = self.critic_lr_reduce_rate actor_lr_reduce_rate = self.actor_lr_reduce_rate reward_reduce_rate = self.reward_reduce_rate if self.critic is not None: self.critic_learning_rate = max(self.critic_lr_min, self.critic_learning_rate * critic_lr_reduce_rate) self.critic_optimizer = torch.optim.SGD(self.critic_params, lr=self.critic_learning_rate) if self.actor is not None: self.actor_learning_rate = max(self.actor_lr_min, self.actor_learning_rate * actor_lr_reduce_rate) self.actor_optimizer = torch.optim.SGD(self.actor_params, lr=self.actor_learning_rate) self.reward_rate = max(self.reward_min, self.reward_rate * reward_reduce_rate) def _critic_loss_func(self,value,next_value,reward,avg_reward,rate, invloss,fwdloss): if invloss is None: invloss = torch.zeros(len(reward)) fwdloss = torch.zeros(len(reward)) reward_int = (reward.view(1,-1) - cmp.invLoss_weight * invloss.view(1,-1) - (1-cmp.invLoss_weight) * fwdloss.view(1,-1)).mean() reward_int = reward_int.detach() advantage = (reward + next_value - value - cmp.invLoss_weight * invloss.view(-1,1) - (1-cmp.invLoss_weight) * fwdloss.view(-1,1)) for i in range(len(advantage)): advantage[i] -= avg_reward if not torch.isnan(advantage[i]): avg_reward += rate * advantage[i].item() return advantage.pow(2).mean(),advantage,avg_reward,reward_int def _createCovMat(self,diag,tril): # with batchsize z = torch.zeros(size=[diag.size(0)],device=DEVICE).type(DTYPE) diag = 1E-7 + diag # strictly positive elements = [] trilPointer = 0 for i in range(diag.shape[1]): for j in range(diag.shape[1]): if j<i: elements.append(tril[:,trilPointer]) trilPointer += 1 elif j==i: elements.append(diag[:,i]) else: elements.append(z) scale_tril = torch.stack(elements,dim=-1).view(-1,self.dimOutput, self.dimOutput) return scale_tril def _actor_loss_func(self,log_prob_actions,advantage): ''' log_prob is the loss function according to the policy gradient with continuous action space. the MSELoss between budget ratio and 1 is to ensure the output will approach 1 in total. ''' # pytorch default optimizer uses gradient descent methods, while # some algorithms such as REINFORCE assume gradient ascent for # update. If such algorithm, then use -log_prob instead. return (advantage.detach() * -log_prob_actions ).mean() def _chooseAction(self,params): ''' action space is multi-dimentional continuous variables. therefore use parameterized action estimators, and a multivariate gaussian distribution to output joint probability of the actions. parameters in this case includes N means and N*N covariance matrix elements. Therefore this solution is not scalable when N increases. Another solution would be to use a RNN, such as in https://arxiv.org/pdf/1806.00589.pdf or http://papers.nips.cc/paper/6398-learning-multiagent-communication-with-backpropagation.pdf or https://arxiv.org/pdf/1705.05035.pdf derivatives of a multivariate gaussian: see matrix cookbook chapter 8: http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3274/pdf/imm3274.pdf params are split into mean, covariance matrix diagonal, cov matrix triangle lower half (since cov matrix is symmetric). also make sure cov is positive definite. ''' mean,diag,tril = params.split([self.dimOutput,self.dimOutput, params.shape[1]-2*self.dimOutput],dim=-1) scale_tril = self._createCovMat(diag,tril) dist = MultivariateNormal(loc=mean,scale_tril=scale_tril) # https://pytorch.org/docs/stable/distributions.html#pathwise-derivative actions = dist.rsample() log_prob_actions = dist.log_prob(actions) return actions,log_prob_actions,mean def _saveModel(self): if self.critic is not None: torch.save(self.critic.state_dict(),self.criticpath) if self.actor is not None: torch.save(self.actor.state_dict(),self.actorpath) if self.attention is not None: torch.save(self.attention.state_dict(),self.attentionpath) def _inference_prepInput(self,inputVec,randomness=None,output_r=False): if self.critic is None or self.actor is None: x = tensor(self._initBudget(),device=DEVICE).type(DTYPE) r = torch.rand(len(x)) return (False,x,r) if randomness is None: randomness = self.add_randomness * self.actor_learning_rate nr = np.random.rand() if nr<randomness: x = tensor(self._initBudget(),device=DEVICE).type(DTYPE) r = torch.rand(len(x)) return (False,x,r) fullInput = list(self.inputVec.values())[ -(self.batch_size-1):] + [inputVec] x = self._prepInput(inputVec=fullInput) if self.curiosity: # add latest MEC reward to the state vector r,_,_ = self._prep_reward(self.reward,randomize=True, normalize=True,curiosity=False) r = Variable(r[-len(x):]).view(-1,1) x = torch.cat([x,r],dim=1) if not output_r: return (True,x,None) else: r_output,_,_ = self._prep_reward(self.reward_curious, randomize=True,normalize=True,curiosity=False) r_output = r_output[-len(x):].view(1,-1) return (True,x,r_output) else: if not output_r: return (True,x,None) else: r,_,_ = self._prep_reward(self.reward,randomize=True, normalize=True,curiosity=False) r_output = r[-len(x):].view(1,-1) return (True,x,r_output) def inference(self,inputVec,randomness=None): exist,x,_ = self._inference_prepInput(inputVec,randomness) if not exist: return x self.actor.eval() with torch.no_grad(): x = x[None, :, :] params = self.actor(x) actions,_,_ = self._chooseAction(params) return torch.clamp(actions[0],0,1) def inference_weightVec(self,phi=None,r=None): output = self.attention.inference(input_tensor=phi,target_tensor=r) output = output * len(output) return output def train(self,time,plmfile,rewardfile,invfile,fwdfile,curMdl=None): self.trainingdata = self.prep_data(time,plmfile, curious=self.curiosity) if self.trainingdata is None: return if not self.curiosity: currentIdx,x,y,r,_,pos = self.trainingdata else: currentIdx,s_t,s_tp1,r,_,_,pos = self.trainingdata s_t = s_t[:-1] # if curiosity model is detached from price learning model x = s_t y = s_tp1 if self.critic is None: self._initCritic(x.shape[-1],1) if self.actor is None and currentIdx>=self.actor_pretrain_nr_record: self._initActor(x.shape[-1],self.dimOutput, self.critic.sharedLayers) if self.attention is None and self.ca: self._initAttention( inputDim=self.actor.sharedLayers.outputDim,outputDim=1) self._saveModel() for epoch in range(self.epoch): # price learning model epoch=1 pointer = 0 epoch_loss_critic = [] epoch_loss_actor = [] epoch_loss_attention = [] epoch_reward_int = [] while pointer+1<len(x): idx = range(pointer,min(pointer+self.batch_size,len(x))) invloss_vec = torch.zeros(len(idx)) fwdloss_vec = torch.zeros(len(idx)) if self.curiosity: invloss_vec,fwdloss_vec = curMdl.train(time, trainingdata=self.trainingdata,invmodelfile=invfile, forwardmodelfile=fwdfile,pretrain=False,idx=idx, sharedLayers=self.actor.sharedLayers) x_batch = x[idx] y_batch = y[idx] r_batch = r[idx] reward = np.nan get_r_weight = (self.actor is not None and self.ca and pointer+self.batch_size<=len(x)) if get_r_weight: r_weight = self.inference_weightVec( phi=self.actor.sharedLayers(x_batch), r=r_batch.type(DTYPE)) r_weight = tensor(r_weight) if r_weight.sum()==0 or torch.isnan(r_weight.sum()): r_weight = torch.ones(len(r_batch)) r_batch = r_batch.view(-1,1) * r_weight.view(-1,1) values = self.critic(x_batch) next_values = self.critic(y_batch) (critic_loss,advantage,self.avg_reward, reward_int) = self._critic_loss_func(values,next_values, r_batch,self.avg_reward,self.reward_rate, invloss_vec,fwdloss_vec) epoch_loss_critic.append(critic_loss) epoch_reward_int.append(reward_int) loss = critic_loss if self.actor is not None: action_params = self.actor(x_batch) actions,log_prob_actions,mean = self._chooseAction( action_params) actor_loss = self._actor_loss_func(log_prob_actions, advantage) epoch_loss_actor.append(actor_loss) loss += actor_loss self.actor_optimizer.zero_grad() self.critic_optimizer.zero_grad() loss.backward() self.actor_optimizer.step() self.critic_optimizer.step() # record intrinsic and extrinsic rewards if self.trainWeightvector[1]: # new ext. reward try: reward_ext_key = str(max([int(k) for k in self.reward_ext.keys()])) reward = self.reward_ext[reward_ext_key] except: pass rewardfile.write('{};{};{};{};{}\n'.format(time, self.unique_id,epoch,reward_int,reward)) rewardfile.flush() # trainWeightVector[0]: true when price learning model # is trained, or when there is new external reward. # trainWeightVector[1]: true when there is new external reward # train weight vector on the last batch before ext. reward if (self.curiosity and pointer+self.batch_size==len(x) and self.trainWeightvector[0]): try: reward_ext_key = str(max([int(k) for k in self.reward_ext.keys()])) except: break reward = self.reward_ext[reward_ext_key] if self.ca: # if attention net: if self.trainWeightvector[1]: # new ext. reward input_tensor = self.actor.sharedLayersOutput.detach().clone() attention_loss = self.attention.train( input_tensor=input_tensor, target_tensor=r_batch.type(DTYPE), end_value=reward) self.attention.trainingdata = (currentIdx,s_t, s_tp1,r) # retrain on new features and past ext. reward else: try: (currentIdx,s_t, s_tp1,r) = self.attention.trainingdata x = s_t x_batch = x[idx] r_batch = r[idx] except: break input_tensor = self.actor.sharedLayers(x_batch).detach().clone() attention_loss = self.attention.train( input_tensor=input_tensor, target_tensor=r_batch.type(DTYPE), end_value=reward) if (attention_loss==np.inf or attention_loss==np.nan or torch.isinf(attention_loss) or torch.isnan(attention_loss)): self._initAttention( inputDim=self.actor.sharedLayers.outputDim, outputDim=1) self._reload(self.attentionpath) else: epoch_loss_attention.append(attention_loss) pointer += 1 if pointer+self.batch_size>len(x): break avgLossCritic = sum(epoch_loss_critic) if len(epoch_loss_critic) > 0: avgLossCritic /= len(epoch_loss_critic) avgLossActor = sum(epoch_loss_actor) if len(epoch_loss_actor) > 0: avgLossActor /= len(epoch_loss_actor) avgLossAttention = sum(epoch_loss_attention) if len(epoch_loss_attention) > 0: avgLossAttention /= len(epoch_loss_attention) else: avgLossAttention = np.nan plmfile.write('{};{};{};{};{};{};{};{}\n'.format(time, self.unique_id,epoch,len(x),self.avg_reward, avgLossCritic, avgLossActor, avgLossAttention)) if avgLossCritic!=0 and torch.isnan(avgLossCritic): plmfile.write( '{};{};{};{};{};{};{};{};critic restarted.\n'.format( time,self.unique_id,epoch,len(x),self.avg_reward, avgLossCritic,avgLossActor,avgLossAttention)) self._initCritic(x.shape[-1],1) self._reload(self.criticpath) if avgLossActor!=0 and torch.isnan(avgLossActor): plmfile.write( '{};{};{};{};{};{};{};{};actor restarted.\n'.format( time,self.unique_id,epoch,len(x),self.avg_reward, avgLossCritic,avgLossActor,avgLossAttention)) self._initActor(x.shape[-1],self.dimOutput, self.critic.sharedLayers) self._reload(self.actorpath) plmfile.flush() self._updateLearningRate() self.trainingdata = None def collectNextState(self,stateVec,idx): envVec = self.inputVec[idx][len(stateVec):] nextState = stateVec + envVec self.nextStateVec[idx] = nextState def collectReward(self,reward,idx,rewardType='in'): if rewardType=='in': if (idx not in self.reward.keys() or self.reward[idx] is None or np.isnan(self.reward[idx])): if idx in self.inputVec.keys(): self.reward[idx] = reward else: self.reward[idx] += reward else: # if rewardType=='ex': self.reward_ext[idx] = reward def update_curiousReward(self,rewardVec): if rewardVec is None: for k in self.reward_normalized.keys(): # add bidding payoff self.reward_curious[k] = (pmp.reward_int_weight * self.reward_normalized[k]) self.trainingdata = None return for (k,v) in rewardVec.items(): self.reward_curious[k] = v # add reward from curiosity model if k in self.reward_normalized.keys(): # add bidding payoff self.reward_curious[k] += (pmp.reward_int_weight * self.reward_normalized[k]) self.reward_curious[k] = ((1-pmp.reward_ext_weight) * self.reward_curious[k]) if k in self.reward_ext.keys(): self.reward_curious[k] += (pmp.reward_ext_weight * self.reward_ext[k]/self.maxReward) self.trainingdata = None class MLP(nn.Module): '''multilayer perceptron as another form of highway ''' def __init__(self,inputDim,outputDim,hidden_size1,hidden_size2): super().__init__() self.batchNorm = nn.BatchNorm1d(inputDim) self.hidden1 = nn.Linear(inputDim,hidden_size1) self.hidden2 = nn.Linear(hidden_size1,hidden_size2) self.batchNorm2 = nn.BatchNorm1d(hidden_size2) self.hidden3 = nn.Linear(hidden_size2,outputDim) def forward(self,x): batchnorm = self.batchNorm(x) hidden1 = F.relu(self.hidden1(batchnorm)) hidden2 = F.relu(self.batchNorm2(self.hidden2(hidden1))) hidden3 = self.hidden3(hidden2) return hidden3 class MLP_Wrapper(nn.Module): '''value function estimator. sigmoid layer is used for output to control the output range. ''' def __init__(self,inputDim,outputDim,hidden_size1,hidden_size2): super().__init__() self.mlp = MLP(inputDim,outputDim,hidden_size1,hidden_size2) self.predict = nn.Sigmoid() # output between 0 and 1 def forward(self,x): mlp = self.mlp(x) predict = self.predict(mlp) return predict class Highway(nn.Module): def __init__(self,in_features,out_features,num_layers=1,bias=0): super().__init__() self.in_features = in_features self.out_features = out_features self.num_layers = num_layers self.bias = bias self.cells = nn.ModuleList() for idx in range(self.num_layers): g = nn.Sequential( nn.Linear(self.in_features, self.out_features), nn.ReLU(inplace=True) ) t = nn.Sequential( nn.Linear(self.in_features, self.out_features), nn.Sigmoid() ) self.cells.append(g) self.cells.append(t) def forward(self,x): for i in range(0,len(self.cells),2): g = self.cells[i] t = self.cells[i+1] nonlinearity = g(x) transformGate = t(x) + self.bias x = nonlinearity * transformGate + (1-transformGate) * x return x class SharedLayers(nn.Module): filter_size = list(np.arange(1,pmp.batch_size,step=2,dtype=int)) def __init__(self,inputDim,outputDim,num_filter): super().__init__() self.num_filter = ([num_filter] + [num_filter * 2] * int(len(self.filter_size)/2) + [num_filter] * len(self.filter_size))[0:len(self.filter_size)] self.num_filter_total = sum(self.num_filter) self.inputDim = inputDim self.outputDim = outputDim if outputDim>0 else self.num_filter_total self.seqLength = pmp.batch_size self.batchNorm = nn.BatchNorm1d(pmp.batch_size) self.convs = nn.ModuleList() for fsize, fnum in zip(self.filter_size, self.num_filter): # kernel_size = depth, height, width conv = nn.Sequential( nn.Conv2d(in_channels=1,out_channels=fnum, kernel_size=(fsize,inputDim), padding=0,stride=1), nn.ReLU(inplace=True), nn.BatchNorm2d(fnum), nn.MaxPool2d(kernel_size=(self.seqLength-fsize+1,1),stride=1) ) self.convs.append(conv) self.highway = Highway(self.num_filter_total,self.num_filter_total, num_layers=1, bias=0) self.compress = nn.Linear(self.num_filter_total,self.outputDim) def forward(self,x): batchnorm = self.batchNorm(x) xs = list() for i,conv in enumerate(self.convs): x0 = conv(batchnorm.view(-1,1,self.seqLength,self.inputDim)) x0 = x0.view((x0.shape[0],x0.shape[1])) xs.append(x0) cats = torch.cat(xs,1) highwayOutput = self.highway(cats) sharedLayersOutput = nn.Sigmoid()(self.compress(highwayOutput)) return sharedLayersOutput class CNNHighway(nn.Module): def __init__(self,inputDim,outputDim,num_filter,dropout_rate, hidden_size1,hidden_size2,sharedlayer_output_dim, sharedLayers): super().__init__() self.inputDim = inputDim self.outputDim = outputDim self.dropout_rate = dropout_rate if sharedLayers is None: self.sharedLayers = SharedLayers(inputDim,sharedlayer_output_dim, num_filter) else: self.sharedLayers = sharedLayers self.sharedLayersOutputDim = self.sharedLayers.outputDim # p: probability of an element to be zeroed. Default: 0.0 self.dropout = nn.Dropout(p=self.dropout_rate) self.fc_conv = nn.Linear(self.sharedLayersOutputDim,outputDim) self.predict = nn.Sigmoid() def forward(self,x): self.sharedLayersOutput = self.sharedLayers(x) dropout = F.relu(self.dropout(self.sharedLayersOutput)) fc_conv = F.relu(self.fc_conv(dropout)) predict = self.predict(fc_conv) return predict class SupervisedModel(Model): supervise_learning_rate = pmp.supervise_learning_rate supervise_hidden_size1 = pmp.supervise_hidden_size1 supervise_hidden_size2 = pmp.supervise_hidden_size2 targetUpperBound = vp.totalBudget[0] def __init__(self,uniqueId,dimOutput=1,evaluation=False,loadModel=False, curiosity=False,maxReward=1): super().__init__(evaluation,loadModel,curiosity,maxReward) self.unique_id = uniqueId + '_supervised' self.dimOutput = dimOutput self.supervise = None # the model self.supervisepath = os.path.join(MODEL_DIR, self.unique_id+'_train_fsp.pkl') def _initBudget(self): ''' random budget split if model is not available ''' return list(np.random.rand(self.dimOutput)) def _reload(self,path): try: checkpoint = torch.load(path) if path==self.supervisepath: self.supervise.load_state_dict(checkpoint) except: pass def _saveModel(self,supervise=True): if supervise: torch.save(self.supervise.state_dict(),self.supervisepath) def _initSupervise(self,inputDim,outputDim): self.supervise = MLP_Wrapper(inputDim,outputDim, self.supervise_hidden_size1,self.supervise_hidden_size2) if DEVICE!=torch.device('cpu'): self.supervise = nn.DataParallel(self.supervise) self.supervise.to(DEVICE) self.supervise_params = list(filter(lambda p: p.requires_grad, self.supervise.parameters())) self.supervise_optimizer = torch.optim.SGD(self.supervise_params, lr=self.supervise_learning_rate) self.loss_func = torch.nn.MSELoss() if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload(self.supervisepath) def inference(self,inputVec,pmdlReward=None): if self.supervise is None: return tensor(self._initBudget(),device=DEVICE).type(DTYPE) if self.curiosity: # add latest MEC reward to the state vector fullInput = list(self.inputVec.values())[ -(self.batch_size-1):] + [inputVec] x = self._prepInput(inputVec=fullInput) r,_,_ = self._prep_reward(pmdlReward,randomize=False, normalize=True,curiosity=False) r = Variable(r[-len(x):]).view(x.shape[0],1) x = torch.cat([x,r],dim=1) else: x = self._prepInput(inputVec=inputVec) x = x.reshape(1,-1) self.supervise.eval() actions = self.supervise(x) return torch.clamp(actions[0],0,1) def train(self,time,supervisefile,pmdlReward): trainingdata = self.prep_data(time,supervisefile,reward=pmdlReward, reward_curious=pmdlReward,inputVec=self.inputVec, nextStateVec=self.inputVec,output=self.output, curious=self.curiosity,model='supervisedModel') if trainingdata is not None: if not self.curiosity: currentIdx,x,_,_,y,_ = trainingdata else: currentIdx,x,_,_,y,_,_ = trainingdata else: return x = x.view(x.size()[0],-1) if self.supervise is None: self._initSupervise(x.shape[1],self.dimOutput) self._saveModel() if len(x)<self.batch_size: replace = True else: replace = False for epoch in range(self.epoch_supervise): epoch_loss_supervise = [] idx = np.random.choice(len(x),size=self.batch_size, replace=replace) x_batch = x[idx] y_batch = y[idx] prediction = self.supervise(x_batch) supervise_loss = self.loss_func(prediction, y_batch) self.supervise_optimizer.zero_grad() supervise_loss.backward() self.supervise_optimizer.step() epoch_loss_supervise.append(supervise_loss) avgLossSupervise = sum(epoch_loss_supervise) if len(epoch_loss_supervise) > 0: avgLossSupervise /= len(epoch_loss_supervise) supervisefile.write('{};{};{};{};{}\n'.format(time, self.unique_id,epoch,len(x),avgLossSupervise)) if avgLossSupervise!=0 and torch.isnan(avgLossSupervise): supervisefile.write( '{};{};{};{};{};supervised learning restarted.\n'.format( time,self.unique_id,epoch,len(x),avgLossSupervise)) self._initSupervise(x.shape[1],self.dimOutput) self._reload(self.supervisepath) supervisefile.flush() class InverseModel(nn.Module): '''The inverse module in curiosity model ''' def __init__(self,feature_hidden_size1,feature_hidden_size2, inv_hidden_size1,inv_hidden_size2,outputDim, sharedLayers=None): if sharedLayers is None: return super().__init__() self.features = sharedLayers self.feature_outputDim = sharedLayers.outputDim inv_inputDim = 2 * self.feature_outputDim self.batchNorm = nn.BatchNorm1d(inv_inputDim) self.hidden1 = nn.Linear(inv_inputDim,inv_hidden_size1) self.hidden2 = nn.Linear(inv_hidden_size1,inv_hidden_size2) self.batchNorm2 = nn.BatchNorm1d(inv_hidden_size2) self.hidden3 = nn.Linear(inv_hidden_size2,outputDim) self.predict = nn.Sigmoid() def forward(self,oldstate,newstate): # states: (batchsize,batchsize,featureDim) # features (sharedlayers) output: (batchsize,sharedlayers.outputDim) # cat output (batchnorm1d input): (batchsize,2xsharedlayers.outputDim) # therefore the size of batchnorm1d should be 2xsharedlayers.outputDim oldfeatures = self.features(oldstate) self.oldfeatures = oldfeatures.detach().clone() newfeatures = self.features(newstate) self.newfeatures = newfeatures.detach().clone() x = torch.cat((oldfeatures,newfeatures),-1) batchnorm = self.batchNorm(x) hidden1 = F.relu(self.hidden1(batchnorm)) hidden2 = F.relu(self.batchNorm2(self.hidden2(hidden1))) hidden3 = self.hidden3(hidden2) predict = self.predict(hidden3) return predict class ForwardModel(nn.Module): '''The forward module in curiosity model ''' feature_hidden_size1 = cmp.feature_hidden_size1 feature_hidden_size2 = cmp.feature_hidden_size2 def __init__(self,inputDim_action, forward_hidden_size1,forward_hidden_size2,outputDim, sharedLayers=None): if sharedLayers is None: return super().__init__() self.features = sharedLayers self.feature_outputDim = sharedLayers.outputDim forward_inputDim = inputDim_action + self.feature_outputDim self.batchNorm = nn.BatchNorm1d(forward_inputDim) self.hidden1 = nn.Linear(forward_inputDim,forward_hidden_size1) self.hidden2 = nn.Linear(forward_hidden_size1,forward_hidden_size2) self.batchNorm2 = nn.BatchNorm1d(forward_hidden_size2) self.hidden3 = nn.Linear(forward_hidden_size2,outputDim) self.predict = nn.Sigmoid() def forward(self,action,oldstate): oldfeatures = self.features(oldstate) x = torch.cat((action,oldfeatures),-1) batchnorm = self.batchNorm(x) hidden1 = F.relu(self.hidden1(batchnorm)) hidden2 = F.relu(self.batchNorm2(self.hidden2(hidden1))) hidden3 = self.hidden3(hidden2) predict = self.predict(hidden3) return predict class Curiosity(Model): feature_hidden_size1 = cmp.feature_hidden_size1 feature_hidden_size2 = cmp.feature_hidden_size2 inv_hidden_size1 = cmp.inv_hidden_size1 inv_hidden_size2 = cmp.inv_hidden_size2 inv_learning_rate = cmp.inv_learning_rate forward_hidden_size1 = cmp.forward_hidden_size1 forward_hidden_size2 = cmp.forward_hidden_size2 forward_learning_rate = cmp.forward_learning_rate batch_size = cmp.batch_size epoch = cmp.epoch def __init__(self,uniqueId, dimAction=1,evaluation=False,loadModel=False,maxReward=1): super().__init__(evaluation,loadModel,curiosity=True, maxReward=maxReward) self.unique_id = uniqueId + '_curious' self.dimOutput_action = dimAction self.invmodel = None # the inverse model self.invmodelpath = os.path.join(MODEL_DIR, self.unique_id+'_train_inv.pkl') self.forwardmodel = None # the forward model self.forwardmodelpath = os.path.join(MODEL_DIR, self.unique_id+'_train_forward.pkl') self.reward = None self.sharedLayers = None def _initSharedLayers(self,sharedLayers=None): if self.sharedLayers is None: self.sharedLayers = sharedLayers self.feature_outputDim = sharedLayers.outputDim def _initOutput_action(self): ''' random output if inverse model is not available ''' return list(np.random.rand(self.dimOutput_action)) def _initOutput_features(self): ''' random output if forward model is not available ''' return list(np.random.rand(self.feature_outputDim)) def _reload_invmodel(self,path): try: checkpoint = torch.load(path) if path==self.invmodelpath: self.invmodel.load_state_dict(checkpoint) except: pass def _reload_forwardmodel(self,path): try: checkpoint = torch.load(path) if path==self.forwardmodelpath: self.forwardmodel.load_state_dict(checkpoint) except: pass def _saveModel(self,invmodel=True,forwardmodel=True): if invmodel and self.invmodel is not None: torch.save(self.invmodel.state_dict(),self.invmodelpath) if forwardmodel and self.forwardmodel is not None: torch.save(self.forwardmodel.state_dict(),self.forwardmodelpath) def _initInvmodel(self,sharedLayers=None): self._initSharedLayers(sharedLayers) self.invmodel = InverseModel( self.feature_hidden_size1,self.feature_hidden_size2, self.inv_hidden_size1,self.inv_hidden_size2, self.dimOutput_action,self.sharedLayers) if DEVICE!=torch.device('cpu'): self.invmodel = nn.DataParallel(self.invmodel) self.invmodel.to(DEVICE) self.invmodel_params = list(filter(lambda p: p.requires_grad, self.invmodel.parameters())) self.invmodel_optimizer = torch.optim.SGD(self.invmodel_params, lr=self.inv_learning_rate) self.invmodel_loss_func = torch.nn.MSELoss() if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload_invmodel(self.invmodelpath) def _initForwardmodel(self): if self.invmodel is None: return self.forwardmodel = ForwardModel(self.dimOutput_action, self.forward_hidden_size1,self.forward_hidden_size2, self.feature_outputDim,self.invmodel.features) if DEVICE!=torch.device('cpu'): self.forwardmodel = nn.DataParallel(self.forwardmodel) self.forwardmodel.to(DEVICE) self.forwardmodel_params = list(filter(lambda p: p.requires_grad, self.forwardmodel.parameters())) self.forwardmodel_optimizer = torch.optim.SGD(self.forwardmodel_params, lr=self.forward_learning_rate) self.forwardmodel_loss_func = torch.nn.MSELoss() if self.evaluation or self.loadModel: # evaluation: only run inference with previously trained model # loadModel: load pre-trained model self._reload_forwardmodel(self.forwardmodelpath) def _calc_reward(self,pos,oldInputVec_state,newInputVec_state, inputVec_actualAction): idx = range(len(oldInputVec_state)) s_t_batch = oldInputVec_state[idx] s_tp1_batch = newInputVec_state[idx] a_f_batch = inputVec_actualAction[idx] a,phi,phi_tp1 = self.inference_invmodel(s_t_batch,s_tp1_batch) phi_tp1_hat = self.inference_forwardmodel( s_t_batch,a_f_batch).detach().numpy() phi_tp1 = phi_tp1.detach().numpy() a_i_batch = a.detach().numpy() a_f_batch = a_f_batch.detach().numpy() invLoss = list(((a_i_batch-a_f_batch)**2).mean(axis=1)) fwdLoss = list(((phi_tp1-phi_tp1_hat)**2).mean(axis=1)) predLoss = fwdLoss keys = [str(k) for k in pos] self.reward = dict([(k,(1-pmp.reward_int_weight)*v) for (k,v) in zip(keys,predLoss)]) def inference_invmodel(self,oldInputVec_state,newInputVec_state): if self.invmodel is None: return (tensor(self._initOutput_action(), device=DEVICE).type(DTYPE), tensor(self._initOutput_features(), device=DEVICE).type(DTYPE), tensor(self._initOutput_features(), device=DEVICE).type(DTYPE)) self.invmodel.eval() actions = self.invmodel(oldInputVec_state,newInputVec_state) newfeatures = self.invmodel.newfeatures oldfeatures = self.invmodel.oldfeatures return torch.clamp(actions,0,1), oldfeatures, newfeatures def inference_forwardmodel(self,oldInputVec_state,actualAction): self.forwardmodel.eval() newstate = self.forwardmodel(actualAction,oldInputVec_state) return newstate def train(self,time,trainingdata,invmodelfile,forwardmodelfile, pretrain=True,idx=None,sharedLayers=None): if trainingdata is None: return None,None (currentIdx,oldInputVec_state,newInputVec_state,_, actualAction_inv,actualAction_fwd,pos) = trainingdata s_t = oldInputVec_state[:-1] s_tp1 = newInputVec_state a_t_inv = actualAction_inv[:-1] a_t_fwd = actualAction_fwd[:-1] pos = pos[:-1] if self.invmodel is None: self._initInvmodel(sharedLayers) self._initForwardmodel() self._saveModel() if len(s_t)<self.batch_size: replace = True else: replace = False training_epoch = 1 if pretrain: training_epoch = self.epoch for epoch in range(training_epoch): epoch_loss_invmodel = [] epoch_loss_forwardmodel = [] if pretrain or idx is None: idx = np.random.choice(len(s_t),size=self.batch_size, replace=replace) s_t_batch = s_t[idx] s_tp1_batch = s_tp1[idx] a_i_batch = a_t_inv[idx] a_f_batch = a_t_fwd[idx] action_pred = self.invmodel(s_t_batch,s_tp1_batch) invmodel_loss = self.invmodel_loss_func(action_pred,a_i_batch) invloss_vec = (action_pred-a_i_batch).pow(2).mean(dim=-1) if pretrain: self.invmodel_optimizer.zero_grad() invmodel_loss.backward() self.invmodel_optimizer.step() epoch_loss_invmodel.append(invmodel_loss.detach()) newfeature_actual = self.invmodel.newfeatures feature_pred = self.forwardmodel(a_f_batch,s_t_batch) forwardmodel_loss = self.forwardmodel_loss_func(feature_pred, newfeature_actual) fwdloss_vec = (feature_pred-newfeature_actual).pow(2).mean(dim=-1) if pretrain: self.forwardmodel_optimizer.zero_grad() forwardmodel_loss.backward() self.forwardmodel_optimizer.step() epoch_loss_forwardmodel.append(forwardmodel_loss.detach()) avgLossInvmodel = sum(epoch_loss_invmodel) avgLossForwardmodel = sum(epoch_loss_forwardmodel) if len(epoch_loss_invmodel) > 0: avgLossInvmodel /= len(epoch_loss_invmodel) if len(epoch_loss_forwardmodel) > 0: avgLossForwardmodel /= len(epoch_loss_forwardmodel) if pretrain: invmodelfile.write('{};{};{};{};{}\n'.format(time, self.unique_id,epoch,len(s_t),avgLossInvmodel)) invmodelfile.flush() forwardmodelfile.write('{};{};{};{};{}\n'.format(time, self.unique_id,epoch,len(s_t),avgLossForwardmodel)) forwardmodelfile.flush() if avgLossInvmodel!=0 and torch.isnan(avgLossInvmodel): invmodelfile.write( '{};{};{};{};{};inverse model learning restarted.\n'.format( time,self.unique_id,epoch,len(s_t),avgLossInvmodel)) invmodelfile.flush() self._initInvmodel(self.sharedLayers) self._reload_invmodel(self.invmodelpath) if avgLossForwardmodel!=0 and torch.isnan(avgLossForwardmodel): forwardmodelfile.write( '{};{};{};{};{};forward model learning restarted.\n'.format( time,self.unique_id,epoch,len(s_t),avgLossForwardmodel)) forwardmodelfile.flush() self._initForwardmodel() self._reload_forwardmodel(self.forwardmodelpath) self._calc_reward(pos,s_t,s_tp1,a_t_fwd) return invloss_vec,fwdloss_vec
58,987
42.373529
106
py
malfoy
malfoy-master/v2x/solutions/v2x.py
# -*- coding: utf-8 -*- from ..utils.common_utils import CommonUtils as utCom from ..supports.data import (ServiceType,ServiceAmount,ServiceProposal, ResourceSiteDistance,SiteType,BidStatus,BidState, BidFailureReason as bfr,QoSType,Task,DefaultProfile, ResourceName,ResourceType,Resource, SecondPriceData as sec,CompetitorBaseData as cbd, TraceData) from ..config.config import (RESOURCE_SITE_PARAMS as rsp,SERVICE_PARAMS as sp, VEHICLE_PARAMS as vp, BID_PARAMS as bp, MDL_PARAMS as mp, RSU_PARAMS as rp, TRANSITION_PARAMS as tp, \ PRICE_MODEL_PARAMS as pmp, FILES,COUNTDOWN_FILE,BATCHCREATE_FILE, MODEL_DIR,LOGS_DIR) from ..solutions.price_model_curious import (PriceLearningModel as plm, SupervisedModel as spv, Curiosity as cur) import numpy as np import pandas as pd from scipy.stats import truncnorm from collections import Counter from scipy.stats import expon import os,sys,re from mesa import Agent, Model from mesa.time import SimultaneousActivation from mesa.space import MultiGrid import weakref import pickle class ResourceSite(Agent): ''' step:. estimate: 1. release resource from finished tasks. 2. adjust services capacity based on updated resource profiles. 3. collect resource and service information for the next time step (after the release of resources). 4. estimate time and cost of each bid. ResourceSite.estimTimeInSystem called from Bid.estimate. allocate:. advance: load newly assigned tasks to service queues. ''' _instances = set() serviceCapa = {(SiteType.TYPE1,ServiceType.TYPE1):rsp.serviceCapa[0], (SiteType.TYPE1,ServiceType.TYPE2):rsp.serviceCapa[1], (SiteType.TYPE2,ServiceType.TYPE1):rsp.serviceCapa[0], (SiteType.TYPE2,ServiceType.TYPE2):rsp.serviceCapa[1], (SiteType.TYPE3,ServiceType.TYPE1):rsp.serviceCapa[2], (SiteType.TYPE3,ServiceType.TYPE2):rsp.serviceCapa[2]} transCost = rsp.transCost burnIn = rsp.burnIn lowerCapaLimit = rsp.lowerCapaLimit upperCapaLimit = rsp.upperCapaLimit resProfileSelectionThreshold = rsp.resProfileSelectionThreshold randomizeQueueTimeThres = rsp.randomizeQueueTimeThres def __init__(self,uniqueId,sitetype,resourceCapaIdx,model): super().__init__(uniqueId, model) self.unique_id = uniqueId self.sitetype = sitetype self.pos = (0,0) # coordinate of the resource site self.availBudget = 0 # dummy variable self.resourceCapa = None self._updateResCapa(resourceCapaIdx) self.servicelist = dict() # list of service ids self.resourcelist = dict() # list of resource ids self.bidlist = list() # list of bids allocated by the RSU self.currentTimeInSys = dict() # expected waiting time in queue self.maxAmounts = dict() # queue+server capacity of services self.currentCost = dict() # cost of one unit of service self.currentOccupied = dict() # occupied service units self.predictOccupied = dict() # predicted occupied service units # based on predicted service utilization self.currentUtilization = dict() # utilization of service capacities self.currentResourceOccupied = dict() # resource occupied by servers self.currentResourceUtilization = dict() # resource utilized by servers self.toBeReleased = dict() # resource to release from finished tasks self.siteInfo = dict() # information of other sites self.prevBidCounter = 0 # record the previous time step's nr bids self.bidCounter = 0 # record current time step's nr bids self.serviceOccupiedHistory = dict() # history of service occupied self.serviceMaxAmountHistory = dict() self.randomizeQueueTimeHistory = dict() # history of waiting time self.randomizeQueueTimeParams = dict() # mean and std of queue length self.paramsHistory = dict() # history of randomization params self._populate() self._instances.add(weakref.ref(self)) def _updateResCapa(self,idx): self.resourceCapa = { (SiteType.TYPE1,ResourceType.TYPE1):rsp.resourceCapa[idx][0], (SiteType.TYPE1,ResourceType.TYPE2):rsp.resourceCapa[idx][1], (SiteType.TYPE2,ResourceType.TYPE1):rsp.resourceCapa[idx][0], (SiteType.TYPE2,ResourceType.TYPE2):rsp.resourceCapa[idx][1], (SiteType.TYPE3,ResourceType.TYPE1):rsp.resourceCapa[idx][2], (SiteType.TYPE3,ResourceType.TYPE2):rsp.resourceCapa[idx][2]} try: for key in self.resourcelist.keys(): self.maxAmounts[key] += np.random.randint( *self.resourceCapa[(self.sitetype,key[1])]) res = self.resourcelist[key] res.maxAmount = self.maxAmounts[key] for servKeys in res.occupied.keys(): res._updateInfo(servKeys[0],servKeys[1],0, self.model.schedule.steps) except: pass def _populate(self): ''' populate ResourceSite with resources and services. Currently: every ResourceSite has all available resources and service types in the system. ''' resources = utCom.listClassVariables(ResourceName,'__',include=False) resCosts = dict() for resName,resType in resources: self.maxAmounts[(resName,resType)] = np.random.randint( *self.resourceCapa[(self.sitetype,resType)]) newRes = Resource(resName,resType, str(self.unique_id)+'_'+str(resName), self.maxAmounts[(resName,resType)]) self.resourcelist[(resName,resType)] = newRes resCosts[(resName,resType)] = newRes.cost self.toBeReleased[(resName,resType)] = list() self._getResourceInfo(resName,resType) resCosts = utCom.recreateDict(self.resourcelist,'cost') services = cbd.services for servName,servType in services: self.maxAmounts[(servName,servType)] = np.random.randint( *self.serviceCapa[(self.sitetype,servType)]) newServ = Service(servName,servType, str(self.unique_id)+'_'+str(servName), self.unique_id,self.sitetype,resCosts,self.model, self.maxAmounts[(servName,servType)]) self.servicelist[(servName,servType)] = newServ self.model.schedule.add(newServ) self.model.servicelist[newServ.unique_id] = newServ self._getServiceInfo(servName,servType) for res in newServ.resNeedsAvg.keys(): resAmount = (newServ.resNeedsAvg[res][0] * newServ.serviceCapacity) self.resourcelist[res].maxAmount += resAmount _ = self.resourcelist[res].allocateResource(servName,servType, resAmount,self.model.schedule.steps) def _estimTaskDuration(self,task,serv,qos=None): ''' estimates duration of given task. called by estimTimeInSystem, which is called by Bid.estimate. this function calls _selectResourceProfile by default. However if a specific qos requirement is given, the function calls Service.estimateResourceAmount and Service.estimateServiceDuration directly. @param task: given task to be evaluated @param serv: service object required @param qos: required quality of service (time to finish) @return: selected resource profile, estimated task cost, estimated task duration. ''' if qos is None: profile = self._selectResourceProfile(task.resProfileOriginal, task.serviceName, task.serviceType) else: profile = serv.estimateResourceAmount(qos/task.serviceAmount) resAmounts = utCom.recreateDict(profile,0) feasible,_ = self.checkResFeasibility(resAmounts,serv.serviceName, serv.serviceType) if not feasible: return None cost = serv.calculateUnitCost(profile) * task.serviceAmount if qos is None: duration = serv.estimateServiceDuration( resAmounts) * task.serviceAmount else: duration = qos return profile,cost,duration def _getResourceInfo(self,resName,resType): ''' collect resource information in ResourceSite.estimate. @param resName: name of resource @param resType: type of resource ''' res = self.resourcelist[(resName,resType)] self.maxAmounts[(resName,resType)] = res.maxAmount self.currentResourceOccupied[(resName,resType)] = res.occupied self.currentResourceUtilization[(resName,resType)] = np.round( res.utilization,1) def _getServiceInfo(self,servName,servType,prediction=True): ''' collect service information in ResourceSite.estimate. @param servName: name of service @param servType: type of service @param prediction: if true: use predictive methods to forecast utilization and estimate cost of one unit of service. if false: use the most recent utilization value. ''' key = (servName,servType) serv = self.servicelist[key] self.currentCost[key] = serv.calculateUnitCost(serv.resNeedsAvg, prediction) self.currentOccupied[key] = serv.occupied self.predictOccupied[key] = serv.predictedUtil * serv.maxAmount if key not in self.serviceOccupiedHistory.keys(): self.serviceOccupiedHistory[key] = list() self.serviceMaxAmountHistory[key] = list() self.randomizeQueueTimeHistory[key] = list() self.randomizeQueueTimeParams[key] = (1,0) buffer = int(max(500,rsp.randomizeQueueTimeThres*2)) self.serviceOccupiedHistory[key].append(serv.occupied) if len(self.serviceOccupiedHistory[key])>buffer: self.serviceOccupiedHistory[key] = self.serviceOccupiedHistory[key][-buffer:] self.serviceMaxAmountHistory[key].append(serv.maxAmount) if len(self.serviceMaxAmountHistory[key])>buffer: self.serviceMaxAmountHistory[key] = self.serviceMaxAmountHistory[key][-buffer:] self.randomizeQueueTimeHistory[key].append( [serv.occupied,self.prevBidCounter,1]) if len(self.randomizeQueueTimeHistory[key])>buffer: self.randomizeQueueTimeHistory[key] = self.randomizeQueueTimeHistory[key][-buffer:] self.currentUtilization[key] = np.round(serv.utilization,1) self.maxAmounts[key] = serv.maxAmount serviceTime = int(max([x[1] for x in serv.resNeedsAvg.values()])) try: avgServiceAmountPerTask = int(np.round(serv.occupied / (len(serv.queuelist)+len(serv.servicelist)),decimals=0)) except: avgServiceAmountPerTask = 1 if len(serv.queuelist)>0: self.currentTimeInSys[key] = (serv.estimTimeInQueue + serviceTime * avgServiceAmountPerTask) elif (len(serv.servicelist)*avgServiceAmountPerTask <serv.serviceCapacity): self.currentTimeInSys[key] = 0 else: self.currentTimeInSys[key] = serviceTime * avgServiceAmountPerTask def _adjustCapacity(self): ''' Adjusts queue and service capacity based on updated resource profile. Trigger is Service.resNeedsRequested information from Service._genActualServiceDuration called in Service.advance. The value is generated by Service._estimateResNeedCurve() which runs a linear regression of duration vs. resource amount based on historical records of actual resource needs. To prevent jitters, adjustments are done with minimum interval controlled by Service.recentCapaDecrease, Service.recentCapaIncrease and Service.avgCapacityPeriod. For previously over-estimated resource profiles: simply release the excess. For previously under-estimated resource profiles: an increase in allocated resource to the service needs to be 1. prioritized between services, based on the urgency of the need; and 2. checked for feasibility among all resources. ''' if self.model.schedule.steps <= self.burnIn: return required = dict() for servNameType in self.servicelist.keys(): serv = self.servicelist[servNameType] # update resource needs after new estimation of resource # need becomes available. no change to capacity if serv.resNeedsRequested is not None: oldMax = serv.serviceCapacity newMax = self._adjustResAllocation(servNameType, serv.resNeedsRequested) serv.updateUtilization(0,newMax-oldMax) serv.resNeedsRequested = None # update capacity if (len(serv.occupiedHistory)>=serv.avgCapacityPeriod): peak = max(list( serv.occupiedHistory.values())[-serv.avgCapacityPeriod:]) else: peak = max(list(serv.occupiedHistory.values())) # in case of recent overflow if (len(serv.overCapacityHistory)>0 and max([int(x) for x in serv.overCapacityHistory.keys()]) >= self.model.schedule.steps - serv.avgCapacityPeriod): peak = serv.maxAmount req = peak + serv.capacityBuffer * serv.maxAmount reqPerc = req/serv.maxAmount if (reqPerc < self.lowerCapaLimit and serv.recentCapaDecrease < self.model.schedule.steps - serv.avgCapacityPeriod): released = -int(serv.serviceCapacity / 2) # make sure serviceCapacity is at least 1 if released == -serv.serviceCapacity: released += 1 for res in serv.resNeedsEstim.keys(): _ = self.resourcelist[res].allocateResource( servNameType[0],servNameType[1], released,self.model.schedule.steps) serv.updateUtilization(0,diffMax=released) elif (reqPerc >= self.upperCapaLimit and serv.recentCapaIncrease < self.model.schedule.steps - serv.avgCapacityPeriod): required[servNameType] = 2 * serv.serviceCapacity # total required # prioritize service by amount of resource increase required. for servNameType in sorted(required,key=required.get,reverse=True): serv = self.servicelist[servNameType] oldMax = serv.serviceCapacity if required[servNameType]==oldMax or required[servNameType]<=0: break resAmount = dict([(k,serv.resNeedsAvg[k][0]*required[servNameType]) for k in serv.resNeedsAvg.keys()]) # check feasibility of the increase newMax = self._adjustResAllocation(servNameType,resAmount) serv.updateUtilization(0,newMax-oldMax) def _adjustResAllocation(self,servNameType,requestResAmount): ''' check feasibility of a resource allocation increase to a service. called by ResourceSite._adjustCapacity from ResrouceSite.estimate. @param servNameType: (service name, service type) key. @param requestResAmount: new maximum resource amounts requested ( when service capacity is fully utilized). @return: new value for the service's maximum capacity, based on availability of resources. ''' serv = self.servicelist[servNameType] originalMax = dict([(k,self.resourcelist[k].allocated[servNameType]) for k in requestResAmount.keys()]) requested = dict([(k,requestResAmount[k]-originalMax[k]) for k in requestResAmount.keys()]) key = list(requested.keys())[0] requestServAmount = int(requestResAmount[key] / serv.resNeedsAvg[key][0]) feasible,diffAmount = self.checkResFeasibility( requested,servNameType[0],servNameType[1], capaChange=True) newMaxAmountService = max(requestServAmount, serv.occupied) if not feasible: diffAmount = dict([(k,diffAmount[k]) for k in diffAmount.keys() if serv.resNeedsAvg[k][0]>0]) reduce = [int(diffAmount[k]/serv.resNeedsAvg[k][0]) for k in diffAmount.keys() if int(diffAmount[k] /serv.resNeedsAvg[k][0])==int(min(diffAmount.values()) /serv.resNeedsAvg[k][0])][0] newMaxAmountService = max(newMaxAmountService + reduce, 1) actualDiff = dict() for res in requestResAmount.keys(): requested[res] = (newMaxAmountService * serv.resNeedsAvg[res][0] - originalMax[res]) resource = self.resourcelist[res] _,actualDiff[res] = resource.allocateResource(servNameType[0], servNameType[1],requested[res],self.model.schedule.steps) if not np.alltrue([x==0 for x in actualDiff.values()]): reduce = [int(actualDiff[k]/serv.resNeedsAvg[k][0]) for k in actualDiff.keys() if int(actualDiff[k] /serv.resNeedsAvg[k][0])==int(min(actualDiff.values()) /serv.resNeedsAvg[k][0])][0] newMaxAmountService = max(newMaxAmountService + reduce, 1) return newMaxAmountService def _selectResourceProfile(self,userResProfile,servName,servType): ''' placeholder for more sophisticated resource profile selection. currently: if ResourceSite has seen the service enough times, it uses its own resource profile learned from the past. Else it takes the suggested resource profile from the vehicle. Currently: actual resource consumed is generated when task is loaded to server for processing through Service._genActualServiceDuration which is called in Service._loadService by Service.advance. The actual resource consumed value is drawn from data.DefaultProfile. duration is a inverse function of amount, however in Service.estimateServiceDuration and Service.estimateResourceAmount, a linear approximation is used. this function is called by ResourceSite._estimTaskDuration which is called by ResourceSite.estimTimeInSystem in Bid.estimate. The selected profile is used if the estimated duration is within the bid's qos requirements. @param userResProfile: resource profile suggested by the vehicle @param servName: required service name @param servType: required service type @return: resource amount required for the service as given by the selected resource profile. ''' serv = self.servicelist[(servName,servType)] if len(serv.servicedTaskHistory) < self.resProfileSelectionThreshold: return userResProfile else: qos = max([x[1] for x in userResProfile.values()]) return serv.estimateResourceAmount(qos) def _load(self): ''' load newly assigned tasks to services queues. called from ResourceSite.advance. function through Service.loadQueue. ''' for bidId in self.bidlist: bid = self.model.bidlist[bidId] # in transit bids if bid.transmissionTimeToGo > 0: bid.updateResult(BidStatus.TRANSMIT,self.model.schedule.steps) bid.transmissionTimeToGo -= 1 continue bid.updateResult(BidStatus.PROCESS,self.model.schedule.steps) task = bid.chain[bid.currentTask] if (not task.isInQueue): try: resAmounts = utCom.recreateDict(task.resProfileSelected,0) except: resAmounts = utCom.recreateDict(task.resProfileOriginal,0) serv = self.servicelist[(task.serviceName,task.serviceType)] taskDuration = serv.estimateServiceDuration( resAmounts) * task.serviceAmount if (taskDuration + serv.estimTimeInQueue > bid.dueTime): queuetime = None else: binding,queuetime = serv.loadQueue(task.unique_id,bidId, task.serviceAmount,resAmounts) if queuetime is not None: bid.priority = 0 # reset priority task.serviceBinding = binding task.updateQueueTime(queuetime,self.model.schedule.steps) else: bid.priority += 1 # increase bid priority bid.updateResult(BidStatus.REALLOCATE, self.model.schedule.steps) def checkResFeasibility(self,resAmounts,servName,servType, capaChange=False): ''' check if the requested resource amount is feasible and can be assigned. called by ResourceSite._adjustCapacity from ResourceSite.estimate and Service._loadService from Service.advance. @param resAmounts: requests resource amounts @param servName: service name @param servType: service type @param capaChange: if the resource request comes from ResourceSite._adjustCapacity, then capaChange is true. if it is to check feasibility at the time of Service._loadService, then it is false. @return: if the resource requested can be assigned, and if there are discrepancies between requested and assigned, the difference is also returned. ''' if not capaChange: difference = [self.resourcelist[k].checkResourceFeasibility( servName,servType,resAmounts[k]) for k in resAmounts.keys()] else: difference = [self.resourcelist[k].allocateResource(servName, servType,resAmounts[k],self.model.schedule.steps, estim=True) for k in resAmounts.keys()] feasible = np.alltrue([x[0] for x in difference]) diffAmount = [x[1] for x in difference] return feasible, dict(zip(resAmounts.keys(),diffAmount)) def randomizeQueueTime(self): ''' randomize estimate of expected time in queue. The ResourceSite.randomizeQueueTimeHistory is the record of service capacity occupied and actual number of bids in queue at the time, collected in ResourceSite._getServiceInfo from ResourceSite.estimate. This data will be the input to a linear regression model with the target of the actual service capacity occupied in the following time step. The result is a parameterized linear model to predict next time step's occupied service capacity. randomness is added from the distribution of the residuals. This affects the price offer from the resource site. Params are stored in ResourceSite.randomizeQueueTimeParams, and used in ResourceSite.estimTimeInSystem called from Bid.estimate. this function is called in ResourceSite.step. ''' for key in self.randomizeQueueTimeHistory.keys(): if (len(self.randomizeQueueTimeHistory[key]) >= self.randomizeQueueTimeThres): x = np.array(self.randomizeQueueTimeHistory[key][:-1]) y = self.serviceOccupiedHistory[key][1:] try: params = np.linalg.lstsq(x,y,rcond=None)[0] except: params = np.zeros(x.shape[1]) residuals = y - np.dot(x, params) self.randomizeQueueTimeParams[key] = (np.mean(residuals), np.std(residuals)) if key not in self.paramsHistory.keys(): self.paramsHistory[key] = list() self.paramsHistory[key].append((params,residuals)) def estimTimeInSystem(self,bidId): ''' estimates for the given bidId the total cost and duration, based on a snapshot of the current service utilization. if the default resource profile cannot meet qos requirements, a reverse calculation is done to get the required resource amount. the function is called from Bid.estimate. @param bidId: unique_id of the bid in question. @return: total estimated duration for the bid, leftover time until requested qos, selected resource profile for each service in bid, total estimated cost for the bid, and duration to transmit the data from another site if applicable. ''' bid = self.model.bidlist[bidId] pos = bid.currentTask waitingTime = dict() taskDuration = dict() transDuration = 0 estimCost = dict() transCost = 0 resProfile = dict() # list of dictionaries leftover = 0 maxIter = 10 for i in np.arange(pos,len(bid.chain)): task = bid.chain[i] servNameType = (task.serviceName,task.serviceType) serv = self.servicelist[servNameType] if ( (i==pos) and (task.serviceAmount +self.currentOccupied[servNameType] >=self.maxAmounts[servNameType]) ): # if queue is full return 0,0,resProfile,sys.maxsize,0 # waiting time estimate in queue if self.currentOccupied[servNameType]==0: waitingTime[str(i)] = 0 else: waitingTime[str(i)] = int(serv.estimTimeInQueue + serv.estimTimeInQueue / serv.occupied * np.random.normal( *self.randomizeQueueTimeParams[servNameType])) # task duration estimate for the current task result = self._estimTaskDuration(task,serv,None) if result is None: # if resource is fully utilized return 0,0,resProfile,sys.maxsize,0 resProfile[str(i)],estimCost[str(i)],taskDuration[str(i)] = result leftover = (bid.dueTime - self.model.schedule.steps - sum(waitingTime.values()) - sum(taskDuration.values()) ) transDuration = self.siteInfo.getWiredLatency(bid.siteBinding, self.unique_id,bid.datasize) leftover -= transDuration transCost = self.transCost * self.siteInfo.distanceMatrix[ (bid.siteBinding,self.unique_id)] count = 0 while leftover<0 and count<maxIter: taskIdx = max(taskDuration,key=taskDuration.get) leftover -= taskDuration[taskIdx] task = bid.chain[int(taskIdx)] serv = self.servicelist[(task.serviceName,task.serviceType)] qos = int(max(1,taskDuration[taskIdx] / 2)) result = self._estimTaskDuration(task,serv,qos) if result is None: return 0,0,resProfile,sys.maxsize,0 resProfile[taskIdx],estimCost[taskIdx],taskDuration[taskIdx]=result leftover += taskDuration[taskIdx] count += 1 if leftover < 0: return 0,0,resProfile,sys.maxsize,0 totalDuration = int(sum(waitingTime.values()) + sum(taskDuration.values()) + transDuration) totalCost = int(sum(estimCost.values()) + transCost) self.bidCounter += 1 return totalDuration,leftover,resProfile,totalCost,int(transDuration) def step(self): self.prevBidCounter = self.bidCounter self.bidCounter = 0 self.randomizeQueueTime() def estimate(self): for res in self.toBeReleased.keys(): for taskId in self.toBeReleased[res]: self.resourcelist[res].endTask(taskId, self.model.schedule.steps) self.toBeReleased[res] = list() self._adjustCapacity() for res in self.resourcelist.keys(): self._getResourceInfo(*res) for serv in self.servicelist.keys(): self._getServiceInfo(*serv) def allocate(self): pass def advance(self): self._load() @classmethod def getInstances(cls): nonexistent = set() for ref in cls._instances: obj = ref() if obj is not None: yield obj else: nonexistent.add(ref) cls._instances -= nonexistent class Service(Agent): ''' step: 1. Unload finished task from the service (Service._unloadService), free up resource for the current time unit. 2.Predict service utilization (Service._predictUtilization) based on previous utilization level. The result will be used to calculate current cost of one unit of service, which in turn will be used in ResourceSite for estimating offering price. estimate: ResourceSite adjusts capacity (ResourceSite._adjustCapacity) based on Service.resNeedsRequested, which is calculated while loading service (Service._loadService) based on the actual service duration (Service._genActualServiceDuration) in the "advance" step from the previous time unit. allocate: Service checks queuelist for overdue tasks and kicks them out. Time in queue estimation is updated (Service.estimTimeInQueue). advance: ResourceSite calls Service.loadQueue. Time in queue estimation is updated (Service.estimTimeInQueue). At the same time the service loads service from queue (Service._loadService). ''' _instances = set() avgCapacityPeriod = sp.avgCapacityPeriod avgCostPeriod = sp.avgCostPeriod utilPredictionWeights = sp.utilPredictionWeights capacityBuffer = sp.capacityBuffer resProfileUpdateThreshold = sp.resProfileUpdateThreshold null = sp.null def __init__(self,servName,servType,uniqueId,resourceSiteId,sitetype, resCosts,model,maxAmount): super().__init__(uniqueId, model) self.serviceName = servName self.serviceType = servType self.unique_id = uniqueId self.model = model self.availBudget = 0 # dummy variable self.rs = resourceSiteId self.rsType = sitetype if sitetype==SiteType.TYPE2: # slow servers self.discount = sp.discount else: self.discount = 1 self.maxAmount = maxAmount # server + queue capacity in unit of service self.serviceCapacity = maxAmount # simplified self.occupied = 0 # nr of occupied service units in queue and server self.utilization = 0 # percentage of occupied service capacity self.predictedUtil = 0 # predicted utilization of next time step self.queuelist = list() # list of bids in queue self.servicelist = list() # list of bids being served self.estimTimeInQueue = 0 # estim. time to wait in queue for a new task self.servicing = False # if any servers are occupied self.servicedTaskHistory = list() # history of serviced bids self.occupiedHistory = {'0':0} # history of nr. occupied service units self.utilHistory = dict() # history of utilization self.overCapacityHistory = dict() # history of overcapacity self.recentCapaIncrease = 0 # time unit of the most recent increase self.recentCapaDecrease = 0 # time unit of the most recent decrease self.resNeedsEstim = dict() # slope and intercept of the linear model self.resNeedsRandom = dict() # mean and stddev of randomness added # to the resNeedsEstim curve self.resNeedsAvg = dict() # average amount and duration self.resNeedsRequested = dict() # requested amount from resource self.resNeedsHistory = dict() # history of the actual self.resCosts = resCosts # fixed unit costs of resources self._createResourceNeeds() self._instances.add(weakref.ref(self)) def _createResourceNeeds(self): ''' initiate resource needs ''' resources = utCom.listClassVariables(ResourceName,'__',False) self.resNeedsHistory = dict([(res, [DefaultProfile.randomGenerate(self.rsType,self.serviceType)]) for res in resources]) for k in self.resNeedsHistory.keys(): self.resNeedsHistory[k][0] = (self.resNeedsHistory[k][0][0], self.resNeedsHistory[k][0][1],self.resNeedsHistory[k][0][1]) self.resNeedsRequested = self._estimateResNeedCurve() def _estimateResNeedCurve(self): ''' estimate resource needs (parameterized and average) of one unit of service based on historical (actual) records. Linear regression is used and the output is slope and intersect params stored in Service.resNeedsEstim. Around this curve, based on the residuals, randomness is stored in Service.resNeedsRandom as the parameters of a normal distribution. The randomness will be added to the estimation of resource amounts in Service.estimateServiceDuration and Service.estimateResourceAmount, which in turn randomizes the ResourceSite's price offers in ResourceSite._estimTaskDuration and ResourceSite.estimTimeInSystem, called by Bid.estimate. The average Service.resNeedsAvg is the median point on this curve. the average is used in ResourceSite._adjustCapacity (called from ResourceSite.estimate) to update the resource site's resource profile for the service. This function is called in Service._genActualServiceDuration from Service.advance. ''' requested = dict() for k in self.resNeedsHistory.keys(): amountlist = [x[0] for x in self.resNeedsHistory[k]] durationlist = [x[1] for x in self.resNeedsHistory[k]] if len(amountlist) > 2: A = np.vstack([np.array(amountlist), np.ones(len(amountlist))]).T try: result = np.linalg.lstsq(A,durationlist,rcond=None)[0] except: result = np.zeros(A.shape[1]) residuals = durationlist - np.dot(A, result) self.resNeedsEstim[k] = (result[0],result[1]) self.resNeedsRandom[k] = (np.mean(residuals),np.std(residuals)) else: self.resNeedsEstim[k] = (np.mean(durationlist) /np.mean(amountlist),0) self.resNeedsRandom[k] = (0,0) if len(amountlist) >= self.resProfileUpdateThreshold: self.resNeedsAvg[k] = (int(np.median(amountlist)), int(self.resNeedsEstim[k][0] * np.median(amountlist) + self.resNeedsEstim[k][1])) else: self.resNeedsAvg[k] = (int(np.mean(amountlist)), int(np.mean(durationlist))) requested[k] = int(self.serviceCapacity * self.resNeedsAvg[k][0]) return requested def _genActualServiceDuration(self,resAmounts): ''' generate actual service duration given resource amount needed. called in Service._loadService, from Service.advance. DefaultProfile creates duration based on resource amounts with a normal distribution. ''' resNeedsActual = dict() buffer = 10000 for res in resAmounts.keys(): duration = DefaultProfile.DURATION[ (self.rsType,self.serviceType)](resAmounts[res]) # actual profile: amount, total duration, duration to go resNeedsActual[res] = (resAmounts[res],duration,duration) self.resNeedsHistory[res].append(resNeedsActual[res]) if len(self.resNeedsHistory[res])>buffer: self.resNeedsHistory[res] = self.resNeedsHistory[res][-buffer:] self.resNeedsRequested = self._estimateResNeedCurve() return resNeedsActual def _checkQueuelist(self): ''' in case of long waiting time: check queue list for overdue tasks and discard them. called in Service.allocate. ''' reduceTime = 0 prevWaitingTime = 0 toBeDeleted = list() for bidId in self.queuelist: bid = self.model.bidlist[bidId] if self.model.schedule.steps >= bid.dueTime: toBeDeleted.append(bidId) bid.chain[bid.currentTask].isInQueue = False self.model.sites[self.rs].bidlist.append(bidId) self.updateUtilization( -bid.chain[bid.currentTask].serviceAmount) reduceTime += (bid.chain[bid.currentTask].estimWaitingTimeTotal - prevWaitingTime) else: bid.chain[bid.currentTask].estimWaitingTimeTotal -= reduceTime prevWaitingTime = bid.chain[bid.currentTask].estimWaitingTimeTotal self.queuelist = [x for x in self.queuelist if x not in toBeDeleted] def _predictUtilization(self): ''' placeholder for more sophisticated service capacity utilization prediction methods. Currently: simply take the weighted average over a given period of time, weights are specified in the config file. called in Service.step. result is saved in Service.predictedUtil which is used in Service.calculateUnitCost (either called from ResourceSite.estimate or from Service.advance) ''' periods = range(self.model.schedule.steps - min(len(self.utilHistory), self.avgCostPeriod), self.model.schedule.steps) weights = [self.utilPredictionWeights[self.model.schedule.steps -1-int(k)] for k,_ in self.utilHistory.items() if int(k) in periods] if sum(weights)>0: weights = [x/sum(weights) for x in weights] value = [np.mean(v) for k,v in self.utilHistory.items() if int(k) in periods] self.predictedUtil = sum([x*y for x,y in zip(value,weights)]) def _loadService(self): ''' load service from queue to server for processing. function is called in Service.advance. create real resource needs with randomness, and update Task.resProfileActual of the current task. Currently, if the next-service-in-line cannot be served by the server due to resource shortage, the entire service queue waits until resources can be freed. However this will be recorded, and will be used in ResourceSite._adjustCapacity to request for a increase in resource allocation to the service. ''' while (len(self.servicelist) < self.serviceCapacity and len(self.queuelist) > 0): # unload queue: bidId = self.queuelist[0] bid = self.model.bidlist[bidId] task = bid.chain[bid.currentTask] resAmounts = utCom.recreateDict(task.resProfileSelected,0) totalAmounts = dict([k,resAmounts[k] * task.serviceAmount] for k in resAmounts.keys()) if task.resProfileActual is None: task.resProfileActual = self._genActualServiceDuration( resAmounts) # resource shortage at time of loading feasible,diffAmount = self.model.sites[ self.rs].checkResFeasibility(totalAmounts, self.serviceName,self.serviceType) if not feasible: self.overCapacityHistory[str(self.model.schedule.steps)] = ( self.occupied, self.maxAmount - self.occupied - task.serviceAmount) return # allocate resource for res in resAmounts.keys(): self.model.sites[self.rs].resourcelist[res].startTask( task.unique_id,self.serviceName,self.serviceType, task.resProfileActual[res][0] * task.serviceAmount, task.resProfileActual[res][1], self.model.schedule.steps) # update queue list self.queuelist = self.queuelist[1:] self.servicelist.append(bidId) self.servicing = True # update current task task.queueEnd = self.model.schedule.steps actualServiceTime = max([task.resProfileActual[res][1] for res in task.resProfileActual.keys()]) task.updateServiceTime(actualServiceTime,self.model.schedule.steps) unitCost = self.calculateUnitCost(task.resProfileActual, prediction=False) task.cost = unitCost * task.serviceAmount def _unloadService(self): ''' end of service for a task when any task being served reaches end of its service time. this function is called from Service.step. ''' for bidId in self.servicelist: bid = self.model.bidlist[bidId] task = bid.chain[bid.currentTask] task.serviceTimeToGo -= 1 release = task.updateResourceTime() if len(release)>0: for res in release: self.model.sites[self.rs].toBeReleased[res].append( task.unique_id) if task.serviceTimeToGo <= 0: # update task task.serviceEnd = self.model.schedule.steps task.isFinished = True # update resource for res in task.resProfileActual.keys(): self.model.sites[self.rs].toBeReleased[res].append( task.unique_id) # update service self.servicedTaskHistory.append(bidId) buffer = int(max(rsp.resProfileSelectionThreshold*2,500)) if len(self.servicedTaskHistory)>buffer: self.servicedTaskHistory = self.servicedTaskHistory[-buffer:] self.servicelist.remove(bidId) self.updateUtilization(-task.serviceAmount) if len(self.servicelist)==0: self.servicing = False # update bid bid.priceLeftover -= task.cost if (task.pos==len(bid.chain)-1) or (bid.priceLeftover<0): bid.updateResult(BidStatus.FINISH, self.model.schedule.steps, self.model.schedule.steps-bid.batchCreateTime) else: bid.currentTask += 1 bid.updateResult(BidStatus.REALLOCATE, self.model.schedule.steps) def _estimateTimeInQueue(self): ''' update estimated time in queue for a new task coming into the queue. called by Service.updateUtilization. ''' resAmount = utCom.recreateDict(self.resNeedsAvg,0) self.estimTimeInQueue = (self.occupied * self.estimateServiceDuration(resAmount) / self.serviceCapacity) def loadQueue(self,taskId,bidId,serviceAmount,resAmounts): ''' load newly arrived tasks into service queue. called by ResourceSite._load from ResourceSite.advance. ''' # service queue overflow at time of loading if self.occupied + serviceAmount > self.maxAmount: time = self.model.schedule.steps self.overCapacityHistory[str(time)] = (self.occupied, self.maxAmount - self.occupied - serviceAmount) return None,None queuetime = self.estimTimeInQueue self.updateUtilization(serviceAmount) self.queuelist.append(bidId) return self.unique_id,queuetime def estimateServiceDuration(self,resAmounts): ''' estimate duration for one time service, given resource profile ''' result = np.max([1] + [self.resNeedsEstim[k][0] * resAmounts[k] + self.resNeedsEstim[k][1] + np.random.normal(*self.resNeedsRandom[k]) for k in self.resNeedsEstim.keys()]) return result def estimateResourceAmount(self,duration): ''' estimate resource profile for quotes, given QoS ''' duration = max(1,duration) result = dict() for k in self.resNeedsEstim.keys(): if self.resNeedsEstim[k][0]==0: # if slope is 0 result[k] = (1,self.resNeedsEstim[k][1]) else: result[k] = (max( 1,int(np.round( (duration - np.random.normal(*self.resNeedsRandom[k]) - self.resNeedsEstim[k][1]) / self.resNeedsEstim[k][0])) ), int(np.round(duration,0))) return result def calculateUnitCost(self,resNeeds,prediction=True): ''' estimates cost of one unit of service based on the service capacity utilization. called by ResourceSite.getServiceInfo from ResourceSite.estimate for estimation of the service cost, and by Service._loadService from Service.advance with actual resource requirements and no prediction method. @param resNeeds: amount and duration of resources needed for the service. cost is based on estimated required resource amount and duration of one unit of service. @param prediction: if true, use predicted utilization based on the timeseries. if false, use the most recent utilization value. @return: cost for one unit of service. ''' if self.utilization == 1: return sys.maxsize else: if prediction: utilization = self.predictedUtil else: utilization = self.utilization return self.discount * utilization * sum([self.resCosts[res] * resNeeds[res][0] * resNeeds[res][1] for res in resNeeds.keys()]) def updateUtilization(self,serviceAmount,diffMax=0): ''' update service capacity utilization after Service.loadQueue from ResourceSite._load (ResourceSite.advance), Service._unloadService from Service.step, ResourceSite._adjustCapacity from ResourceSite.estimate. ''' key = str(self.model.schedule.steps) self.occupied = np.max([0,self.occupied + serviceAmount]) self.occupiedHistory[key] = self.occupied buffer = self.avgCapacityPeriod * 2 if len(self.occupiedHistory)>buffer: for k in range(int(key)-buffer): if str(k) in self.occupiedHistory.keys(): _ = self.occupiedHistory.pop(str(k)) self.maxAmount = max(self.occupied, self.maxAmount + diffMax) self.utilization = self.occupied / self.maxAmount if key not in self.utilHistory.keys(): self.utilHistory[key] = list() self.utilHistory[key].append(self.utilization) if len(self.utilHistory)>buffer: for k in range(int(key)-buffer): if str(k) in self.utilHistory.keys(): _ = self.utilHistory.pop(str(k)) self._estimateTimeInQueue() self.serviceCapacity = max(1, self.serviceCapacity + diffMax) if diffMax > 0: self.recentCapaIncrease = self.model.schedule.steps elif diffMax < 0: self.recentCapaDecrease = self.model.schedule.steps def step(self): self._unloadService() self._predictUtilization() def estimate(self): for bidId in self.queuelist: bid = self.model.bidlist[bidId] task = bid.chain[bid.currentTask] task.estimWaitingTimeToGo -= 1 def allocate(self): self._checkQueuelist() def advance(self): self._loadService() @classmethod def getInstances(cls): nonexistent = set() for ref in cls._instances: obj = ref() if obj is not None: yield obj else: nonexistent.add(ref) cls._instances -= nonexistent class RSU(Agent): ''' step:. estimate: 1. update nrVehicles and nrBids. 2. update resource sites' free capacity allocate: 1. allocate bids to resource sites 2. calculate payment and feed back to vehicles 3. update competitor states in TransitionTbl for learning. The state information will be consolidated in TransitionTbl._addStateRecord in TransitionTbl.advance as the actual state, which is the target output for previous input to CompetitorLearningModel, as well as the nextStateVec for PriceLearningModel's critic module. advance:. ''' secondPriceThres = rp.secondPriceThres overload = rp.overload _instances = set() def __init__(self,uniqueId,siteMat,model): super().__init__(uniqueId, model) self.unique_id = uniqueId self.pos = (0,0) # coordinate of the RSU self.availBudget = 0 # dummy variable self.bids = list() # bid ids submitted by vehicles to the RSU self.sortedBids = dict() # sorted bids according to profitability self.sites = list() # connected resource site ids self.homesite = None # directly connected resource site id self.vehicles = list() # vehicles connected to the RSU self.siteMat = siteMat # information of all resource sites self.siteDist = dict() # distance to all resource sites self.siteFreeCapa = dict() # estimation of resource site free capa self.siteMaxAmounts = dict() # record site max amount self.nrVehicles = 0 # nr of connected vehicles self.nrActiveBids = 0 # nr of active bids on the RSU self.secondPriceRecords = list() # records eligible for calculation # of second price self.secondPrices = dict() # records second price by category self.secondPriceParams = None # curve for 2.price self.bidRecordedForPrice = list() # for debugging self._instances.add(weakref.ref(self)) def _findResourceSites(self): ''' placeholder for finding resource sites dynamically ''' self.sites = self.model.siteId self.secondPriceParams = np.zeros(len(self.sites)+len(sec.keys)+1) def _getSiteDistance(self,siteMat): ''' look up the distance table from resource site information. @ param siteMat: matrix of distance between sites ''' try: homesite = self.sites[1] # standard server except: homesite = self.sites[0] self.siteDist = siteMat.distanceMatrix for s in self.sites: self.siteDist[(self.unique_id,s)] = self.siteDist[(homesite,s)] self.homesite = homesite def _sortBids(self): ''' sort active bids by prio and profitability. called by RSU.allocate ''' sortedBids = [(x.unique_id,(x.priority,x.priceLeftover - x.bestProposal.proposedBidCost)) for x in self.model.bidlist.values() if (x.unique_id in self.bids) and (x.isActive==1) and (x.status not in (BidStatus.PREP,BidStatus.PROCESS, BidStatus.TRANSMIT)) ] sortedBids = dict(sortedBids) return {k: v for k,v in sorted(sortedBids.items(), key=lambda item:item[1],reverse=True)} def _populateSecondPriceRecord(self,bid,siteId,target=None): ''' helper function to create second price records. used in RSU._recordSecondPrice, and RSU.allocate for inputs to RSU._calculatePayment. Container is a SecondPriceData class. ''' record = sec(self.sites).record record[sec.TIME] = self.model.schedule.steps record[sec.QOS] = bid.dueTime - self.model.schedule.steps record[sec.VEH] = self.nrVehicles record[sec.BID] = self.nrActiveBids if target is None: record[sec.ESTIM] = bid.priceLeftover else: record[sec.ESTIM] = target record[siteId] = 1 for i in np.arange(start=bid.currentTask,stop=len(bid.chain)): t = bid.chain[i] servNameType = (t.serviceName,t.serviceType) record[servNameType] = t.serviceAmount return record def _recordSecondPrice(self,bid,siteId,target=None): ''' based on all bid records eligible for second price calculation (i.e. the bids which did not get allocated by are next-in-line), fit a curve from bids' qos requirements, nr active bids in env, amount in unit of service, etc. to the estimated second price. a linear regression model is used. params are stored in RSU.secondPriceParams which is used in RSU._calculatePayment called from RSU.allocate. @param bid: bid object for the second price record. note that within the same class, objects can be passed on to functions. Across classes the objects need to be accessed directly from the mesa model, or the copies of objects are not sync'd. ''' self.bidRecordedForPrice.append(bid.unique_id) record = self._populateSecondPriceRecord(bid,siteId,target=target) if record not in self.secondPriceRecords: self.secondPriceRecords.append(record) if len(self.secondPriceRecords) > self.secondPriceThres: arr = np.array([list(x.values()) for x in self.secondPriceRecords]) xcol = np.hstack([arr[:,:-1], np.ones(arr.shape[0]).reshape(arr.shape[0],-1)]) ycol = arr[:,-1] try: params = np.linalg.lstsq(xcol,ycol,rcond=None)[0] self.secondPriceParams = params except: pass def _calculatePayment(self,serviceRecord): ''' calculate second price payment based on linear regression of service needs, env. variables, etc. the function is called from RSU.allocate. @param serviceRecord: a dictionary containing bid info, for which the payment needs to be calculated. @return: second price for the given bid. ''' if len(self.secondPriceRecords) <= self.secondPriceThres: denom = 0 total = 0 for key in serviceRecord: if key in sec.services: denom += sum([x[key] for x in self.secondPriceRecords]) total += serviceRecord[key] if denom<=0: unit = 0 else: unit = sum([x[sec.ESTIM] for x in self.secondPriceRecords]) / denom return max(0, unit * total) else: result = np.dot(np.array(list(serviceRecord.values()))[:-1], self.secondPriceParams[:-1]) + self.secondPriceParams[-1] return max(0, result) def _rejectBids(self,bid,rejectReason): ''' helper function to include steps when bids are rejected ''' bid.updateResult(BidStatus.REJECT,self.model.schedule.steps, reason=rejectReason) self.removeBids(bid.siteBinding,bid.unique_id) # calculate reward and record state info in case of rejection: self.model.vehicles[bid.user].deactivateBid(bid.unique_id) def step(self): if len(self.sites)==0: self._findResourceSites() self._getSiteDistance(self.siteMat) def estimate(self): self.nrVehicles = sum([self.model.vehicles[x].isActive for x in self.vehicles]) self.nrActiveBids = sum([self.model.bidlist[x].isActive for x in self.bids]) for siteId in self.model.sites.keys(): site = self.model.sites[siteId] delay = int(np.ceil(self.siteMat.getWiredLatency( self.homesite,siteId,8))) for serviceNameType in site.servicelist.keys(): # add the effect of data transmission delay try: maxAmount = site.serviceMaxAmountHistory[ serviceNameType][-delay] except: maxAmount = site.maxAmounts[serviceNameType] try: currentOccupied = site.serviceOccupiedHistory[ serviceNameType][-delay] except: currentOccupied = 0 self.siteFreeCapa[(siteId,serviceNameType)] = ( maxAmount * (1 + self.overload) - currentOccupied) self.siteMaxAmounts[(siteId,serviceNameType)] = ( maxAmount * (1 + self.overload)) def allocate(self): ''' if bids dont have feasible quotes from any resource sites, or if one of the duplicate bids are already accepted, or if the bid is down-prioritized and there is no free capacity left in the resource sites. if a bid is accepted and allocated, it is appended to the resource site's bidlist. a payment is also calculated for the bid. all results are fed back to the vehicle. payment as a indicator of competitor states is updated in corresponding TransitionTbl. ''' logfile = self.model.filedict[FILES.ALLOC_FILE[0]] self.sortedBids = self._sortBids() acceptedBids = list() recordedForSecondPrice = dict() secondPrices = dict() for s in self.sites: for k in cbd.keys: recordedForSecondPrice[(s,k)] = False secondPrices[(s,k)] = 0 counter = -1 for bidId in self.sortedBids.keys(): bid = self.model.bidlist[bidId] counter += 1 def myLogFunc(decision): if bid.bestProposal.proposedDest is None: sitetype = None else: sitetype = self.model.sites[ bid.bestProposal.proposedDest].sitetype if decision=='skipped': return nrRebid = bp.nrRebid logfile.write( '{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{}\n'.format( self.model.schedule.steps+self.model.cumstep, len(self.sortedBids),counter, bidId,bid.status,bid.learningKey,bid.qostype, bid.price,bid.payment,bid.availBudget,bid.batchCreateTime, bid.createTime,bid.bestProposal.proposedDest,sitetype, bid.finishTime,nrRebid-bid.nrRebid,decision,bid.value, self.model.extRewardInterval)) # ignore those in progress if bid.status in (BidStatus.PREP,BidStatus.PROCESS, BidStatus.TRANSMIT): # in the new version: already filtered out in _sortbids myLogFunc('skipped') continue # reject duplicate bids if another bid in the same batch # is admitted. This is used when multiple bids are created under # the same batch number so that there are many choices for the RSU # but only one of them can be accepted and allocated. if bid.batch_id in acceptedBids: # the other qos is accepted self._rejectBids(bid,rejectReason=bfr.DUPLICATE) myLogFunc('same batch duplicate rejected') continue serviceNameType = (bid.chain[bid.currentTask].serviceName, bid.chain[bid.currentTask].serviceType) serviceAmount = bid.chain[bid.currentTask].serviceAmount siteId = bid.bestProposal.proposedDest learningKey = (bid.learningKey,bid.qostype) if siteId is not None: # reject bids with low priority when the total capacity # of the resource site is exceeded. Test all proposals before # rejection: if (self.siteFreeCapa[(siteId, serviceNameType)]-serviceAmount<0): for proposal in sorted(bid.proposals.values(), reverse=True): sid = proposal.proposedDest if (self.siteFreeCapa[(sid,serviceNameType)] -serviceAmount>=0 and proposal.proposedBidCost<=bid.priceLeftover): bid.bestProposal = proposal siteId = sid break if self.siteFreeCapa[(siteId,serviceNameType)]-serviceAmount<0: if (not recordedForSecondPrice[(siteId,learningKey)] and bid.priority==0): secondPrices[(siteId, learningKey)] = bid.priceLeftover self._recordSecondPrice(bid,siteId) recordedForSecondPrice[(siteId,learningKey)] = True self._rejectBids(bid,rejectReason=bfr.NOPRIO) myLogFunc('down prioritized rejected') continue bidStatus = dict(Counter([x[0] for x in bid.statusHistory])) if (BidStatus.ADMIT not in bidStatus or bidStatus[BidStatus.ADMIT]<bidStatus[BidStatus.PREP]): bid.updateResult(BidStatus.ADMIT,self.model.schedule.steps) if bid.siteBinding != siteId: self.removeBids(bid.siteBinding,bidId) self.appendBids(siteId,bidId) bid.acceptProposal(siteId=siteId,rsuId=self.unique_id, rsuHomesiteId=self.homesite) self.siteFreeCapa[(siteId,serviceNameType)] -= serviceAmount serviceRecord = self._populateSecondPriceRecord(bid,siteId) if bid.payment==-1: # first time allocated bid.payment = min(bid.price-1, self._calculatePayment(serviceRecord)) self.model.vehicles[bid.user].rewardBidlist.append(bidId) transTbl = self.model.vehicles[bid.user].transitionTbl if transTbl is not None: self.model.transitionTbl[ transTbl].updateStateInfo(bidId) acceptedBids.append(bid.batch_id) myLogFunc('admitted') else: self._rejectBids(bid,rejectReason=bfr.NO_AVAILABLE_SITE) myLogFunc('no proposals rejected') for siteId in self.sites: recorded = False for key in cbd.keys: if (len(self.sortedBids)>0 and not recordedForSecondPrice[(siteId,key)]): secondPrices[(siteId,key)] = 0 if not recorded: self._recordSecondPrice(bid,siteId,target=0) recorded = True self.secondPrices = secondPrices.copy() def advance(self): pass def removeBids(self,siteId,bidId): ''' helper function to remove the given bidId from the given site ''' if siteId != self.unique_id: self.model.sites[siteId].bidlist.remove(bidId) def appendBids(self,siteId,bidId): ''' helper function to append given bidId to the given site ''' self.model.sites[siteId].bidlist.append(bidId) @classmethod def getInstances(cls): nonexistent = set() for ref in cls._instances: obj = ref() if obj is not None: yield obj else: nonexistent.add(ref) cls._instances -= nonexistent class Vehicle(Agent): ''' step: 1. activate bids in the pipeline (put into the pipeline in the previous time step in Vehicle.estimate). 2. periodically re-train price learning model (when nr of new inputs exceeds a given threshold). estimate: in Vehicle._fillPipeline, 1. create new bids which share the same budget. 2. run competitor learning model's inference function to get competitor's next state. 3. run price learning model's inference function to get budget split between bids, assign bidding price to each bid, and put the bids into pipeline for activation in next time step. allocate: RSU.allocate will make decisions to allocate or reject bids, calculate payment for each, and record state information. advance: 1. if TransitionTbl is not yet created, create and populate the TransitionTbl. in TransitionTbl.advance, actual state information from RSU.allocate will be consolidated to create one record of nextStateVec, which is used as the next state value in Vehicle.priceMdl.critic. 2. calculate bids' rewards and add to PriceLearningModel. ''' _instances = set() # randomness to each vehicle's maximum budget minNrBids = vp.minNrBids maxNrBids = vp.maxNrBids totalNrBids = vp.totalNrBids maxSensingDist = vp.maxSensingDist budgetRenewal = vp.budgetRenewal qostypes = cbd.qosTypes servAmount = cbd.serviceAmounts competitorDataThres = vp.competitorDataThres plmTrainingThres = vp.plmTrainingThres lamMax = vp.lamMax lamMin = vp.lamMin lamChangeInterval = vp.lamChangeInterval lamCategory = vp.lamCategory ph = vp.ph pl = vp.pl stagingMaxsize = vp.stagingMaxsize stagingMaxtime = vp.stagingMaxtime stagingThreshold = np.random.choice(vp.stagingThreshold) stagingPeriod = vp.stagingPeriod curiosityTrainingThres = vp.curiosityTrainingThres maxLifespan=vp.maxLifespan curiosityExtRewardThres = vp.curiosityExtRewardThres def __init__(self,uniqueId,createTime,availLifespan,pos,speed, model,sumoId=None,totalBudget=None,rebid=False,ca=True): super().__init__(uniqueId, model) self.unique_id = uniqueId if totalBudget is None: self.totalBudget = np.random.choice([vp.totalBudget[0], vp.totalBudget[1]]) else: self.totalBudget = totalBudget self.createTime = createTime self.availBudget = 0 # dummy variable self.availRsu = list() self.bidCount = 0 # for generating unique ids for the bids self.bidPipeline = list() # bids which are to be activated self.bidStaging = list() # bids which are not to be activated self.lam = 0 self._updateLambda() # for repeatability self.countdownHistory = list() self.batchCreateHistory = list() self.saveRecord = True if self.model.repeatable: _ = self._loadRepeatable() # for random creation of bid batches: self.countdown = self._generateCountdown(randomize=True) self.countdownHigh = self._generateCountdown(randomize=False, qostype=QoSType.HIGH) self.countdownLow = int(self._generateCountdown(randomize=False, qostype=QoSType.LOW)) - np.random.randint(10,bp.requestCountdown1-10) self.activeBid = list() # bids which are active # temporary list to record rewards in self._activateBids self.rewardBidlist = list() # bids to be collected rewards self.rebidlist = list() # bids to be re-bid self.freeCapa_assigned = dict() # free capacity in each site for each # service as input state information self.freeCapa_all = dict() # free capacity from each rsu estimate self._initFreeCapaInfo() self.bidHistory = list() # history of finished bids self.rebid = rebid self.ca = ca self.stagingDistr = 'uniform' self.rsu = None self.availLifespanPrev = (-1,None) self.reset(availLifespan=availLifespan,pos=pos,speed=speed, sumoId=sumoId,rsu=None,isActive=True) # object to hold all competitor learning model related information: self.transitionTbl = None # for normalization of environment variable (total nr.bids) self.benchmarkNrBid = (vp.budgetRenewal+vp.minNrBids) * mp.initVehicles # output of the price learning model: prediction of best response # 1st digit is whether to # activate bid in the current time unit. rest of output is # proportion of allocated budget to each bid. self.priceMdl = plm(uniqueId=self.unique_id, dimOutput=1+self.budgetRenewal, evaluation=self.model.evaluation, loadModel=self.model.loadModel, curiosity=self.model.curiosity, cumstep=self.model.cumstep, endOfGame=self.model.endOfGame, ca=self.ca) # output of the supervised learning: prediction of own behavior self.superviseMdl = spv(uniqueId=self.unique_id, dimOutput=1+self.budgetRenewal, evaluation=self.model.evaluation, loadModel=self.model.loadModel, curiosity=self.model.curiosity) # connection key to link input records to rewards and outputs self.learningDataPos = str(0) self.learningDataPosSL = str(0) # for supervised learning model self.prevRecordNr = 0 # used to determine if to re-train the priceMdl. self.budgetPool = 0 # for cumulated budget in curiosity mode self.curiosityMdl = None self.prevRecordNr_curiosity = sys.maxsize if self.model.curiosity: self.curiosityMdl = cur(uniqueId=self.unique_id, dimAction=1+self.budgetRenewal, evaluation=self.model.evaluation, loadModel=self.model.loadModel) self.prevRecordNr_curiosity = 0 # to re-train curiosity model. self.curiosityExtRewardThres = self.model.extRewardInterval self.extRandom = int(np.random.rand()*self.curiosityExtRewardThres) self._instances.add(weakref.ref(self)) def _loadRepeatable(self): try: filename0 = COUNTDOWN_FILE + '_' + self.unique_id + '.pkl' self.countdownHistory = pickle.load(open(filename0,'rb')) filename1 = BATCHCREATE_FILE + '_' + self.unique_id + '.pkl' self.batchCreateHistory = pickle.load(open(filename1,'rb')) self.saveRecord = False return (filename0,filename1) except: pass try: locations = [x.span() for x in re.finditer('_',self.unique_id)] uid = (self.unique_id[:locations[-1][1]] + str(not self.model.trainable)) filename0 = COUNTDOWN_FILE + '_' + uid + '.pkl' self.countdownHistory = pickle.load(open(filename0,'rb')) filename1 = BATCHCREATE_FILE + '_' + uid + '.pkl' self.batchCreateHistory = pickle.load(open(filename1,'rb')) self.saveRecord = False return (filename0,filename1) except: return (None,None) def _generateCountdown(self,randomize=True,qostype=QoSType.HIGH): if self.model.repeatable and not self.saveRecord: try: record = self.countdownHistory.pop(0) return record except: pass # average interval of bid creation is 1/lambda time steps self.saveRecord = True if randomize: record = int(np.random.exponential(scale=1/self.lam)) else: if qostype==QoSType.HIGH: record = bp.requestCountdown1 else: record = bp.requestCountdown2 return record def _updateLambda(self): if self.lam==0: self.lam = self.lamMin return avg = (self.lamMax + self.lamMin) / 2 band = (self.lamMax - self.lamMin) / self.lamCategory prob = np.random.rand() if self.lam >= avg: if prob<=self.ph: self.lam = np.random.uniform(low=self.lamMin, high=self.lamMin+band) else: if prob<=self.pl: self.lam = np.random.uniform(low=self.lamMax-band, high=self.lamMax) def _initFreeCapaInfo(self): for rsu in self.model.rsu.keys(): for siteId in self.model.sites.keys(): for servKey in self.model.sites[siteId].servicelist.keys(): self.freeCapa_assigned[(rsu,siteId,servKey)] = 1 self.freeCapa_all[rsu] = 1 def _createBid(self,bidId=None,qos=None,servAmountLevel=None, savedRecord=None): ''' called by Vehicle._fillPipeline in Vehicle.estimate. randomly create a batch of bids in different (service amount,qos requirement) categories, which share the same budget. ''' if bidId is None: bidId = str(self.unique_id) + '_' + str(self.bidCount) if qos is None: qos = np.random.choice(self.qostypes) if servAmountLevel is None: servAmountLevel = np.random.choice(self.servAmount) bid = Bid(bidId=bidId,qostype=qos,servAmount=servAmountLevel, user=self.unique_id, budget=self.totalBudget/self.budgetRenewal, createTime=self.model.schedule.steps, coord=self.pos,model=self.model,savedRecord=savedRecord) self.bidCount += 1 if (bid.dueTime < self.model.schedule.steps + self.availLifespan and bid.dueTime < self.model.totalSimTime): bid.rsu = self.rsu bid.environment = self.model.rsu[self.rsu].nrActiveBids return bid else: return None def _calDistance(self,otherCoord): ''' placeholder for finding RSUs. not used. ''' return np.sqrt((otherCoord[0] - self.pos[0])^2 + (otherCoord[1] - self.pos[1])^2) def _findRSU(self): ''' placeholder for finding RSUs. not used. ''' self.availRsu = list() for obj in RSU.getInstances(): self.availRsu.append(obj.unique_id) def _chooseRSU(self): ''' placeholder for finding RSUs. not used. ''' if len(self.availRsu)>0: self.rsu = self.availRsu[0] self.model.rsu[self.rsu].vehicles.append(self.unique_id) def _createTransitionTbl(self): ''' called in Vehicle.advance to create object for CompetitorLearningModel. ''' transitionTbl = TransitionTbl(vehicleId=self.unique_id, budget=self.totalBudget/self.budgetRenewal, benchmarkNrBid=self.benchmarkNrBid,model=self.model) self.transitionTbl = transitionTbl.unique_id self.model.schedule.add(transitionTbl) self.model.transitionTbl[self.transitionTbl] = transitionTbl def _fsp(self,bestResponse,behavior,const=None): ''' choose best response with probability ''' if const is None: const = pmp.fsp_rl_weight_constant mixingParam = const / (self.model.schedule.steps + const) randomNr = np.random.rand() if randomNr <= mixingParam: return bestResponse else: return behavior def _fillPipeline(self): ''' 1. create new bids which share the same budget. 2. run competitor learning model's inference function to get competitor's next state. 3. run price learning model's inference function to get budget split between bids, assign bidding price to each bid, and put the bids into pipeline for activation in next time step. the function is called in Vehicle.estimate. ''' createQostype = None if not self.model.extTraceData: countdown = self.countdown if self.countdown<0: self.countdown = self._generateCountdown(randomize=True) else: countdown = min(self.countdownHigh,self.countdownLow) if self.countdownHigh<0: createQostype = QoSType.HIGH self.countdownHigh = self._generateCountdown(randomize=False, qostype=QoSType.HIGH) elif self.countdownLow<0: createQostype = QoSType.LOW self.countdownLow = self._generateCountdown(randomize=False, qostype=QoSType.LOW) if countdown<0: # create new batch with given avg. interval if not self.saveRecord: try: batchNew = self.batchCreateHistory.pop(0) except: batchNew = list() self.saveRecord = True else: batchNew = list() # bidVector is a onehot matrix indicating which bid belongs # to which category. bidVectorNew = list() batchRecord = list() for i in range(self.budgetRenewal): if self.saveRecord: bid = self._createBid(qos=createQostype) batchNew.append(bid) if bid is None: batchRecord.append(None) else: batchRecord.append(bid.savedRecord) else: savedRecord = batchNew[i] if savedRecord is None: bid = None else: bidId = (savedRecord['user'] + str(self.model.trainable) + '_' + savedRecord['batch']) bid = self._createBid(bidId=bidId, qos=savedRecord['qostype'], servAmountLevel=savedRecord['servAmount'], savedRecord=savedRecord) batchNew[i] = bid bidInfo = {k:0 for k in cbd.keys} taskSeq = [0] * len(cbd.services) if bid is not None: bidInfo[(bid.learningKey,bid.qostype)] += 1 taskSeq = bid.taskSeq.values() bidVectorNew += list(bidInfo.values()) bidVectorNew += taskSeq if sum(bidVectorNew)>0: for i in range(len(batchNew)): bid = batchNew[i] if bid is None: batchNew[i] = (None,0) continue self.model.schedule.add(bid) self.model.bidlist[bid.unique_id] = bid batchNew[i] = (bid.unique_id,bid.qosRequired) self.bidStaging.append((self.model.schedule.steps, batchNew,bidVectorNew, self.model.schedule.steps)) if len(self.bidStaging)==0: return toRemove = [] toDeactivate = [] normalizedStagingSize = len(self.bidStaging) / self.stagingMaxsize if (self.transitionTbl is not None and len(self.model.transitionTbl[ self.transitionTbl].estimNextState)>0): competitorState = self.model.transitionTbl[ self.transitionTbl].estimNextState else: competitorState = list(np.random.rand( len(self.model.sites) * len(cbd.keys))) for i in range(len(self.bidStaging)): createTime, batch, bidVector, nextChance = self.bidStaging[i] if nextChance > self.model.schedule.steps: continue dueTime = max([self.model.bidlist[bidId].dueTime for (bidId,qos) in batch]) if dueTime>0 and dueTime <= self.model.schedule.steps: toDeactivate.append(self.bidStaging[i]) continue normalizedNrBids = (self.model.rsu[self.rsu].nrActiveBids / self.benchmarkNrBid) normalizedStagingTime = (self.model.schedule.steps - createTime) / self.stagingMaxtime availBudget = (self.totalBudget / self.budgetRenewal + self.budgetPool / self.budgetRenewal) envVec = [normalizedNrBids,normalizedStagingTime, normalizedStagingSize,self.lam,availBudget] # for supervised learning inputVecSL = (bidVector + envVec + list(self.freeCapa_all.values()) + list(self.freeCapa_assigned.values())) # RL inputVec = competitorState + inputVecSL self.learningDataPos = self.priceMdl.collectInput(inputVec) if self.model.evaluation: randomness = 0 else: randomness = None # best response \beta_{j+1} from reinforcement learning bestResp = self.priceMdl.inference(inputVec=inputVec, randomness=randomness).tolist() # average behavior record for supervised learning self.learningDataPosSL = self.superviseMdl.collectInput( inputVecSL,model='supervisedModel') behavior = self.superviseMdl.inference(inputVecSL, pmdlReward=self.priceMdl.reward).tolist() result = self._fsp(bestResp,behavior) # best response behavior record for supervised learning self.superviseMdl.collectOutput(result,self.learningDataPosSL) self.learningDataPosSL = self.superviseMdl.collectInput( inputVecSL,model='supervisedModel') self.superviseMdl.collectOutput(bestResp,self.learningDataPosSL) if self.model.trainable: act = result[0] else: act = 0 prices = [x * availBudget for x in result[1:]] savings = [self.totalBudget / self.budgetRenewal - x for (x,y) in zip(prices,batch) if y[0] is not None] stagingRandom = self._getAction() if stagingRandom<act: # decision to hold bids self.priceMdl.collectOutput(result,self.learningDataPos) # nextStateVec is the same as current state self.collectPriceModelNextState(competitorState, self.learningDataPos) stagingPeriod = (1-act) * self.stagingPeriod # loss per time unit delayed is porportional to the budget qos = [qos for bidId,qos in batch if bidId is not None] avg = self.totalBudget / self.budgetRenewal / len(qos) delay = (self.model.schedule.steps + 1 - createTime + stagingPeriod) reward = -sum([avg / x * delay for x in qos]) self.priceMdl.collectReward(reward/10,self.learningDataPos) self.bidStaging[i] = (createTime, batch, bidVector, nextChance + stagingPeriod) continue self.priceMdl.collectOutput(result,self.learningDataPos) self.collectPriceModelNextState(competitorState, self.learningDataPos) #placeholder self.priceMdl.collectReward(reward=0,idx=self.learningDataPos) #placeholder output = dict([(y[0],x) for (x,y) in zip(prices,batch) if y[0] is not None]) for bidId,_ in batch: if bidId is None: continue bid = self.model.bidlist[bidId] bid.setPrice(output[bid.unique_id],availBudget) bid.priceLearningDataPos = self.learningDataPos self.bidPipeline.append(bid.unique_id) # update shared budget pool self.budgetPool += sum(savings) # move eligible batches to pipeline toRemove.append(i) self.bidStaging = [x for i,x in enumerate(self.bidStaging) if i not in toRemove] # clean the queue tobeDeleted = [(w,x,y,z) for (w,x,y,z) in self.bidStaging if (self.model.schedule.steps - w >= self.stagingMaxtime) or (z - w >= max([qos for bidId,qos in x if bidId is not None]))] tobeDeleted += toDeactivate if len(self.bidStaging)>self.stagingMaxsize: tobeDeleted.append(self.bidStaging[0]) for i in range(len(tobeDeleted)): createTime,batch,bidVector,nextChance = tobeDeleted[i] try: self.bidStaging.remove(tobeDeleted[i]) except: # if there are duplicates in the list continue for bidId,_ in batch: if bidId is None: continue bid = self.model.bidlist[bidId] bid.updateResult(BidStatus.REJECT,self.model.schedule.steps, reason=bfr.ONHOLD) self.deactivateBid(bidId) def _collectRewards(self): ''' calculate bid rewards and write to priceMdl. payment and rewardBidlist is updated in RSU.allocate through vehicle.deactivateBid, or directly in RSU.allocate if the bid is admitted. this function is called in Vehicle.advance. ''' loadBalancingWeight = 0.1 for rsu in self.model.rsu.keys(): freeCapa = maxAmount = 0 for siteId in self.model.sites.keys(): for servKey in self.model.sites[siteId].servicelist.keys(): try: freeCapa_assigned = self.model.rsu[rsu].siteFreeCapa[ (siteId,servKey)] except: freeCapa_assigned = 1000 try: maxAmount_assigned = self.model.rsu[ rsu].siteMaxAmounts[(siteId,servKey)] except: maxAmount_assigned = 1000 self.freeCapa_assigned[(rsu,siteId,servKey)] = ( freeCapa_assigned / maxAmount_assigned) freeCapa += freeCapa_assigned maxAmount += maxAmount_assigned self.freeCapa_all[rsu] = freeCapa / maxAmount for bidId in self.rewardBidlist: bid = self.model.bidlist[bidId] rsu = bid.rsu addReward = loadBalancingWeight * ( self.totalBudget / self.budgetRenewal * self.freeCapa_all[rsu]) # bid.addreward is used as an indicator and set to true in # Vehicle.deactivateBid when the bid is added to the rewardlist if bid.addReward: reward = bid.value - bid.payment + addReward if bid.payment==0: reward = reward - bid.value else: #if bid.failReason in [bfr.NO_AVAILABLE_SITE,bfr.NOPRIO reward = -bid.value + addReward pos = bid.priceLearningDataPos self.priceMdl.collectReward(reward,pos) self.rewardBidlist = list() for bidId in self.rebidlist: bid = self.model.bidlist[bidId] self._rebid(bid) self.rebidlist = list() def _activateBids(self): ''' activate bids in pipeline: set the indicator, and append it to RSU. update bid state information for CompetitorLearningModel. called in Vehicle.step. ''' while (len(self.activeBid)<self.maxNrBids and len(self.bidPipeline)>0 and self.bidCount<=self.totalNrBids): bidId = self.bidPipeline.pop(0) bid = self.model.bidlist[bidId] if bid.model is None: continue bid.rsu = self.rsu bid.pos = self.pos bid.activate() self.activeBid.append(bid.unique_id) self.model.rsu[self.rsu].bids.append(bid.unique_id) if self.transitionTbl is not None: self.model.transitionTbl[ self.transitionTbl].updateBidStateInfo(bid.unique_id) def _getAction(self): lower = 0 upper = 1 mu = self.stagingThreshold sigma = max(mu-lower,upper-mu)/2 return truncnorm.rvs((lower-mu)/sigma,(upper-mu)/sigma, loc=mu,scale=sigma) def _rebid(self,bid): ''' put rejected bids back into staging area. called at the end of Vehicle._collectRewards in Vehicle.advance. ''' bid.updateResult(BidStatus.PREP,self.model.schedule.steps) bid.payment = -1 bid.price = 0 bid.rsu = self.rsu bid.siteBinding = self.rsu bid.isActive = 0 bidVectorNew = list() for i in range(self.budgetRenewal): bidInfo = {k:0 for k in cbd.keys} taskSeq = [0] * len(cbd.services) if i==0: bidInfo[(bid.learningKey,bid.qostype)] += 1 taskSeq = bid.taskSeq.values() bidVectorNew += list(bidInfo.values()) bidVectorNew += taskSeq batchNew = [(None,0)] * self.budgetRenewal batchNew[0] = (bid.unique_id,bid.qosRequired) self.bidStaging.append((self.model.schedule.steps, batchNew,bidVectorNew, self.model.schedule.steps)) def _calLifespan(self,availLifespan): if availLifespan is None: prev = self.model.schedule.steps - 1 if (prev==self.availLifespanPrev[0] and self.availLifespanPrev[1] is not None): self.availLifespan = self.availLifespanPrev[1] else: self.availLifespan = self.maxLifespan else: self.availLifespan = availLifespan def reset(self,availLifespan,pos,speed,sumoId=None,rsu=None,isActive=None): #time to stay in the system: self._calLifespan(availLifespan) self.pos = pos self.speed = speed self.availLifespanPrev = (self.model.schedule.steps,availLifespan) if rsu is None: self._findRSU() self._chooseRSU() else: self.rsu = rsu # connected rsu if isActive is not None: self.isActive = isActive # indicator if sumoId is not None: self.sumoId = sumoId def deactivateVehicle(self): self.isActive = False def deactivateBid(self,bidId): ''' helper function to deactivate a given bid. currently removing it from the activeBid list will give space to create more bids. currently reward is collected immediately after admission decision in RSU.allocate, and not when the bids are serviced. Therefore reward is not collected AGAIN if payment has already been determined in RSU.allocate. called from RSU._rejectBids in RSU.allocate. also called from Bid.estimate, to catch finished bids from Service._unloadService in Service.step. @param bidId: unique_id of the bid to be deactivated. ''' bid = self.model.bidlist[bidId] bid.isActive = 0 try: self.activeBid.remove(bidId) except: pass try: self.model.rsu[self.rsu].bids.remove(bid.unique_id) except: pass bidStatus = dict(Counter([x[0] for x in bid.statusHistory])) if (BidStatus.BID in bidStatus.keys() and bidStatus[BidStatus.BID]>=bidStatus[BidStatus.PREP]): # if not directly from bidStaging: if bid.payment==-1 and bid.failReason!=bfr.DUPLICATE: if np.isnan(bid.price): bid.price = -1 # if the bid is not re-allocated before rejected: # (currently only recording admission rewards. if admitted # the reward is collected in rsu.allocate) if self.transitionTbl is not None: transTbl = self.model.transitionTbl[self.transitionTbl] try: idx = list(transTbl.stateChangeFlag.keys()).index( (bid.siteBinding,(bid.learningKey,bid.qostype))) history = [x[idx]*self.totalBudget/self.budgetRenewal for x in transTbl.stateHistory] start = max(0,len(history)-self.lamChangeInterval) history = max(history[start:]) except: history = (self.totalBudget / self.budgetRenewal) high = max(history,bid.price+2) bid.payment = np.random.randint(low=bid.price+1,high=high) transTbl.updateStateInfo(bidId) else: bid.payment = np.random.randint(low=bid.price+1, high=max(self.totalBudget,bid.price+2)) self.rewardBidlist.append(bidId) if (BidStatus.ADMIT in bidStatus.keys() and bidStatus[BidStatus.ADMIT]>=bidStatus[BidStatus.PREP]): bid.addReward = True # rebid or clean up if (self.rebid and bid.status in [BidStatus.REJECT] and bid.failReason not in [bfr.NA,bfr.DUPLICATE,bfr.ACTUAL_DUE_TIME] and self.model.schedule.steps < bid.dueTime and bid.nrRebid>0): bid.nrRebid -= 1 self.rebidlist.append(bidId) else: bid.finishTime = self.model.schedule.steps nrRebid = bp.nrRebid bidfile = self.model.filedict[FILES.BID_FILE[0]] bidfile.write( '{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{}\n'.format( self.model.schedule.steps+self.model.cumstep, bidId,bid.status,bid.isSuccess, bid.learningKey,bid.qostype,bid.price,bid.payment,bid.availBudget, bid.batchCreateTime,bid.createTime,bid.bestProposal.proposedDest, bid.finishTime,nrRebid-bid.nrRebid,bid.failReason,bid.value, self.curiosityExtRewardThres)) key = str(self.model.schedule.steps) if key not in self.model.acceptedBid.keys(): self.model.acceptedBid[key] = 0 if key not in self.model.rejectedBid.keys(): self.model.rejectedBid[key] = 0 accept = False for x in bid.statusHistory: if x[0]==BidStatus.ADMIT: self.model.acceptedBid[key] += 1 accept = True break if not accept: for x in bid.statusHistory: if (x[0]==BidStatus.REJECT and bid.finishTime>bid.batchCreateTime and bid.failReason!=bfr.DUPLICATE): self.model.rejectedBid[key] += 1 break # clean up bid.model = None bid.proposals = None bid.statusHistory = None self.bidHistory.append(bidId) def collectPriceModelNextState(self,stateVec,pos): ''' helper to record target state data in PriceLearningModel. the data is from TransitionTbl object while creating state vector for CompetitorLearningModel in TransitionTbl._addStateRecord from TransitionTbl.advance. @param stateVec: actual competitor state from TransitionTbl @param pos: corresponding position of data in priceMdl. ''' self.priceMdl.collectNextState(stateVec,pos) def step(self): if self.isActive: self.countdown -= 1 self.countdownHigh -= 1 self.countdownLow -= 1 if self.availLifespan <= 300: return if self.rsu is None: self._findRSU() self._chooseRSU() self._activateBids() # add external reward for curiosity model if (self.model.curiosity and self.model.schedule.steps % self.curiosityExtRewardThres==self.extRandom): bids = [x for k,x in self.model.bidlist.items() if (k in self.bidHistory) and (x.finishTime> self.model.schedule.steps-self.curiosityExtRewardThres)] totalBid = len(set([x.batch_id for x in bids])) if totalBid==0: totalBid = 1 successBid = sum([x.isSuccess for x in bids]) reward_ext = successBid / totalBid self.priceMdl.collectReward(reward_ext, self.learningDataPos,rewardType='ex') # reset budget pool for the next curiosityExtRewardThres steps self.budgetPool = 0 # (to train, to save attention.trainingData) self.priceMdl.trainWeightvector = (True,True) else: self.priceMdl.trainWeightvector = ( (int(self.learningDataPos)-self.prevRecordNr >=self.plmTrainingThres),False) if ((not self.model.trainable) or (self.model.evaluation) or (self.model.schedule.steps>=pmp.evaluation_start)): return trainPlm = ((int(self.learningDataPos)-self.prevRecordNr >=self.plmTrainingThres) or self.priceMdl.trainWeightvector[0]) trainCur = (int(self.learningDataPos)-self.prevRecordNr_curiosity >=self.curiosityTrainingThres) if trainCur: self.priceMdl.trainingdata = self.priceMdl.prep_data( self.model.schedule.steps+self.model.cumstep, self.model.filedict[FILES.FWDMDL_FILE[0]], curious=self.model.curiosity, model='curiosity') if self.priceMdl.actor is not None: _,_ = self.curiosityMdl.train( self.model.schedule.steps+self.model.cumstep, trainingdata=self.priceMdl.trainingdata, invmodelfile=self.model.filedict[FILES.INVMDL_FILE[0]], forwardmodelfile=self.model.filedict[FILES.FWDMDL_FILE[0]], pretrain=True,sharedLayers=self.priceMdl.actor.sharedLayers) self.prevRecordNr_curiosity = int(self.learningDataPos) self.priceMdl.update_curiousReward(self.curiosityMdl.reward) if trainPlm: self.priceMdl.train( time=self.model.schedule.steps+self.model.cumstep, plmfile=self.model.filedict[FILES.PLM_FILE[0]], rewardfile = self.model.filedict[FILES.REWARD_FILE[0]], invfile=self.model.filedict[FILES.INVMDL_FILE[0]], fwdfile=self.model.filedict[FILES.FWDMDL_FILE[0]], curMdl=self.curiosityMdl) self.superviseMdl.train( self.model.schedule.steps+self.model.cumstep, self.model.filedict[FILES.SL_FILE[0]], pmdlReward=self.priceMdl.reward) self.prevRecordNr = int(self.learningDataPos) def estimate(self): if self.isActive: self._fillPipeline() def allocate(self): # rsu allocates bids and adds rewards if (self.model.schedule.steps>0 and np.mod(self.model.schedule.steps,self.lamChangeInterval)==0): self._updateLambda() def advance(self): if (self.transitionTbl is None and len(self.bidHistory) >= self.competitorDataThres): self._createTransitionTbl() bidlist = self.bidHistory + self.activeBid self.model.transitionTbl[self.transitionTbl].populateTbl(bidlist) self._collectRewards() def move(self): self.model.grid.move_agent(self,(int(self.pos[0]),int(self.pos[1])) ) @classmethod def getInstances(cls): nonexistent = set() for ref in cls._instances: obj = ref() if obj is not None: yield obj else: nonexistent.add(ref) cls._instances -= nonexistent class Bid(Agent): ''' step:. estimate: 1. catch finished bids from Service._unloadService in Service.step, to deactivate the bid. Currently rewards are collected only upon admission in RSU.allocate (only when payment is determined for the first time, through a if-clause in the Vehicle.deactivateBid function). There is the possibility of implementing delayed reward on successfully finishing the bid. 2. collect proposals from all resource sites in range (currently all resource site are in range). pre-select the best proposal by ordering rules defined in ServiceProposal class. the bids will be allocated in RSU.allocate after this step. allocate:. advance:. ''' QoS1 = bp.QoS1 QoS2 = bp.QoS2 servAmount1 = bp.servAmount1 servAmount2 = bp.servAmount2 minDataSize = bp.minDataSize maxDataSize = bp.maxDataSize nrRebid = bp.nrRebid def __init__(self,bidId,qostype,servAmount,user,budget, createTime,coord,model,savedRecord=None): self.unique_id = bidId + '_' + str(qostype) super().__init__(self.unique_id, model) self.batch_id = bidId # bids with same batch id can only be # allocated once. self.user = user # associated vehicle. self.rsu = None # associated RSU. self.pos = coord # coordination of the bid, not used. self.availBudget = budget # vehicle total budget / budget renewal self.batchCreateTime = createTime # time bid is created self.finishTime = -1 # time bid is done self.createTime = createTime # time bid is sent to RSU for allocation self.siteBinding = None # current resource site processing the bid self.transmissionTimeTotal = 0 # transmission time if different sites self.transmissionTimeToGo = 0 # if zero then can be process by site. self.datasize = 0 # packet size relevant if allocated site changes self.price = 0 # total bidding price self.priceLeftover = 0 # calculated after each task is finished self.priority = 0 # if admitted by RSU but cannot be served, increase # priority to be considered earlier by RSU. self.qostype = qostype # qos type as part of bid category self.qosRequired = self.QoS1 if qostype==QoSType.HIGH else self.QoS2 self.servAmountLvl = servAmount # service amount level description self.servAmount = self.servAmount2 self.chain = list() # chain of tasks (instances of services) self.status = BidStatus.PREP # stage the bid is in self.statusHistory = [(self.status,self.createTime)] self.dueTime = 0 # required due time calculated from qos. self.estimFinishTime = 0 # estimated time for finishing the bid self.currentTask = 0 # current task in progress self.qosActual = -1 # actual qos needed self.isSuccess = 0 # indicator if successfully finished self.isActive = 0 # indicator if still active (in queue or process) self.proposals = dict() # duration and cost proposals from sites self.bestProposal = ServiceProposal(sys.maxsize,None, self.dueTime,None,0,dict()) # best proposal self.payment = -1 # second price as payment self.addReward = None # if admitted: additional reward from # free capacity of sites, calculated in # vehicle._collectRewards: # freeCapa,maxAmount,addReward self.environment = 0 # e.g. nr bids in rsu at time of creation self.competitorEnv = 0 # e.g. nr bids in rsu at time of allocation # to help find position for reward data in model self.priceLearningDataPos = -1 # key to connect input, output and # reward in PriceLearningModel self.failReason = bfr.NA # failed reason if rejected self.uplink = -1 # uplink delay self.uplinkEnd = -1 # timestep when uplink is finished if savedRecord is None: self._createPacket() self.savedRecord = self._saveRecord() self._createTaskChain(maxlength=bp.maxlength) else: self.datasize = savedRecord['datasize'] self._createTaskChainFromRecord(savedRecord) self.learningKey,self.taskSeq = self._createLearningKey() # bid category identifier, # also used as a state id for CompetitorLearningModel self.value = self._getBidValue() def _getBidValue(self): maxServiceAmount = max(self.servAmount1,self.servAmount2) maxQoS = max(1/self.QoS1,1/self.QoS2) maxTaskChainLen = len(cbd.services) proportion = ( (self.servAmount / maxServiceAmount) * (1/self.qosRequired / maxQoS) * (len(self.chain) / maxTaskChainLen) ) minProportion = 0.75 value = (minProportion * self.availBudget + (1 - minProportion) * self.availBudget * proportion) return value def _createPacket(self): ''' 0.4Mbit for odometry, 4Mbit for image ''' if self.qostype==QoSType.HIGH: self.datasize = self.minDataSize else: self.datasize = self.maxDataSize def _createTaskChain(self,maxlength=2): ''' create chain of tasks with random service type and sequence. resource profile associated with the service is also randomly generated based on a normal distribution defined in DefaultProfile. ''' if maxlength>1: services = cbd.services prob = [expon.pdf(x) for x in np.arange(1,len(services)+1)] prob = [x/sum(prob) for x in prob] length = 1 chain = [services[i] for i in np.random.choice(range(len(services)), size=length,replace=False,p=prob)] else: # regular tasks every 500 timesteps for 4Mbit packet, # every 100 timesteps for 0.4Mbit packet. if self.qostype==QoSType.HIGH: chain = [cbd.services[0]] else: chain = [cbd.services[1]] self.savedRecord['chain'] = chain savedProfiles = [] for pos, tup in enumerate(chain): serv, servType = tup # estim. resource profile created based on standard type of site: resProfile = DefaultProfile.randomPopulate(SiteType.TYPE1,servType) task = Task(pos,serv,servType,self.servAmount,self.unique_id, self.batchCreateTime,self.qosRequired,resProfile) savedProfiles.append(resProfile) self.chain.append(task) self.savedRecord['resProfile'] = savedProfiles def _createTaskChainFromRecord(self,savedRecord): ''' for repeatability, create bids from historical records ''' chain = savedRecord['chain'] for pos, tup in enumerate(chain): serv, servType = tup resProfile = savedRecord['resProfile'][pos] task = Task(pos,serv,servType,self.servAmount,self.unique_id, self.batchCreateTime,self.qosRequired,resProfile) self.chain.append(task) def _createLearningKey(self): ''' helper function to create key indicating the bid category, used in CompetitorLearningModel ''' key = list() bidTasks = dict([((x.serviceName,x.serviceType), x.pos) for x in self.chain[self.currentTask:]]) taskSequence = dict() for service in cbd.services: if service in bidTasks.keys(): key.append((service,self.servAmountLvl)) taskSequence[service] = bidTasks[service] + 1 else: key.append((service,ServiceAmount.LOW)) taskSequence[service] = 0 if len(key)==1: return key[0],taskSequence else: return tuple(key),taskSequence def _saveRecord(self): ''' save for repeatability''' locations = [x.span() for x in re.finditer('_',self.unique_id)] user = self.unique_id[0:locations[1][1]] batch = self.unique_id[locations[2][1]:locations[3][0]] savedRecord = {'qostype':self.qostype,'datasize':self.datasize, 'servAmount':self.servAmountLvl,'user':user, 'batch':batch,'batchCreateTime':self.batchCreateTime} return savedRecord def _calUplink(self): ''' protocal 802.11ac, with max. throughput of 1690Mbps; 250 grid units are equivalent to transmission range of 65 meters; transm. time = packet size in Mbit / (total throughput in Mbps / nr. users) * 1000 ms = 1000 * packet size in Mbit * nr. users / (-6.76 * distance in nr. grid units + 1690 Mbps) ''' origin = self.pos rsu = self.model.rsu[self.rsu] destiny = rsu.pos self.competitorEnv = rsu.nrActiveBids dist = np.sqrt((destiny[0]-origin[0])**2 + (destiny[1]-origin[1])**2) self.uplink = int(1000 * self.datasize * self.competitorEnv / (-6.76 * dist + 1690)) self.uplinkEnd = self.model.schedule.steps + self.uplink def setPrice(self,price,budget): ''' placeholder for setting bidding price (if deviation from given price). called from Vehicle._fillPipeline in Vehicle.estimate. @param price: learned bidding price for the bid from Vehicle.priceMdl. ''' # if the bid is from rebidding, deduct incurred costs self.price = min(price,budget - sum([t.cost for t in self.chain])) self.priceLeftover = self.price def activate(self): ''' helper function called from Vehicle._activateBids in Vehicle.step ''' self.isActive = 1 self.createTime = self.model.schedule.steps if self.uplink < 0: # not a rebid # TODO: in this setup, no uplink required for rebid self._calUplink() # update to transmission status, to consider uplink time self.updateResult(BidStatus.TRANSMIT,self.model.schedule.steps) else: self.uplinkEnd = self.model.schedule.steps # estim. downlink time, assuming same environment params if self.qostype==QoSType.LOW: # segmentation output: object-level labels # if pixel-level: downlink = uplink / 3 self.downlink = int(self.uplink / 10) else: self.downlink = 0 # motion plan output is negligible self.dueTime = self.batchCreateTime + self.qosRequired - self.downlink self.estimFinishTime = self.dueTime def updateResult(self,status,time,qosActual=-1,reason=None): ''' called in every stage of the bid lifecycle for a complete record. @param status: keyword of the stage @param time: status change time @param qosActual: actual time the bid is closed @param reason: fail reason if the bid is rejected. ''' if self.status == status: return self.status = status self.statusHistory.append((self.status,time)) if status==BidStatus.FINISH: self.qosActual = qosActual if qosActual<=0: self.failReason = bfr.ACTUAL_DUE_TIME elif self.qosRequired<qosActual: self.failReason = bfr.ESTIM_DUE_TIME elif (self.currentTask<len(self.chain)-1) and self.priceLeftover<0: self.failReason = bfr.COST else: self.isSuccess = 1 if status==BidStatus.REJECT: self.failReason = reason if status in (BidStatus.FINISH,BidStatus.REJECT): self.isActive = 0 def acceptProposal(self,siteId,rsuId,rsuHomesiteId): ''' called by RSU.allocate after evaluation of all proposals. @param siteId: unique_id of the resource site in RSU's allocation decision. @param rsuId: unique_id of the RSU @param rsuHomesiteId: unique_id of the resource site where RSU resides. ''' proposal = self.proposals[siteId] for pos in proposal.proposedResProfile.keys(): self.chain[ int(pos)].resProfileSelected = proposal.proposedResProfile[pos] self.siteBinding = proposal.proposedDest self.estimFinishTime = proposal.proposedEstimFinishTime self.transmissionTimeTotal = proposal.proposedTransmitTime self.transmissionTimeToGo = proposal.proposedTransmitTime def step(self): pass def estimate(self): ''' 1. catch finished bids from Service._unloadService in Service.step, to deactivate the bid. Currently rewards are collected only upon admission in RSU.allocate (only when payment is determined for the first time, through a if-clause in the Vehicle.deactivateBid function). There is the possibility of implementing delayed reward on successfully finishing the bid. 2. collect proposals from all resource sites in range (currently all resource site are in range). pre-select the best proposal by ordering rules defined in ServiceProposal class. the bids will be allocated in RSU.allocate after this step. ''' if self.siteBinding is None: self.siteBinding = self.rsu if self.model is None: # already deactivated: return if self.model.schedule.steps==self.uplinkEnd: self.updateResult(BidStatus.BID,self.model.schedule.steps) # some task of the bid is being processed: if self.status in (BidStatus.PREP,BidStatus.PROCESS, BidStatus.TRANSMIT): return if self.status in (BidStatus.REJECT,BidStatus.FINISH): self.model.rsu[self.rsu].removeBids(self.siteBinding, self.unique_id) self.model.vehicles[self.user].deactivateBid(self.unique_id) return self.proposals = dict() self.bestProposal = ServiceProposal(sys.maxsize,None, self.dueTime,None,0,dict()) for siteId in self.model.rsu[self.rsu].sites: s = self.model.sites[siteId] (duration,leftover,resProfile, cost,transmitTime) = s.estimTimeInSystem(self.unique_id) self.proposals[siteId] = ServiceProposal(cost,siteId, self.dueTime-leftover,self.unique_id,transmitTime,resProfile) if (self.proposals[siteId] > self.bestProposal and cost <= self.priceLeftover): self.bestProposal = self.proposals[siteId] def allocate(self): pass def advance(self): pass def __eq__(self, other): if isinstance(other, Bid): return (self.batch_id==other.batch_id and self.qostype==other.qostype) or ( self.unique_id==other.unique_id) return False class TransitionTbl(Agent): ''' step: 1. vehicle._activateBids triggers self.updateBidStateInfo to record actual bidding behavior of time t, which will become part of the inputVec(t) to CompetitorLearningModel. Full record will be created in self.advance in t, and collected into learning model in self.step in t+1. 2. self._chooseNextState is called to collect inputVec from t-1, and to "guess" current competitor state (output from the model) for time t. The output will be used in vehicle.estimate, where vehicle._fillPipeline will be called to run the PriceLearningModel and set prices for the next batch of bids. Note that due to the lag between pipeline and activation, these bids may not necessarily be activated in the time unit t+1. estimate: 1. vehicle._fillPipeline will create bids and assign budget to each bid based on guesses of current competitor state and the bids' service requirements, for activation in time t+1. 2. activated bids will be roll-calling sites for offering prices. 3. train competitor learning model in self.estimate. allocate: 1. rsu.allocate will allocate activated bids to sites or reject. admission result and payment in each bid is calculated for time t. 2. self.updateStateInfo is called by rsu.allocate to update "actual" competitor states for time t. This competitor state is a sampling of the actual distribution only with payment information. The information will become part of the inputVec in self.advance. advance: 1. self._addStateRecord creates competitor state record for time t based on activated bid info of time t from self.step, and actual competitor state info of time t from self.allocate. 2. self._addStateRecord also adds actual competitor state info to CompetitorLearningModel as result of the previous inputVec (for future supervised learning). 3. self.populateTbl can be run in this stage too for batch creation of dataset for training purposes. 4. self._addStateRecord also calls Vehicle.collectPriceModelNextState to add next stateVec to price learning model for $\hat V(S_{t+1},w)$ ''' trainingThres = tp.trainingThres historyPeriods = tp.historyPeriods def __init__(self,vehicleId,budget,benchmarkNrBid,model): self.unique_id = vehicleId + '_transition' super().__init__(self.unique_id,model) self.availBudget = budget # vehicle total budget / budget renewal self.benchmarkNrBid = benchmarkNrBid # for normalization of env. var. self.vehicle = vehicleId # associated vehicle # indicator if state has changed self.stateChangeFlag = {(s,k):0 for k in cbd.keys for s in self.model.sites.keys()} self.states = dict() # competitor states, categorized by # bid categories (service amount and qos type) self._resetCompetitorStates() # initiate state info self.bidStates = dict() # bid states, categorized by bid categories self._resetBidStates() # initiate bid state info self.estimNextState = list() # estimated next state self.stateHistory = list() # for creating input vector. keeping the # history enables creating input vector # from more than one previous state records self.newRecordFlag = False # flag if there are new state records. self.prevRecordNr = 0 # previous record number in clm self.priceLearningDataPos = 0 # for updating the next state in plm def _resetCompetitorStates(self): ''' initial setup ''' for siteId in self.model.sites.keys(): for k in cbd.keys: self.states[(siteId,k)] = list() def _getCompetitorStateRecord(self,rsuId=None): ''' simple processing of state inputs to avoid duplicate. e.g. if state information from different bids are different, simply take the maximum payment as the actual state. called by TransitionTbl._addStateRecord in TransitionTbl.advance ''' if rsuId is not None: secondPrices = self.model.rsu[rsuId].secondPrices state = list() for siteId in self.model.sites.keys(): for k in cbd.keys: if (siteId,k) in secondPrices.keys(): state.append(secondPrices[(siteId,k)]) else: state.append(0) return state state = list() for siteId in self.model.sites.keys(): for k in cbd.keys: if len(self.states[(siteId,k)])>0: state.append(max(self.states[(siteId,k)])) else: state.append(0) return state def _resetBidStates(self): ''' reset after each TransitionTbl._addStateRecord in TransitionTbl.advance ''' for k in cbd.keys: if k not in self.bidStates.keys(): self.bidStates[k] = BidState() else: self.bidStates[k].reset() def _chooseNextState(self,infer=False): ''' create TransitionTbl.estimNextState by running the CompetitorLearningModel's inference function. run in each time step in TransitionTbl.step. The estimated next state will be used in Vehicle._fillPipeline from Vehicle.estimate. also used in TransitionTbl.populateTbl, when batch inputs and target outputs are created before the TransitionTbl is created. In this case the function is used for generating input vectors, but the next state estimation will not be necessary. @param infer: if True, TransitionTbl.estimNextState is created normally. if False, it's only for populateTbl. ''' # if no updates, omit the step. if self.newRecordFlag is False: return # omit the time step record in history inputVec = [x[:-1] for x in self.stateHistory[-self.historyPeriods:]] if self.historyPeriods > 1: inputVec = [x for y in inputVec for x in y] #flatten else: inputVec = inputVec[0] # output: estimated current competitor state self.estimNextState = self.competitorStates self.newRecordFlag = False def _addStateRecord(self,nrActiveBids,timestep,rsuId=None): ''' called in TransitionTbl.advance. consolidates state information from individual bids (in RSU.allocate), bid state information, and environment variables to create input vectors and target outputs. also provide next state to vehicle's PriceLearningModel's critic. all variables and target outputs are normalized. @param nrActiveBids: environment variable. In reality this should be equivalent to channel occupancy and can be obtained by pinging the RSU and perceiving the delay. @param timestep: state record's time step. Normally this is the current time step. in populateTbl this is the bid creation time. ''' if sum(self.stateChangeFlag.values())==0: # no change in this time step self._resetBidStates() return if (len(self.stateHistory)>0 and self.stateHistory[-1][-1]==self.model.schedule.steps): # prevent duplicates in the same time step self._resetBidStates() return normalizedNrBids = nrActiveBids / self.benchmarkNrBid bidStates = [y for x in self.bidStates.values() for y in x.getRecord()] # if rsuId is given, the competitor state is from the rsu failed # bid information (rsu.secondPrices) # if rsuId is not given, then an estimation from the bid payment # information is used (self.state) # estimate of next state: if self.step has infer=False, # then use the current state. # if self.step has infer=True, then use the competitor model inference. self.competitorStates = self._getCompetitorStateRecord(rsuId=rsuId) self.stateHistory.append(self.competitorStates + bidStates + [normalizedNrBids,timestep]) buffer = int(max(vp.lamChangeInterval*2,tp.historyPeriods)*2) if len(self.stateHistory)>buffer: self.stateHistory = self.stateHistory[-buffer:] for key in self.stateChangeFlag.keys(): self.stateChangeFlag[key] = 0 self._resetBidStates() self.newRecordFlag = True self.model.vehicles[self.vehicle].collectPriceModelNextState( self.competitorStates,self.priceLearningDataPos) def populateTbl(self,bidlist): '''batch-create data record for CompetitorLearningModel''' if (len(bidlist)==0): return bidDict = dict([(x.unique_id,(x.createTime,x.environment)) for x in self.model.bidlist.values() if x.unique_id in bidlist]) sortedBids = [(k,v) for k,v in sorted(bidDict.items(), key=lambda item:item[1][0])] createTime = sortedBids[0][1][0] for bidId,(bidCreateTime,env) in sortedBids: if bidCreateTime>createTime: # collect output for training self._addStateRecord(env,bidCreateTime) # collect input for training self._chooseNextState(infer=False) createTime = bidCreateTime self.updateStateInfo(bidId) self.updateBidStateInfo(bidId) self._addStateRecord(env,bidCreateTime) def updateBidStateInfo(self,bidId): ''' collect bid information. called by Vehicle._activateBids in Vehicle.step. @param bidId: unique_id of the bid in question. ''' bid = self.model.bidlist[bidId] key = (bid.learningKey,bid.qostype) self.bidStates[key].nrBidsInCategory += 1 if bid.price / self.availBudget > self.bidStates[key].highestPrice: self.bidStates[key].highestPrice = bid.price / self.availBudget if bid.price / self.availBudget < self.bidStates[key].lowestPrice: self.bidStates[key].lowestPrice = bid.price / self.availBudget for pos in range(bid.currentTask,len(bid.chain)): servNameType = (bid.chain[pos].serviceName, bid.chain[pos].serviceType) if pos==bid.currentTask: self.bidStates[key].currentService[servNameType] += 1 else: self.bidStates[key].futureService[servNameType] += 1 self.priceLearningDataPos = bid.priceLearningDataPos def updateStateInfo(self,bidId): '''record actual competitor states after rsu.allocate''' bid = self.model.bidlist[bidId] rsu = self.model.vehicles[self.vehicle].rsu if bid.siteBinding is None or bid.siteBinding==rsu: return currentStateKey = (bid.siteBinding,(bid.learningKey,bid.qostype)) if self.stateChangeFlag[currentStateKey]==0: self.states[currentStateKey] = list() self.stateChangeFlag[currentStateKey] = 1 # if admitted is true, price is bid payment. else it is bidding price. bidStatus = dict(Counter([x[0] for x in bid.statusHistory])) if (BidStatus.ADMIT in bidStatus.keys() and bidStatus[BidStatus.ADMIT]>=bidStatus[BidStatus.PREP]): self.states[currentStateKey].append(bid.payment/self.availBudget) else: # use average of past guesses as state. for rejected bids, # payments are calculated in vehicle.deactivateBid self.states[currentStateKey].append((bid.payment)/self.availBudget) def step(self): ''' bids are activated from Vehicle._activateBids. bid information is also collected there by calling self.updateBidStateInfo. competitor states are collected in self.advance, either from rsu.secondPrices directly, or estimated from bid payment info and stored in self.states. If in self._chooseNextState infer=True, for the next step of setting bidding price, next competitor state is from model inference. Otherwise it's the copy of current competitor state. ''' self._chooseNextState(infer=False) def estimate(self): ''' bidding prices are set in Vehicle.estimate. ''' pass def allocate(self): ''' bid info with reward info collected here by rsu.allocate. updateStateInfo is called from Vehicle.allocate. ''' pass def advance(self): rsu = self.model.vehicles[self.vehicle].rsu env = self.model.rsu[rsu].nrActiveBids timestep = self.model.schedule.steps self._addStateRecord(env,timestep,rsuId=rsu) class V2XModel(Model): width = mp.width height = mp.height rsuPos = mp.rsuPos rsuInterval = mp.rsuInterval resSitePos = mp.resSitePos resSiteInterval = mp.resSiteInterval vehicleYposChoice = list(np.arange(*mp.vehicleYposChoice)) vehicleInterval = mp.vehicleInterval lam = mp.lam totalSimTime = mp.totalSimTime timeForNewVehicles = mp.timeForNewVehicles recent = mp.recent def __init__(self,filedict,nrSites=mp.nrSites,initVehicles=mp.initVehicles, nrRsu=mp.nrRsu,train=True,evaluation=False,repeatable=True, loadModel=False,resourceCapaIdx=0,rebid=False,curious=False, extRewardInterval=None,cumstep=0,endOfGame=5000, sumoDataOffset=0,ca=True): self.nrSites = nrSites # number of resource sites to create self.nrRsu = nrRsu # number of RSUs to create self.totalNrVehicles = 0 # for naming vehicles self.sites = dict() # list of ResourceSite objects self.rsu = dict() # list of RSU objects self.vehicles = dict() # list of Vehicle objects self.bidlist = dict() # list of Bid objects self.servicelist = dict() # list of Service objects self.transitionTbl = dict() # list of TransitionTbl objects self.filedict = filedict # all paths and names of output files self.trainable = train # if to run the training algorithms self.evaluation = evaluation # if only to run inference with already # trained model self.repeatable = repeatable # if create same bids with same interval self.loadModel = loadModel # if to use pre-trained models self.resourceCapaIdx = resourceCapaIdx self.rebid = rebid self.cumstep = cumstep self.endOfGame = endOfGame self.curiosity = curious self.ca = ca # if true: run simple credit assignment module; # if false: run attentionRNN module if extRewardInterval is None and self.curiosity: self.extRewardInterval = vp.curiosityExtRewardThres else: self.extRewardInterval = extRewardInterval # for curiosity model self._prepNewVehicle() self.trace = None self.extTraceData = False # if true, then read from SUMO self.sumoMatchTbl = dict() # matching sumo vehicle id to draco self.sumoActive = list() # active vehicle id (in draco) self.sumoActivePrev = list() # active id in previous round (in sumo) self.sumoInactive = list() # inactive vehicle id (in draco) self.maxActive = initVehicles # max. nr vehicles in graph at any time self.acceptedBid = dict() # record of nr. accepted bids self.rejectedBid = dict() # record of nr. rejected bids self._printHeader() # print all file headers # requires each agent to implement all methods # step, estimate, allocate, advance: self.schedule = SimultaneousActivation(self) # for visualization. not used. self.grid = MultiGrid(self.width, self.height, torus = False) # create sites for i in range(nrSites): if i==0: # sitetype = SiteType.TYPE3 # cloud elif i==1: sitetype = SiteType.TYPE1 # standard server elif i==2: sitetype = SiteType.TYPE2 # slow server else: sitetype = SiteType.TYPE1 if nrSites==1: sitetype = SiteType.TYPE1 agent = ResourceSite('site'+str(i),sitetype,self.resourceCapaIdx, self) agent.pos = (self.resSitePos[0] +self.resSiteInterval*i, self.resSitePos[1]) self.sites[agent.unique_id] = agent self.schedule.add(agent) self.siteId = [s.unique_id for s in self.sites.values()] self.siteDist = ResourceSiteDistance(self.siteId) for s in self.sites.values(): s.siteInfo = self.siteDist # create RSU for i in range(nrRsu): agent = RSU(uniqueId='RSU'+str(i),siteMat=self.siteDist,model=self) agent.pos = (self.rsuPos[0] +self.rsuInterval*i, self.rsuPos[1]) self.rsu[agent.unique_id] = agent self.schedule.add(agent) # create cars try: # load trace data path = os.path.join(LOGS_DIR,'vanetdata') if self.evaluation: if sumoDataOffset<endOfGame: filename = 'sumoTrace_schwantalerhoehe_eval.xml' else: filename = 'sumoTrace_schwantalerhoehe_trainNew.xml' else: filename = 'sumoTrace_schwantalerhoehe_trainNew.xml' self.trace = TraceData(path=path,filename=filename, gridRangeX=(1,self.width-1),gridRangeY=(1,self.height-1), dataOffset=sumoDataOffset) self.extTraceData = True except: # no trace data found if self.schedule.steps < self.timeForNewVehicles: self._createNewVehicles(initVehicles) def _prepNewVehicle(self): self.addId = '_' + str(self.nrSites) + '_' + str(self.trainable) # for identifying different models self.vehicleBudgetPath = os.path.join(MODEL_DIR,'vehicleBudget.pkl') self.saveVehicleBudgets = False try: self.vehicleBudgets = pickle.load(open(self.vehicleBudgetPath,'rb')) except: self.vehicleBudgets = None self.saveVehicleBudgets = True def _deactivateVehicle(self,agentId): self.sumoActive.remove(agentId) self.sumoInactive.append(agentId) agent = self.vehicles[agentId] agent.deactivateVehicle() def _reactivateVehicle(self,agentId,availLifespan,pos,speed, sumoId,rsu): agent = self.vehicles[agentId] agent.reset(availLifespan=availLifespan,pos=pos,speed=speed, sumoId=sumoId,rsu=rsu,isActive=True) self.sumoActive.append(agentId) self.sumoInactive.remove(agentId) def _createSingleNewVehicleFromSumo(self): singleFrame = self.trace.readSingleFrameFromSumo() # update newly removed ids activeIdsSumo = singleFrame['id'] newInactiveSumo = list(set(self.sumoActivePrev)-set(activeIdsSumo)) newInactiveDraco = [v for k,v in self.sumoMatchTbl.items() if k in newInactiveSumo] for agentId in newInactiveDraco: self._deactivateVehicle(agentId) self.sumoActivePrev = activeIdsSumo # create new vehicles in draco for nr in range(len(singleFrame['time'])): sumoId = singleFrame['id'][nr] pos = (singleFrame['x'][nr],singleFrame['y'][nr]) speed = singleFrame['speed'][nr] estimLifespan = singleFrame['estimLifespan'][nr] if sumoId not in self.sumoMatchTbl.keys(): if len(self.sumoActive)>=self.maxActive: # if too many active break if len(self.sumoInactive)==0: # create new in draco try: budget = self.vehicleBudgets[self.totalNrVehicles] except: budget = None self.saveVehicleBudgets = True if self.saveVehicleBudgets: vehicleBudgets = [x.totalBudget for x in self.vehicles.values()] pickle.dump(vehicleBudgets, open(self.vehicleBudgetPath,'wb')) agentId = self._createSingleNewVehicle(budget=budget, availLifespan=estimLifespan,pos=pos,speed=speed, sumoId=sumoId) self.sumoMatchTbl[sumoId] = agentId self.sumoActive.append(agentId) else: # reuse inactive draco vehicle agentId = self.sumoInactive[0] self.sumoMatchTbl[sumoId] = agentId self._reactivateVehicle(agentId=agentId, availLifespan=estimLifespan,pos=pos,speed=speed, sumoId=sumoId,rsu=None) else: # the same sumoId is still active, so is the draco id. agentId = self.sumoMatchTbl[sumoId] vehicle = self.vehicles[agentId] vehicle.reset(availLifespan=estimLifespan,pos=pos,speed=speed) def _createSingleNewVehicle(self,budget,availLifespan,pos,speed, sumoId=None): agent = Vehicle( uniqueId='vehicle'+str(self.totalNrVehicles)+self.addId, createTime=self.schedule.steps, availLifespan=availLifespan,pos=pos,speed=speed, model=self,sumoId=sumoId,totalBudget=budget,rebid=self.rebid, ca=self.ca) self.vehicles[agent.unique_id] = agent self.schedule.add(agent) self.totalNrVehicles += 1 return agent.unique_id def _createNewVehicles(self,nrArrivals): for i in range(nrArrivals): try: budget = self.vehicleBudgets[i] except: budget = None self.saveVehicleBudgets = True pos = (0+self.vehicleInterval*i, np.random.choice(self.vehicleYposChoice)) _ = self._createSingleNewVehicle(budget=budget,availLifespan=None, speed=0,pos=pos) if self.saveVehicleBudgets: vehicleBudgets = [x.totalBudget for x in self.vehicles.values()] pickle.dump(vehicleBudgets,open(self.vehicleBudgetPath,'wb')) def _printHeader(self): perfile = self.filedict[FILES.PERF_FILE[0]] perfTitle = 'step;occupied;utilization;maxAmount;sitetype;pmdlRecord;' perfTitle += 'totalBid;active;success;recentSuccess;accepted;' perfTitle += 'recentAccepted;rejectedBid;recentReject;finishedBid;' perfTitle += 'totalSuccessRatio;totalAcceptRatio;totalNonRejectRatio;' perfTitle += 'recentSuccessRatio;recentAcceptRatio;recentNonRejectRatio;' perfTitle += 'modelType;capacity;markovProb;budget;' perfTitle += 'extRewardInterval\n' if os.path.getsize(perfile.name) == 0: perfile.write(perfTitle) logfile = self.filedict[FILES.ALLOC_FILE[0]] logTitle = 'step;totalActiveBids;sortIdx;bidId;status;' logTitle += 'bidServiceKey;bidQoS;bidPrice;bidPayment;carBudget;' logTitle += 'batchCreate;createTime;site;sitetype;' logTitle += 'finishTime;nrRebid;decision;bidValue;' logTitle += 'extRewardInterval\n' if os.path.getsize(logfile.name) == 0: logfile.write(logTitle) bidfile = self.filedict[FILES.BID_FILE[0]] bidTitle = 'step;bidId;status;success;' bidTitle += 'bidServiceKey;bidQoS;bidPrice;bidPayment;carBudget;' bidTitle += 'batchCreate;createTime;site;' bidTitle += 'finishTime;nrRebid;failReason;bidValue;' bidTitle += 'extRewardInterval\n' if os.path.getsize(bidfile.name) == 0: bidfile.write(bidTitle) if self.trainable and not self.evaluation: plmfile = self.filedict[FILES.PLM_FILE[0]] plmTitle = 'step;vehicle;epoch;nrInput;avgReward;' plmTitle += 'criticLoss;actorLoss;attentionLoss;restart\n' if os.path.getsize(plmfile.name)==0: plmfile.write(plmTitle) slfile = self.filedict[FILES.SL_FILE[0]] slTitle = 'step;vehicle;epoch;nrInput;avgReward\n' if os.path.getsize(slfile.name)==0: slfile.write(slTitle) invmodelfile = self.filedict[FILES.INVMDL_FILE[0]] invTitle = 'step;vehicle;epoch;nrInput;avgInvLoss\n' if os.path.getsize(invmodelfile.name)==0: invmodelfile.write(invTitle) forwardmodelfile = self.filedict[FILES.FWDMDL_FILE[0]] fwdTitle = 'step;vehicle;epoch;nrInput;avgFwdLoss\n' if os.path.getsize(forwardmodelfile.name)==0: forwardmodelfile.write(fwdTitle) rewardfile = self.filedict[FILES.REWARD_FILE[0]] rewardTitle = 'step;vehicle;epoch;intReward;extReward\n' if os.path.getsize(rewardfile.name)==0: rewardfile.write(rewardTitle) def _print(self,perfile): if np.mod(self.schedule.steps,100)==0: print("step:{}".format(self.schedule.steps+self.cumstep)) recent = min(self.schedule.steps,self.recent) totalBid = len(set([x.batch_id for x in self.bidlist.values()])) if totalBid==0: totalBid = 1 # active bids being processed by rsu or servers # (not equal to unfinished. when bids are in pipeline # they are inactive). activeBid = len([x for x in self.bidlist.values() if x.isActive==1]) # finished bids finishedBid = len(set([x.batch_id for x in self.bidlist.values() if x.finishTime>x.batchCreateTime] )) # successfully finished bids successBid = sum([x.isSuccess for x in self.bidlist.values()]) # nr bids at least admitted once (but may have failed at the end) # regardless if the bid is finished acceptedBid = sum(self.acceptedBid.values()) # nr bids at least rejected once (but may be successful at the end) # until the bid is finished rejectedBid = sum(self.rejectedBid.values()) if finishedBid==0: finishedBid = 1 # nr of bids which are finished within the recent period of time recentBids = [x for x in self.bidlist.values() if x.finishTime>=self.schedule.steps-recent] recentTotal = len(set([x.batch_id for x in recentBids])) if recentTotal==0: recentTotal = 1 recentSuccess = sum([x.isSuccess for x in recentBids]) recentAccept = sum([v for k,v in self.acceptedBid.items() if int(k)>=self.schedule.steps-recent]) recentReject = sum([v for k,v in self.rejectedBid.items() if int(k)>=self.schedule.steps-recent]) perfile.write('{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{};{}\n'.format( self.schedule.steps+self.cumstep, [x.currentOccupied for x in self.sites.values()], # occupied [x.currentUtilization for x in self.sites.values()], # utilization [x.maxAmounts for x in self.sites.values()], # maxamount [x.sitetype for x in self.sites.values()], # sitetype pmp.history_record,totalBid,activeBid,successBid,recentSuccess, # pmdlRecord,totalBid,active,success,recentSuccess acceptedBid,recentAccept,rejectedBid,recentReject,finishedBid, # accepted,recentAccepted,rejectedBid,recentReject,finishedBid successBid/totalBid,acceptedBid/totalBid,1-rejectedBid/totalBid, # totalSuccessRatio(output used),totalAcceptRatio,totalNonRejectRatio recentSuccess/recentTotal,recentAccept/recentTotal,1-recentReject/recentTotal,# recentSuccessRatio,recentAcceptRatio,recentNonRejectRatio pmp.critic_type+'_'+pmp.actor_type, # modelType rsp.serviceCapa,vp.ph,vp.totalBudget, # capacity,markovProb,budget self.extRewardInterval # external reward interval in time steps )) def step(self): if self.extTraceData: self._createSingleNewVehicleFromSumo() else: nrArrivals = np.random.poisson(self.lam) self._createNewVehicles(nrArrivals) for agent in self.schedule.agents[:]: agent.step() for agent in self.schedule.agents[:]: agent.estimate() for agent in self.schedule.agents[:]: agent.allocate() for agent in self.schedule.agents[:]: agent.advance() self._print(self.filedict[FILES.PERF_FILE[0]]) self.schedule.steps += 1 self.schedule.time += 1 def calWin(model): totalWinning = 0 for agent in model.schedule.agents: if isinstance(agent, Vehicle): won = [x.isSuccess for x in agent.bidHistory] totalWinning = totalWinning + np.sum(won) return totalWinning
153,617
46.47157
151
py
malfoy
malfoy-master/v2x/solutions/__init__.py
0
0
0
py
malfoy
malfoy-master/v2x/solutions/attention.py
# -*- coding: utf-8 -*- import torch from torch import nn,optim,tensor from torch.nn import functional as F from ..config.config import (PRICE_MODEL_PARAMS as pmp,DEVICE) class EncoderRNN(nn.Module): max_length = pmp.batch_size def __init__(self, input_size, hidden_size=128): super().__init__() self.hidden_size = hidden_size self.embedding = nn.Linear(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size) def forward(self, input_tensor, hidden): embedded = F.relu(self.embedding(input_tensor)).view(1, 1, -1) output = embedded output, hidden = self.gru(output, hidden) return output, hidden class DecoderRNN(nn.Module): dropout_p = 0.1 max_length = pmp.batch_size def __init__(self, output_size, hidden_size=128): super().__init__() self.embedding = nn.Linear(output_size, hidden_size) self.attn = nn.Linear(hidden_size * 2, self.max_length) self.attn_combine = nn.Linear(hidden_size * 2, hidden_size) self.dropout = nn.Dropout(self.dropout_p) self.gru = nn.GRU(hidden_size, hidden_size) self.out = nn.Linear(hidden_size, output_size) def forward(self, decoder_input, hidden, encoder_outputs): embedded = F.relu(self.embedding(decoder_input)).view(1,1,-1) embedded = self.dropout(embedded) attn_weights = F.softmax( self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1) attn_applied = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0)) output = torch.cat((embedded[0], attn_applied[0]), 1) output = self.attn_combine(output).unsqueeze(0) output = F.relu(output) output, hidden = self.gru(output, hidden) output = nn.Sigmoid()(self.out(output[0])) return output, hidden, attn_weights class Attention(nn.Module): teacher_forcing_ratio = 0.5 epoch = 5 criterion = nn.MSELoss() def __init__(self,unique_id,input_size,output_size,maxReward): super().__init__() self.unique_id = unique_id + '_attentionMdl' self.output_size = output_size self.maxReward = maxReward self.encoder = EncoderRNN(input_size) self.decoder = DecoderRNN(output_size,self.encoder.hidden_size) self.encoder_optimizer = None self.decoder_optimizer = None self.avg_reward = 0 self.trainingdata = None def setOptim(self,lr=0.01): self.encoder_optimizer = optim.SGD(self.encoder.parameters(),lr=lr) self.decoder_optimizer = optim.SGD(self.decoder.parameters(),lr=lr) def initHidden(self,hidden_size): return torch.zeros(1, 1, hidden_size, device=DEVICE).float() def train(self,input_tensor,target_tensor,end_value=0): if end_value > self.maxReward: self.maxReward = end_value end_value = end_value / self.maxReward encoder_hidden = self.initHidden(self.encoder.hidden_size) sequence_length = input_tensor.size()[0] # input/output sequence length encoder_outputs = torch.zeros(self.encoder.max_length, self.encoder.hidden_size, device=DEVICE) for ei in range(sequence_length): encoder_output, encoder_hidden = self.encoder( input_tensor[ei], encoder_hidden) encoder_outputs[ei] = encoder_output[0, 0] # first (virtual) input decoder_inputs = torch.cat([ target_tensor.view(-1,1).float(), tensor([end_value],device=DEVICE).view(-1,1).float()]) decoder_hidden = encoder_hidden loss = 0 for di in range(sequence_length): decoder_output, decoder_hidden, decoder_attention = self.decoder( decoder_inputs[di], decoder_hidden, encoder_outputs) loss += self.criterion(decoder_output.view(-1,1), decoder_inputs[di+1].view(-1,1)) attention_loss = loss.detach() self.encoder_optimizer.zero_grad() self.decoder_optimizer.zero_grad() loss.backward() self.encoder_optimizer.step() self.decoder_optimizer.step() return attention_loss def inference(self,input_tensor,target_tensor,end_value=0.0): maxlength = self.encoder.max_length self.encoder.eval() self.decoder.eval() with torch.no_grad(): encoder_hidden = self.initHidden(self.encoder.hidden_size) sequence_length = input_tensor.size()[0] # input/output sequence length encoder_outputs = torch.zeros(maxlength, self.encoder.hidden_size, device=DEVICE) for ei in range(sequence_length): encoder_output, encoder_hidden = self.encoder(input_tensor[ei], encoder_hidden) encoder_outputs[ei] += encoder_output[0, 0] decoder_inputs = torch.cat( [tensor([-1.],device=DEVICE).view(-1,1), target_tensor.view(-1,1), tensor([end_value],device=DEVICE).view(-1,1)]).float() decoder_hidden = encoder_hidden for di in range(maxlength): decoder_output,decoder_hidden,decoder_attention = self.decoder( decoder_inputs[di], decoder_hidden, encoder_outputs) return decoder_attention.data.squeeze()
5,674
39.827338
83
py
malfoy
malfoy-master/v2x/supports/data.py
# -*- coding: utf-8 -*- import pandas as pd import numpy as np from itertools import combinations,product import sys,os #import xml.etree.ElementTree as et from lxml import etree from ..utils.common_utils import CommonUtils as utCom from ..config.config import (LOGS_DIR, RESOURCE_PARAMS as rp, VEHICLE_PARAMS as vp) #%% class Distr(): GAUSSIAN = 'gaussian' POISSON = 'poisson' class ServiceType(): TYPE1 = 'service1' # service capacity = max amount #/ 2 TYPE2 = 'service2' # service capacity = max amount class ServiceAmount(): HIGH = 'high' LOW = 'low' class ServiceName(): F1 = ('F1',ServiceType.TYPE1) F2 = ('F2',ServiceType.TYPE2) class SiteType(): TYPE1 = 'standard' TYPE2 = 'slow' TYPE3 = 'cloud' class ResourceType(): TYPE1 = 'resource1' TYPE2 = 'resource2' class ResourceName(): H1 = ('cpu', ResourceType.TYPE1) H2 = ('memory', ResourceType.TYPE2) class BidStatus(): PREP = 'in preparation' BID = 'new bid' ADMIT = 'admitted' TRANSMIT = 'in transmission' PROCESS = 'in process' REALLOCATE = 'can be reallocated' REJECT = 'rejected' FINISH = 'finished' ARCHIVE = 'archived' class BidFailureReason(): DUPLICATE = 'other bids in batch accepted' NO_AVAILABLE_SITE = 'no proposals from sites' COST = 'service cost too high' ESTIM_DUE_TIME = 'estimated time required too long' ACTUAL_DUE_TIME = 'already too late' NOPRIO = 'not prioritized' ONHOLD = 'on-hold for too long' NA = 'not applicable' class QoSType(): HIGH = 'high quality' LOW = 'low quality' class BidState(): lowest = vp.totalBudget[0] * 10 services = utCom.listClassVariables(ServiceName,'__',include=False) def __init__(self): self.reset() def reset(self): self.nrBidsInCategory = 0 self.highestPrice = 0 self.lowestPrice = self.lowest self.currentService = dict() self.futureService =dict() for s in self.services: self.currentService[s] = 0 self.futureService[s] = 0 def getRecord(self): if self.nrBidsInCategory==0: lowestPrice = 0 else: lowestPrice = self.lowestPrice return ( [self.nrBidsInCategory,self.highestPrice,lowestPrice] + list(self.currentService.values()) + list(self.futureService.values()) ) class DefaultProfile(): ''' creates duration based on amount from a normal distribution. Duration is a inverse function of amount. currently not scalable as only two service types are allowed. ''' # setting all std deviations of resource profiles to zero, to simplify # simulation of service time. AVG_AMT = {ServiceType.TYPE1:(8, 0), ServiceType.TYPE2:(16, 0)} DURATION = dict() DURATION[(SiteType.TYPE1,ServiceType.TYPE1)] = lambda amount: 10 DURATION[(SiteType.TYPE1,ServiceType.TYPE2)] = lambda amount: int(max(1, np.random.normal(100 / (amount + 1), 0))) DURATION[(SiteType.TYPE2,ServiceType.TYPE1)] = lambda amount: 20 DURATION[(SiteType.TYPE2,ServiceType.TYPE2)] = lambda amount: int(max(1, np.random.normal(200 / (amount + 1), 0))) DURATION[(SiteType.TYPE3,ServiceType.TYPE1)] = lambda amount: 10 DURATION[(SiteType.TYPE3,ServiceType.TYPE2)] = lambda amount: int(max(1, np.random.normal(100 / (amount + 1), 0))) @classmethod def randomGenerate(cls,siteType,serviceType): ''' given service type, create randomly amount required and duration required of one (random) resource. @param serviceType: service type name @return: resource amount required, duration required ''' amount = int(np.max([1,np.random.normal(*cls.AVG_AMT[serviceType])])) duration = cls.DURATION[(siteType,serviceType)](amount) return amount,duration @classmethod def randomPopulate(cls,siteType,serviceType): ''' given service type, randomly generate a resource profile. Currently services require all resources available. @param serviceType: service type name @return: resource profile (amount, duration) including all resources ''' resources = utCom.listClassVariables(ResourceName,'__',include=False) resProfile = dict() for res in resources: resProfile[res] = cls.randomGenerate(siteType,serviceType) return resProfile class ResourceSiteDistance(): ''' calculate distance between sites and transmission time in case the data need to be transmitted. ''' minDistance = 10 #km maxDistance = 50 cloudDistance = 4000 h = 127 # channel gain base sigmaSqrt = 2E-13 # gaussian noise p = 0.5 # transmission power of sender I = 1E-12 # inter-cell interference power W = 20E6 # channel width for wireless bitrate = 10E6 # 10Gbps, or 10 megabits per millisecond for wired # speed of light in fiber assumed to be 70% of vacuum speedOfLight = 299792458 / 1000 / 1000 * 0.7 # km/ms propRandomVar = 10 # random factor in calculating propagation delay def __init__(self,sitelist): self.sitelist = sitelist.copy() self.distanceMatrix = dict() for site in sitelist: self.distanceMatrix[(site,site)] = 0 for send,recv in combinations(sitelist,2): if send==sitelist[0]: self.distanceMatrix[(send,recv)] = self.cloudDistance else: self.distanceMatrix[(send,recv)] = np.random.randint( self.minDistance,self.maxDistance) self.distanceMatrix[(recv,send)] = self.distanceMatrix[(send,recv)] def addSite(self,siteid): if siteid in self.sitelist: print('siteid {} already exsists.'.format(siteid)) return self.distanceMatrix[(siteid,siteid)] = 0 for site in self.sitelist: self.distanceMatrix[(site,siteid)] = np.random.randint( self.minDistance,self.maxDistance) self.distanceMatrix[(siteid,site)] = self.distanceMatrix[ (site,siteid)] self.sitelist.append(siteid) def deleteSite(self,siteid): if siteid not in self.sitelist: print('siteid {} does not exsist.'.format(siteid)) return self.sitelist.remove(siteid) del self.distanceMatrix[(siteid,siteid)] for site in self.sitelist: del self.distanceMatrix[(site,siteid)] del self.distanceMatrix[(siteid,site)] def getWirelessLatency(self,sendId,recvId,dataSize): D = self.distanceMatrix[(sendId,recvId)] h = self.h + 30 * np.log10(D) r = self.W * np.log2(1+(self.p * h)/(self.sigmaSqrt + self.I)) return dataSize / r def getWiredLatency(self,sendId,recvId,dataSize): # datasize in Mbit propagation = self._getPropagationDelay(sendId,recvId) transmission = dataSize * 1e6 / self.bitrate return propagation + transmission def _getPropagationDelay(self,sendId,recvId): avg = self.distanceMatrix[(sendId,recvId)] / self.speedOfLight # in ms avg = avg + np.abs(np.random.normal(avg,avg/self.propRandomVar)) return avg class Task(): ''' tasks of a bid. each task is an instance of one service. ''' def __init__(self,position,serviceName,serviceType,serviceAmount, bidId,bidCreatetime,bidQos,resourceProfile): self.unique_id = 'task_' + str(bidId) + '_' + str(position) self.pos = position # position of the task in the service chain self.bidId = bidId # bid info self.bidQos = bidQos # bid info self.bidCreatetime = bidCreatetime # bid info self.serviceName = serviceName # corresponding service info self.serviceType = serviceType # corresponding service info self.serviceAmount = serviceAmount # number of service units required self.resProfileOriginal = resourceProfile # suggested resource profile self.resProfileSelected = None # final selected resource profile # by the resource site self.resProfileActual = None # final consumed resource profile in # resource site self.cost = 0 # cost of the task self.serviceBinding = None # service unique_id self.queueStart = 0 # time unit when entering the queue self.queueEnd = 0 # time unit when exiting the queue self.estimWaitingTimeTotal = 0 # estimated time to wait in queue self.estimWaitingTimeToGo = 0 # count down, not used self.serviceStart = 0 # time unit when entering server self.serviceEnd = 0 # time unit when exiting server self.serviceTime = 0 # total time served self.serviceTimeToGo = self.serviceTime # count down. when down to # zero, Service._unloadService is triggered self.isInQueue = False # indicator if in queue self.isInService = False # indicator if in service self.isFinished = False # indicator if done def updateResourceTime(self): ''' called by Service._unloadService from Service.step. deduct 1 in each time step from the time-to-go created in Task.resProfileActual. ''' release = list() for res in self.resProfileActual.keys(): resAmount, resDuration, resTimeToGo = self.resProfileActual[res] if resTimeToGo<=0: continue resTimeToGo -= 1 self.resProfileActual[res] = (resAmount,resDuration,resTimeToGo) if resTimeToGo==0: release.append(res) return release def updateServiceTime(self,servicetime,time,estim=False): ''' update service-related indicators and info ''' if estim is False: self.isInService = True self.serviceStart = time self.serviceTime = servicetime self.serviceTimeToGo = self.serviceTime def updateQueueTime(self,queuetime,time,estim=False): if estim is False: self.isInQueue = True self.queueStart = time self.estimWaitingTimeTotal = queuetime self.estimWaitingTimeToGo = queuetime class ActiveTaskInfo(): def __init__(self,taskId,serviceName,serviceType, amount,duration,startTime): ''' container for active task information specifically in resources ''' self.taskId = taskId self.serviceName = serviceName self.serviceType = serviceType self.amount = amount self.duration = duration self.startTime = startTime self.endTime = None class Resource(): ''' Resource created by resource sites. keeps track of utilization, loading and unloading, and allocation to different services sharing the same resource. ''' defaultMaxAmount = rp.defaultMaxAmount unitCost = {ResourceType.TYPE1:rp.unitCost[0], ResourceType.TYPE2:rp.unitCost[1]} def __init__(self,resName,resType,uniqueId,maxAmount=None): self.resName = resName self.resType = resType self.unique_id = uniqueId self.maxAmount = (maxAmount if maxAmount is not None else self.defaultMaxAmount) self.cost = self._calculateCost() self.occupied = dict() self.activeTaskList = dict() self.utilization = 0 # occupied / maxAmount self.occupiedHistory = dict() self.utilizationHistory = dict() self.taskHistory = list() self.allocated = dict() # allocated (max) resource per service self.allocatedHistory = dict() def _calculateCost(self): return int(np.max([1,np.random.normal(*self.unitCost[self.resType])])) def _updateInfo(self,serviceName,serviceType,resAmount,time): ''' helper function to update utilization ''' self.occupied[(serviceName,serviceType)] += resAmount self.occupiedHistory[(serviceName,serviceType)].append((self.occupied[ (serviceName,serviceType)],time)) self.utilization = sum(self.occupied.values()) / self.maxAmount self.utilizationHistory[str(time)] = self.utilization def _fillin(self,servNameType): ''' helper function ''' if servNameType not in self.occupied.keys(): self.occupied[servNameType] = 0 self.occupiedHistory[servNameType] = [(0,0)] if servNameType not in self.allocated.keys(): self.allocated[servNameType] = 0 self.allocatedHistory[servNameType] = [(0,0)] def startTask(self,taskId,serviceName,serviceType, amount,duration,startTime): ''' load task into server ''' self.activeTaskList[taskId] = ActiveTaskInfo(taskId, serviceName,serviceType,amount,duration,startTime) self._updateInfo(serviceName,serviceType,amount,startTime) def endTask(self,taskId,endTime): ''' unload task from server ''' if taskId in self.activeTaskList.keys(): taskInfo = self.activeTaskList.pop(taskId) taskInfo.endTime = endTime self.taskHistory.append(taskInfo) self._updateInfo(taskInfo.serviceName,taskInfo.serviceType, -taskInfo.amount,endTime) def checkResourceFeasibility(self,servName,servType,resAmount): ''' check if a required resource amount is feasible (within the limit of allocation to service). The function does not change maximum resource allocation to service. it's called by ResourceSite.checkResFeasibility and ultimately by Service._loadService. If not enough resource for the next-task-in-line then the queue waits. @param servName, servType: service identifiers @param resAmount: resource amount requested @return: feasibility, deviation from requested ''' servNameType = (servName,servType) self._fillin(servNameType) if resAmount > 0: # requests leftover = (self.allocated[servNameType] - self.occupied[servNameType]) if leftover < 0: return False,0 amount = min(resAmount,leftover) else: amount = resAmount return amount==resAmount, amount-resAmount def allocateResource(self,servName,servType,resAmount,time,estim=False): ''' allocate resource to the given service. called by ResourceSite.checkResFeasibility (for estimation only) and _adjustResAllocation (for actual allocation), and ultimately by ResourceSite._adjustCapacity. @param servName,servType: service identifier @param resAmount: requested resource amount @param time: time step for debugging @param estim: if True: estimate feasibility for capacity adjustment (specifically for a request to increase allocation to the given service). if False: do the allocation. ''' servNameType = (servName,servType) self._fillin(servNameType) if resAmount > 0: # requests leftover = self.maxAmount - sum(self.allocated.values()) if leftover < 0: return False,0 amount = min(resAmount,leftover) else: amount = resAmount if not estim: # actually allocate: self.allocated[servNameType] = max(self.occupied[servNameType], self.allocated[servNameType] + amount) self.allocatedHistory[servNameType].append( (time,self.allocated[servNameType])) return amount==resAmount, amount-resAmount class ServiceProposal(): ''' container for proposals created by resource sites and sent to the bids. ''' def __init__(self,bidCost,destId,estimFinishTime,dataId, transmitTime,resProfileSelected): self.proposedBidCost = bidCost self.proposedDest = destId self.proposedEstimFinishTime = estimFinishTime self.proposedDataId = dataId self.proposedTransmitTime = transmitTime self.proposedResProfile = resProfileSelected def reset(self): self.proposedBidCost = sys.maxsize self.proposedDest = None self.proposedEstimFinishTime = self.dueTime self.proposedDataId = None self.proposedTransmitTime = 0 self.proposedResProfile = dict() def __gt__(self,other): # "better than" return self.proposedBidCost < other.proposedBidCost def updateTaskSuccess(self,taskPos,taskSuccess=False): if self.taskPos==taskPos: self.taskSuccess = taskSuccess def updateTaskTransferred(self,taskPos,taskTransferred=False): if self.taskPos==taskPos: self.taskTransferred = taskTransferred def updateEnvInfo(self,nrVehicles,nrActiveBids): self.nrVehicles = nrVehicles self.nrActiveBids = nrActiveBids def updateBidInfo(self,bidSuccess,qosActual,priceLeftover): self.qosActual = qosActual self.bidSuccess = bidSuccess self.finalPriceLeftover = priceLeftover class SecondPriceData(): ''' container for creating bid records either for estimating the second price in v2x.RSU._recordSecondPrice, or for calculating the payment in v2x.RSU._calculatePayment. ''' services = utCom.listClassVariables(ServiceName,'__',include=False) TIME = 'time' QOS = 'qos' VEH = 'nrVehicles' BID = 'nrBids' ESTIM = 'estimSecondPrice' keys = services + [TIME,QOS,VEH,BID,ESTIM] def __init__(self,sites): self.record = dict() for k in sites + self.keys: self.record[k] = 0 def createKeysDeco(cls): # https://stackoverflow.com/questions/13900515/how-can-i-access-a-classmethod-from-inside-a-class-in-python cls.createKeys() return cls @createKeysDeco class CompetitorBaseData(): ''' container for static list of all services and resources, and keys for CompetitorLearningModel to access a class method from inside a static class, a decorator is used. This class method is executed together with creation of the static class (done via the decorator which calls on the class method). No need to instantiate. ''' services = utCom.listClassVariables(ServiceName,'__',include=False) serviceAmounts = utCom.listClassVariables(ServiceAmount,'__',include=False) qosTypes = utCom.listClassVariables(QoSType,'__',include=False) serviceLevels = list() keys = list() @classmethod def createKeys(cls): if len(cls.services)>1: levels = list() for s in cls.services: levels.append([(s,a) for a in cls.serviceAmounts]) serviceLevels = list(product(*levels)) else: serviceLevels = [(cls.services[0],a) for a in cls.serviceAmounts] cls.serviceLevels = serviceLevels cls.keys = list(product(serviceLevels,cls.qosTypes)) class TraceData(): def __init__(self,path=None,filename=None, gridRangeX=(0,200),gridRangeY=(0,200),dataOffset=0): if path is None: self.path = os.path.join(LOGS_DIR,'vanetdata') else: self.path = path if filename is None: filename = 'sumoTrace.xml' self.file = os.path.join(self.path,filename) self.context = etree.iterparse(self.file,tag='timestep') self.sumoTitle = ['time','id','x','y','angle','type', 'speed','lane','slope'] self.sumoTitleAdd = ['estimLifespan'] self.gridRangeX = gridRangeX self.gridRangeY = gridRangeY self.dataRangeX = (0,402) self.dataRangeY = (0,308) self.dataOffset = dataOffset # timestep to start simulation def _estimDataRange(self): self.readTraceDataFromSumo(nrRecord=100000,posOffset=False) self.dataRangeX = (int(min(self.sumoData['x'])), int(max(self.sumoData['x']))+1) self.dataRangeY = (int(min(self.sumoData['y'])), int(max(self.sumoData['y']))+1) def _posOffset(self,xpos,ypos): # fit the data value from dataRange to gridRange xposNew = int((xpos - self.dataRangeX[0]) / (self.dataRangeX[1] - self.dataRangeX[0]) * (self.gridRangeX[1] - self.gridRangeX[0]) + self.gridRangeX[0]) xposNew = np.clip(xposNew,self.gridRangeX[0],self.gridRangeX[1]) yposNew = int((ypos - self.dataRangeY[0]) / (self.dataRangeY[1] - self.dataRangeY[0]) * (self.gridRangeY[1] - self.gridRangeY[0]) + self.gridRangeY[0]) yposNew = np.clip(yposNew,self.gridRangeY[0],self.gridRangeY[1]) return (xposNew,yposNew) def _estimateLifespan(self,xpos,ypos,speed,angle): if speed==0: return None if angle < 180: x = self.dataRangeX[1] - xpos else: x = xpos if angle < 90 or angle > 270: y = self.dataRangeY[1] - ypos else: y = ypos dist = int(min(x/max(np.abs(np.cos(angle)),1e-4), y/max(np.abs(np.sin(angle)),1e-4) )) lifespan = int(dist/speed) return lifespan def _createEmptyDict(self,title): data = {} for t in title: data[t] = [] return data def _mergeDicts(self,dict0,dict1,title): for t in title: dict0[t] += dict1[t] return dict0 def _keepVehicle(self,vehicle): if vehicle['x']<self.dataRangeX[0] or vehicle['x']>self.dataRangeX[1]: return False if vehicle['y']<self.dataRangeX[0] or vehicle['y']>self.dataRangeX[1]: return False return True def _getNextNode(self,context): try: _,node = context.__next__() return node except StopIteration: # end of data del context return def readSingleFrameFromSumo(self,context=None, nrRecord=None,posOffset=False): if context is None: context = self.context node = self._getNextNode(context) if node is None: return timestep = int(float( node.attrib.get(self.sumoTitle[0]))) - self.dataOffset while timestep<0: node = self._getNextNode(context) if node is None: return timestep = int(float( node.attrib.get(self.sumoTitle[0]))) - self.dataOffset if nrRecord is not None and timestep > nrRecord: while node.getprevious() is not None: del node.getparent()[0] del context return singleFrame = self._createEmptyDict(self.sumoTitle+self.sumoTitleAdd) for node_child in list(node): # get each vehicle record at current timestep vehicle = {} for t in self.sumoTitle[1:]: # each data field for current vehicle vehicle[t] = node_child.attrib.get(t) if t not in ['id','lane','type']: vehicle[t] = np.round(float(vehicle[t]),decimals=2) if not self._keepVehicle(vehicle): continue # add estimated time to graph border given speed and angle vehicle[self.sumoTitleAdd[0]] = self._estimateLifespan( vehicle['x'],vehicle['y'],vehicle['speed'],vehicle['angle']) if posOffset: vehicle['x'],vehicle['y'] = self._posOffset(vehicle['x'], vehicle['y']) singleFrame[self.sumoTitle[0]].append(timestep) for t in self.sumoTitle[1:]+self.sumoTitleAdd: singleFrame[t].append(vehicle[t]) while node.getprevious() is not None: del node.getparent()[0] return singleFrame def readTraceDataFromSumo(self,nrRecord=100000,posOffset=False): self.sumoData = self._createEmptyDict(self.sumoTitle+self.sumoTitleAdd) context = etree.iterparse(self.file,tag='timestep') while True: # get each timestep singleFrame = self.readSingleFrameFromSumo(context=context, nrRecord=nrRecord,posOffset=posOffset) if singleFrame is None: break self.sumoData = self._mergeDicts(self.sumoData,singleFrame, self.sumoTitle+self.sumoTitleAdd) data = pd.DataFrame(self.sumoData) tmp = data.groupby(by='time',as_index=False).size() tmp = pd.DataFrame(tmp,columns=['count']) self.sumoGrpData = tmp
26,138
39.029096
111
py
malfoy
malfoy-master/v2x/supports/__init__.py
0
0
0
py
malfoy
malfoy-master/v2x/utils/name_utils.py
# -*- coding: utf-8 -*- class ColumnHead(): ATT = 'D2+R_2000' CUR = 'CUR' LEARNED = 'D2+R_1' RANDOM = 'RIAL' ACTORLOSS = 'actorLoss' ADMITTED = 'admitted' ADMITTEDRATE = 'totalAcceptRatio' ADMITTEDRATEBYTIME = 'admitted rate by time' # includes also bids admitted by # failed to execute, of total number of bids ATTENTIONLOSS = 'attentionLoss' AVERAGEATTENTIONLOSS = 'average attention loss' AVERAGEINTRINSICREWARD ='average intrinsic reward' AVERAGELOSS = 'average loss' AVERAGELOSSFORWARD = 'average loss forward' AVERAGELOSSINVERSE = 'average loss inverse' AVERAGELOSSSL = 'average loss_sl' AVERAGEREWARDRL = 'average reward_rl' AVGFWDLOSS = 'avgFwdLoss' AVGINVLOSS = 'avgInvLoss' AVGREWARD = 'avgReward' ALGORITHMTYPE = 'algorithm type' BACKOFFTIME = 'backoff time' BATCHCREATE = 'batchCreate' BATCHSIZE = 'batchsize' BIDID = 'bidId' BIDPAYMENT = 'bidPayment' BIDPRICE = 'bidPrice' BIDQOS = 'bidQoS' BIDVALUE = 'bidValue' BUDGET = 'budget' CAPACITY = 'capacity' # or 'resource' CARBUDGET = 'carBudget' CAT = 'cat' CATEGORY = 'category' CLOUD = 'cloud' COMPETITORLOSS = 'competitorLoss' CREATETIME = 'createTime' CRITICLOSS = 'criticLoss' CURIOSITYLOSS = 'curiosity loss' DEADLINE = 'deadline' DECISION = 'decision' DIFFERENCE = 'difference' EXTREWARD = 'extReward' EXTREWARDINTERVAL = 'extRewardInterval' EXTRINSICREWARD = 'extrinsic reward' FAILEDRATE = 'failure rate' FAILURERATEBYTIME = 'failure rate by time' # includes both rejected and admitted but failed, of finished bids FILEVERSION = 'file version' FINISHEDBID = 'finishedBid' FINISHTIME = 'finishTime' INTERVAL = 'interval' INTREWARD = 'intReward' INTRINSICREWARD = 'intrinsic reward' MAXAMOUNT = 'maxAmount' MAXREBIDOLD = 'max. rebid' MAXREBIDOLD2 = 'max rebid' MEANDIFFERENCE = 'mean difference' MODELTYPE = 'modelType' MP = 'MP' # previously 'max. rebid' or 'max rebid' or 'rebid' NRREBID = 'nrRebid' NRSITES = 'nrSites' OCCUPIED = 'occupied' PRICERANGE = 'price range' REBID = 'rebid' RECENTNONREJECTRATIO = 'recentNonRejectRatio' RELIABILITY = 'reliability' REJECTEDBID = 'rejectedBid' REJECTEDRATEBYTIME = 'rejection rate by time' # only rejected, of total number of bids RETRAIN = 'retrained' SAVING = 'saving' SELECTED = 'selected' SITE = 'site' SITETYPE = 'sitetype' SORTIDX = 'sortIdx' STANDARD = 'standard' STATUS = 'status' STEP = 'step' SUCCESS = 'success' SUCCESSRATE = 'success rate' # admitted and successfully executed before deadline, of finished bids SUCCESSRATEBYTIME = 'success rate by time' TOTALACTIVEBIDS = 'totalActiveBids' TOTALBID = 'totalBid' TOTALBYQOS = 'total_byQos' TOTALSUCCESSRATIO = 'totalSuccessRatio' TRAINED = 'trained' TYPE = 'type' UTILIZATION = 'utilization' VEHICLE = 'vehicle' VEHICLECOUNT = 'vehicle count' VERSION = 'version' WEIGHTEDINTRINSICREWARD = 'weighted intrinsic reward'
3,805
37.06
123
py
malfoy
malfoy-master/v2x/utils/common_utils.py
# -*- coding: utf-8 -*- import re from ..config.config import FILES class CommonUtils(): def listClassVariables(clazz,text='__',include=False): pattern = re.compile(text) if include: elements = [clazz.__dict__[variable] for variable in clazz.__dict__.keys() if pattern.match(variable)] else: elements = [clazz.__dict__[variable] for variable in clazz.__dict__.keys() if not pattern.match(variable)] return elements def listClassNames(clazz,text='__',include=False,func=False): pattern = re.compile(text) if not func: names = [variable for variable in clazz.__dict__.keys() if not callable(clazz.__dict__[variable])] else: names = [variable for variable in clazz.__dict__.keys()] if include: names = [x for x in names if pattern.match(x)] else: names = [x for x in names if not pattern.match(x)] return names def listClassItems(clazz,text='__',include=False,func=False): pattern = re.compile(text) if not func: items = [(k,v) for k,v in clazz.__dict__.items() if not callable(v)] else: items = [(k,v) for k,v in clazz.__dict__.items()] if include: items = dict([x for x in items if pattern.match(x[0])]) else: items = dict([x for x in items if not pattern.match(x[0])]) return items def recreateDict(originalDict,idx): if isinstance(idx,int): return dict(zip(originalDict.keys(),[x[idx] for x in originalDict.values()])) elif isinstance(idx,str): return dict(zip(originalDict.keys(),[eval('x.'+idx) for x in originalDict.values()])) else: return originalDict def openFiles(additional=None,files=None,trainable=True): if additional is None: additional = [] if files is None: files = CommonUtils.listClassVariables(FILES,'__') filedict = dict() for name,addr in files: for i in additional: addr = addr + '_' + str(i) addr += '.txt' if 'Model' in addr and not trainable: filedict[name] = None else: filedict[name] = open(addr,'a+') return filedict def closeFiles(filedict): for addr in filedict.values(): if addr is not None: addr.close()
2,624
35.971831
84
py
malfoy
malfoy-master/v2x/utils/__init__.py
0
0
0
py
malfoy
malfoy-master/v2x/utils/graphic_utils.py
# -*- coding: utf-8 -*- from ..config.config import (GRAPH_DIR, MDL_PARAMS as mp, RESOURCE_SITE_PARAMS as rsp, VEHICLE_PARAMS as vp, PRICE_MODEL_PARAMS as pmp) from ..supports.data import TraceData from ..utils.name_utils import ColumnHead as ch import glob,os,re,ast import pandas as pd import numpy as np from scipy.optimize import curve_fit from itertools import product import matplotlib.pyplot as plt from matplotlib.ticker import ScalarFormatter plt.rcParams['xtick.labelsize']=15 plt.rcParams['ytick.labelsize']=15 plt.rc('pdf',fonttype=42) plt.ioff() import seaborn as sns from scipy.stats import gaussian_kde class OOMFormatter(ScalarFormatter): def __init__(self, order=0, fformat="%1.1f", offset=True, mathText=True): self.oom = order self.fformat = fformat ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText) def _set_order_of_magnitude(self): self.orderOfMagnitude = self.oom def _set_format(self, vmin=None, vmax=None): self.format = self.fformat if self._useMathText: self.format = r'$\mathdefault{%s}$' % self.format class Graphics: learned = ch.LEARNED random = ch.RANDOM retrain = ch.RETRAIN att = ch.ATT cur = ch.CUR def __init__(self,path): self.path = path def _collectData(self,name,density=1): name = name + '*' filename = os.path.join(self.path,name) perfiles = glob.glob(filename) data = pd.DataFrame() data_part = pd.DataFrame() for f in perfiles: try: data_part = pd.read_csv(f,sep=';') except: continue if density>1: data_part[ch.STEP] = data_part[ch.STEP].apply( lambda x: int(x/density) * density) groupcols = list(data_part.columns) groupcols = [x for x in groupcols if data_part[x].dtype==np.object and x not in [ch.OCCUPIED,ch.UTILIZATION,ch.MAXAMOUNT]] data_part = data_part.groupby( [ch.STEP]+groupcols, as_index=False).mean() locations = [x.span() for x in re.finditer('_',f)] try: nrSites = str(f[locations[-2][1]:locations[-1][0]]) + 'sites' fileversion = str(f[locations[-2][0]-1 :locations[-2][0]]) if not re.match('\d',fileversion): fileversion = '' except: continue trained = (self.learned if f[locations[-1][1]:-4]=='True' else self.random) if 'att' in f.lower(): trained = self.att elif 'cur' in f.lower(): trained = self.cur if 'Retrain' in f: trained = trained + ' ' + self.retrain data_part[ch.NRSITES] = nrSites data_part[ch.TRAINED] = trained try: interval = str(f[locations[-3][1]:locations[-2][0]]) except: interval = 0 data_part[ch.INTERVAL] = interval if ch.BIDID in data_part.columns: data_part[ch.BIDID] = data_part[ch.BIDID].apply( lambda x: fileversion+x) if data.shape[0]==0: data = data_part else: data = pd.concat([data,data_part],axis=0) if not ch.MODELTYPE in data.columns: data[ch.MODELTYPE] = 'MLP' data[ch.BATCHSIZE] = pmp.batch_size return data def _drawLineplot(self,df,x,y,title,style=None,hue=None,order='flex', hue_order=None,legends=2,legendFontsize=None, tickFontsize=None,size=None,separate=None, decimals=1,ci=None,showTable=False,vertical=True, ylim=None,yscale='linear',yaxisTick='left'): defaultFontsize = 16 if tickFontsize is None: tickFontsize = defaultFontsize if legendFontsize is None: legendFontsize = defaultFontsize if size is None: length = 5 height = 4 else: length = size[0] height = size[1] if separate is None: if hue is not None: if hue_order is None: if order=='flex': tmp = df.groupby(hue) tmp = (tmp.tail(1).drop_duplicates() .sort_values(y,ascending=False)) else: tmp = df.groupby( hue,as_index=False).max().sort_values(hue) hue_order = tmp[hue].tolist() else: hue_order = None fig,ax = plt.subplots() fig.set_size_inches(length,height) try: # density = max(len(hue_order),5) # dashes = [(density-x, max(2,x) if x>0 else 0, # 2*x, max(2,x) if x>0 else 0) # for x in list(range(len(hue_order)))] dashes = [(len(hue_order)-x,x,2*x,x) for x in list(range(len(hue_order)))] except: dashes = None try: ax = sns.lineplot(x=x,y=y,style=style,hue=hue,data=df,ci=ci, hue_order=hue_order,style_order=hue_order, dashes=dashes) except ValueError: # not enough styles ax = sns.lineplot(x=x,y=y,style=style,hue=hue,data=df,ci=ci, hue_order=hue_order,dashes=dashes) if ylim is not None: ax.set_ylim(ylim[0],ylim[1]) ax.set_yscale(yscale) ax.set_xlabel(xlabel=x,fontsize=tickFontsize) ax.set_ylabel(ylabel=y,fontsize=tickFontsize) # ax.set_xticklabels(np.int0(ax.get_xticks()),size=tickFontsize) ax.tick_params(axis='both',which='major',labelsize=tickFontsize) ax.tick_params(axis='both',which='minor',labelsize=tickFontsize-3) yformatter = ScalarFormatter(useOffset=True,useMathText=True) xformatter = OOMFormatter(order=3,fformat='%2.0f') ax.yaxis.set_major_formatter(yformatter) ax.yaxis.set_minor_formatter(yformatter) ax.xaxis.set_major_formatter(xformatter) ax.xaxis.get_offset_text().set_fontsize(tickFontsize) # ax.ticklabel_format(style='sci', axis='x', scilimits=(3,3)) if decimals==0: ax.set_yticklabels(np.int0(ax.get_yticks()),size=tickFontsize) else: ax.set_yticklabels(np.round(ax.get_yticks(), decimals=decimals),size=tickFontsize) if yaxisTick=='right': ax.yaxis.tick_right() if legends is not None: handles, labels = ax.get_legend_handles_labels() l = ax.legend(handles[1:],labels[1:],loc=legends, fontsize=legendFontsize) plt.savefig(os.path.join(GRAPH_DIR, title.replace(' ','')+'.pdf'), bbox_extra_artists=(l,), bbox_inches='tight') else: l = ax.legend() l.remove() plt.savefig(os.path.join(GRAPH_DIR, title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() else: sepCol = list(set(df[separate])) if vertical: fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) else: fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True) fig.set_size_inches(length,height) df1 = df.loc[df[separate]==sepCol[0]] df2 = df.loc[df[separate]==sepCol[1]] if hue is not None: if hue_order is None: if order=='flex': tmp1 = df1.groupby(hue) tmp1 = (tmp1.tail(1).drop_duplicates() .sort_values(y,ascending=False)) tmp2 = df2.groupby(hue) tmp2 = (tmp2.tail(1).drop_duplicates() .sort_values(y,ascending=False)) else: tmp1 = df1.groupby( hue,as_index=False).max().sort_values(hue) tmp2 = df2.groupby( hue,as_index=False).max().sort_values(hue) hue_order1 = tmp1[hue].tolist() hue_order2 = tmp2[hue].tolist() else: hue_order1 = None hue_order2 = None g1 = sns.lineplot(x=x,y=y,style=style,hue=hue,data=df1,ci=ci, hue_order=hue_order1,style_order=hue_order1,ax=ax1) g2 = sns.lineplot(x=x,y=y,style=style,hue=hue,data=df2,ci=ci, hue_order=hue_order2,style_order=hue_order2,ax=ax2) ax1.set_yscale(yscale) ax2.set_yscale(yscale) ax1.set_xticklabels(np.int0(ax1.get_xticks()), size=tickFontsize) ax2.set_xticklabels(np.int0(ax2.get_xticks()), size=tickFontsize) ax1.set_yticklabels(np.round(ax1.get_yticks(), decimals=decimals),size=tickFontsize) ax2.set_yticklabels(np.round(ax2.get_yticks(), decimals=decimals),size=tickFontsize) ax1.xaxis.label.set_size(tickFontsize) ax2.xaxis.label.set_size(tickFontsize) ax1.yaxis.label.set_size(tickFontsize) ax2.yaxis.label.set_size(tickFontsize) if showTable: fig.subplots_adjust(hspace=0.5) ax1.xaxis.set_visible(False) ax2.set_xticklabels([]) ax2.xaxis.labelpad = 30 ax2.tick_params(bottom=False) values1,values5,alg,column = self._createTbl(servicedata=df, hue=hue,alg=[self.learned,self.random], separate=separate,target=y) ax1.table(cellText=values1,rowLabels=alg, colLabels=column,loc='bottom') ax2.table(cellText=values5,rowLabels=alg, colLabels=column,loc='bottom') if yaxisTick=='right': ax1.yaxis.tick_right() ax2.yaxis.tick_right() if legends is not None: handles1, labels1 = ax1.get_legend_handles_labels() ax1.legend(handles1[1:],labels1[1:],loc=legends, fontsize=legendFontsize) handles2, labels2 = ax2.get_legend_handles_labels() ax2.legend(handles2[1:],labels2[1:],loc=legends, fontsize=legendFontsize) else: l = ax.legend() l.remove() plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() def _drawCdfFromKde(self,df,hue,target,style,title, col=None,xlim=(0,1),loc=4,size=(10,4)): if col is None: plt.figure(figsize=(5,4)) hue_order = list(set(df[hue])) hue_order.sort() for grp in hue_order: tmp = df.loc[df[hue]==grp,target] tmp = np.array(tmp) kde = gaussian_kde(tmp) cdf = np.vectorize(lambda x: kde.integrate_box_1d(-np.inf,x)) x = np.linspace(xlim[0],xlim[1]) plt.plot(x,cdf(x),linestyle=style[grp],label=grp) plt.legend(loc=loc,fontsize=15) plt.ylabel('CDF',fontsize=15) plt.xlabel(target,fontsize=15) print(target) plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() else: x = np.linspace(xlim[0],xlim[1]) newDf = pd.DataFrame() for c in set(df[col]): for grp in set(df[hue]): tmp = df.loc[(df[hue]==grp) & (df[col]==c),target] tmp = np.array(tmp) kde = gaussian_kde(tmp) cdf = np.vectorize( lambda y:kde.integrate_box_1d(-np.inf,y)) tmp0 = pd.DataFrame(np.vstack([x,cdf(x)]).transpose(), columns=[target,'CDF']) tmp0[hue] = grp tmp0[col] = c if len(newDf)==0: newDf = tmp0 else: newDf = pd.concat([newDf,tmp0],axis=0) fig,ax = plt.subplots() ax = sns.FacetGrid(data=newDf,col=col,) ax.fig.set_size_inches(size[0],size[1]) ax.map_dataframe(sns.lineplot,target,'CDF',hue, style=hue,hue_order=list(style.keys()), style_order=list(style.keys()),ci=None) ax.set(xlim=xlim) for axes in ax.axes.flat: axes.set_ylabel('CDF', fontsize=15) axes.set_xlabel(target, fontsize=15) axes.set_title(axes.get_title(),fontsize=15) handles, labels = ax.axes[0][-1].get_legend_handles_labels() l = ax.axes[0][-1].legend(handles[1:],labels[1:], loc=loc,fontsize=15) plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_extra_artists=(l,),bbox_inches='tight') plt.clf() def _drawBoxplot(self,df,x,y,title,hue=None,legends=3,ylabel=None, legendFontsize=None,figsize=None, myPalette=None,hue_order=None): if figsize is None: figsize = (5,4) defaultFontsize = 16 if legendFontsize is None: legendFontsize = defaultFontsize if ylabel is None: ylabel = y sns.set_style('white') fig, ax = plt.subplots() fig.set_size_inches(figsize) if myPalette is None: myPalette = {self.random:'C1',self.learned:'C0'} sns.boxplot(data=df,x=x,y=y,ax=ax,hue=hue, showfliers=False,palette=myPalette, showmeans=True,meanprops={'marker':'o','markerfacecolor':'white', 'markeredgecolor':'white'},hue_order=hue_order) ax.set_xlabel(xlabel=x,fontsize=defaultFontsize) ax.set_ylabel(ylabel=ylabel,fontsize=defaultFontsize) if len(set(df[x]))>12: for ind, label in enumerate(ax.get_xticklabels()): if ind % 2 == 0: label.set_visible(True) else: label.set_visible(False) if legends is not None: handles, labels = ax.get_legend_handles_labels() l = ax.legend(handles,labels,loc=legends,fontsize=legendFontsize) plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_extra_artists=(l,), bbox_inches='tight') else: l = ax.legend() l.remove() plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() def _parse(self,value,sitetype): a = ast.literal_eval(value) values = {} for i,x in enumerate(a): site = 'site' + str(i) stype = sitetype[site] for key in x.keys(): values[stype+'_'+site+'_'+str(key[1])] = x[key] return pd.Series(values) def _parseColumn(self,df,target,sitetype): result = df[target].apply(lambda x: self._parse(x,sitetype)) col = result.columns col0 = [target + '_' + x for x in col] result.columns = col0 return result def _outputFailureComparison(self,data=None,path=None,prefix='', textOutput=False,graphicOutput=True,legends=2,stepRange=None, nrSites='2sites'): name = 'performance' if data is None: data = self._collectData(name) try: data[ch.SUCCESSRATE] = data[ch.SUCCESS]/data[ch.FINISHEDBID] except: data[ch.SUCCESSRATE] = data[ch.SUCCESS]/data[ch.TOTALBID] try: data[ch.FAILEDRATE] = data[ch.REJECTEDBID]/data[ch.FINISHEDBID] except: data[ch.FAILEDRATE] = data[ch.REJECTEDBID]/data[ch.TOTALBID] # data[ch.TRAINED] = np.where(data[ch.TRAINED]==self.random, # self.random,self.learned) data[ch.CATEGORY] = data.apply(lambda row: row[ch.TRAINED] + '_' + str(row[ch.NRSITES]) + '_' + str(row[ch.MODELTYPE]),axis=1) cols = list(data.columns) if ch.SUCCESSRATEBYTIME not in cols: cols[cols.index(ch.TOTALSUCCESSRATIO)] = ch.SUCCESSRATEBYTIME data.columns = cols barChart = pd.DataFrame() coln = [ch.NRSITES,'success '+self.learned, 'success '+self.random, ch.SUCCESSRATE,'failed '+self.learned, 'failed '+self.random,ch.FAILEDRATE] barGrp = ['failed '+self.random, 'failed '+self.learned] barGrp2 = ['success '+self.random,'success '+self.learned] note = 'learned_vs_random' learned = data[(data.trained==self.learned) & (data.nrSites==nrSites)] random = data[(data.trained==self.random) & (data.nrSites==nrSites)] try: min_learned = max(learned[ch.STEP]) - mp.recent except: min_learned = 0 try: min_random = max(random[ch.STEP]) - mp.recent except: min_random = 0 learned = learned.loc[learned[ch.STEP]>=min_learned,:] random = random.loc[random[ch.STEP]>=min_random,:] successLearned = np.mean(learned[ch.SUCCESSRATE]) successRandom = np.mean(random[ch.SUCCESSRATE]) successRate = (successLearned-successRandom)/successRandom failedLearned = np.mean(learned[ch.FAILEDRATE]) failedRandom = np.mean(random[ch.FAILEDRATE]) failedRate = -(failedLearned-failedRandom)/failedRandom row = pd.DataFrame([[nrSites,successLearned,successRandom,successRate, failedLearned,failedRandom,failedRate]],columns=coln) if len(barChart)==0: barChart = row else: barChart = pd.concat([barChart,row],axis=0) if stepRange is None: if max(data.step)>4000: data = data[data.step>800] else: data = data.loc[(data[ch.STEP]<=stepRange[1]) & (data[ch.STEP]>=stepRange[0])] xGrp = ch.NRSITES barChart.sort_values(by=xGrp,inplace=True) data = data[[ch.STEP,ch.MODELTYPE,ch.TRAINED,ch.SUCCESSRATE]].groupby( [ch.STEP,ch.MODELTYPE,ch.TRAINED],as_index=False).mean() if graphicOutput: self._drawLineplot(df=data,x=ch.STEP,y=ch.SUCCESSRATE, title=name+'_line_'+prefix+'_success rate_'+note, style=ch.TRAINED,hue=ch.TRAINED,order='flex',legends=legends) self._drawBarChart(df=barChart,xGrp=xGrp,barGrp=barGrp2, yLabel=ch.SUCCESSRATE, title=name+'_'+prefix+'_success rate_'+note) self._drawBarChart(df=barChart,xGrp=xGrp,barGrp=barGrp, yLabel='failed rate', title=name+'_'+prefix+'_failed rate_'+note) if textOutput: print('capa:{},target:{},value:{}'.format( rsp.serviceCapa,ch.SUCCESSRATE,barChart[barGrp2])) else: return(barChart[barGrp2]) def _createTbl(self,servicedata,hue,alg=None,separate=ch.MAXREBIDOLD, target=ch.SUCCESSRATE): servicedata[separate] = servicedata[separate].apply(str) if alg is None: alg = list(set(servicedata[ch.ALGORITHMTYPE])) alg.sort(reverse=False) rebid = list(set(servicedata[separate])) rebid.sort() row1 = [x+','+ch.MP+'='+rebid[0] for x in alg] row5 = [x+','+ch.MP+'='+rebid[1] for x in alg] column = np.arange( min(servicedata[servicedata[separate]==rebid[0]][ch.CAPACITY]), max(servicedata[servicedata[separate]==rebid[0]][ch.CAPACITY])+1, 10,dtype=int).tolist() servicedata = servicedata[[ch.CAPACITY,hue,target]] for capa,algorithm in product(column,row1+row5): tmp = pd.DataFrame([[int(capa),algorithm,np.nan]], columns=servicedata.columns) servicedata = pd.concat([servicedata,tmp],axis=0) data = servicedata[[ch.CAPACITY,hue,target]].groupby( [ch.CAPACITY,hue],as_index=False).mean().round(3) data.sort_values(by=ch.CAPACITY,ascending=True,inplace=True) values1 = [] values5 = [] for r in row1: values = data[data[ch.TYPE]==r][target].tolist() values0 = [np.round(x,decimals=2) if not np.isnan(x) else '' for x in values] values1.append(values0) for r in row5: values = data[data[ch.TYPE]==r][target].tolist() values0 = [np.round(x,decimals=2) if not np.isnan(x) else '' for x in values] values5.append(values0) return values1,values5,alg,column def _getPerformanceData(self,name,stepRange,sites, extRewardInterval='all',density=1): data = self._collectData(name,density) if stepRange is None: stepRange = (min(data[ch.STEP]),max(data[ch.STEP])) try: data = data.loc[(data[ch.STEP]<=stepRange[1]) & (data[ch.STEP]>=stepRange[0])] except: try: stepRange = (min(data[ch.STEP]),max(data[ch.STEP])) except: return data = data.loc[(data[ch.STEP]<=stepRange[1]) & (data[ch.STEP]>=stepRange[0])] if len(data)==0: return data[ch.SUCCESSRATE] = data[ch.SUCCESS] / data[ch.FINISHEDBID] data[ch.MODELTYPE] = np.where( data[ch.MODELTYPE]=='ConvCritic_ConvActor','CNN-HW','MLP') data[ch.MODELTYPE] = np.where(data[ch.TRAINED]==self.random, '',data[ch.MODELTYPE]) try: data[ch.CATEGORY] = data.apply(lambda row: row[ch.TRAINED] + '_' + str(row[ch.NRSITES]) + '_' + str(row[ch.EXTREWARDINTERVAL]) + '_' + str(row[ch.MODELTYPE]),axis=1) except: data[ch.CATEGORY] = data.apply(lambda row: row[ch.TRAINED] + '_' + str(row[ch.NRSITES]) + '_' + str(row[ch.MODELTYPE]),axis=1) cols = list(data.columns) cols[cols.index(ch.TOTALSUCCESSRATIO)] = ch.SUCCESSRATEBYTIME data.columns = cols if sites is None: sites = set(data[ch.NRSITES]) data = data.loc[data[ch.NRSITES].isin(sites)] if isinstance(extRewardInterval,str): try: extRewardInterval = set(data[ch.EXTREWARDINTERVAL]) except: data[ch.EXTREWARDINTERVAL] = vp.curiosityExtRewardThres extRewardInterval = [vp.curiosityExtRewardThres] try: data = data.loc[data[ch.EXTREWARDINTERVAL].isin(extRewardInterval)] except: pass return data def _getRegData(self,data,x,y): model = lambda x,a1,a2,a3,a4,a5,a6,a7: a1+a2*x+a3*x**2+a4*x**3+a5*x**4 mdl = model a,b = curve_fit(mdl,data[x],data[y]) lst = np.array(data[x]) pts = mdl(lst,*a) return pts def drawRegplot(self,df,x,y,title,style=None,hue=None,order='flex', hue_order=None,legends=2,legendFontsize=None, tickFontsize=None,size=None,separate=None, x_decimals=1,y_decimals=1,linestyle=None, dataRange=None,xticklabel=None): defaultFontsize = 15 if tickFontsize is None: tickFontsize = defaultFontsize if legendFontsize is None: legendFontsize = defaultFontsize if size is None: length = 5 height = 4 else: length = size[0] height = size[1] if linestyle is None: linestyle = ['-','--'] if dataRange is not None: try: df = df[(df[x]>=min(dataRange)) & (df[x]<=max(dataRange))] except: pass if separate is None: if hue is not None: if hue_order is None: if order=='flex': tmp = df.groupby(hue) tmp = (tmp.tail(1).drop_duplicates() .sort_values(y,ascending=False)) else: tmp = df.groupby( hue,as_index=False).max().sort_values(hue) hue_order = tmp[hue].tolist() else: hue_order = None fig,ax = plt.subplots() fig.set_size_inches(length,height) for i,h in enumerate(hue_order): tmp = df[df[hue]==h] regData = self._getRegData(tmp,x,y) ax.scatter(x=tmp[x].values,y=tmp[y].values) ax.plot(tmp[x].values,regData,label=h,linestyle=linestyle[i]) ax.set_xlabel(xlabel=x,fontsize=tickFontsize) ax.set_ylabel(ylabel=y,fontsize=tickFontsize) if dataRange is not None: ax.set_xticks(dataRange[0::2]) if xticklabel is not None: xticklabel = xticklabel[0::2] ax.set_xticklabels(xticklabel) else: xticklabel = ax.get_xticks() if tickFontsize!=defaultFontsize: if x_decimals>0: ax.set_xticklabels(np.round(xticklabel, decimals=x_decimals), size=tickFontsize) else: ax.set_xticklabels(np.int0(xticklabel), size=tickFontsize) if y_decimals>0: ax.set_yticklabels(np.round(ax.get_yticks(), decimals=x_decimals), size=tickFontsize) else: ax.set_yticklabels(np.int0(ax.get_yticks()), size=tickFontsize) if legends is not None: handles, labels = ax.get_legend_handles_labels() l = ax.legend(handles[0:],labels[0:],loc=legends, fontsize=legendFontsize) plt.savefig(os.path.join(GRAPH_DIR, title.replace(' ','')+'.pdf'), bbox_extra_artists=(l,), bbox_inches='tight') else: l = ax.legend() l.remove() plt.savefig(os.path.join(GRAPH_DIR, title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() else: sepCol = list(set(df[separate])) sepCol.sort() fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) fig.set_size_inches(length,height) df1 = df.loc[df[separate]==sepCol[0]] df2 = df.loc[df[separate]==sepCol[1]] if hue is not None: if hue_order is None: if order=='flex': tmp1 = df1.groupby(hue) tmp1 = (tmp1.tail(1).drop_duplicates() .sort_values(y,ascending=False)) tmp2 = df2.groupby(hue) tmp2 = (tmp2.tail(1).drop_duplicates() .sort_values(y,ascending=False)) else: tmp1 = df1.groupby( hue,as_index=False).max().sort_values(hue) tmp2 = df2.groupby( hue,as_index=False).max().sort_values(hue) hue_order1 = tmp1[hue].tolist() hue_order2 = tmp2[hue].tolist() else: hue_order1 = None hue_order2 = None for i,sep in enumerate(sepCol): if i==0: for j,h in enumerate(hue_order1): tmp = df[(df[separate]==sep) & (df[hue]==h)] regData = self._getRegData(tmp,x,y) ax1.scatter(x=tmp[x].values,y=tmp[y].values,s=4) ax1.plot(tmp[x].values,regData, label=h+', '+separate+'='+str(sep), linestyle=linestyle[j]) else: for j,h in enumerate(hue_order2): tmp = df[(df[separate]==sep) & (df[hue]==h)] regData = self._getRegData(tmp,x,y) ax2.scatter(x=tmp[x].values,y=tmp[y].values,s=4) ax2.plot(tmp[x].values,regData, label=h+', '+separate+'='+str(sep), linestyle=linestyle[j]) ax1.set_ylabel(ylabel=y,fontsize=tickFontsize) ax2.set_ylabel(ylabel=y,fontsize=tickFontsize) ax2.set_xlabel(xlabel=x,fontsize=tickFontsize) if dataRange is not None: ax2.set_xticks(dataRange[0::2]) if xticklabel is not None: xticklabel = xticklabel[0::2] ax2.set_xticklabels(xticklabel) else: xticklabel = ax2.get_xticks() if tickFontsize!=defaultFontsize: if x_decimals>0: ax1.set_xticklabels(np.round(xticklabel, decimals=x_decimals), size=tickFontsize) ax2.set_xticklabels(np.round(xticklabel, decimals=x_decimals), size=tickFontsize) else: ax1.set_xticklabels(np.int0(xticklabel), size=tickFontsize) ax2.set_xticklabels(np.int0(xticklabel), size=tickFontsize) if y_decimals>0: ax1.set_yticklabels(np.round(ax1.get_yticks(), decimals=x_decimals), size=tickFontsize) ax2.set_yticklabels(np.round(ax2.get_yticks(), decimals=x_decimals), size=tickFontsize) else: ax1.set_yticklabels(np.int0(ax1.get_yticks()), size=tickFontsize) ax2.set_yticklabels(np.int0(ax2.get_yticks()), size=tickFontsize) ax1.xaxis.label.set_size(tickFontsize) ax2.xaxis.label.set_size(tickFontsize) ax1.yaxis.label.set_size(tickFontsize) ax2.yaxis.label.set_size(tickFontsize) # if showTable: # fig.subplots_adjust(hspace=0.5) # ax1.xaxis.set_visible(False) # ax2.set_xticklabels([]) # ax2.xaxis.labelpad = 30 # ax2.tick_params(bottom=False) # # values1,values5,alg,column = self._createTbl(servicedata=df, # hue=hue,alg=['DRACO','RIAL'],separate=separate) # ax1.table(cellText=values1,rowLabels=alg, # colLabels=column,loc='bottom') # ax2.table(cellText=values5,rowLabels=alg, # colLabels=column,loc='bottom') if legends is not None: handles1, labels1 = ax1.get_legend_handles_labels() ax1.legend(handles1[0:],labels1[0:],loc=legends, fontsize=legendFontsize) handles2, labels2 = ax2.get_legend_handles_labels() ax2.legend(handles2[0:],labels2[0:],loc=legends, fontsize=legendFontsize) else: l = ax.legend() l.remove() plt.savefig(os.path.join(GRAPH_DIR,title.replace(' ','')+'.pdf'), bbox_inches='tight') plt.clf() def drawPerformance(self,name='performance',drawPerformanceOnly=True, target=ch.RECENTNONREJECTRATIO,prefix='', textOutput=False,sites=None,legends=None, stepRange=None, decimals=1,ci=None,extRewardInterval='all', outputThres=None,endOfGame=None, yaxisTick='left',orderHue=None,density=1): if outputThres is None: outputThres = 1000 if sites is not None: sites = [sites] else: sites = ['2sites'] if extRewardInterval is None: extRewardInterval = [vp.curiosityExtRewardThres] elif isinstance(extRewardInterval,int): extRewardInterval = [extRewardInterval] if target==ch.TOTALSUCCESSRATIO: target = ch.SUCCESSRATEBYTIME data = self._getPerformanceData(name,stepRange, sites,extRewardInterval,density) if data is None: return data = data[~data[target].isnull()] try: data[ch.CAT] = data[ch.TRAINED]+' '+data[ch.INTERVAL] except: data[ch.CAT] = data[ch.TRAINED] extRewardInterval = list(set(data[ch.EXTREWARDINTERVAL])) if not drawPerformanceOnly: pattern = re.compile('cloud|standard|slow') for nrSites in sites: df = data.loc[data[ch.NRSITES]==nrSites] sitetype = pattern.findall(df.sitetype.iloc[0]) sitetype = dict([('site'+str(i),x) for i,x in enumerate(sitetype)]) utilized = self._parseColumn(df,ch.UTILIZATION,sitetype) df = pd.concat([df,utilized],axis=1) analyzeCols = utilized.columns for t in analyzeCols: tmp = df[[ch.STEP,ch.TRAINED,t]].groupby( [ch.STEP,ch.TRAINED],as_index=False).mean() self._drawLineplot(df=tmp,x=ch.STEP,y=t, title=t+'_'+nrSites, style=ch.TRAINED,hue=ch.TRAINED, order='fix',legends=None) if ( (len(sites)==1 and len(extRewardInterval)==1) or (orderHue=='by algorithm') ): hue = ch.TRAINED else: hue = ch.CAT if ci is None: data0 = data[[ch.STEP,hue,target]].groupby( [ch.STEP,hue],as_index=False).mean() else: data0 = data offset = min(data0[ch.STEP]) data0[ch.STEP] = data0[ch.STEP] - offset hue_order = None if orderHue=='by algorithm': hue_retrain = [x for x in set(data0[hue].tolist()) if self.learned+' '+self.retrain in x] hue_draco = [x for x in set(data0[hue].tolist()) if self.learned in x] hue_rial = [x for x in set(data0[hue].tolist()) if self.random in x] hue_att = [x for x in set(data0[hue].tolist()) if self.att in x] hue_cur = [x for x in set(data0[hue].tolist()) if self.cur in x] hue_retrain.sort(reverse=True) hue_draco.sort(reverse=True) hue_order = hue_rial + hue_draco + hue_cur + hue_att + hue_retrain # if target==ch.SUCCESSRATEBYTIME: excludes admitted but failed bids self._drawLineplot(df=data0,x=ch.STEP,y=target, title=name+'_' + target, style=hue,hue=hue,order='fixed',legends=legends, legendFontsize=10,tickFontsize=10, decimals=decimals,ci=ci,yaxisTick=yaxisTick, hue_order=hue_order) if target==ch.SUCCESSRATEBYTIME: data[ch.FAILURERATEBYTIME] = 1- data[target] data[ch.ADMITTEDRATEBYTIME] = data[ch.ADMITTEDRATE] data[ch.REJECTEDRATEBYTIME] = 1 - data[ch.ADMITTEDRATEBYTIME] # # admitted, both successful and failed execution, double counted if bid is admitted more than one time # self._drawLineplot(df=data,x=ch.STEP,y=ch.ADMITTEDRATEBYTIME, # title=name+'_'+ch.ADMITTEDRATEBYTIME, # style=hue,hue=hue,order='flex',legends=legends, # legendFontsize=10,tickFontsize=10, # decimals=decimals,ci=ci, # yaxisTick=yaxisTick,hue_order=hue_order) if hue_order is not None: hue_order.reverse() # rejected + admitted but failed self._drawLineplot(df=data,x=ch.STEP,y=ch.FAILURERATEBYTIME, title=name+'_'+ch.FAILURERATEBYTIME, style=hue,hue=hue,order='fixed',legends=legends, legendFontsize=10,tickFontsize=10, decimals=decimals,ci=ci,yscale='log', yaxisTick=yaxisTick,hue_order=hue_order) # # rejected # self._drawLineplot(df=data,x=ch.STEP,y=ch.REJECTEDRATEBYTIME, # title=name+'_'+ch.REJECTEDRATEBYTIME, # style=hue,hue=hue,order='flex',legends=legends, # legendFontsize=10,tickFontsize=10, # decimals=decimals,ci=ci,yscale='log', # yaxisTick=yaxisTick,hue_order=hue_order) if textOutput: eogDataAll = None for target in [ch.SUCCESSRATEBYTIME,ch.FAILURERATEBYTIME]: eogData = None print('\n{} :\n'.format(target)) for cat in set(data[hue]): tmp = data.loc[(data[hue]==cat),[ch.STEP,target]] tmp.columns = [ch.STEP,'result'] tmp1 = np.mean( tmp.loc[tmp[ch.STEP]>=max(tmp[ch.STEP])-outputThres, 'result']) print('{} : {:.3f}'.format(cat,tmp1)) maxStep = max(tmp[ch.STEP]) if endOfGame is None or maxStep < endOfGame: outputRange = list(range(maxStep-outputThres,maxStep)) else: outputRange = [] for i in range(int(maxStep / endOfGame)): eog = (i + 1) * endOfGame outputRange += list(range(eog-outputThres,eog)) tmp[hue] = cat if eogData is None: eogData = tmp.loc[tmp[ch.STEP].isin(outputRange)] else: eogData = pd.concat([ eogData,tmp.loc[tmp[ch.STEP].isin(outputRange)]], axis=0) eogData[ch.TYPE] = target if eogDataAll is None: eogDataAll = eogData else: eogDataAll = pd.concat([eogDataAll,eogData],axis=0) result = eogDataAll.groupby([ch.TYPE,hue],as_index=False).agg( {'result':['mean','std']}) return (eogDataAll,result) else: return def drawPriceModelLoss(self,name='priceLearningModel'): data = self._collectData(name) data = data.loc[(~data[ch.ACTORLOSS].isnull()) & (data[ch.ACTORLOSS]<3) & (data[ch.ACTORLOSS]>-3)] for target in [ch.AVGREWARD,ch.CRITICLOSS,ch.ACTORLOSS]: title = name + '_' + target df = data[[ch.STEP,ch.NRSITES,target]].groupby( [ch.STEP,ch.NRSITES],as_index=False).mean() self._drawLineplot(df=df,x=ch.STEP,y=target, title=title,style=ch.NRSITES,hue=ch.NRSITES, order='fix') def drawCompetitorModelLoss(self,name='competitorLearningModel'): target = ch.COMPETITORLOSS data = self._collectData(name) data = data.loc[~data[target].isnull()] df = data.loc[data[ch.STEP]>=10] df = df[[ch.STEP,ch.NRSITES,target]].groupby( [ch.STEP,ch.NRSITES],as_index=False).mean() outlier = np.percentile(df[target],80) df = df[df[target]<outlier] self._drawLineplot(df=df,x=ch.STEP,y=target,title=name, style=ch.NRSITES,hue=ch.NRSITES,order='fix') def drawTraceDataDistr(self,file='',gridRangeX=(1,401),gridRangeY=(1,307), sumoDataOffset=50000,nrRecord=200000): if 'eval' in file or 'test' in file or 'trainNew' in file: file = '_' + file else: file = '' filename = 'sumoTrace_schwantalerhoehe' + file + '.xml' trace = TraceData(path=os.path.join(self.path,'vanetdata'), filename=filename,gridRangeX=gridRangeX, gridRangeY=gridRangeY,dataOffset=sumoDataOffset) trace.readTraceDataFromSumo(nrRecord=nrRecord,posOffset=True) df = trace.sumoGrpData.copy() df.reset_index(inplace=True) df.columns = [ch.STEP,ch.VEHICLECOUNT] df[ch.VEHICLECOUNT].hist() plt.savefig(os.path.join(GRAPH_DIR,'vehicleCountDistr'+file+'.pdf')) self._drawLineplot(df=df,x=ch.STEP,y=ch.VEHICLECOUNT, title='vehicleCountByTime'+file, decimals=0,legends=None, legendFontsize=12,tickFontsize=12) return df
44,748
43.749
115
py
ESSENCE
ESSENCE-main/essence/essence.py
""" Copyright (C) 2022, Takafumi Tsukui E-mail: [email protected] Updated versions of the software are available from my web page https://sites.google.com/view/takafumitk/home?authuser=0 If you have found this software useful for your research, I would appreciate an acknowledgement to the use of the "Essense (Evaluating Statistical Significance undEr CorrElation) of Tsukui (2022)" This software is provided as is without any warranty whatsoever. Permission to use, for non-commercial purposes is granted. Permission to modify for personal or internal use is granted, provided this copyright and disclaimer are included unchanged at the beginning of the file. All other rights are reserved. In particular, redistribution of the code is not allowed. """ import os import sys import matplotlib.pyplot as plt import astropy.units as u from spectral_cube import SpectralCube import numpy as np from astropy.io import fits import time #from multiprocessing import Pool #https://stackoverflow.com/questions/41385708/multiprocessing-example-giving-attributeerror import multiprocess as mp import functools from scipy import signal from astropy.stats import sigma_clip from scipy import ndimage import scipy from astropy.modeling import models, fitting ################################################################################################# def mk_noisemap(image, pb, pbfrac=0.7, sigma=4): """ make noisemap from data by (1) sigma clipping emission regions (2) growing the clipped region with the beam FWHM (pixels) (3) clip region where primaly beam < pbfrac The clipped regions are filled with nan values. image: data (2d image or cube), spectral-cube class, if image.shape==3 we assume (v, x, y) pb: primary beam image, spectral-cube class pbfrac: minimum primary beam fraction not to clip sigma: threthold for sigma clipping return masked cube or image with nan """ # first mask primary beam>pbfrac Pbmask=mk_pbmask(image._data,pb,pbfrac=pbfrac,plot=False) if len(image.shape)==3: Pbmasked=np.copy(image._data) Pbmasked[~Pbmask]=np.nan Sigmacliped = sigma_clip(Pbmasked, sigma=sigma, maxiters=5,masked=True, axis=(1,2), grow=0) growpix=image.hdu.header['BMAJ']/image.hdu.header['CDELT2'] Yy, Xx = np.indices([int(3*growpix),int(3*growpix)], dtype='float') CX=(int(3*growpix)-1)/2 CY=(int(3*growpix)-1)/2 Kernel = (((Yy-CY)**2 + (Xx-CX)**2)**0.5<growpix).astype('float') Finalmask=np.array([signal.fftconvolve(np.copy(i.mask.astype(float)), Kernel, mode="same")>1 for i in Sigmacliped]) Finalmasked=np.copy(image.hdu.data) Finalmasked[Finalmask]=np.nan return Finalmasked if len(image.shape)==2: Pbmasked=np.copy(image.hdu.data) Pbmasked[~Pbmask]=np.nan Sigmacliped = sigma_clip(Pbmasked, sigma=sigma, maxiters=5,masked=True, axis=None, grow=0) growpix=image.hdu.header['BMAJ']/image.hdu.header['CDELT2'] Yy, Xx = np.indices([int(3*growpix),int(3*growpix)], dtype='float') CX=(int(3*growpix)-1)/2 CY=(int(3*growpix)-1)/2 Kernel = (((Yy-CY)**2 + (Xx-CX)**2)**0.5<growpix).astype('float') Finalmask=signal.fftconvolve(np.copy(Sigmacliped.mask.astype(float)), Kernel, mode="same")>1 Finalmasked=np.copy(image.hdu.data) Finalmasked[Finalmask]=np.nan return Finalmasked ####################################################################################################################### def mk_pbmask(image, pb, pbfrac=0.7, plot=True): """mask image with nan, where pb<pbfrac """ if len(image.shape)==3: YY, XX = np.indices(image.shape[1:], dtype='float') Cx=image.shape[1]/2 Cy=image.shape[2]/2 if len(image.shape)==2: YY, XX = np.indices(image.shape[:], dtype='float') Cx=image.shape[0]/2 Cy=image.shape[1]/2 Radius = ((YY-Cy)**2 + (XX-Cx)**2)**0.5 if len(image.shape)==3: Mask = (pb._data>pbfrac) if len(image.shape)==2: Mask = (pb._data[0]>pbfrac) return Mask ############################################################################################################################################## def zoompeak(image,Width, plot=False): cenx,ceny=np.where(image==np.nanmax(image)) if plot: plt.imshow(image[cenx[0]-Width:cenx[0]+Width+1,ceny[0]-Width:ceny[0]+Width+1],extent=[Width-0.5,-Width+.5,-Width-0.5,Width+.5]) plt.colorbar() plt.xlabel(r"$\Delta$x (pixels)") plt.ylabel(r"$\Delta$y (pixels)") return image[cenx[0]-Width:cenx[0]+Width+1,ceny[0]-Width:ceny[0]+Width+1] ############################################################################################################################################### def zoomcen(image,Width, plot=False): """ zoom Width x Width pixels of image """ image_s=image[int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1,int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1] try: s=np.where(image_s==np.max(image_s))==(np.array([int((image_s.shape[0]-1)/2)]),np.array([int((image_s.shape[0]-1)/2)])) if s: print("peak coincide with the image center") else: print("peak do not coicide with the image center") except: print("there seem to be multiple peaks") if plot: plt.imshow(image[int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1,int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1],extent=[Width-0.5,-Width+.5,-Width-0.5,Width+.5]) plt.colorbar() plt.xlabel(r"$\Delta$x (pixels)") plt.ylabel(r"$\Delta$y (pixels)") return image[int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1,int((image.shape[0]-1)/2)-Width:int((image.shape[0]-1)/2)+Width+1] #################################################################################################################################################### def shift_2d_replace(data, dx, dy, constant=np.nan): """ Shifts the array in two dimensions while setting rolled values to constant :param data: The 2d numpy array to be shifted :param dx: The shift in x :param dy: The shift in y :param constant: The constant to replace rolled values with :return: The shifted array with "constant" where roll occurs """ shifted_data = np.roll(data, dx, axis=1) if dx < 0: shifted_data[:, dx:] = constant elif dx > 0: shifted_data[:, 0:dx] = constant shifted_data = np.roll(shifted_data, dy, axis=0) if dy < 0: shifted_data[dy:, :] = constant elif dy > 0: shifted_data[0:dy, :] = constant return shifted_data #################################################################################################################################################### def acf_calc(image, dx, dy, beamarea_pix=None): """ dx pixel shift for x axis dy pixel shift for y axis return (1) ACF at shift (dx, dy) (2) standared error on measured noise ACF if beamarea_pix is given. """ acfimage=shift_2d_replace(image, dx, dy, constant=np.nan)*image if np.any(beamarea_pix): return np.nanmean(acfimage), np.nanstd(acfimage)/np.sqrt(acfimage.size/beamarea_pix) else: return np.nanmean(acfimage) #################################################################################################################################################### def mk_acf(noiseimage, pixelhwidth=30, filedir="", filename="", beamarea_pix=None, cpus2use=8): """ Compute noise ACF pixelhwidth: required size of noise ACF (half of the width) in pixel, producing (2xpixelwidth+1) x (2xpixelwidth+1) noise ACF note that we need ACF jsut include all the relative vector (in pixel) of interested aperture when computing the variance associated with the integrated flux or spectrum over the aperture beamarea_pix: optional parameter required to compute standard error in ACF. output: noise ACF if beamarea (in pixel) is given, it compute symmetrized standard error in ACF following Eq.(5) np.array([noiseACF, symmetrized standard error in ACF]) """ t1=time.time() if isinstance(pixelhwidth, int): if len(noiseimage.shape)==3: if np.any(beamarea_pix): Acf_array=np.zeros([noiseimage.shape[0], int(pixelhwidth*2+1),int(pixelhwidth*2+1),2]) else: Acf_array=np.zeros([noiseimage.shape[0], int(pixelhwidth*2+1),int(pixelhwidth*2+1)]) if len(noiseimage.shape)==2: if np.any(beamarea_pix): Acf_array=np.zeros([int(pixelhwidth*2+1),int(pixelhwidth*2+1),2]) else: Acf_array=np.zeros([int(pixelhwidth*2+1),int(pixelhwidth*2+1)]) else: raise Exception("put integer for pixelhwidth, which is required ACF size to compute") print("output noise ACF array shape is ",Acf_array.shape) if filename and os.path.exists(filedir+"noise_acf_"+filename+"_"+str(pixelhwidth)+".npy"): print("file found") return np.load(filedir+"noise_acf_"+filename+"_"+str(pixelhwidth)+".npy") itest,jtest=np.meshgrid([i for i in range(0,int((Acf_array.shape[1]-1)/2)+1)],[i for i in range(-int((Acf_array.shape[1]-1)/2),int((Acf_array.shape[1]-1)/2)+1)]) zipped_ji=np.column_stack((jtest.ravel(), itest.ravel())) if len(noiseimage.shape)==3: if cpus2use: #if __name__ == "__main__": print('multiprocess is enabled') p = mp.Pool(cpus2use) result=np.array([list(p.starmap(functools.partial(acf_calc, i, beamarea_pix=beamarea_pix), zipped_ji)) for i in noiseimage]) #else: # result=np.array([[acf_calc(i, *ij, beamarea_pix=beamarea_pix) for ij in zipped_ji] for i in noiseimage]) else: result=np.array([[acf_calc(i, *ij, beamarea_pix=beamarea_pix) for ij in zipped_ji] for i in noiseimage]) if np.any(beamarea_pix): Acf_array[:,int((Acf_array.shape[1]-1)/2)+itest.ravel(), int((Acf_array.shape[1]-1)/2)+jtest.ravel(),:]=result Acf_array[:,int((Acf_array.shape[1]-1)/2)-itest.ravel(), int((Acf_array.shape[1]-1)/2)-jtest.ravel(),:]=result else: Acf_array[:,int((Acf_array.shape[1]-1)/2)+itest.ravel(), int((Acf_array.shape[1]-1)/2)+jtest.ravel()]=result Acf_array[:,int((Acf_array.shape[1]-1)/2)-itest.ravel(), int((Acf_array.shape[1]-1)/2)-jtest.ravel()]=result if len(noiseimage.shape)==2: if cpus2use: #if __name__ == "__main__": print('multiprocess is enabled') p = mp.Pool(cpus2use) result=np.array(list(p.starmap(functools.partial(acf_calc, noiseimage, beamarea_pix=beamarea_pix), zipped_ji))) #else: # result=np.array([acf_calc(noiseimage, *ij, beamarea_pix=beamarea_pix) for ij in zipped_ji]) else: result=np.array([acf_calc(noiseimage, *ij, beamarea_pix=beamarea_pix) for ij in zipped_ji]) if np.any(beamarea_pix): Acf_array[int((Acf_array.shape[0]-1)/2)+itest.ravel(), int((Acf_array.shape[0]-1)/2)+jtest.ravel(),:]=result Acf_array[int((Acf_array.shape[0]-1)/2)-itest.ravel(), int((Acf_array.shape[0]-1)/2)-jtest.ravel(),:]=result else: Acf_array[int((Acf_array.shape[0]-1)/2)+itest.ravel(), int((Acf_array.shape[0]-1)/2)+jtest.ravel()]=result Acf_array[int((Acf_array.shape[0]-1)/2)-itest.ravel(), int((Acf_array.shape[0]-1)/2)-jtest.ravel()]=result if filename and os.path.exists(filedir+"noise_acf_"+filename+"_"+str(pixelhwidth)+".npy")==False: np.save(filedir+"noise_acf_"+filename+"_"+str(pixelhwidth), Acf_array) t2=time.time() print("It took:",t2-t1,"sec to compute the noise ACF.") return Acf_array #################################################################################################################################################### def nodiag_view3D(a): #https://stackoverflow.com/questions/55588122/how-to-calculate-the-relative-vectors-from-a-list-of-points-from-one-point-to-e m = a.shape[0] p,q,r = a.strides return np.lib.stride_tricks.as_strided(a[:,1:], shape=(m-1,m,2), strides=(p+q,q,r)) #################################################################################################################################################### def mk_relvec(mask): """ return a set of relative position vectors for pairs of True pixel in the input masked array. for example, given two True pixel it returns two relative position vector 1->2, 2->1 masked array: return array with size of N(N-1) of dx and dy """ ytest,xtest=np.where((mask)==1) atest=np.column_stack([xtest, ytest]) testd = (atest-atest[:,None,:]) return nodiag_view3D(testd).reshape(-1,atest.shape[1])[:,0], nodiag_view3D(testd).reshape(-1,atest.shape[1])[:,1] # dx, and dy #################################################################################################################################################### def mk_noise_var_noiseACF(mask, acf, split=False): """ compute variance (std**2) of noise in integrated flux within aperture following Eq.(). mask 2d boolean mask, where True represent the aperture region. acf 2d noise auto-correlation function """ dx,dy=mk_relvec(mask) # generate a set of relative position vectors from mask image variance=acf[int((len(acf)-1)/2),int((len(acf)-1)/2)]*(mask).sum() # variance term acf(0,0) position times the number of pixels covariance=acf[dy+int((len(acf)-1)/2),dx+int((len(acf)-1)/2)].sum() # covariance term acf(dx,dy) for relative position vectors if split: return variance+covariance, variance,covariance else: return variance+covariance #################################################################################################################################################### def mk_intflux(mask,img): """ return integrated flux, sum of the pixels where mask==True """ return img._data[mask].sum() #################################################################################################################################################### def mk_aperture(img, rad, plot=False): """ img: 2dimage rad: radius of the circular aperture in pix. generate circular aperture """ if len(img.shape)==2: YY, XX = np.indices(img.shape[:], dtype='float') Cx=img.shape[0]/2 Cy=img.shape[1]/2 Radius = ((YY-Cy)**2 + (XX-Cx)**2)**0.5 if len(img.shape)==2: Mask = (Radius <= rad) if plot: plt.imshow(Mask) plt.show() plt.title("generated aperture") return Mask else: raise Exception("this works only for 2d image") #################################################################################################################################################### def mk_sigmasqrtnumbeam(noise_image, mask, beamarea): """ noise in the integrated flux estimated by sigma_N*\sqrt(N_beam) """ return np.sqrt(mask.sum()/beamarea)*np.nanstd(noise_image) #################################################################################################################################################### def mk_noisespec(mask, acf_cube): """ return underlying noise (1sigma) associated with the spectrum within the given aperture mask: aperture acf_cube: 3d array with (velocity, y, x) """ cubemask=np.array([mask for i in range(0,acf_cube[:,:,:].shape[0])]) noisespec=np.array([np.sqrt(mk_noise_var_noiseACF(mask, acf_cube[i,:,:])) for i in range(0, acf_cube[:,:,:].shape[0])]) return noisespec #################################################################################################################################################### def mk_noise_var_randaperture(noise_image, mask, plot=True): """ generate noise in spatially integrated flux (2d image) or spectrum (cube) by placing aperture in the noise region randomly and taking the rms across the summed values on the aperture. noise_image: noise_map produced by mk_noisemap mask: 2d boolean aperture mask """ rng=np.random.default_rng() if len(noise_image.shape)==3: rms=np.copy(noise_image[:,0,0]*0) independent_data=np.copy(noise_image[:,0,0]*0) cp=np.copy(noise_image) convolved_cp=np.copy(noise_image)*0 for i,j in enumerate(cp): convolved_cp[i]=ndimage.convolve(j, mask, mode="constant",cval=np.nan) rms[i]=np.nanstd(convolved_cp[i],ddof=1) independent_data[i]=np.sum(~np.isnan(convolved_cp[i]))/np.nansum(mask) if plot==True: plt.imshow(convolved_cp[i]) plt.colorbar() plt.title('summed maps by the aperture') plt.show() plt.imshow(mask) plt.title('aperture shape') plt.colorbar() plt.show() return rms, rms/np.sqrt(2*independent_data-2) #standard deivation and standard error if len(noise_image.shape)==2: cp=np.copy(noise_image) convolved_cp=ndimage.convolve(cp, mask, mode="constant",cval=np.nan) rms=np.nanstd(convolved_cp,ddof=1) independent_data=np.sum(~np.isnan(cp))/np.nansum(mask) if plot==True: plt.imshow(convolved_cp) plt.title('summed maps by the aperture') plt.colorbar() plt.show() plt.imshow(mask) plt.title('aperture shape') plt.colorbar() plt.show() plt.hist(convolved_cp[~np.isnan(convolved_cp)].ravel(), bins='auto') plt.title('histgram of data points') plt.show() return rms, rms/np.sqrt(2*independent_data-2) #################################################################################################################################################### def mk_simnoise(pixwidth, acf, silent=False): """ simulate noise map (pixwidth x pixwidth) from measured acf """ t1=time.time() X,Y = np.meshgrid(np.arange(pixwidth),np.arange(pixwidth)) # Create a vector of cells #XY = np.column_stack((np.ndarray.flatten(X),np.ndarray.flatten(Y))) X=np.ndarray.flatten(X) Y=np.ndarray.flatten(Y) # Calculate a matrix of relative distance vector between the cells X = X.reshape(-1,1) Xdist = X.T - X+int((acf.shape[0]-1)/2) Y = Y.reshape(-1,1) Ydist = Y.T - Y+int((acf.shape[0]-1)/2) #acf relative distance vectorの(0,0) cov = np.copy(acf[Ydist,Xdist]) # covariance matrix to be input for the scipy multivariate_normal noise = scipy.stats.multivariate_normal.rvs(mean = np.zeros(pixwidth**2), cov = cov) noisemap=noise.reshape((pixwidth,pixwidth)) if silent==False: print("It took",str(time.time()-t1),'second to generate '+str(pixwidth)+'x'+str(pixwidth)+' noise map') return noisemap #################################################################################################################################################### def mk_simnoise_cube(pixwidth, acf, cpus2use=None): """ simulate noise cube from measured acf """ t1=time.time() if len(acf.shape)==3: if cpus2use: #if __name__ == "__main__": print("multiprocess is enabled") p = mp.Pool(cpus2use) result=np.array(list(p.map(functools.partial(mk_simnoise, pixwidth, silent=True), list(acf)))) #else: # result=np.array([mk_simnoise(pixwidth, i, silent=True) for i in list(acf)]) else: result=np.array([mk_simnoise(pixwidth, i, silent=True) for i in list(acf)]) print("It took",time.time()-t1,'second to generate '+str(acf.shape[0])+'x'+str(pixwidth)+'x'+str(pixwidth)+' (v, x, y) noise cube') return result else: print("use mk_simnoise") ################################################################################################################################################### def mk_cov(pixwidth, acf, silent=False): """ compute covariance from measured acf the output covariance has dimension of pixwidth^2 x pixwidth^2 """ t1=time.time() X,Y = np.meshgrid(np.arange(pixwidth),np.arange(pixwidth)) # Create a vector of cells #XY = np.column_stack((np.ndarray.flatten(X),np.ndarray.flatten(Y))) X=np.ndarray.flatten(X) Y=np.ndarray.flatten(Y) # Calculate a matrix of relative distance vector between the cells X = X.reshape(-1,1) Xdist = X.T - X+int((acf.shape[0]-1)/2) Y = Y.reshape(-1,1) Ydist = Y.T - Y+int((acf.shape[0]-1)/2) #acf relative distance vector (0,0) cov = np.copy(acf[Ydist,Xdist]) return cov
21,578
44.334034
207
py
ESSENCE
ESSENCE-main/essence/__init__.py
__version__ = "0.0.1"
22
10.5
21
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/merge_qrels.py
from utils import load_from_trec import argparse import torch import csv if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--scores_path", type=str) parser.add_argument("--qrels_path", type=str) parser.add_argument("--save_path", type=str) parser.add_argument("run") args = parser.parse_args() scores = torch.load(args.scores_path) print(scores.size()) run = load_from_trec(args.run, as_list=True) g = open(args.save_path, "w") qrels = {} with open(args.qrels_path, encoding="utf8") as f: tsvreader = csv.reader(f, delimiter="\t") for [qid, _, docid, rel] in tsvreader: assert rel == "1" if qid in qrels: qrels[qid].append(docid) else: qrels[qid] = [docid] id = 0 sum, overlap = 0, 0 for qid, rank_list in run.items(): docids = [] for doc_rank, (docid, _) in enumerate(rank_list): docids.append(docid) if len(docids) == 10: break sort_scores, sort_index = torch.sort(scores[id], descending=True) for docid in qrels[qid]: # pass g.write(f"{qid}\t0\t{docid}\t1\n") sum += len(qrels[qid]) for i in sort_index[:2]: if docids[i] not in qrels[qid]: # pass g.write(f"{qid}\t0\t{docids[i]}\t1\n") else: overlap += 1 id += 1 if id >= scores.size(0): break print(overlap, sum, overlap / sum)
1,581
28.296296
73
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/transform.py
# coding:utf-8 import torch import argparse import os import tqdm import copy def transform_new_model(model_hf, layer_num): model_new = {} cnt = 0 for i in range(layer_num): # encoder target_k = "encoder.blocks.{}.self_attn.self_attn.project.weight".format(i) source = [ "encoder.block.{}.layer.0.SelfAttention.q.weight".format(i), "encoder.block.{}.layer.0.SelfAttention.k.weight".format(i), "encoder.block.{}.layer.0.SelfAttention.v.weight".format(i), ] # qkv model_new[target_k] = torch.cat([model_hf[x] for x in source], 0) cnt += 3 target_k = "encoder.blocks.{}.self_attn.self_attn.dense.weight".format(i) source = "encoder.block.{}.layer.0.SelfAttention.o.weight".format(i) model_new[target_k] = model_hf[source] / 100 cnt += 1 target_k = "encoder.blocks.{}.self_attn.layer_norm.weight".format(i) source = "encoder.block.{}.layer.0.layer_norm.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "encoder.blocks.{}.ff.dense_relu_dense.wi_0.weight".format(i) source = "encoder.block.{}.layer.1.DenseReluDense.wi_0.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "encoder.blocks.{}.ff.dense_relu_dense.wi_1.weight".format(i) source = "encoder.block.{}.layer.1.DenseReluDense.wi_1.weight".format(i) model_new[target_k] = model_hf[source] / 10 cnt += 1 target_k = "encoder.blocks.{}.ff.dense_relu_dense.wo.weight".format(i) source = "encoder.block.{}.layer.1.DenseReluDense.wo.weight".format(i) model_new[target_k] = model_hf[source] / 10 cnt += 1 target_k = "encoder.blocks.{}.ff.layer_norm.weight".format(i) source = "encoder.block.{}.layer.1.layer_norm.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 # decoder target_k = "decoder.blocks.{}.self_attn.self_attn.project.weight".format(i) source = [ "decoder.block.{}.layer.0.SelfAttention.q.weight".format(i), "decoder.block.{}.layer.0.SelfAttention.k.weight".format(i), "decoder.block.{}.layer.0.SelfAttention.v.weight".format(i), ] # qkv model_new[target_k] = torch.cat([model_hf[x] for x in source], 0) cnt += 3 target_k = "decoder.blocks.{}.cross_attn.cross_attn.project_kv.weight".format(i) source = [ "decoder.block.{}.layer.1.EncDecAttention.k.weight".format(i), "decoder.block.{}.layer.1.EncDecAttention.v.weight".format(i), ] # kv model_new[target_k] = torch.cat([model_hf[x] for x in source], 0) cnt += 2 target_k = "decoder.blocks.{}.cross_attn.cross_attn.project_q.weight".format(i) source = "decoder.block.{}.layer.1.EncDecAttention.q.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "decoder.blocks.{}.cross_attn.cross_attn.dense.weight".format(i) source = "decoder.block.{}.layer.1.EncDecAttention.o.weight".format(i) model_new[target_k] = model_hf[source] / 100 cnt += 1 target_k = "decoder.blocks.{}.cross_attn.layer_norm.weight".format(i) source = "decoder.block.{}.layer.1.layer_norm.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "decoder.blocks.{}.self_attn.self_attn.dense.weight".format(i) source = "decoder.block.{}.layer.0.SelfAttention.o.weight".format(i) model_new[target_k] = model_hf[source] / 100 cnt += 1 target_k = "decoder.blocks.{}.self_attn.layer_norm.weight".format(i) source = "decoder.block.{}.layer.0.layer_norm.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "decoder.blocks.{}.ff.dense_relu_dense.wi_0.weight".format(i) source = "decoder.block.{}.layer.2.DenseReluDense.wi_0.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 target_k = "decoder.blocks.{}.ff.dense_relu_dense.wi_1.weight".format(i) source = "decoder.block.{}.layer.2.DenseReluDense.wi_1.weight".format(i) model_new[target_k] = model_hf[source] / 10 cnt += 1 target_k = "decoder.blocks.{}.ff.dense_relu_dense.wo.weight".format(i) source = "decoder.block.{}.layer.2.DenseReluDense.wo.weight".format(i) model_new[target_k] = model_hf[source] / 10 cnt += 1 target_k = "decoder.blocks.{}.ff.layer_norm.weight".format(i) source = "decoder.block.{}.layer.2.layer_norm.weight".format(i) model_new[target_k] = model_hf[source] cnt += 1 source = "shared.weight" target_k = "word_embeds.weight" embeds = model_hf[source] model_new[target_k] = embeds / 100 target_k = "encoder.word_embeds.weight" model_new[target_k] = embeds / 100 target_k = "decoder.word_embeds.weight" model_new[target_k] = embeds / 100 cnt += 3 source = "encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight" target_k = "encoder.blocks.0.self_attn.self_attn.relative_attention_bias.weight" model_new[target_k] = model_hf[source] cnt += 1 source = "decoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight" target_k = "decoder.blocks.0.self_attn.self_attn.relative_attention_bias.weight" model_new[target_k] = model_hf[source] cnt += 1 source = "lm_head.weight" target_k = "lm_head.weight" embeds = model_hf[source] model_new[target_k] = embeds cnt += 1 source = "encoder.final_layer_norm.weight" target_k = "encoder.final_layernorm.weight" model_new[target_k] = model_hf[source] cnt += 1 source = "decoder.final_layer_norm.weight" target_k = "decoder.final_layernorm.weight" model_new[target_k] = model_hf[source] cnt += 1 print("new module number:", cnt, "origin module number:", len(model_hf)) return {"module": model_new} def change_mp(d, output_dir, mp_size, half=False): os.makedirs(output_dir, exist_ok=True) os.makedirs(os.path.join(output_dir, "1"), exist_ok=True) with open(os.path.join(output_dir, "latest_checkpointed_iteration.txt"), "w") as f: f.write(str(1) + "\n") preserve_keys = [ "lr_scheduler", "skipped_steps", "global_steps", "global_samples", "dp_world_size", "iteration", ] dd = {} dd["lr_scheduler"] = {} dd["lr_scheduler"]["num_iters"] = 1 dd["lr_scheduler"]["start_lr"] = 0.001 dd["lr_scheduler"]["warmup_iter"] = 10000 dd["skipped_steps"] = 0 dd["global_steps"] = 1 dd["global_samples"] = 100 dd["iteration"] = 1 dd["dp_world_size"] = 1 print("Increase MP size.") ratio = mp_size start = 0 end = ratio for j in tqdm.tqdm(range(start, end)): d_new = {} shift = j - start for k, v in dd.items(): if k != "module": if k in preserve_keys: d_new[k] = copy.deepcopy(dd[k]) elif k == "mp_world_size": d_new[k] = ratio else: d_new[k] = None d_new["module"] = {} for k, v in d["module"].items(): assert len(v.shape) < 3 if len(v.shape) == 2: if "project.weight" in k: part = v.shape[0] // ratio // 3 d_new["module"][k] = torch.cat( [ v[shift * part : (shift + 1) * part, :], v[(shift + ratio) * part : (shift + 1 + ratio) * part, :], v[ (shift + 2 * ratio) * part : (shift + 1 + 2 * ratio) * part, :, ], ], 0, ) elif "project_q.weight" in k: part = v.shape[0] // ratio d_new["module"][k] = v[shift * part : (shift + 1) * part, :] elif "project_kv.weight" in k: part = v.shape[0] // ratio // 2 d_new["module"][k] = torch.cat( [ v[shift * part : (shift + 1) * part, :], v[(shift + ratio) * part : (shift + 1 + ratio) * part, :], ], 0, ) elif ( "word_embeds.weight" in k or "dense_relu_dense.wi_1.weight" in k or "dense_relu_dense.wi_0.weight" in k or "lm_head.weight" in k ): part = v.shape[0] // ratio d_new["module"][k] = v[shift * part : (shift + 1) * part, :] else: part = v.shape[1] // ratio d_new["module"][k] = v[:, shift * part : (shift + 1) * part] else: d_new["module"][k] = v if half: d_new["module"][k] = d_new["module"][k].half() filename = os.path.join( output_dir, "1", "mp_rank_0{}_model_states.pt".format(j) ) torch.save(d_new, filename) def main(): parser = argparse.ArgumentParser( "Transform huggingface checkpoints to megatron+deepspeed checkpoints" ) parser.add_argument("--hf_path", type=str) parser.add_argument("--ext_path", type=str, default="") parser.add_argument("--mp_size", type=int, default=1) parser.add_argument("--save_path", type=str) parser.add_argument("--half", action="store_true") args = parser.parse_args() model_hf = torch.load(args.hf_path, map_location="cpu") if args.ext_path: model_ext = torch.load(args.ext_path, map_location="cpu") model_hf.update(model_ext) print(len(model_hf)) new_model = transform_new_model(model_hf, 12 if "base" in args.save_path else 24) change_mp(new_model, args.save_path, args.mp_size, half=args.half) if __name__ == "__main__": main()
10,433
34.610922
88
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/utils.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import csv import json import warnings from dataclasses import dataclass from typing import Dict, List import datasets import torch from transformers import PreTrainedTokenizer @dataclass class SimpleTrainPreProcessor: query_file: str collection_file: str tokenizer: PreTrainedTokenizer doc_max_len: int = 128 query_max_len: int = 32 columns = ['text_id', 'title', 'text'] title_field = 'title' text_field = 'text' query_field = 'text' doc_template: str = None query_template: str = None allow_not_found: bool = False def __post_init__(self): self.queries = self.read_queries(self.query_file) self.collection = datasets.load_dataset( 'csv', data_files=self.collection_file, column_names=self.columns, delimiter='\t', )['train'] @staticmethod def read_queries(queries): qmap = {} with open(queries) as f: for l in f: qid, qry = l.strip().split('\t') qmap[qid] = qry return qmap @staticmethod def read_qrel(relevance_file): qrel = {} with open(relevance_file, encoding='utf8') as f: tsvreader = csv.reader(f, delimiter="\t") for [topicid, _, docid, rel] in tsvreader: assert rel == "1" if topicid in qrel: qrel[topicid].append(docid) else: qrel[topicid] = [docid] return qrel def get_query(self, q): if self.query_template is None: query = self.queries[q] else: query = fill_template(self.query_template, data={self.query_field: self.queries[q]}, allow_not_found=self.allow_not_found) query_encoded = self.tokenizer.encode( query, add_special_tokens=False, max_length=self.query_max_len, truncation=True ) return query_encoded def get_passage(self, p): entry = self.collection[int(p)] title = entry[self.title_field] title = "" if title is None else title body = entry[self.text_field] if self.doc_template is None: content = title + self.tokenizer.sep_token + body else: content = fill_template(self.doc_template, data=entry, allow_not_found=self.allow_not_found) passage_encoded = self.tokenizer.encode( content, add_special_tokens=False, max_length=self.doc_max_len, truncation=True ) return passage_encoded def process_one(self, train): q, pp, nn = train train_example = { 'query': self.get_query(q), 'positives': [self.get_passage(p) for p in pp], 'negatives': [self.get_passage(n) for n in nn], } return json.dumps(train_example) @dataclass class SimpleCollectionPreProcessor: tokenizer: PreTrainedTokenizer separator: str = '\t' max_length: int = 128 def process_line(self, line: str): xx = line.strip().split(self.separator) text_id, text = xx[0], xx[1:] text_encoded = self.tokenizer.encode( self.tokenizer.sep_token.join(text), add_special_tokens=False, max_length=self.max_length, truncation=True ) encoded = { 'text_id': text_id, 'text': text_encoded } return json.dumps(encoded) def save_as_trec(rank_result: Dict[str, Dict[str, float]], output_path: str, run_id: str = "OpenMatch"): """ Save the rank result as TREC format: <query_id> Q0 <doc_id> <rank> <score> <run_id> """ with open(output_path, "w") as f: for qid in rank_result: # sort the results by score sorted_results = sorted(rank_result[qid].items(), key=lambda x: x[1], reverse=True) for i, (doc_id, score) in enumerate(sorted_results): f.write("{} Q0 {} {} {} {}\n".format(qid, doc_id, i + 1, score, run_id)) def load_from_trec(input_path: str, as_list: bool = False, max_len_per_q: int = None): """ Load the rank result from TREC format: <query_id> Q0 <doc_id> <rank> <score> <run_id> or <query_id> <doc_id> <score> """ rank_result = {} cnt = 0 with open(input_path, "r") as f: for line in f: content = line.strip().split() if len(content) == 6: qid, _, doc_id, _, score, _ = content elif len(content) == 3: qid, doc_id, score = content else: raise ValueError("Invalid run format") if not as_list: if qid not in rank_result: rank_result[qid] = {} cnt = 0 if max_len_per_q is None or cnt < max_len_per_q: rank_result[qid][doc_id] = float(score) else: if qid not in rank_result: rank_result[qid] = [] cnt = 0 if max_len_per_q is None or cnt < max_len_per_q: rank_result[qid].append((doc_id, float(score))) cnt += 1 return rank_result def find_all_markers(template: str): """ Find all markers' names (quoted in "<>") in a template. """ markers = [] start = 0 while True: start = template.find("<", start) if start == -1: break end = template.find(">", start) if end == -1: break markers.append(template[start + 1:end]) start = end + 1 return markers def fill_template(template: str, data: Dict, markers: List[str] = None, allow_not_found: bool = False): """ Fill a template with data. """ if markers is None: markers = find_all_markers(template) for marker in markers: marker_hierarchy = marker.split(".") found = True content = data for marker_level in marker_hierarchy: content = content.get(marker_level, None) if content is None: found = False break if not found: if allow_not_found: warnings.warn("Marker '{}' not found in data. Replacing it with an empty string.".format(marker), RuntimeWarning) content = "" else: raise ValueError("Cannot find the marker '{}' in the data".format(marker)) template = template.replace("<{}>".format(marker), str(content)) return template def merge_retrieval_results_by_score(results: List[Dict[str, Dict[str, float]]], topk: int = 100): """ Merge retrieval results from multiple partitions of document embeddings and keep topk. """ merged_results = {} for result in results: for qid in result: if qid not in merged_results: merged_results[qid] = {} for doc_id in result[qid]: if doc_id not in merged_results[qid]: merged_results[qid][doc_id] = result[qid][doc_id] for qid in merged_results: merged_results[qid] = {k: v for k, v in sorted(merged_results[qid].items(), key=lambda x: x[1], reverse=True)[:topk]} return merged_results # Mean Pooling - Take attention mask into account for correct averaging def mean_pooling(token_embeddings, attention_mask): input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
7,762
31.894068
134
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/build_hn.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) from utils import SimpleTrainPreProcessor as TrainPreProcessor from argparse import ArgumentParser from transformers import AutoTokenizer import os import random from tqdm import tqdm from datetime import datetime from multiprocessing import Pool def load_ranking(rank_file, relevance, n_sample, depth, skip_sample): with open(rank_file) as rf: lines = iter(rf) q_0, _, p_0, rank, _, _ = next(lines).strip().split() rank = int(rank) curr_q = q_0 negatives = ( [] if q_0 not in relevance or p_0 in relevance[q_0] or rank <= skip_sample else [p_0] ) while True: try: q, _, p, rank, _, _ = next(lines).strip().split() rank = int(rank) if q != curr_q: negatives = negatives[:depth] random.shuffle(negatives) if curr_q in relevance and len(relevance[curr_q]) == 3: yield curr_q, relevance[curr_q], negatives[:n_sample] curr_q = q negatives = ( [] if q not in relevance or p in relevance[q] or rank <= skip_sample else [p] ) else: if q in relevance and p not in relevance[q] and rank > skip_sample: negatives.append(p) except StopIteration: negatives = negatives[:depth] random.shuffle(negatives) if curr_q in relevance and len(relevance[curr_q]) == 3: yield curr_q, relevance[curr_q], negatives[:n_sample] return random.seed(datetime.now()) parser = ArgumentParser() parser.add_argument("--tokenizer_name", required=True) parser.add_argument("--hn_file", required=True) parser.add_argument("--qrels", required=True) parser.add_argument("--queries", required=True) parser.add_argument("--collection", required=True) parser.add_argument("--save_to", required=True) parser.add_argument("--doc_template", type=str, default=None) parser.add_argument("--query_template", type=str, default=None) parser.add_argument("--query_max_len", type=int, default=32) parser.add_argument("--truncate", type=int, default=128) parser.add_argument("--n_sample", type=int, default=30) parser.add_argument("--depth", type=int, default=200) parser.add_argument("--skip_sample", type=int, default=0) parser.add_argument("--mp_chunk_size", type=int, default=500) parser.add_argument("--shard_size", type=int, default=45000) args = parser.parse_args() qrel = TrainPreProcessor.read_qrel(args.qrels) tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) processor = TrainPreProcessor( query_file=args.queries, query_max_len=args.query_max_len, collection_file=args.collection, tokenizer=tokenizer, doc_max_len=args.truncate, doc_template=args.doc_template, query_template=args.query_template, allow_not_found=True, ) counter = 0 shard_id = 0 f = None os.makedirs(args.save_to, exist_ok=True) pbar = tqdm( load_ranking(args.hn_file, qrel, args.n_sample, args.depth, args.skip_sample) ) with Pool() as p: for x in p.imap(processor.process_one, pbar, chunksize=args.mp_chunk_size): counter += 1 if f is None: f = open(os.path.join(args.save_to, f"split{shard_id:02d}.hn.jsonl"), "w") pbar.set_description(f"split - {shard_id:02d}") f.write(x + "\n") if counter == args.shard_size: f.close() f = None shard_id += 1 counter = 0 if f is not None: f.close()
3,844
33.026549
87
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/get_docs.py
from utils import load_from_trec import argparse import csv import json import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--collection", type=str, required=False) parser.add_argument("--ra_name", type=str, required=False) parser.add_argument("--FiD", action="store_true") parser.add_argument("run") args = parser.parse_args() collection = {} csv.field_size_limit(500 * 1024 * 1024) with open(args.collection, "r") as f: reader = csv.DictReader(f, fieldnames=["id", "title", "text"], delimiter="\t") for row in reader: # The id_ is the same as the index id_ = row.pop("id") collection[id_] = row run = load_from_trec(args.run, as_list=True) dataset = [] data_names = { "mmlu": "mmlu_msmarco_ra_ance_aar", "popQA": "popQA_kilt_wikipedia_ra_ance_aar", "marco_qa": "marco_qa_msmarco_ra_ance", "kilt": "kilt_kilt_wikipedia_ra_ance", } for name in data_names: if name in args.ra_name: data_name = data_names[name] break with open(f"data/{data_name}/cache/validation.jsonl") as f: lines = f.readlines() for line in lines: dataset.append(json.loads(line)) id = 0 for qid, rank_list in run.items(): texts = [] for doc_rank, (docid, _) in enumerate(rank_list): text = collection[docid]["text"] texts.append(text) if len(texts) == 10: break if args.FiD: dataset[id].pop("mmlu_demo", None) dataset[id]["passages"] = texts else: dataset[id]["mmlu_demo"] = " ".join(texts) id += 1 os.makedirs(f"data/{args.ra_name}/cache/", exist_ok=True) g = open( f"data/{args.ra_name}/cache/validation.jsonl", "w", ) for data in dataset: g.write(json.dumps(data) + "\n")
1,972
29.828125
86
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/gather_result_MMLU.py
import argparse import os import csv import numpy as np subcategories_mapping = { "abstract_algebra": ["math"], "anatomy": ["health"], "astronomy": ["physics"], "business_ethics": ["business"], "clinical_knowledge": ["health"], "college_biology": ["biology"], "college_chemistry": ["chemistry"], "college_computer_science": ["computer science"], "college_mathematics": ["math"], "college_medicine": ["health"], "college_physics": ["physics"], "computer_security": ["computer science"], "conceptual_physics": ["physics"], "econometrics": ["economics"], "electrical_engineering": ["engineering"], "elementary_mathematics": ["math"], "formal_logic": ["philosophy"], "global_facts": ["other"], "high_school_biology": ["biology"], "high_school_chemistry": ["chemistry"], "high_school_computer_science": ["computer science"], "high_school_european_history": ["history"], "high_school_geography": ["geography"], "high_school_government_and_politics": ["politics"], "high_school_macroeconomics": ["economics"], "high_school_mathematics": ["math"], "high_school_microeconomics": ["economics"], "high_school_physics": ["physics"], "high_school_psychology": ["psychology"], "high_school_statistics": ["math"], "high_school_us_history": ["history"], "high_school_world_history": ["history"], "human_aging": ["health"], "human_sexuality": ["culture"], "international_law": ["law"], "jurisprudence": ["law"], "logical_fallacies": ["philosophy"], "machine_learning": ["computer science"], "management": ["business"], "marketing": ["business"], "medical_genetics": ["health"], "miscellaneous": ["other"], "moral_disputes": ["philosophy"], "moral_scenarios": ["philosophy"], "nutrition": ["health"], "philosophy": ["philosophy"], "prehistory": ["history"], "professional_accounting": ["other"], "professional_law": ["law"], "professional_medicine": ["health"], "professional_psychology": ["psychology"], "public_relations": ["politics"], "security_studies": ["politics"], "sociology": ["culture"], "us_foreign_policy": ["politics"], "virology": ["health"], "world_religions": ["philosophy"], } categories = { "humanities": ["history", "philosophy", "law"], "social sciences": ["politics", "culture", "economics", "geography", "psychology"], "STEM": [ "physics", "chemistry", "biology", "computer science", "math", "engineering", ], "other (business, health, misc.)": ["other", "business", "health"], } task_len = { "high_school_biology": 32, "jurisprudence": 11, "prehistory": 35, "high_school_microeconomics": 26, "nutrition": 33, "high_school_geography": 22, "human_sexuality": 12, "astronomy": 16, "moral_scenarios": 100, "clinical_knowledge": 29, "electrical_engineering": 16, "econometrics": 12, "high_school_computer_science": 9, "college_biology": 16, "miscellaneous": 86, "high_school_mathematics": 29, "college_medicine": 22, "high_school_macroeconomics": 43, "us_foreign_policy": 11, "professional_law": 170, "high_school_government_and_politics": 21, "security_studies": 27, "public_relations": 12, "global_facts": 10, "marketing": 25, "high_school_chemistry": 22, "machine_learning": 11, "sociology": 22, "moral_disputes": 38, "college_physics": 11, "high_school_statistics": 23, "management": 11, "virology": 18, "high_school_physics": 17, "high_school_world_history": 26, "international_law": 13, "logical_fallacies": 18, "world_religions": 19, "professional_accounting": 31, "elementary_mathematics": 41, "conceptual_physics": 26, "college_computer_science": 11, "human_aging": 23, "high_school_psychology": 60, "college_mathematics": 11, "medical_genetics": 11, "abstract_algebra": 11, "professional_medicine": 31, "computer_security": 11, "philosophy": 34, "business_ethics": 11, "professional_psychology": 69, "high_school_us_history": 22, "high_school_european_history": 18, "college_chemistry": 8, "formal_logic": 14, "anatomy": 13, } def main(): parser = argparse.ArgumentParser() parser.add_argument("--task_name", type=str, help="Task name") parser.add_argument("--subtask_name", type=str, help="Subtask name") parser.add_argument("--method_name", type=str, help="Method name") parser.add_argument("--score", type=str, help="Score") args = parser.parse_args() accs = {} category_accs = {} with open( f"results/{args.method_name}/fp16/zs/{args.task_name}/preds/{args.task_name}/{args.score}_0.txt" ) as f: lines = f.readlines()[3:] begin, end = 0, 0 for key, value in task_len.items(): begin, end = end, end + value sum = 0 for i in range(begin, end): pred, label = lines[i].strip().split("\t\t") sum += pred == label # gather acc for each category for category, subcategories in categories.items(): for subcategory in subcategories: if subcategory in subcategories_mapping[key]: if category not in category_accs: category_accs[category] = [0, 0] category_accs[category][0] += sum / value category_accs[category][1] += 1 accs[key] = sum / value print("All: {:.1f}".format(np.mean(list(accs.values())) * 100)) # print acc for each category sum = 0 for category, subcategories in categories.items(): print( "{}: {:.1f}".format( category, category_accs[category][0] / category_accs[category][1] * 100 ) ) sum += category_accs[category][1] if __name__ == "__main__": main()
6,104
31.822581
104
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/ds_fix/engine.py
''' Copyright 2019 The Microsoft DeepSpeed Team ''' import os import time import torch import warnings import torch.distributed as dist from torch.nn.modules import Module from torch.distributed.distributed_c10d import _get_global_rank from tensorboardX import SummaryWriter from deepspeed.runtime.zero.stage2 import FP16_DeepSpeedZeroOptimizer from deepspeed.runtime.zero.stage1 import FP16_DeepSpeedZeroOptimizer_Stage1 from deepspeed.runtime.zero.utils import is_zero_supported_optimizer from deepspeed.runtime.activation_checkpointing import checkpointing as activation_checkpointing from deepspeed.runtime.fp16.fused_optimizer import FP16_Optimizer from deepspeed.runtime.fp16.unfused_optimizer import FP16_UnfusedOptimizer from deepspeed.runtime.config import DeepSpeedConfig, DEEPSPEED_OPTIMIZERS, \ ADAM_OPTIMIZER, LAMB_OPTIMIZER, ONEBIT_ADAM_OPTIMIZER, \ TORCH_ADAM_PARAM, ADAM_W_MODE_PARAM from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.runtime.constants import \ ROUTE_TRAIN, ROUTE_PREDICT, ROUTE_EVAL, \ PLD_THETA, PLD_GAMMA from deepspeed.runtime.zero.constants import \ ZERO_OPTIMIZATION_OPTIMIZER_STATES, ZERO_OPTIMIZATION_GRADIENTS from deepspeed.runtime.csr_tensor import CSRTensor import deepspeed.runtime.lr_schedules as lr_schedules from deepspeed.utils import logger, log_dist, init_distributed from deepspeed.utils.timer import ThroughputTimer, SynchronizedWallClockTimer from deepspeed.runtime.progressive_layer_drop import ProgressiveLayerDrop from .pipe.module import PipelineModule from .utils import ensure_directory_exists from ..ops.op_builder import UtilsBuilder from ..ops.adam import DeepSpeedCPUAdam from ..ops.adam import FusedAdam MEMORY_OPT_ALLREDUCE_SIZE = 500000000 try: from apex import amp except ImportError: # Fail silently so we don't spam logs unnecessarily if user isn't using amp pass def split_half_float_double_csr(tensors): dtypes = [ "torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor", CSRTensor.type() ] buckets = [] for i, dtype in enumerate(dtypes): bucket = [t for t in tensors if t.type() == dtype] if bucket: buckets.append((dtype, bucket)) return buckets def _initialize_parameter_parallel_groups(parameter_parallel_size=None): data_parallel_size = int(dist.get_world_size()) if parameter_parallel_size is None: parameter_parallel_size = int(data_parallel_size) logger.info("data_parallel_size: %s, parameter_parallel_size: %s", data_parallel_size, parameter_parallel_size) assert data_parallel_size % parameter_parallel_size == 0, \ 'world size should be divisible by parameter parallel size' rank = dist.get_rank() my_group = None for i in range(dist.get_world_size() // parameter_parallel_size): ranks = range(i * parameter_parallel_size, (i + 1) * parameter_parallel_size) group = torch.distributed.new_group(ranks) if rank in ranks: my_group = group return my_group def print_configuration(args, name): logger.info('{}:'.format(name)) for arg in sorted(vars(args)): dots = '.' * (29 - len(arg)) logger.info(' {} {} {}'.format(arg, dots, getattr(args, arg))) class DeepSpeedEngine(Module): r"""DeepSpeed engine for training. """ def __init__(self, args, model, optimizer=None, model_parameters=None, training_data=None, lr_scheduler=None, mpu=None, dist_init_required=None, collate_fn=None, config_params=None): super(DeepSpeedEngine, self).__init__() self.client_optimizer = optimizer self.client_model_parameters = model_parameters self.client_lr_scheduler = lr_scheduler self.training_data = training_data self.collate_fn = collate_fn self.mpu = mpu self.data_parallel_group = None self.global_steps = 0 self.global_samples = 0 self.micro_steps = 0 self.skipped_steps = 0 self.gradient_average = True self.warn_unscaled_loss = True self.config_params = config_params self.loaded_checkpoint_mp_world_size = None self.loaded_checkpoint_dp_world_size = None self.enable_backward_allreduce = True self.progressive_layer_drop = None self.dist_backend = "nccl" if dist_init_required is None: dist_init_required = not dist.is_initialized() if dist_init_required is False: assert (dist.is_initialized()==True), "Torch distributed not initialized. Please set dist_init_required to True or initialize before calling deepspeed.initialize()" # Initialize torch distributed if needed init_distributed(dist_backend=self.dist_backend) self._do_args_sanity_check(args) self._configure_with_arguments(args, mpu) self._do_sanity_check() if mpu is not None: assert not self.elasticity_enabled(), "Elasticity is not currently supported" \ " with model parallelism." self._set_distributed_vars() if self.tensorboard_enabled() and self.global_rank == 0: self.summary_writer = self.get_summary_writer() # Configure distributed model self._configure_distributed_model(model) # Configure wall clock timer self.timers = SynchronizedWallClockTimer() # Throughput timer self.tput_timer = ThroughputTimer( batch_size=self.train_micro_batch_size_per_gpu(), num_workers=self.dp_world_size, steps_per_output=self.steps_per_print(), monitor_memory=False) if training_data: self.training_dataloader = self.deepspeed_io(training_data) else: self.training_dataloader = None # Configure optimizer and scheduler self.optimizer = None self.lr_scheduler = None if model_parameters or optimizer: self._configure_optimizer(optimizer, model_parameters) self._configure_lr_scheduler(lr_scheduler) self._report_progress(0) # Bookkeeping for csr support self.csr_tensor_module_names = set() if self.sparse_gradients_enabled(): for name, module in self.module.named_modules(): if isinstance(module, torch.nn.Embedding): self.csr_tensor_module_names.add(name + ".weight") logger.info("Will convert {} to sparse (csr) " "tensor during training".format(name)) self.save_non_zero_checkpoint = False self.save_zero_checkpoint = False self._configure_checkpointing(dist_init_required) if self.pld_enabled(): self.progressive_layer_drop = self._configure_progressive_layer_drop() if self.global_rank == 0: self._config.print('DeepSpeedEngine configuration') if self.dump_state(): print_configuration(self, 'DeepSpeedEngine') # Load pre-installed or JIT compile (un)flatten ops util_ops = UtilsBuilder().load() self.flatten = util_ops.flatten self.unflatten = util_ops.unflatten def get_batch_info(self): """ Get all training batch related settings. Returns: train_batch_size (int): The effective training batch size. This is the amount of data samples that leads to one step of model update. train_micro_batch_size_per_gpu (int): Batch size to be processed by one GPU in one step (without gradient accumulation). gradient_accumulation_steps (int): Number of training steps to accumulate gradients before averaging and applying them. """ return self.train_batch_size, self.train_micro_batch_size_per_gpu, self.gradient_accumulation_steps def elasticity_enabled(self): return self._config.elasticity_enabled def pld_enabled(self): return self._config.pld_enabled def pld_params(self): return self._config.pld_params def pld_theta(self): return self.pld_params()[PLD_THETA] def pld_gamma(self): return self.pld_params()[PLD_GAMMA] def tensorboard_enabled(self): return self._config.tensorboard_enabled def tensorboard_output_path(self): return self._config.tensorboard_output_path def tensorboard_job_name(self): return self._config.tensorboard_job_name def get_summary_writer(self, name="DeepSpeedJobName", base=os.path.join(os.environ["HOME"], "tensorboard")): if self.tensorboard_output_path(): base_dir = self.tensorboard_output_path() job_name = self.tensorboard_job_name() log_dir = os.path.join(base_dir, job_name) else: if self.tensorboard_job_name(): name = self.tensorboard_job_name() # Infrastructure-specific job-id if 'DLWS_JOB_ID' in os.environ: infra_job_id = os.environ['DLWS_JOB_ID'] elif 'DLTS_JOB_ID' in os.environ: infra_job_id = os.environ['DLTS_JOB_ID'] else: infra_job_id = 'unknown-job-id' summary_writer_dir_name = os.path.join(infra_job_id, "logs") log_dir = os.path.join(base, summary_writer_dir_name, name) os.makedirs(log_dir, exist_ok=True) return SummaryWriter(log_dir=log_dir) def wall_clock_breakdown(self): return self._config.wall_clock_breakdown def memory_breakdown(self): return self._config.memory_breakdown def sparse_gradients_enabled(self): return self._config.sparse_gradients_enabled def train_batch_size(self): return self._config.train_batch_size def train_micro_batch_size_per_gpu(self): return self._config.train_micro_batch_size_per_gpu def optimizer_name(self): return self.client_optimizer.__class__.__name__ if self.client_optimizer else self._config.optimizer_name def optimizer_params(self): return self._config.optimizer_params def optimizer_legacy_fusion(self): return self._config.optimizer_legacy_fusion def scheduler_name(self): return self._config.scheduler_name def scheduler_params(self): return self._config.scheduler_params def zero_optimization(self): return self._config.zero_enabled def zero_allow_untested_optimizer(self): return self._config.zero_allow_untested_optimizer def zero_reduce_scatter(self): return self._config.zero_config.reduce_scatter def zero_overlap_comm(self): return self._config.zero_config.overlap_comm def zero_cpu_offload(self): return self._config.zero_config.cpu_offload def zero_optimization_stage(self): return self._config.zero_optimization_stage def zero_reduce_bucket_size(self): return self._config.zero_config.reduce_bucket_size def zero_allgather_bucket_size(self): return self._config.zero_config.allgather_bucket_size def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZERO_OPTIMIZATION_GRADIENTS def zero_contiguous_gradients(self): return self._config.zero_config.contiguous_gradients def zero_load_from_fp32_weights(self): return self._config.zero_config.load_from_fp32_weights def zero_elastic_checkpoint(self): return self._config.zero_config.elastic_checkpoint def fp16_enabled(self): return self._config.fp16_enabled def amp_enabled(self): return self._config.amp_enabled def amp_params(self): return self._config.amp_params def loss_scale(self): return self._config.loss_scale def gradient_accumulation_steps(self): return self._config.gradient_accumulation_steps def allreduce_always_fp32(self): return self._config.allreduce_always_fp32 def postscale_gradients(self): return not self._config.prescale_gradients def gradient_predivide_factor(self): return self._config.gradient_predivide_factor def steps_per_print(self): return self._config.steps_per_print def zero_allgather_partitions(self): return self._config.zero_config.allgather_partitions def dump_state(self): return self._config.dump_state def gradient_clipping(self): return self._config.gradient_clipping def dynamic_loss_scale(self): return self._config.loss_scale == 0 def initial_dynamic_scale(self): return self._config.initial_dynamic_scale def dynamic_loss_scale_args(self): return self._config.dynamic_loss_scale_args def _configure_lr_scheduler(self, client_lr_scheduler): # First check for scheduler in json configuration lr_scheduler = self._scheduler_from_config(self.optimizer) if lr_scheduler: if self.global_rank == 0: logger.info( f'DeepSpeed using configured LR scheduler = {self.scheduler_name()}') self.lr_scheduler = lr_scheduler else: if self.global_rank == 0: logger.info('DeepSpeed using client LR scheduler') self.lr_scheduler = client_lr_scheduler log_dist(f'DeepSpeed LR Scheduler = {self.lr_scheduler}', ranks=[0]) def _configure_checkpointing(self, dist_init_required): dp_rank = self.global_rank if self.mpu: dp_rank = self.mpu.get_data_parallel_rank() # only the first data parallel process needs to store the model checkpoint self.save_non_zero_checkpoint = (dp_rank == 0) if self.zero_optimization() and self.optimizer is not None: param_rank = torch.distributed.get_rank( group=self.optimizer.dp_process_group) # Only the first parameter parallel process needs to store the # optimizer state checkpoints for zero self.save_zero_checkpoint = (param_rank == dp_rank) def _scheduler_from_config(self, optimizer): scheduler_name = self.scheduler_name() if scheduler_name is not None: if hasattr(lr_schedules, scheduler_name): scheduler = getattr(lr_schedules, scheduler_name) else: assert hasattr(torch.optim.lr_scheduler, scheduler_name), \ f"DeepSpeed does not recognize LR scheduler {scheduler_name}" scheduler = getattr(torch.optim.lr_scheduler, scheduler_name) scheduler_params = self.scheduler_params() instantiated_scheduler = scheduler(optimizer, **scheduler_params) return instantiated_scheduler else: return None def _set_distributed_vars(self): if self.local_rank >= 0: torch.cuda.set_device(self.local_rank) self.device = torch.device("cuda", self.local_rank) self.world_size = dist.get_world_size() self.global_rank = dist.get_rank() else: self.world_size = 1 self.global_rank = 0 self.device = torch.device("cuda") # Configure based on command line arguments def _configure_with_arguments(self, args, mpu): self.local_rank = args.local_rank if hasattr(args, 'local_rank') else 0 config_file = args.deepspeed_config if hasattr(args, 'deepspeed_config') else None self._config = DeepSpeedConfig(config_file, mpu, param_dict=self.config_params) # Validate command line arguments def _do_args_sanity_check(self, args): if hasattr(args, 'deepscale_config') and args.deepscale_config is not None: logger.warning( "************ --deepscale_config is deprecated, please use --deepspeed_config ************" ) if hasattr(args, 'deepspeed_config'): assert args.deepspeed_config is None, "Not sure how to proceed, we were given both a deepscale_config and deepspeed_config" args.deepspeed_config = args.deepscale_config assert hasattr(args, 'local_rank') and type(args.local_rank) == int, \ 'DeepSpeed requires integer command line parameter --local_rank' if self.config_params is None: assert hasattr(args, 'deepspeed_config') and args.deepspeed_config is not None, \ 'DeepSpeed requires --deepspeed_config to specify configuration file' assert os.path.isfile(args.deepspeed_config), \ 'DeepSpeed configuration file: {} is not an existing file'.format(args.deepspeed_config) def _is_supported_optimizer(self, optimizer_name): return optimizer_name in DEEPSPEED_OPTIMIZERS or \ getattr(torch.optim, optimizer_name, None) is not None # Validate configuration based on command line arguments def _do_sanity_check(self): if not self.client_optimizer: if self.optimizer_name() is not None: assert self._is_supported_optimizer(self.optimizer_name()), \ '{} is not a supported DeepSpeed Optimizer'.format(self.optimizer_name()) if self.optimizer_name() == LAMB_OPTIMIZER: assert self.dynamic_loss_scale(), \ 'DeepSpeed {} optimizer requires dynamic loss scaling'.format(self.optimizer_name()) def _broadcast_model(self): for p in self.module.parameters(): if torch.is_tensor(p): dist.broadcast(p, self.broadcast_src_rank, group=self.data_parallel_group) def _configure_distributed_model(self, model): self.module = model if self.fp16_enabled(): self.module.half() self.module.to(self.device) if self.mpu is None: self.data_parallel_group = _initialize_parameter_parallel_groups() self.dp_world_size = dist.get_world_size() self.mp_world_size = 1 self.broadcast_src_rank = 0 else: self.data_parallel_group = self.mpu.get_data_parallel_group() self.dp_world_size = self.mpu.get_data_parallel_world_size() self.mp_world_size = self.mpu.get_model_parallel_world_size() self.broadcast_src_rank = _get_global_rank( self.mpu.get_data_parallel_group(), 0) if not self.amp_enabled(): self._broadcast_model() # Configure optimizer def _configure_optimizer(self, client_optimizer, model_parameters): if client_optimizer is not None: basic_optimizer = client_optimizer if self.global_rank == 0: logger.info('Using client Optimizer as basic optimizer') else: basic_optimizer = self._configure_basic_optimizer(model_parameters) if self.global_rank == 0: logger.info( 'Using DeepSpeed Optimizer param name {} as basic optimizer'.format( self.optimizer_name())) if self.global_rank == 0: logger.info('DeepSpeed Basic Optimizer = {}'.format(basic_optimizer)) if self.zero_optimization(): assert not self.amp_enabled(), "Amp and ZeRO are not currently compatible, please use (legacy) fp16 mode which performs similar to amp opt_mode=O2" if not is_zero_supported_optimizer(basic_optimizer): assert self.zero_allow_untested_optimizer(), \ 'You are using an untested ZeRO Optimizer. Please add <"zero_allow_untested_optimizer": true> in the configuration file to use it.' if self.global_rank == 0: logger.warning( "**** You are using ZeRO with an untested optimizer, proceed with caution *****" ) self.optimizer = self._configure_zero_optimizer(basic_optimizer) elif self.amp_enabled(): assert not self.fp16_enabled(), "Cannot enable both amp with (legacy) fp16 mode" amp_params = self.amp_params() if self.global_rank == 0: logger.info(f"Initializing AMP with these params: {amp_params}") try: logger.info("Initializing Apex amp from: {}".format(amp.__path__)) except NameError: # If apex/amp is available it will be imported above raise RuntimeError( "Unable to import apex/amp, please make sure it is installed") self.module, self.optimizer = amp.initialize(self.module, basic_optimizer, **amp_params) self._broadcast_model() elif self.fp16_enabled(): self.optimizer = self._configure_fp16_optimizer(basic_optimizer) else: self.optimizer = basic_optimizer logger.info('DeepSpeed Final Optimizer = {}'.format(self.optimizer)) logger.info('DeepSpeed Final Optimizer = {}'.format(self.optimizer.state_dict())) def _configure_basic_optimizer(self, model_parameters): optimizer_parameters = self.optimizer_params() # print(optimizer_parameters.keys()) if 'max_grad_norm' in optimizer_parameters.keys(): raise ValueError( "'max_grad_norm' is not supported as an optimizer parameter, please switch to using the deepspeed parameter 'gradient_clipping' see: https://www.deepspeed.ai/docs/config-json/#gradient-clipping for more details" ) if self.optimizer_name() == ADAM_OPTIMIZER: torch_adam = optimizer_parameters.pop(TORCH_ADAM_PARAM, False) adam_w_mode = optimizer_parameters.pop(ADAM_W_MODE_PARAM, True) # zero-offload torch-adam adam_w_mode optimizer # T|F T T torch.optim.AdamW # T|F T F torch.optim.Adam # T F T|F DeepSpeedCPUAdam(adam_w_mode) # F F T|F FusedAdam(adam_w_mode) if torch_adam: if adam_w_mode: optimizer = torch.optim.AdamW(model_parameters, **optimizer_parameters) else: optimizer = torch.optim.Adam(model_parameters, **optimizer_parameters) elif self.zero_cpu_offload(): optimizer = DeepSpeedCPUAdam(model_parameters, **optimizer_parameters, adamw_mode=adam_w_mode) else: optimizer_parameters[ADAM_W_MODE_PARAM] = adam_w_mode optimizer = FusedAdam(model_parameters, **optimizer_parameters) elif self.optimizer_name() == LAMB_OPTIMIZER: from deepspeed.ops.lamb import FusedLamb optimizer = FusedLamb(model_parameters, **optimizer_parameters) elif self.optimizer_name() == ONEBIT_ADAM_OPTIMIZER: from deepspeed.runtime.fp16.onebit_adam import OnebitAdam optimizer = OnebitAdam(model_parameters, self, **optimizer_parameters) else: torch_optimizer = getattr(torch.optim, self.optimizer_name()) optimizer = torch_optimizer(model_parameters, **optimizer_parameters) return optimizer def _configure_fp16_optimizer(self, optimizer): initial_dynamic_scale = self.initial_dynamic_scale() dynamic_loss_args = self.dynamic_loss_scale_args() clip_grad = self.gradient_clipping() if isinstance(optimizer, FusedAdam) or self.optimizer_name() == ONEBIT_ADAM_OPTIMIZER: if self.dynamic_loss_scale(): logger.info('Creating fp16 optimizer with dynamic loss scale') timers = self.timers if self.wall_clock_breakdown() else None optimizer = FP16_Optimizer( optimizer, dynamic_loss_scale=True, initial_dynamic_scale=initial_dynamic_scale, dynamic_loss_args=dynamic_loss_args, mpu=self.mpu, clip_grad=clip_grad, fused_adam_legacy=self.optimizer_legacy_fusion(), timers=timers) else: logger.info('Creating fp16 optimizer with static loss scale: {}'.format( self.loss_scale())) optimizer = FP16_Optimizer( optimizer, static_loss_scale=self.loss_scale(), mpu=self.mpu, clip_grad=clip_grad, fused_adam_legacy=self.optimizer_legacy_fusion()) else: logger.info('Creating fp16 unfused optimizer with dynamic loss scale') optimizer = FP16_UnfusedOptimizer( optimizer, static_loss_scale=self.loss_scale(), dynamic_loss_scale=self.dynamic_loss_scale(), dynamic_loss_args=dynamic_loss_args, mpu=self.mpu, clip_grad=clip_grad, fused_lamb_legacy=self.optimizer_name() == LAMB_OPTIMIZER) return optimizer def _configure_zero_optimizer(self, optimizer): zero_stage = self.zero_optimization_stage() logger.info('Creating fp16 ZeRO stage {} optimizer'.format(zero_stage)) assert not self.allreduce_always_fp32(), "ZeRO does not support 'fp32_allreduce': true" if zero_stage == ZERO_OPTIMIZATION_OPTIMIZER_STATES: assert self.zero_reduce_scatter(), 'Stage 1 only supports reduce scatter mode' optimizer = FP16_DeepSpeedZeroOptimizer_Stage1( optimizer, static_loss_scale=self.loss_scale(), dynamic_loss_scale=self.dynamic_loss_scale(), dynamic_loss_args=self.dynamic_loss_scale_args(), clip_grad=self.gradient_clipping(), all_gather_partitions=self.zero_allgather_partitions(), allgather_size=self.zero_allgather_bucket_size(), max_elements_per_comm=self.zero_reduce_bucket_size(), dp_process_group=self.data_parallel_group, elastic_checkpoint=self.zero_elastic_checkpoint(), mpu=self.mpu) elif zero_stage == ZERO_OPTIMIZATION_GRADIENTS: optimizer = FP16_DeepSpeedZeroOptimizer( optimizer, timers=self.timers, static_loss_scale=self.loss_scale(), dynamic_loss_scale=self.dynamic_loss_scale(), dynamic_loss_args=self.dynamic_loss_scale_args(), clip_grad=self.gradient_clipping(), contiguous_gradients=self.zero_contiguous_gradients(), reduce_bucket_size=self.zero_reduce_bucket_size(), allgather_bucket_size=self.zero_allgather_bucket_size(), dp_process_group=self.data_parallel_group, reduce_scatter=self.zero_reduce_scatter(), overlap_comm=self.zero_overlap_comm(), cpu_offload=self.zero_cpu_offload(), mpu=self.mpu, postscale_gradients=self.postscale_gradients(), gradient_predivide_factor=self.gradient_predivide_factor(), gradient_accumulation_steps=self.gradient_accumulation_steps()) else: raise NotImplementedError("ZeRO stage {} not implemented".format(zero_stage)) return optimizer def _configure_progressive_layer_drop(self): pld = ProgressiveLayerDrop(theta=self.pld_theta(), gamma=self.pld_gamma()) return pld def deepspeed_io(self, dataset, batch_size=None, route=ROUTE_TRAIN, pin_memory=True, data_sampler=None, collate_fn=None, num_local_io_workers=None): if not isinstance(dataset, torch.utils.data.Dataset): raise ValueError("Training data must be a torch Dataset") if data_sampler is None and (route == ROUTE_PREDICT or route == ROUTE_EVAL): data_sampler = torch.utils.data.SequentialSampler(dataset) if batch_size is None: batch_size = self.train_micro_batch_size_per_gpu() if collate_fn is None: collate_fn = self.collate_fn # Currently we only use timer in train route deepspeed_io_timer = None if route == ROUTE_TRAIN: deepspeed_io_timer = self.tput_timer # If mpu is provied, forward world size and parallel rank to sampler. data_parallel_world_size = None data_parallel_rank = None if self.mpu is not None: data_parallel_world_size = self.mpu.get_data_parallel_world_size() data_parallel_rank = self.mpu.get_data_parallel_rank() return DeepSpeedDataLoader(dataset=dataset, batch_size=batch_size, pin_memory=pin_memory, collate_fn=collate_fn, local_rank=self.local_rank, tput_timer=deepspeed_io_timer, num_local_io_workers=num_local_io_workers, data_sampler=data_sampler, data_parallel_world_size=data_parallel_world_size, data_parallel_rank=data_parallel_rank) def train(self, mode=True): r""" """ self.warn_unscaled_loss = True self.module.train(mode) def eval(self): r""" """ self.warn_unscaled_loss = True self.module.train(False) def _scale_loss(self, prescaled_loss): if isinstance(prescaled_loss, torch.Tensor): scaled_loss = prescaled_loss / self.gradient_accumulation_steps() elif isinstance(prescaled_loss, tuple) or isinstance(prescaled_loss, list): scaled_loss = [] for l in prescaled_loss: if isinstance(l, torch.Tensor): scaled_loss.append(l / self.gradient_accumulation_steps()) else: scaled_loss.append(l) else: scaled_loss = prescaled_loss if self.warn_unscaled_loss: logger.warning( f'DeepSpeed unable to scale loss because of type: {type(prescaled_loss)}' ) self.warn_unscaled_loss = False return scaled_loss def forward(self, *inputs, **kwargs): r"""Execute forward propagation Arguments: *inputs: Variable length input list **kwargs: variable length keyword arguments """ if self.module.training and self.progressive_layer_drop: kwargs.update(self.progressive_layer_drop.get_state()) if self.wall_clock_breakdown(): self.timers('forward_microstep').start() self.timers('forward').start() if self.training_dataloader is None: self.tput_timer.start() loss = self.module(*inputs, **kwargs) if self.wall_clock_breakdown(): self.timers('forward').stop() self.timers('forward_microstep').stop() return loss def allreduce_gradients(self, bucket_size=MEMORY_OPT_ALLREDUCE_SIZE): #Zero stage 2 communicates during non gradient accumulation boundaries as well if self.zero_optimization_partition_gradients(): self.optimizer.overlapping_partition_gradients_reduce_epilogue() #Communicate only at gradient accumulation boundaries elif self.is_gradient_accumulation_boundary(): if self.zero_optimization_stage() == ZERO_OPTIMIZATION_OPTIMIZER_STATES: assert self.zero_reduce_scatter() self.optimizer.reduce_scatter_gradients( postscale_gradients=self.postscale_gradients(), gradient_predivide_factor=self.gradient_predivide_factor(), gradient_average=self.gradient_average) else: self.buffered_allreduce_fallback(elements_per_buffer=bucket_size) def backward(self, loss, allreduce_gradients=True, release_loss=False): r"""Execute backward pass on the loss Arguments: loss: Torch tensor on which to execute backward propagation allreduce_gradients: If this is False, then gradient averaging will be skipped. Default is True. """ if not allreduce_gradients: logger.warning( f'Argument `allreduce_gradients` is deprecated, ignored, and will soon be removed' ) # scale loss w.r.t. gradient accumulation if needed if self.gradient_accumulation_steps() > 1: loss = self._scale_loss(loss.float()) # Log training Loss if self.tensorboard_enabled(): if self.is_gradient_accumulation_boundary(): if self.global_rank == 0: self.summary_events = [ (f'Train/Samples/train_loss', loss.mean().item() * self.gradient_accumulation_steps(), self.global_samples) ] for event in self.summary_events: # write_summary_events self.summary_writer.add_scalar(event[0], event[1], event[2]) self.summary_writer.flush() if self.wall_clock_breakdown(): self.timers('backward_microstep').start() self.timers('backward').start() assert self.optimizer is not None, "must provide optimizer during " \ "init in order to use backward" if self.wall_clock_breakdown(): self.timers('backward_inner_microstep').start() self.timers('backward_inner').start() if self.zero_optimization(): self.optimizer.is_gradient_accumulation_boundary = self.is_gradient_accumulation_boundary( ) self.optimizer.backward(loss) elif self.amp_enabled(): # AMP requires delaying unscale when inside gradient accumulation boundaries # https://nvidia.github.io/apex/advanced.html#gradient-accumulation-across-iterations delay_unscale = not self.is_gradient_accumulation_boundary() with amp.scale_loss(loss, self.optimizer, delay_unscale=delay_unscale) as scaled_loss: scaled_loss.backward() elif self.fp16_enabled(): self.optimizer.backward(loss) else: loss.backward() if self.wall_clock_breakdown(): self.timers('backward_inner').stop() self.timers('backward_inner_microstep').stop() if self.wall_clock_breakdown(): self.timers('backward_allreduce_microstep').start() self.timers('backward_allreduce').start() if self.enable_backward_allreduce: self.allreduce_gradients() if self.wall_clock_breakdown(): self.timers('backward_allreduce').stop() self.timers('backward_allreduce_microstep').stop() self.timers('backward').stop() self.timers('backward_microstep').stop() if release_loss: # loss.data = None pass return loss def is_gradient_accumulation_boundary(self): """Query whether the current micro-batch is at the boundary of gradient accumulation, and thus will trigger gradient reductions and an optimizer step. Returns: bool: if the current step is a gradient accumulation boundary. """ return (self.micro_steps + 1) % \ self.gradient_accumulation_steps() == 0 def zero_grad(self): """ Zero parameter grads. """ for param_name, param in self.module.named_parameters(): param.grad = None def clip_fp32_gradients(self): torch.nn.utils.clip_grad_norm_(parameters=self.module.parameters(), max_norm=self.gradient_clipping()) def _take_model_step(self, lr_kwargs): if self.gradient_clipping() > 0.0: if not self.fp16_enabled() and not self.amp_enabled(): self.clip_fp32_gradients() elif self.amp_enabled(): # AMP's recommended way of doing clipping # https://nvidia.github.io/apex/advanced.html#gradient-clipping master_params = amp.master_params(self.optimizer) torch.nn.utils.clip_grad_norm_(parameters=master_params, max_norm=self.gradient_clipping()) self.optimizer.step() #zero grad in basic optimizer could be unreliable and may not exhibit #the behaviour that we want if not self.zero_optimization() and not self.fp16_enabled( ) and not self.amp_enabled(): self.zero_grad() else: self.optimizer.zero_grad() report_progress = self.global_rank == 0 if self.global_rank else True # Check overlow here since in DS fp16 optimizer, the overflow is updated in above step() function. overflow = False if hasattr(self.optimizer, 'overflow'): overflow = self.optimizer.overflow if overflow: self.skipped_steps += 1 else: if self.lr_scheduler is not None: self.lr_scheduler.step(**(lr_kwargs or {})) if report_progress and (self.global_steps + 1) % self.steps_per_print() == 0: self._report_progress(self.global_steps + 1) self.global_steps += 1 self.global_samples += self.train_batch_size() def step(self, lr_kwargs=None): r"""Execute the weight update step after forward and backward propagation on effective_train_batch. """ if self.wall_clock_breakdown(): self.timers('step_microstep').start() self.timers('step').start() assert self.optimizer is not None, "must provide optimizer during " \ "init in order to use step" report_progress = self.global_rank == 0 if self.global_rank else True # Update the model when we reach gradient accumulation boundaries if self.is_gradient_accumulation_boundary(): if self.progressive_layer_drop: self.progressive_layer_drop.update_state(self.global_steps) self._take_model_step(lr_kwargs) self.tput_timer.stop(report_progress) # Log learning rate if self.tensorboard_enabled(): if self.is_gradient_accumulation_boundary(): if self.global_rank == 0: self.summary_events = [(f'Train/Samples/lr', self.get_lr()[0], self.global_samples)] for event in self.summary_events: # write_summary_events self.summary_writer.add_scalar(event[0], event[1], event[2]) if self.fp16_enabled() and hasattr(self.optimizer, 'cur_scale'): self.summary_events.append((f'Train/Samples/loss_scale', self.optimizer.cur_scale, self.global_samples)) for event in self.summary_events: # write_summary_events self.summary_writer.add_scalar(event[0], event[1], event[2]) self.summary_writer.flush() if self.wall_clock_breakdown(): self.timers('step').stop() self.timers('step_microstep').stop() timer_names = [ 'forward_microstep', 'backward_microstep', 'backward_inner_microstep', 'backward_allreduce_microstep', 'step_microstep' ] self.timers.log(names=timer_names, memory_breakdown=self.memory_breakdown()) # Log timing if self.is_gradient_accumulation_boundary(): if self.tensorboard_enabled(): if self.global_rank == 0: self.summary_events = [ (f'Train/Samples/elapsed_time_ms_forward', self.timers('forward').elapsed(reset=False) * 1000.0, self.global_samples), (f'Train/Samples/elapsed_time_ms_backward', self.timers('backward').elapsed(reset=False) * 1000.0, self.global_samples), (f'Train/Samples/elapsed_time_ms_backward_inner', self.timers('backward_inner').elapsed(reset=False) * 1000.0, self.global_samples), (f'Train/Samples/elapsed_time_ms_backward_allreduce', self.timers('backward_allreduce').elapsed(reset=False) * 1000.0, self.global_samples), (f'Train/Samples/elapsed_time_ms_step', self.timers('step').elapsed(reset=False) * 1000.0, self.global_samples) ] for event in self.summary_events: # write_summary_events self.summary_writer.add_scalar(event[0], event[1], event[2]) self.summary_writer.flush() if self.wall_clock_breakdown(): self.timers.log([ 'forward', 'backward', 'backward_inner', 'backward_allreduce', 'step' ]) self.micro_steps += 1 def _get_optimizer_param(self, param_name): result = [] if not self.optimizer: return result for group in self.optimizer.param_groups: if param_name in group: result.append(group[param_name]) else: result.append(0.0) return result def get_lr(self): return self._get_optimizer_param('lr') def get_type(self): return self._get_optimizer_param('type') def get_mom(self): if self.optimizer_name() in ['SGD', 'RMSprop']: return self._get_optimizer_param('momentum') else: return self._get_optimizer_param('betas') def get_pld_theta(self): if self.progressive_layer_drop: return self.progressive_layer_drop.get_theta() else: return None def _report_progress(self, step): lr = self.get_lr() mom = self.get_mom() log_dist(f'step={step}, skipped={self.skipped_steps}, lr={lr}, mom={mom}', ranks=[0]) def allreduce_bucket(self, bucket): tensor = self.flatten(bucket) tensor_to_allreduce = tensor if self.allreduce_always_fp32(): tensor_to_allreduce = tensor.float() if self.postscale_gradients(): if self.gradient_predivide_factor() != 1.0: tensor_to_allreduce.mul_(1. / self.gradient_predivide_factor()) dist.all_reduce(tensor_to_allreduce, group=self.data_parallel_group) if self.gradient_average: if self.gradient_predivide_factor() != self.dp_world_size: tensor_to_allreduce.mul_(self.gradient_predivide_factor() / self.dp_world_size) else: tensor_to_allreduce.div_(self.dp_world_size) dist.all_reduce(tensor_to_allreduce, group=self.data_parallel_group) if self.allreduce_always_fp32() and tensor is not tensor_to_allreduce: tensor.copy_(tensor_to_allreduce) return tensor def allreduce_and_copy(self, small_bucket): allreduced = self.allreduce_bucket(small_bucket) for buf, synced in zip(small_bucket, self.unflatten(allreduced, small_bucket)): buf.copy_(synced) def allreduce_no_retain(self, bucket, numel_per_bucket=500000000): small_bucket = [] numel = 0 for tensor in bucket: small_bucket.append(tensor) numel = numel + tensor.numel() if numel > numel_per_bucket: self.allreduce_and_copy(small_bucket) small_bucket = [] numel = 0 if len(small_bucket) > 0: self.allreduce_and_copy(small_bucket) def buffered_allreduce_fallback(self, grads=None, elements_per_buffer=500000000): grads = [] for param_name, param in self.module.named_parameters(): if param.grad is None: # In cases where there is an imbalance of empty grads across # ranks we must create empty grads, this will ensure that every # rank is reducing the same size. In some cases it may make # sense in the future to support the ability to average not # w.r.t. world size but with a different value. param.grad = torch.zeros(param.size(), dtype=param.dtype, device=param.device) grads.append(param.grad.data) else: grad_data = param.grad.data if self.sparse_gradients_enabled( ) and param_name in self.csr_tensor_module_names: grads.append(CSRTensor(grad_data)) else: grads.append(grad_data) split_buckets = split_half_float_double_csr(grads) for i, bucket_tuple in enumerate(split_buckets): bucket_type, bucket = bucket_tuple if bucket_type == CSRTensor.type(): self.csr_allreduce_no_retain(bucket) else: self.allreduce_no_retain(bucket, numel_per_bucket=elements_per_buffer) def csr_allreduce_no_retain(self, bucket): allreduced_csrs = self.csr_allreduce_bucket(bucket) # Densify csr tensor and copy back to original location for csr in allreduced_csrs: dense_tensor = csr.to_dense() csr.orig_dense_tensor.copy_(dense_tensor) def csr_allreduce_bucket(self, bucket): csr_list = [] for csr in bucket: csr_list.append(self.csr_allreduce(csr)) return csr_list def csr_allreduce(self, csr): # Pre-divide for fp16 stability csr.values.div_(self.dp_world_size) indices_device_list = self.csr_all_gather(csr.indices) values_device_list = self.csr_all_gather(csr.values) csr.indices = torch.cat(indices_device_list) csr.values = torch.cat(values_device_list) return csr def csr_all_gather(self, value): my_size = torch.LongTensor([value.size()[0]]).to(self.device) all_sizes = self.all_gather_scalar(my_size) max_size = torch.cat(all_sizes).max() fill_size = (max_size - my_size) assert value.dim() in [1, 2] if value.dim() == 1: if fill_size > 0: value = torch.cat([value, value.new_zeros(fill_size)]) tensor_list = [value.new_zeros(max_size) for _ in range(self.dp_world_size)] else: if fill_size > 0: value = torch.cat([value, value.new_zeros(fill_size, value.size()[1])]) tensor_list = [ value.new_zeros(max_size, value.size()[1]) for _ in range(self.dp_world_size) ] dist.all_gather(tensor_list, value, group=self.data_parallel_group) tensors = [] for dev_idx, t in enumerate(tensor_list): size = all_sizes[dev_idx][0] tensors.append( t.index_select(0, torch.LongTensor(range(size)).to(self.device))) return tensors def all_gather_scalar(self, value): tensor_list = [value.new_zeros(value.size()) for _ in range(self.dp_world_size)] dist.all_gather(tensor_list, value, group=self.data_parallel_group) return tensor_list def module_state_dict(self, destination=None, prefix='', keep_vars=False): sd = self.module.state_dict(destination, prefix, keep_vars) return sd def load_module_state_dict(self, state_dict, strict=True): self.module.load_state_dict(state_dict, strict=strict) def _get_rank_zero_ckpt_name(self, checkpoints_path, tag, mp_rank, dp_rank): filename = 'zero_pp_rank_{}'.format(dp_rank) zero_ckpt_name = os.path.join( checkpoints_path, str(tag), filename + '_mp_rank_{:02d}'.format(mp_rank) + 'optim_states.pt') return zero_ckpt_name def _get_zero_ckpt_name(self, checkpoints_path, tag): mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank() pp_rank = torch.distributed.get_rank(group=self.optimizer.dp_process_group) return self._get_rank_zero_ckpt_name(checkpoints_path, tag, mp_rank, pp_rank) def _get_ckpt_name(self, checkpoints_path, tag): mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank() ckpt_name = os.path.join(checkpoints_path, str(tag), 'mp_rank_{:02d}'.format(mp_rank) + '_model_states.pt') return ckpt_name def load_checkpoint(self, load_dir, tag=None, load_module_strict=True, load_optimizer_states=True, load_lr_scheduler_states=True): """Load training checkpoint Arguments: load_dir: Required. Directory to load the checkpoint from tag: Checkpoint tag used as a unique identifier for checkpoint, if not provided will attempt to load tag in 'latest' file load_module_strict: Optional. Boolean to strictly enforce that the keys in state_dict of module and checkpoint match. load_optimizer_states: Optional. Boolean to load the training optimizer states from Checkpoint. Ex. ADAM's momentum and variance load_lr_scheduler_states: Optional. Boolean to add the learning rate scheduler states from Checkpoint. Returns: A tuple of ``load_path`` and ``client_state``. *``load_path``: Path of the loaded checkpoint. ``None`` if loading the checkpoint failed. *``client_state``: State dictionary used for loading required training states in the client code. """ if tag is None: latest_path = os.path.join(load_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: logger.warning(f"Unable to find latest file at {latest_path}, if trying to load latest " \ "checkpoint please ensure this file exists or pass an explicit checkpoint tag when loading a checkpoint.") return None, None load_path, client_states = self._load_checkpoint(load_dir, tag, load_module_strict=load_module_strict, load_optimizer_states=load_optimizer_states, load_lr_scheduler_states=load_lr_scheduler_states) if self.zero_optimization() and load_path is not None: self._load_zero_checkpoint(load_dir, tag, load_optimizer_states=load_optimizer_states) return load_path, client_states def _load_checkpoint(self, load_dir, tag, load_module_strict=True, load_optimizer_states=True, load_lr_scheduler_states=True): load_path = self._get_ckpt_name(load_dir, tag) if not os.path.exists(load_path): logger.warn( 'Client provided checkpoint load path: {} does not exist ... skip checkpoint load' .format(load_path)) return None, None logger.info(f'rank: {self.global_rank} loading checkpoint: {load_path}') checkpoint = torch.load(load_path, map_location=lambda storage, loc: storage) if isinstance(self.module, PipelineModule): # Pipeline parallelism uses this to load its own checkpoint files. self._curr_ckpt_path = os.path.join(load_dir, tag) self.load_module_state_dict(state_dict=checkpoint['module'], strict=load_module_strict) if self.optimizer is not None and not self.zero_optimization(): if self.fp16_enabled(): self.optimizer.load_state_dict( checkpoint['optimizer'], load_optimizer_states=load_optimizer_states) elif load_optimizer_states: self.optimizer.load_state_dict(checkpoint['optimizer']) if load_lr_scheduler_states and self.lr_scheduler is not None: self.lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) self.csr_tensor_module_names = checkpoint['csr_tensor_module_names'] self.global_steps = checkpoint['global_steps'] self.global_samples = checkpoint.get('global_samples', self.global_steps * self.train_batch_size()) self.skipped_steps = checkpoint['skipped_steps'] self.loaded_checkpoint_mp_world_size = checkpoint['mp_world_size'] self.loaded_checkpoint_dp_world_size = checkpoint['dp_world_size'] deepspeed_states = [ 'module', 'optimizer', 'lr_scheduler', 'csr_tensor_module_names', 'skipped_steps', 'global_steps', 'dp_world_size', 'mp_world_size' ] client_state = { key: value for key, value in checkpoint.items() if not key in deepspeed_states } return load_path, client_state def _load_zero_checkpoint(self, load_dir, tag, load_optimizer_states=True): zero_sd_list = self._get_all_zero_checkpoints(load_dir, tag) if zero_sd_list is None: return self.optimizer.load_state_dict( state_dict_list=zero_sd_list, load_optimizer_states=load_optimizer_states, load_from_fp32_weights=self.zero_load_from_fp32_weights()) print( f'loading {len(zero_sd_list)} zero partition checkpoints for rank {self.global_rank}' ) def _get_mp_rank_zero_checkpoint_names(self, load_dir, tag, mp_rank, dp_world_size): zero_ckpt_names = [] for dp_rank in range(dp_world_size): ckpt_name = self._get_rank_zero_ckpt_name(checkpoints_path=load_dir, tag=tag, mp_rank=mp_rank, dp_rank=dp_rank) zero_ckpt_names.append(ckpt_name) return zero_ckpt_names def _get_all_zero_checkpoint_names(self, load_dir, tag, mp_world_size, dp_world_size): zero_ckpt_names = [] for mp_rank in range(mp_world_size): mp_rank_ckpt_names = self._get_mp_rank_zero_checkpoint_names( load_dir=load_dir, tag=tag, mp_rank=mp_rank, dp_world_size=dp_world_size) zero_ckpt_names += mp_rank_ckpt_names return zero_ckpt_names def _get_all_zero_checkpoints(self, load_dir, tag): mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank() zero_ckpt_names = self._get_mp_rank_zero_checkpoint_names( load_dir=load_dir, tag=tag, mp_rank=mp_rank, dp_world_size=self.loaded_checkpoint_dp_world_size) invalid_zero_ckpt_paths = [] for ckpt_name in zero_ckpt_names: if not os.path.exists(ckpt_name): invalid_zero_ckpt_paths.append(ckpt_name) if len(invalid_zero_ckpt_paths) > 0: logger.warn( f"Client provided zero checkpoint load paths: {invalid_zero_ckpt_paths} does not exist" ) return None zero_sd_list = [] for ckpt_name in zero_ckpt_names: zero_sd_list.append(torch.load(ckpt_name, map_location='cpu')) zero_optimizer_sd = [sd['optimizer_state_dict'] for sd in zero_sd_list] print( f"successfully loaded {len(zero_optimizer_sd)} ZeRO state_dicts for rank {self.global_rank}" ) return zero_optimizer_sd def save_checkpoint(self, save_dir, tag=None, client_state={}, save_latest=True, save_zero=True): r"""Save training checkpoint Arguments: save_dir: Required. Directory for saving the checkpoint tag: Optional. Checkpoint tag used as a unique identifier for the checkpoint, global step is used if not provided. client_state: Optional. State dictionary used for saving required training states in the client code. save_latest: Optional. Save a file 'latest' pointing to the latest saved checkpoint. """ # This is to make sure the checkpoint names are created without collision # There seems to be issue creating them in parallel # Ensure save_dir directory exists os.makedirs(save_dir, exist_ok=True) if tag is None: tag = f"global_step{self.global_steps}" if self.save_non_zero_checkpoint: self._create_checkpoint_file(save_dir, tag, False) self._save_checkpoint(save_dir, tag, client_state=client_state) if self.save_zero_checkpoint and save_zero: self._create_zero_checkpoint_files(save_dir, tag) self._save_zero_checkpoint(save_dir, tag) # Save latest checkpoint tag if save_latest: with open(os.path.join(save_dir, 'latest'), 'w') as fd: fd.write(tag) return True def _create_checkpoint_file(self, save_dir, tag, zero_checkpoint): name_function = self._get_zero_ckpt_name if zero_checkpoint else self._get_ckpt_name try: checkpoint_name = name_function(save_dir, tag) ensure_directory_exists(checkpoint_name) except: logger.error(f'Failed saving model checkpoint to {save_dir} with tag {tag}') return False return True def _create_zero_checkpoint_files(self, save_dir, tag): # zero checkpoint files are created sequentially try: checkpoint_name = self._get_zero_ckpt_name(save_dir, tag) if self.local_rank == 0: ensure_directory_exists(checkpoint_name) else: while not os.path.exists(os.path.dirname(checkpoint_name)): time.sleep(1) except: logger.error(f'Failed saving model checkpoint to {save_dir} with tag {tag}') return False return True # dist.barrier() def _save_checkpoint(self, save_dir, tag, client_state={}): save_path = self._get_ckpt_name(save_dir, tag) # A hack to save the checkpointing directory. Pipeline parallelism overrides # module_state_dict() and uses this path to save the model. module_state_dict() # then instead just returns None. self._curr_ckpt_path = os.path.join(save_dir, tag) state = { 'module': self.module_state_dict(), 'optimizer': self.optimizer.state_dict() if self.optimizer and not self.zero_optimization() else None, 'lr_scheduler': self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None, 'csr_tensor_module_names': self.csr_tensor_module_names, 'skipped_steps': self.skipped_steps, 'global_steps': self.global_steps, 'global_samples': self.global_samples, 'dp_world_size': self.dp_world_size, 'mp_world_size': self.mp_world_size } state.update(client_state) log_dist(message=f'Saving model checkpoint: {save_path}', ranks=[0]) #logger.info('Saving model checkpoint: {}'.format(save_path)) torch.save(state, save_path) self._curr_save_path = None def _save_zero_checkpoint(self, save_path, tag): zero_checkpoint_name = self._get_zero_ckpt_name(save_path, tag) zero_sd = {'optimizer_state_dict': self.optimizer.state_dict()} torch.save(zero_sd, zero_checkpoint_name) logger.info('zero checkpoint saved {}'.format(zero_checkpoint_name))
62,693
40.740346
227
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/tools/ds_fix/stage1.py
import math import torch import torch.distributed as dist from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from collections import defaultdict from deepspeed.runtime.zero.utils import _initialize_parameter_parallel_groups from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossScaler from deepspeed.runtime.utils import get_grad_norm, CheckOverflow from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION_OPTIMIZER_STATES from deepspeed.utils import logger, log_dist def get_alignment_padding(flattened_lean_size, sub_partition_id, sub_partition_size): sub_partition_high_limit = (sub_partition_id + 1) * sub_partition_size if sub_partition_high_limit <= flattened_lean_size: return 0 else: return min(sub_partition_size, sub_partition_high_limit - flattened_lean_size) def get_group_alignment_padding(tensor_list, sub_partition_size, sub_partition_count): group_paddings = [] flattened_size = sum([tensor.numel() for tensor in tensor_list]) for i in range(sub_partition_count): padding = get_alignment_padding(flattened_size, i, sub_partition_size) group_paddings.append(padding) return group_paddings def flatten_dense_tensors_sub_partition_aligned(tensor_list, dp, max_elements_per_comm, pg): assert max_elements_per_comm >= dp, f"max_elements_per_comm {max_elements_per_comm} < dp {dp}" num_elements = sum(t.numel() for t in tensor_list) log_dist("Total number of elements in model: {}, max elements per com: {}".format( num_elements, max_elements_per_comm), ranks=[0]) # Compute aligned partition size based on parameter count aligned_param_partition_size = math.ceil(num_elements / dp) # Compute aligned partition size based on communication size aligned_comm_partition_size = int(max_elements_per_comm // dp) if aligned_param_partition_size <= aligned_comm_partition_size: sub_partition_count = 1 sub_partition_size = aligned_param_partition_size else: sub_partition_count = math.ceil(aligned_param_partition_size / aligned_comm_partition_size) sub_partition_size = aligned_comm_partition_size # Compute required padding for alignment to dp and max_elements_per_comm padding = (sub_partition_count * sub_partition_size * dp) - num_elements log_dist( f"sub_partition_count: {sub_partition_count}, sub_partition_size: {sub_partition_size}, padding: {padding}", ranks=[0]) log_dist( f"number of elements with padding: {num_elements} + {padding} = {num_elements + padding}", ranks=[0]) if padding == 0: aligned_tensor_list = tensor_list else: pad_tensor = torch.zeros(padding, device=tensor_list[0].device, dtype=tensor_list[0].dtype) aligned_tensor_list = tensor_list + [pad_tensor] flat_tensors = _flatten_dense_tensors(aligned_tensor_list) return flat_tensors def _single_range_check(current_index, start_index, end_index, tensor_size): offset = 0 if (current_index >= start_index) and (current_index < end_index): # Fully inside bounds return True, offset elif (start_index > current_index) and (start_index < (current_index + tensor_size)): # Partially contained, compute offset offset = start_index - current_index return True, offset else: return False, offset def _range_check(current_index, element_intervals, tensor_size): results = [] for comm_idx, interval in enumerate(element_intervals): start_index, end_index = interval contained, offset = _single_range_check(current_index, start_index, end_index, tensor_size) if contained: results.append((contained, offset, comm_idx)) if len(results) == 0: return [(False, 0, -1)] return results class FP16_DeepSpeedZeroOptimizer_Stage1(object): """ FP16_DeepSpeedZeroOptimizer_Stage1 designed to reduce the memory footprint required for training large deep learning models. For more details please see ZeRO: Memory Optimization Towards Training A Trillion Parameter Models https://arxiv.org/abs/1910.02054 This version aligns with stage-1 in the paper above. """ def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=True, dp_process_group=None, partition_size=None, mpu=None, all_gather_partitions=True, allgather_size=500000000, clip_grad=0.0, max_elements_per_comm=5e8, elastic_checkpoint=True): if dp_process_group is not None and partition_size is not None: raise ValueError("Cannot specify both dp_process_group " "and partition size") if dp_process_group is None: dp_process_group = _initialize_parameter_parallel_groups(partition_size) if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.optimizer = init_optimizer self.verbose = verbose self.dp_process_group = dp_process_group # TODO: automatically turn off if #params > some_limit self.all_gather_partitions = all_gather_partitions self.allgather_size = allgather_size # self.max_elements_per_comm = max_elements_per_comm # logger.info("max_elements_per_comm={}".format(max_elements_per_comm)) self.elastic_checkpoint = elastic_checkpoint logger.info(f'ZeRO Elastic Checkpoint = {elastic_checkpoint}') # param flattened by groups self.fp16_groups = [] self.fp16_groups_flat = [] # Setup bookkeeping data structures depending on partitioning type # parallel_sub_partitioned_fp16_groups[group-idx] -> [comm-ids] -> [rank-ids] self.parallel_sub_partitioned_fp16_groups = [] # same underlying data as above but viewed as: [groups] -> [rank-ids] -> [comm-ids] self.parallel_comm_sub_partitioned_fp16_groups = [] # 32-bit sub-partitions of the parallel partitioned parameters # that this process will update self.local_sub_partitions_of_fp32_groups = [] # param partition info # parameters in each group that will not be updated by this process directly self.params_not_local = [] # parameters that will be updated by this process directly self.params_in_rank_sub_partitions = [] # parameter offsets for parameters in sub-partitions. Parameter # boundaries may not align with sub-partition boundaries # so we need to keep track of the offsets self.params_in_rank_sub_partitions_offsets = [] # number of elements per sub-partition in each group self.sub_partition_sizes = [] # number of communication intervals for each group self.num_comm_intervals_per_group = [] local_rank = dist.get_rank(group=self.dp_process_group) self.group_paddings = [] self.partition_count = dist.get_world_size(group=self.dp_process_group) self.default_device = self.optimizer.param_groups[0]['params'][0].device # max elems per param group self.max_elems_per_comm = [] # loop to deal with groups for i, param_group in enumerate(self.optimizer.param_groups): # push this group to list before modify self.fp16_groups.append(param_group['params']) # calculate best max elements per comm based to minimize padding self.max_elems_per_comm.append( self.best_max_elems_per_comm( num_elements=sum(t.numel() for t in self.fp16_groups[i]), max_elements_per_comm=max_elements_per_comm, dp=dist.get_world_size(group=self.dp_process_group))) # flattens all tensors into single 1d tensor aligned with sub-partition size for later dividing # RS: create aligned sub-partitions flat_aligned_params = flatten_dense_tensors_sub_partition_aligned( tensor_list=self.fp16_groups[i], dp=dist.get_world_size(group=self.dp_process_group), max_elements_per_comm=self.max_elems_per_comm[i], pg=self.dp_process_group) self.fp16_groups_flat.append(flat_aligned_params) # TODO: I don't think this does anything? # set model fp16 weight to slices of flattened buffer updated_params = _unflatten_dense_tensors(self.fp16_groups_flat[i], self.fp16_groups[i]) for p, q in zip(self.fp16_groups[i], updated_params): p.data = q.data # divide the flat weights into near equal partition equal to the data parallel degree # each process will compute on a different part of the partition # RS: split into two layer list -> [comm-id] -> [sub-partitions per rank] comm_partitions, dp_sub_partitions, element_intervals, sub_partition_size, num_comm_intervals = \ self.get_data_parallel_sub_partitions( tensor=self.fp16_groups_flat[i], max_elements_per_comm=self.max_elems_per_comm[i], world_size=dist.get_world_size( group=self.dp_process_group), dp_process_group=self.dp_process_group ) self.parallel_comm_sub_partitioned_fp16_groups.append( comm_partitions) # comm -> rank self.parallel_sub_partitioned_fp16_groups.append( dp_sub_partitions) # rank -> comm self.sub_partition_sizes.append(sub_partition_size) self.num_comm_intervals_per_group.append(num_comm_intervals) # data_parallel_partitions = self.get_data_parallel_partitions(self.fp16_groups_flat[i]) # self.parallel_partitioned_fp16_groups.append(data_parallel_partitions) # a partition of the fp32 master weights that will be updated by this process # RS: store/detach/cast our local sub-partitions local_sub_partitions = [] for sub_partition in self.parallel_sub_partitioned_fp16_groups[i][ local_rank]: fp32_sub_partition = sub_partition.clone().float().detach() fp32_sub_partition.requires_grad = True local_sub_partitions.append(fp32_sub_partition) self.local_sub_partitions_of_fp32_groups.append(local_sub_partitions) # Compute sub_partition paddings sub_partition_paddings = get_group_alignment_padding( tensor_list=self.fp16_groups[i], sub_partition_size=sub_partition_size, sub_partition_count=num_comm_intervals * self.partition_count) self.group_paddings.append(sub_partition_paddings) # modify optimizer of have flat master weight # self.single_partition_of_fp32_groups[i].requires_grad = True # keep this in case internal optimizer uses it param_group['params'] = self.local_sub_partitions_of_fp32_groups[i] # RS: divide up the sub-partitions and keep track of offsets for each param # partition_size = len(self.fp16_groups_flat[i]) / dist.get_world_size(group=self.dp_process_group) params_in_rank_sub_partition, params_in_rank_sub_partitions_offsets, params_not_local = self.get_all_sub_partition_info( tensor_list=self.fp16_groups[i], all_element_intervals=element_intervals, local_rank=local_rank, world_size=dist.get_world_size(group=self.dp_process_group) ) self.params_in_rank_sub_partitions.append(params_in_rank_sub_partition) self.params_not_local.append(params_not_local) self.params_in_rank_sub_partitions_offsets.append( params_in_rank_sub_partitions_offsets) # we may have a way of fusing dynamic scale. Do not support for now if dynamic_loss_scale: if dynamic_loss_args is None: self.loss_scaler = DynamicLossScaler() else: self.loss_scaler = DynamicLossScaler(**dynamic_loss_args) self.dynamic_loss_scale = True else: self.dynamic_loss_scale = False self.loss_scaler = LossScaler(scale=static_loss_scale) self.cur_iter = 0 self.mpu = mpu self.clip_grad = clip_grad self.overflow = False self.overflow_checker = CheckOverflow(self.fp16_groups, mpu=self.mpu, zero_reduce_scatter=True) self._initialize_optimizer_states() self.hack_first_step = True def _initialize_optimizer_states(self): for group_idx, group in enumerate(self.local_sub_partitions_of_fp32_groups): for idx, sub_partition_param in enumerate(group): sub_partition_grad = torch.zeros(int( self.sub_partition_sizes[group_idx]), dtype=sub_partition_param.dtype).cuda() sub_partition_param.grad = sub_partition_grad self.optimizer.step() for group in self.local_sub_partitions_of_fp32_groups: for idx, sub_partition_param in enumerate(group): sub_partition_param.grad = None @staticmethod def best_max_elems_per_comm(num_elements, max_elements_per_comm, dp): # if we use max-elems-per-comm as is, how many comm intervals will there be max_comm_intervals = math.ceil(num_elements / max_elements_per_comm) padding_for_max_comm = (max_elements_per_comm * max_comm_intervals) - num_elements # if we use 1 less comm interval how much extra comm padding would be required min_comm_intervals = num_elements // max_elements_per_comm if min_comm_intervals == 0: log_dist(f'Using default max_elements_per_comm {max_elements_per_comm}', ranks=[0]) return max_elements_per_comm padding_for_min_comm = math.ceil(num_elements / (dp * min_comm_intervals)) # choose padding that uses least amount of overhead if padding_for_max_comm > padding_for_min_comm: new_max_elements_per_comm = padding_for_min_comm + max_elements_per_comm log_dist( f'Updating max_elements_per_comm from {max_elements_per_comm} -> {new_max_elements_per_comm}', ranks=[0]) return new_max_elements_per_comm else: log_dist(f'Using default max_elements_per_comm {max_elements_per_comm}', ranks=[0]) return max_elements_per_comm @staticmethod def get_data_parallel_sub_partitions(tensor, max_elements_per_comm, world_size, dp_process_group=None): total_num_elements = tensor.numel() # if total elements is less than our max, revert to splitting into dp partitions max_elements_per_comm = min(total_num_elements, max_elements_per_comm) sub_partition_size = int(max_elements_per_comm // world_size) # Ensure partition alignment was done correctly num_sub_partitions = int(total_num_elements // sub_partition_size) assert total_num_elements % sub_partition_size == 0, "{} % {} != 0".format(total_num_elements, sub_partition_size) # Ensure comm interval alignment was done correctly. num_comm_intervals = int(num_sub_partitions // world_size) assert num_sub_partitions % world_size == 0, "{} % {} != 0".format(num_sub_partitions, world_size) if not dist.is_initialized() or dist.get_rank(group=dp_process_group) == 0: logger.info("**** partition info:") logger.info("\t total_num_elements=%s", total_num_elements) logger.info("\t world_size=%s", world_size) logger.info("\t max_elements_per_comm=%s", max_elements_per_comm) logger.info("\t sub_partition_size=%s", sub_partition_size) logger.info("\t num_sub_partitions=%s", num_sub_partitions) logger.info("\t num_comm_intervals=%s", num_comm_intervals) logger.info("****") # [comm_id] -> [rank] comm_partitions = [] for _ in range(num_comm_intervals): comm_partitions.append([]) start = 0 comm_id = 0 element_intervals = defaultdict( list) # [rank] -> [(start,end), (start,end), ...] for idx in range(num_sub_partitions): rank_id = idx % world_size sub_partition = tensor.narrow(0, start, sub_partition_size).detach() element_intervals[rank_id].append((start, start + sub_partition_size)) comm_partitions[comm_id].append(sub_partition) start = start + sub_partition_size if rank_id == (world_size - 1): comm_id += 1 # [rank] -> [comm_id] sub_partitions = [] for _ in range(world_size): sub_partitions.append([]) for comm_id, partitions in enumerate(comm_partitions): for rank_id, partition in enumerate(partitions): sub_partitions[rank_id].append(partition) return comm_partitions, sub_partitions, element_intervals, sub_partition_size, num_comm_intervals @staticmethod def get_all_sub_partition_info(tensor_list, all_element_intervals, local_rank, world_size): params_not_local = [] # [rank] -> [comm-id] -> [param/offset] params_in_rank_sub_partition = [] params_in_rank_sub_partitions_offsets = [] for rank in range(world_size): params_in_local_sub_partition = [] local_sub_partition_offsets = [] comm_tensor_list = [] comm_offset_list = [] current_index = 0 prev_comm_idx = 0 for iii, tensor in enumerate(tensor_list): tensor_size = tensor.numel() #if local_rank == 0: # # logger.info("rank={}, current_index={}, tensor_size={}, tensor-idx={}".format(rank, # current_index, tensor_size, iii)) results_list = _range_check(current_index, all_element_intervals[rank], tensor_size) for contained, offset, comm_idx in results_list: #if local_rank == 0: # logger.info("rank={}, contained={}, offset={}, comm_idx={}".format(rank, contained, # offset, comm_idx)) if contained: if prev_comm_idx != comm_idx: params_in_local_sub_partition.append(comm_tensor_list) comm_tensor_list = [] local_sub_partition_offsets.append(comm_offset_list) comm_offset_list = [] comm_tensor_list.append(tensor) comm_offset_list.append(offset) prev_comm_idx = comm_idx elif rank == local_rank: params_not_local.append(tensor) current_index = current_index + tensor_size #assert len(comm_tensor_list) > 0 #assert len(comm_offset_list) > 0 params_in_local_sub_partition.append(comm_tensor_list) local_sub_partition_offsets.append(comm_offset_list) params_in_rank_sub_partition.append(params_in_local_sub_partition) params_in_rank_sub_partitions_offsets.append(local_sub_partition_offsets) return params_in_rank_sub_partition, params_in_rank_sub_partitions_offsets, params_not_local @staticmethod def get_flat_sub_partitions(comm_tensor_list, comm_param_offsets, sub_partition_size, dtype, default_device, num_comm_intervals=None, return_partition_params=False): partition_params = [] final_param_offsets = [] flat_sub_partitions = [] for tensor_list, param_offsets in zip(comm_tensor_list, comm_param_offsets): flat_tensor_list = [] current_size = 0 my_offsets = [] my_params = [] for i, tensor in enumerate(tensor_list): if tensor.grad is None: tensor.grad = torch.zeros(tensor.size(), dtype=tensor.dtype, device=tensor.device) param = tensor tensor = tensor.grad num_elements = tensor.numel() tensor_offset = 0 #we need to offset to get to the right element if i == 0 and param_offsets[i] > 0: tensor_offset = param_offsets[i] num_elements = num_elements - tensor_offset # We don't need all elements of the tensor if this tensor is # larger than we have space for in our curr sub-partition if num_elements > (sub_partition_size - current_size): num_elements = sub_partition_size - current_size #we need a narrow view of the tensor based on the tensor offset and number of elements that #we need from this tensor if tensor_offset > 0 or num_elements < tensor.numel(): flat_tensor_list.append(tensor.contiguous().view(-1).narrow( 0, int(tensor_offset), int(num_elements)).to(dtype)) else: flat_tensor_list.append(tensor.to(dtype)) my_params.append(param) #remember offset into partition and #elems for this tensor my_offsets.append((current_size, num_elements)) current_size = current_size + num_elements #this means its the last partition and does not align with the dp boundary. We need to pad before flattening if current_size < sub_partition_size: my_offsets.append((None, None)) my_params.append(None) if len(tensor_list) == 0: assert default_device != None flat_tensor_list.append( torch.zeros(int(sub_partition_size - current_size), dtype=dtype, device=default_device)) else: flat_tensor_list.append( torch.zeros(int(sub_partition_size - current_size), dtype=dtype, device=tensor_list[0].device)) partition_params.append(my_params) #flat_tensor_list) final_param_offsets.append(my_offsets) assert len(flat_tensor_list) == len(my_offsets), "{} {}".format(len(flat_tensor_list), len(my_offsets)) flat_sub_partitions.append(_flatten_dense_tensors(flat_tensor_list)) if num_comm_intervals is not None and len( flat_sub_partitions) < num_comm_intervals: # logger.info("padding w. sub partitions to ensure uniform communication") device = flat_sub_partitions[0].device for _ in range(num_comm_intervals - len(flat_sub_partitions)): flat_sub_partitions.append( torch.zeros(int(sub_partition_size), dtype=dtype, device=device)) partition_params.append([None]) final_param_offsets.append([(None, None)]) if return_partition_params: assert len(flat_sub_partitions) == len(partition_params) assert len(partition_params) == len(final_param_offsets), "{} {}".format(len(partition_params), len(final_param_offsets)) return flat_sub_partitions, partition_params, final_param_offsets return flat_sub_partitions def zero_grad(self, set_grads_to_None=True): """ Zero FP16 parameter grads. """ # FP32 grad should never exist. # For speed, set model fp16 grad to None by default for group in self.fp16_groups: for p in group: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() def free_grad_in_param_list(self, param_list): for p in param_list: if isinstance(p, list): for _p in p: _p.grad = None else: p.grad = None def reduce_scatter_gradients(self, postscale_gradients, gradient_predivide_factor, gradient_average): world_size = dist.get_world_size(group=self.dp_process_group) local_rank = dist.get_rank(group=self.dp_process_group) for i, group in enumerate(self.fp16_groups): num_comm_intervals = self.num_comm_intervals_per_group[i] all_sub_partitions = [] for rank in range(world_size): # gsp is list of partitions indexed by comm_idx grad_sub_partitions = self.get_flat_sub_partitions( comm_tensor_list=self.params_in_rank_sub_partitions[i][rank], comm_param_offsets=self.params_in_rank_sub_partitions_offsets[i] [rank], dtype=torch.half, default_device=self.default_device, sub_partition_size=self.sub_partition_sizes[i], num_comm_intervals=self.num_comm_intervals_per_group[i]) all_sub_partitions.append(grad_sub_partitions) assert len(grad_sub_partitions) == num_comm_intervals local_comm_partitions = [] for comm_idx in range(num_comm_intervals): single_comm_all_partitions = [] for rank in range(world_size): single_comm_all_partitions.append(all_sub_partitions[rank][comm_idx]) if postscale_gradients: if gradient_predivide_factor != 1.0: for partition in single_comm_all_partitions: partition.mul_(1. / gradient_predivide_factor) dist.reduce_scatter(output=single_comm_all_partitions[local_rank], input_list=single_comm_all_partitions, group=self.dp_process_group) if gradient_average: # Only need to average our local grads in post scaling if gradient_predivide_factor != world_size: single_comm_all_partitions[local_rank].mul_( gradient_predivide_factor / world_size) else: for partition in single_comm_all_partitions: partition.div_(world_size) dist.reduce_scatter(output=single_comm_all_partitions[local_rank], input_list=single_comm_all_partitions, group=self.dp_process_group) def step(self, closure=None): # First compute norm for all group so we know if there is overflow self.overflow = self.overflow_checker.check() prev_scale = self.loss_scale self._update_scale(self.overflow) if self.overflow: self.zero_grad() if self.verbose: logger.info("[deepspeed] OVERFLOW! Skipping step. Attempted loss " "scale: {}, reducing to {}".format( prev_scale, self.loss_scale)) return self.overflow norm_groups = [] local_sub_partitions_grad_groups = [] partition_id = dist.get_rank(group=self.dp_process_group) for i, group in enumerate(self.fp16_groups): #TODO RS: update get grad norm to support sub partitions norm_groups.append(get_grad_norm(group, mpu=self.mpu)) #RS: update free grads w.r.t. sub partitions #free gradients for all the parameters that are not updated by this process self.free_grad_in_param_list(self.params_not_local[i]) # create flat gradient partitions for parameters updated by this process local_grad_sub_partitions = self.get_flat_sub_partitions( comm_tensor_list=self.params_in_rank_sub_partitions[i][partition_id], comm_param_offsets=self.params_in_rank_sub_partitions_offsets[i] [partition_id], sub_partition_size=self.sub_partition_sizes[i], dtype=self.local_sub_partitions_of_fp32_groups[i][0].dtype, num_comm_intervals=self.num_comm_intervals_per_group[i], default_device=self.default_device) #RS: update all our local params with sub-partition grads for idx, sub_partition_param in enumerate(self.local_sub_partitions_of_fp32_groups[i]): sub_partition_param.grad = local_grad_sub_partitions[idx] #RS: update free grads for sub-partitions #release all the gradient since we have already created a necessary copy in dp_grad_partition self.free_grad_in_param_list( self.params_in_rank_sub_partitions[i][partition_id]) local_sub_partitions_grad_groups.append(local_grad_sub_partitions) #RS: update unscale/clip with sub partitions self.unscale_and_clip_grads(local_sub_partitions_grad_groups, norm_groups) self.optimizer.step() #RS: clear our sub partition grads #get rid of the fp32 gradients. Not needed anymore for group in self.local_sub_partitions_of_fp32_groups: for idx, sub_partition_param in enumerate(group): sub_partition_param.grad = None #group.grad = None #NOTE RS: removed norm_groups outer loop from original code, i don't think it's needed #RS: copy all sub-partition fp32 data to fp16 sub partitions # copy fp32 param data to fp16 partitions w.r.t. our local rank for fp16_all_sub_partitions, fp32_local_sub_partitions in zip(self.parallel_sub_partitioned_fp16_groups, self.local_sub_partitions_of_fp32_groups): for local_sub_partition_param_fp16, local_sub_partition_param_fp32 in zip(fp16_all_sub_partitions[partition_id], fp32_local_sub_partitions): if self.hack_first_step == True: local_sub_partition_param_fp32.data.copy_(local_sub_partition_param_fp16.data) else: local_sub_partition_param_fp16.data.copy_(local_sub_partition_param_fp32.data) self.hack_first_step = False #RS: all_gather/broadcast sub-partitions in separate comm calls #gather the updated weights from everyone for fp16_all_sub_partitions in self.parallel_comm_sub_partitioned_fp16_groups: for comm_id, sub_partitions in enumerate(fp16_all_sub_partitions): dist.all_gather(sub_partitions, sub_partitions[partition_id], group=self.dp_process_group) # TODO: we probably don't need this? just to be safe for i in range(len(norm_groups)): updated_params = _unflatten_dense_tensors(self.fp16_groups_flat[i], self.fp16_groups[i]) for p, q in zip(self.fp16_groups[i], updated_params): p.data = q.data return self.overflow def unscale_and_clip_grads(self, grad_groups_flat, norm_groups): total_norm = 0.0 for norm in norm_groups: total_norm += norm**2.0 total_norm = math.sqrt(total_norm) # compute combined scale factor for this group combined_scale = self.loss_scale if self.clip_grad > 0.: # norm is in fact norm*scale clip = ((total_norm / self.loss_scale) + 1e-6) / self.clip_grad if clip > 1: combined_scale = clip * self.loss_scale for grad in grad_groups_flat: if isinstance(grad, list): sub_partitions = grad for g in sub_partitions: g.data.mul_(1. / combined_scale) else: grad.data.mul_(1. / combined_scale) def backward(self, loss, retain_graph=False): self.loss_scaler.backward(loss.float(), retain_graph=retain_graph) def _update_scale(self, has_overflow=False): self.loss_scaler.update_scale(has_overflow) # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups) # Promote loss scale so it can be retrieved or set via "fp16_optimizer_instance.loss_scale" def _get_loss_scale(self): return self.loss_scaler.loss_scale def _set_loss_scale(self, value): self.loss_scaler.cur_scale = value loss_scale = property(_get_loss_scale, _set_loss_scale) cur_scale = property(_get_loss_scale, _set_loss_scale) # Return communication interval paddings for local rank and group def _get_local_group_paddings(self, group_index): local_rank = dist.get_rank(group=self.dp_process_group) sub_partition_indices = [ local_rank + (comm_idx * self.partition_count) for comm_idx in range(self.num_comm_intervals_per_group[group_index]) ] group_paddings = [ self.group_paddings[group_index][sub_idx] for sub_idx in sub_partition_indices ] return group_paddings # Return group tensor after removing paddings that are added for alignment to DP world size. # This method works on the assumption that each group contains sub partitions. def _get_groups_without_padding(self, groups_with_padding): groups_without_padding = [] for group_index, group in enumerate(groups_with_padding): group_paddings = self._get_local_group_paddings(group_index) lean_sub_partitions = [] for sub_partition, padding in zip(group, group_paddings): lean_length = sub_partition.numel() - padding lean_sub_partitions.append(sub_partition[:lean_length]) groups_without_padding.append(lean_sub_partitions) return groups_without_padding # Return optimizer state after removing paddings that are added for alignment. def _get_state_without_padding(self, state_with_padding, padding): lean_state = {} for key, value in state_with_padding.items(): if torch.is_tensor(value): lean_length = value.numel() - padding lean_state[key] = value[:lean_length] else: lean_state[key] = value return lean_state # Return base optimizer states. # This method assumes that each param group contains a single flattened tensor. def _get_base_optimizer_state(self): optimizer_groups_state = [] for group_index, group in enumerate(self.optimizer.param_groups): param_paddings = self._get_local_group_paddings(group_index) group_lean_state = [] for param_idx, param in enumerate(group['params']): lean_state = self._get_state_without_padding(self.optimizer.state[param], param_paddings[param_idx]) group_lean_state.append(lean_state) optimizer_groups_state.append(group_lean_state) return optimizer_groups_state def _rigid_state_dict(self): """ Returns a dict that can be loaded for continued training with same DP degree """ """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['base_optimizer_state'] = self.optimizer.state_dict() state_dict[ 'local_sub_partitions_of_fp32_groups'] = self.local_sub_partitions_of_fp32_groups return state_dict def _elastic_state_dict(self): """ Returns a dict that can be loaded for elastic training with different DP degree """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['base_optimizer_state'] = self._get_base_optimizer_state() state_dict['zero_stage'] = ZERO_OPTIMIZATION_OPTIMIZER_STATES state_dict['partition_count'] = self.partition_count state_dict['num_comm_intervals_per_group'] = self.num_comm_intervals_per_group # Remove paddings for DP alignment to enable loading for other alignment values fp32_groups_without_padding = self._get_groups_without_padding( self.local_sub_partitions_of_fp32_groups) state_dict['local_sub_partitions_of_fp32_groups'] = fp32_groups_without_padding return state_dict def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ if self.elastic_checkpoint: return self._elastic_state_dict() return self._rigid_state_dict() # Extract the fp32 weights of the current rank from checkpoint by merging the # sub partitions of communication intervals across ranks. # Let sub_i_j = sub partition of rank i and comm interval j # For 2 ranks and 2 comm intervals, checkpoints (minus padding) are as follows: # rank 0 = [sub_0_0, sub_0_1] # rank 1 = [sub_1_0, sub_1_1] # Merge to get [sub_0_0, sub_1_0, sub_0_1, sub_1_1] => original un-padded flattened tensor. def _retrieve_group_sub_partition_weights(self, all_partition_fp32_weights, max_elems_per_comm): num_partitions = len(all_partition_fp32_weights) num_comm_intervals = len(all_partition_fp32_weights[0]) num_sub_partitions = num_partitions * num_comm_intervals all_sub_partition_weights = [None] * num_sub_partitions for rank, partition_weights in enumerate(all_partition_fp32_weights): for comm_idx, sub_partition_weights in enumerate(partition_weights): #all_sub_partition_weights.append(sub_partition_weights) sub_partition_idx = (comm_idx * num_partitions) + rank all_sub_partition_weights[sub_partition_idx] = sub_partition_weights flat_merged_weights = flatten_dense_tensors_sub_partition_aligned( tensor_list=all_sub_partition_weights, dp=dist.get_world_size(group=self.dp_process_group), max_elements_per_comm=max_elems_per_comm, pg=self.dp_process_group) comm_partitions, dp_sub_partitions, element_intervals, sub_partition_size, num_comm_intervals = \ self.get_data_parallel_sub_partitions( tensor=flat_merged_weights, max_elements_per_comm=max_elems_per_comm, world_size=dist.get_world_size(group=self.dp_process_group), dp_process_group=self.dp_process_group ) partition_id = dist.get_rank(group=self.dp_process_group) return [sub_partition for sub_partition in dp_sub_partitions[partition_id]] # Restore base optimizer fp32 weights from checkpoint by: # 1) Merging fp32 weights from checkpoints of all partitions # 2) Extracting fp32 weights for current partition from merged weights # 3) Using extracted weights to update base optimizer weights directly. def _restore_from_fp32_weights(self, all_state_dict): sub_partition_of_fp32_groups = [] for group_idx in range(len(self.local_sub_partitions_of_fp32_groups)): all_partition_fp32_weights = [ sd['local_sub_partitions_of_fp32_groups'][group_idx] for sd in all_state_dict ] max_elems_per_comm = self.max_elems_per_comm[group_idx] sub_partition_weights = self._retrieve_group_sub_partition_weights( all_partition_fp32_weights, max_elems_per_comm) sub_partition_of_fp32_groups.append(sub_partition_weights) for current_group, saved_group in zip(self.local_sub_partitions_of_fp32_groups, sub_partition_of_fp32_groups): for current_sub_part, saved_sub_part in zip(current_group, saved_group): current_sub_part.data.copy_(saved_sub_part.data) # Extract optimizer state for current partition from merged states of all partitions def _partition_base_optimizer_state(self, state_key, all_partition_states, max_elems_per_comm): if not torch.is_tensor(all_partition_states[0]): return all_partition_states[0] alignment = dist.get_world_size(group=self.dp_process_group) flat_merged_partitions = flatten_dense_tensors_sub_partition_aligned( tensor_list=all_partition_states, dp=dist.get_world_size(group=self.dp_process_group), max_elements_per_comm=max_elems_per_comm, pg=self.dp_process_group) comm_partitions, dp_sub_partitions, element_intervals, sub_partition_size, num_comm_intervals = \ self.get_data_parallel_sub_partitions( tensor=flat_merged_partitions, max_elements_per_comm=max_elems_per_comm, world_size=dist.get_world_size(group=self.dp_process_group), dp_process_group=self.dp_process_group ) partition_id = dist.get_rank(group=self.dp_process_group) return [sub_partition for sub_partition in dp_sub_partitions[partition_id]] # Compute the optimizer state partitions for the group by # 1) Merging state values across the previous partitioning. # 2) Repartition state values for the new partitioning # 3) Return state corresponding to local partition def _retrieve_group_optimizer_states(self, all_partition_states, max_elems_per_comm): merged_optimizer_states = {} num_partitions = len(all_partition_states) num_comm_intervals = len(all_partition_states[0]) num_sub_partitions = num_partitions * num_comm_intervals for rank, partition_state in enumerate(all_partition_states): for comm_idx, sub_partition_state in enumerate(partition_state): for key, value in sub_partition_state.items(): if not key in merged_optimizer_states.keys(): merged_optimizer_states[key] = [None] * num_sub_partitions sub_partition_idx = (comm_idx * num_partitions) + rank merged_optimizer_states[key][sub_partition_idx] = value group_optimizer_states = {} for key, value in merged_optimizer_states.items(): group_optimizer_states[key] = self._partition_base_optimizer_state( key, value, max_elems_per_comm) return group_optimizer_states # Restore base optimizer state from checkpoint by # 1) Merging optimizer state from checkpoints of all partitions # 2) Extracting optimizer state for current partition from the merged state # 3) Using the extracted value to directly update the base optimizer. def _restore_base_optimizer_state(self, state_dict_list): base_optimizer_group_states = [] for group_idx in range(len(self.optimizer.param_groups)): all_partition_group_states = [ sd['base_optimizer_state'][group_idx] for sd in state_dict_list ] max_elems_per_comm = self.max_elems_per_comm[group_idx] group_optimizer_states = self._retrieve_group_optimizer_states( all_partition_group_states, max_elems_per_comm) base_optimizer_group_states.append(group_optimizer_states) for group_idx, group in enumerate(self.optimizer.param_groups): for param_idx, param in enumerate(group['params']): for key, saved in base_optimizer_group_states[group_idx].items(): if torch.is_tensor(self.optimizer.state[param][key]): current = self.optimizer.state[param][key] current.data.copy_(saved[param_idx].data) else: self.optimizer.state[param][key] = saved # Restore base optimizer fp32 weights from ZeRO fp16 weights def _restore_from_fp16_weights(self): partition_id = dist.get_rank(group=self.dp_process_group) for fp16_partitions, fp32_partitions in zip(self.parallel_sub_partitioned_fp16_groups, self.local_sub_partitions_of_fp32_groups): for fp16_sub_partition, fp32_sub_partition in zip(fp16_partitions[partition_id], fp32_partitions): fp32_sub_partition.data.copy_(fp16_sub_partition.data) # Refresh the fp32 master params from the fp16 copies. def refresh_fp32_params(self): self._restore_from_fp16_weights() def _rigid_load_state_dict(self, state_dict, load_optimizer_states=True): # I think it should actually be ok to reload the optimizer before the model. self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] if load_optimizer_states: self.optimizer.load_state_dict(state_dict['base_optimizer_state']) for curr_group, saved_group in zip(self.local_sub_partitions_of_fp32_groups, state_dict['local_sub_partitions_of_fp32_groups']): for curr_param, saved_param in zip(curr_group, saved_group): curr_param.data.copy_(saved_param.data) def _elastic_load_state_dict(self, state_dict_list, load_optimizer_states=True, load_from_fp32_weights=False): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.loss_scaler = state_dict_list[0]['loss_scaler'] self.dynamic_loss_scale = state_dict_list[0]['dynamic_loss_scale'] self.overflow = state_dict_list[0]['overflow'] if load_optimizer_states: self._restore_base_optimizer_state(state_dict_list) if load_from_fp32_weights: self._restore_from_fp32_weights(state_dict_list) else: self._restore_from_fp16_weights() def load_state_dict(self, state_dict_list, load_optimizer_states=True, load_from_fp32_weights=False): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ if self.elastic_checkpoint: self._elastic_load_state_dict(state_dict_list, load_optimizer_states, load_from_fp32_weights) else: self._rigid_load_state_dict( state_dict_list[dist.get_rank(group=self.dp_process_group)], load_optimizer_states) def _dump_optimizer_state(self, message): logger.info(f'{message}') for i, group in enumerate(self.optimizer.param_groups): for j, param in enumerate(group['params']): for key, value in self.optimizer.state[param].items(): t_stats = [ value.min(), value.max(), (value.max() - value.min()), value.mean() ] stats = [float(t) for t in t_stats] logger.info( f'group/param/key/min/max/delta/mean = {i}, {j}, {key}: {stats}')
52,782
45.79344
155
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/InstructGPT/run_PopQA.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from tqdm import tqdm import argparse import os import time import json import torch import random import numpy as np import pandas as pd import openai openai.api_key = "YOUR_API_KEY" seed = 633 torch.backends.cudnn.deterministic = True random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) print("Cuda:", torch.cuda.is_available()) print("pwd", os.getcwd()) from transformers import AutoTokenizer, AutoModelForCausalLM from util_clm import convert_model_to_int8_on_gpu import jsonlines def load_jsonlines(file): with jsonlines.open(file, "r") as jsonl_f: lst = [obj for obj in jsonl_f] return lst q_templates = { 22: "What is {}'s occupation?", 218: "In what city was {} born?", 91: "What genre is {}?", 257: "Who is the father of {}?", 182: "In what country is {}?", 164: "Who was the producer of {}?", 526: "Who was the director of {}?", 97: "What is {} the capital of?", 533: "Who was the screenwriter for {}?", 639: "Who was the composer of {}?", 472: "What color is {}?", 106: "What is the religion of {}?", 560: "What sport does {} play?", 484: "Who is the author of {}?", 292: "Who is the mother of {}?", 422: "What is the capital of {}?", } completion_template = ( "Q: {} A:" # "{}" # "Query: {}\nResult:" # "Q: {} A:" # "{} The answer is" ) genread_template = "Generate a background document from Wikipedia to answer the given question. {}" # This prompt comes from the GenRead paper def call_request(prompt, model, tokenizer, max_new_tokens=15): max_inpt_tokens = tokenizer.model_max_length if ( len(prompt) > tokenizer.model_max_length ): # conservative lower bound, since each token is at least 1 character inpts = tokenizer(prompt, return_tensors="pt") new_prompt = tokenizer.decode( inpts.input_ids[0, -(max_inpt_tokens - max_new_tokens) :] ) else: new_prompt = prompt # try to get a response from the model multiple times if theres a timeout while True: try: # if i > 0: # print("Retrying request") response = openai.Completion.create( model=model, prompt=new_prompt, temperature=0.0, max_tokens=max_new_tokens, logprobs=5, top_p=1, frequency_penalty=0.0, presence_penalty=0.0, ) break except Exception as e: # print(e) print("Timeout, trying again") time.sleep(1) pred = response["choices"][0]["text"] if pred.startswith("\n\n"): pred = pred[2:] pred = pred.split("\n")[0] return pred, response.to_dict_recursive() def call_model( prompt, model, tokenizer, device, max_new_tokens=15, model_max_length=None ): max_inpt_tokens = ( tokenizer.model_max_length if model_max_length is None else model_max_length ) inpts = tokenizer(prompt, return_tensors="pt").to(device) gen = model.generate( input_ids=inpts.input_ids[:, -(max_inpt_tokens - max_new_tokens) :], attention_mask=inpts.attention_mask[:, -(max_inpt_tokens - max_new_tokens) :], pad_token_id=tokenizer.eos_token_id, max_new_tokens=max_new_tokens, num_beams=1, do_sample=False, ) text = tokenizer.decode(gen[0]) actual_prompt = tokenizer.decode( inpts.input_ids[0, -(max_inpt_tokens - max_new_tokens) :] ) pred = text[len(actual_prompt) :] if pred.startswith("\n\n"): pred = pred[2:] pred = pred.split("\n")[0] return pred, text def clip_paragraph(text, eval_method): if eval_method in ["BM25", "genread"]: return text split = text.split(". ") return ". ".join(split[:-1]) + "." def get_few_shot_text_with_retrieval(row, retrieval_dict, eval_method): if eval_method == "vanilla": return completion_template.format(row.question) + " " + row.obj # retrieval_dict[row.id]["ctxs"][0] if row.question.replace("?", "").lower() not in retrieval_dict: print("missing retrieval") return completion_template.format(row.question) + " " + row.obj else: retrieval = retrieval_dict[row.question.replace("?", "").lower()]["ctxs"][0] retrieved_text = clip_paragraph(retrieval["text"], eval_method) return ( retrieved_text + "\n\n" + completion_template.format(row.question) + " " + row.obj ) def get_few_shot_text(row, eval_method): return completion_template.format(row.question) + " " + row.obj def get_genread_passage( question, genread_template, generate_function, max_new_tokens=150 ): prompt = genread_template.format(question) return generate_function(prompt, max_new_tokens=max_new_tokens)[0] def get_few_shot_examples_genread( knowledge, generate_function, n_examples, genread_template, is_templatedQA, max_new_tokens=150, ): if is_templatedQA: few_shot_examples = dict() all_pids = list(q_templates.keys()) examples_per_template = n_examples // (len(q_templates) - 1) for pid in all_pids: for row2 in ( knowledge[knowledge.prop_id == pid].sample(n=examples_per_template).iloc ): if pid not in few_shot_examples: few_shot_examples[pid] = [] generation = get_genread_passage( row2.question, genread_template, generate_function, max_new_tokens=max_new_tokens, ) few_shot_examples[pid].append( get_few_shot_text_with_retrieval( row2, {row2.question: {"ctxs": [{"id": -1, "text": generation}]}}, "genread", ) ) else: few_shot_examples = [] for row2 in knowledge.sample(n=n_examples + 1).iloc: generation = get_genread_passage( row2.question, genread_template, generate_function, max_new_tokens=max_new_tokens, ) few_shot_examples.append( get_few_shot_text_with_retrieval( row2, {row2.question: {"ctxs": [{"id": -1, "text": generation}]}}, "genread", ) ) return few_shot_examples def main(): parser = argparse.ArgumentParser() parser.add_argument("--model_name", type=str, default="text-davinci-002") parser.add_argument("--input_file", type=str) parser.add_argument("--alias", type=str) parser.add_argument("--n_examples", type=int, default=15) parser.add_argument( "--eval_method", type=str, default="contriever", choices=["vanilla", "BM25", "contriever", "genread"], ) parser.add_argument( "--ret_path", type=str, default=None, required=False, help="path to retrieved documents jsonl", ) parser.add_argument("--device", type=str, default="cuda") parser.add_argument("--max_new_tokens", type=int, default=15) parser.add_argument("--sample", type=int, default=0, help="if 0, use all examples") parser.add_argument( "--continue_from", type=str, help="path to previous results file" ) parser.add_argument("--int8bit", action="store_true") parser.add_argument( "--parallel", type=str, help="string of format 'i.n_workers' where i is the index of the worker", ) args = parser.parse_args() use_gpt3 = args.model_name in { "text-davinci-003", "text-davinci-002", "text-curie-001", "text-babbage-001", "text-ada-001", } if use_gpt3: tokenizer = AutoTokenizer.from_pretrained("gpt2") generate = lambda prompt, max_new_tokens: call_request( prompt, args.model_name, tokenizer, max_new_tokens=max_new_tokens ) else: gpt = args.model_name device = args.device tokenizer = AutoTokenizer.from_pretrained(gpt) tokenizer.pad_token = tokenizer.eos_token tokenizer.pad_token_id = tokenizer.eos_token_id if args.int8bit: model = convert_model_to_int8_on_gpu( AutoModelForCausalLM.from_pretrained(gpt), device ) else: model = AutoModelForCausalLM.from_pretrained(gpt).eval().to(device) if "opt" in args.model_name or args.model_name == "EleutherAI/gpt-neox-20b": generate = lambda prompt, max_new_tokens: call_model( prompt, model=model, tokenizer=tokenizer, device=device, max_new_tokens=max_new_tokens, model_max_length=2048, ) else: generate = lambda prompt, max_new_tokens: call_model( prompt, model=model, tokenizer=tokenizer, device=device, max_new_tokens=max_new_tokens, ) input_path = args.input_file knowledge = pd.read_csv(input_path, sep="\t") if args.continue_from is not None: results = pd.read_csv(args.continue_from, sep="\t") knowledge = knowledge[~knowledge.id.isin(results.id)] n = len(knowledge) if args.sample == 0 else args.sample sample = knowledge.sample(n=n, replace=False) if args.parallel is not None: worker_num, n_workers = map(int, args.parallel.split(".")) sample = sample.iloc[worker_num::n_workers] n_examples = args.n_examples is_templatedQA = True examples_per_template = n_examples // (len(q_templates) - 1) preds = [] prompts = [] accuracy = [] responses = [] if args.eval_method in ["BM25", "contriever"]: has_answer = [] retrieval_ids = [] with open(args.ret_path) as f: retrieval_dict = { json.loads(s)["question"]: json.loads(s) for s in f.readlines() } # print(retrieval_dict) if args.eval_method == "genread": genread_few_shot_examples = get_few_shot_examples_genread( knowledge, generate, n_examples, genread_template, is_templatedQA, max_new_tokens=150, ) has_answer = [] gen_passages = [] # main loop row_num = 0 for row in tqdm(sample.iloc, total=n): if row_num < 10000: row_num += 1 continue # get few shot examples text if n_examples == 0: few_shot_examples_text = "" else: few_shot_examples = [] if args.eval_method == "genread": if is_templatedQA: other_pids = list(q_templates.keys()) other_pids.remove(row.prop_id) few_shot_examples = [] for pid in other_pids: few_shot_examples.extend( random.sample( genread_few_shot_examples[pid], examples_per_template ) ) else: few_shot_examples = random.sample( [ ex for ex in genread_few_shot_examples if row.question not in ex ], n_examples, ) else: if is_templatedQA: other_pids = list(q_templates.keys()) other_pids.remove(row.prop_id) for pid in other_pids: for row2 in ( knowledge[knowledge.prop_id == pid] .sample(n=examples_per_template) .iloc ): few_shot_examples.append( get_few_shot_text_with_retrieval( row2, retrieval_dict, args.eval_method ) if args.eval_method in ["BM25", "contriever"] else get_few_shot_text(row2, args.eval_method) ) else: for row2 in ( knowledge[knowledge.question != row.question] .sample(n=n_examples) .iloc ): few_shot_examples.append( get_few_shot_text_with_retrieval( row2, retrieval_dict, args.eval_method ) if args.eval_method in ["BM25", "contriever"] else get_few_shot_text(row2, args.eval_method) ) np.random.shuffle(few_shot_examples) few_shot_examples_text = "\n\n".join(few_shot_examples) + "\n\n" # get prompt if args.eval_method == "vanilla": prompt = few_shot_examples_text + completion_template.format(row.question) elif args.eval_method in ["BM25", "contriever"]: query = row.question try: retrieval = retrieval_dict[query]["ctxs"][ 0 ] # retrieval_dict[row.id]["ctxs"][0] except: print( "No retrieval for", query, " Example query:", list(retrieval_dict.keys())[0], ) retrieval = {"text": "", "id": np.nan, "hasanswer": False} # retrieved_text = clip_paragraph( # retrieval["text"], eval_method=args.eval_method # ) retrieved_text = ( retrieval_dict[query]["ctxs"][0]["text"] + "\n\n" + retrieval_dict[query]["ctxs"][1]["text"] + "\n\n" + retrieval_dict[query]["ctxs"][2]["text"] ) retrieval_id = retrieval["id"] prompt = ( few_shot_examples_text + retrieved_text + "\n\n" + completion_template.format(row.question) ) has_answer.append(retrieval["hasanswer"]) retrieval_ids.append(retrieval_id) elif args.eval_method == "genread": generation = get_genread_passage( row.question, genread_template, generate, max_new_tokens=150 ) prompt = ( few_shot_examples_text + generation + "\n\n" + completion_template.format(row.question) ) gen_passages.append(generation) # generate response pred, response = generate(prompt, max_new_tokens=args.max_new_tokens) prompts.append(prompt) preds.append(pred) responses.append(response) # compute accuracy possible_answers = json.loads(row.possible_answers) is_correct = False genread_has_answer = False for pa in possible_answers: if pa in pred or pa.lower() in pred or pa.capitalize() in pred: is_correct = True if ( args.eval_method == "genread" and pa in response or pa.lower() in response or pa.capitalize() in response ): genread_has_answer = True accuracy.append(is_correct) if args.eval_method == "genread": has_answer.append(genread_has_answer) if len(preds) % 500 == 0: g = open("gpt3.txt", "a") temp_sample = sample.iloc[: len(preds)].copy() temp_sample["is_correct"] = accuracy # print(temp_sample.is_correct.mean()) g.write(str(temp_sample.is_correct.mean()) + "\n") g.flush() # save results intermittently if len(preds) % 100000 == 0: temp_sample = sample.iloc[: len(preds)].copy() temp_sample["pred"] = preds temp_sample["prompt"] = prompts temp_sample["generation"] = responses temp_sample["is_correct"] = accuracy if args.eval_method in ["BM25", "contriever"]: temp_sample["has_answer"] = has_answer temp_sample["retrieval_id"] = retrieval_ids if args.eval_method == "genread": temp_sample["has_answer"] = has_answer temp_sample["gen_passage"] = gen_passages model_name_alias = args.model_name.replace("/", "_") if not os.path.exists(f"results/temp/"): os.makedirs(f"results/temp/") worker_str = "" if args.parallel is None else f"-worker={args.parallel}" output_path = f"results/temp/model={model_name_alias}-input={args.alias}-method={args.eval_method}-shots={n_examples}-n={len(temp_sample)}{'_int8bit' if args.int8bit is True else ''}{worker_str}.csv" temp_sample.to_csv(output_path, index=False) sample["is_correct"] = accuracy sample["prompt"] = prompts sample["pred"] = preds sample["generation"] = responses if args.eval_method in ["BM25", "contriever"]: sample["has_answer"] = has_answer sample["retrieval_id"] = retrieval_ids if args.eval_method == "genread": sample["has_answer"] = has_answer sample["gen_passage"] = gen_passages print(sample.is_correct.mean()) model_name_alias = args.model_name.replace("/", "_") worker_str = "" if args.parallel is None else f"-worker={args.parallel}" sample.to_csv( f"results/model={model_name_alias}-input={args.alias}-method={args.eval_method}-shots={n_examples}-n={len(sample)}{'_int8bit' if args.int8bit is True else ''}{worker_str}.csv" ) if __name__ == "__main__": main()
18,470
34.521154
211
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/InstructGPT/run_MMLU.py
from promptsource.templates import TemplateCollection from tqdm import tqdm import argparse import openai import json import time import numpy as np import os openai.api_key = "YOUR_API_KEY" choices = ["A", "B", "C", "D"] def softmax(x): z = x - max(x) numerator = np.exp(z) denominator = np.sum(numerator) softmax = numerator / denominator return softmax def eval(args, template, lines): cors = [] all_probs = [] answers = choices for line in tqdm(lines): sample = json.loads(line) applied_sample = template.apply(sample) prompt, label = applied_sample if args.method_name != "raw": prompt = ( sample["passages"][0] + "\n\n" + sample["passages"][1] + "\n\n" + sample["passages"][2] + "\n\n" + prompt ) # print("prompt:", prompt) # print("label:", label) while True: try: c = openai.Completion.create( model=args.model_name, prompt=prompt + "\n\nAnswer:", max_tokens=1, logprobs=100, temperature=0, echo=True, ) # g = open("b.txt", "w") # g.write(json.dumps(c)) break except: print("pausing") time.sleep(1) continue lprobs = [] for ans in answers: try: lprobs.append( c["choices"][0]["logprobs"]["top_logprobs"][-1][" {}".format(ans)] ) except: print( "Warning: {} not found. Artificially adding log prob of -100.".format( ans ) ) lprobs.append(-100) pred = {0: "A", 1: "B", 2: "C", 3: "D"}[np.argmax(lprobs)] probs = softmax(np.array(lprobs)) cor = pred == label cors.append(cor) all_probs.append(probs) acc = np.mean(cors) cors = np.array(cors) all_probs = np.array(all_probs) print("Average accuracy {:.3f}".format(acc)) return cors, acc, all_probs def main(args): collection = TemplateCollection() templates = collection.get_dataset("ai2_arc", "ARC-Challenge") template = templates["heres_a_problem"] cors, acc, _ = eval(args, template, open(args.data_dir).readlines()) os.makedirs( args.save_dir + args.task_name + "/" + args.model_name + "/" + args.method_name + "/", exist_ok=True, ) g = open( args.save_dir + args.task_name + "/" + args.model_name + "/" + args.method_name + "/" + "{:.3f}_0.txt".format(acc), "w", ) for cor in cors: g.write(f"{cor}\n") def genread(args): collection = TemplateCollection() templates = collection.get_dataset("ai2_arc", "ARC-Challenge") template = templates["heres_a_problem"] # genread_template = "Generate a background document from Wikipedia to answer the given question. {}" # This prompt comes from the GenRead paper genread_template = "{} Generate a background document from Wikipedia to help answer the given question:" output_file = open("genread.jsonl", "a") for line in tqdm(open(args.data_dir).readlines()): sample = json.loads(line) applied_sample = template.apply(sample) prompt, _ = applied_sample prompt = genread_template.format(prompt) while True: try: c = openai.Completion.create( model=args.model_name, prompt=prompt, temperature=0.0, max_tokens=150, logprobs=5, top_p=1, frequency_penalty=0.0, presence_penalty=0.0, ) break except: print("pausing") time.sleep(1) continue sample["passages"] = [c["choices"][0]["text"]] output_file.write(json.dumps(sample) + "\n") output_file.flush() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data_dir", "-d", type=str, default="data/") parser.add_argument("--save_dir", "-s", type=str, default="results/") parser.add_argument("--task_name", type=str, default="mmlu_validation") parser.add_argument("--model_name", type=str, default="text-davinci-002") parser.add_argument("--method_name", type=str, default="ra") args = parser.parse_args() main(args) # genread(args)
4,880
27.881657
149
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/arguments.py
# coding=utf-8 """argparser configuration""" import argparse import os import torch import deepspeed def add_model_config_args(parser: argparse.ArgumentParser): """Model arguments""" group = parser.add_argument_group("model", "model configuration") group.add_argument( "--model-config", type=str, default=None, help="the configuration of the base model", ) group.add_argument( "--cpu-optimizer", action="store_true", help="Run optimizer on CPU" ) group.add_argument( "--cpu_torch_adam", action="store_true", help="Use Torch Adam as optimizer on CPU.", ) return parser def add_fp16_config_args(parser: argparse.ArgumentParser): """Mixed precision arguments.""" group = parser.add_argument_group("fp16", "fp16 configurations") group.add_argument("--fp16", action="store_true", help="Run model in fp16 mode") group.add_argument( "--fp32-embedding", action="store_true", help="embedding in fp32" ) group.add_argument( "--fp32-layernorm", action="store_true", help="layer norm in fp32" ) group.add_argument( "--fp32-tokentypes", action="store_true", help="embedding token types in fp32" ) group.add_argument( "--fp32-allreduce", action="store_true", help="all-reduce in fp32" ) group.add_argument( "--hysteresis", type=int, default=2, help="hysteresis for dynamic loss scaling" ) group.add_argument( "--loss-scale", type=float, default=None, help="Static loss scaling, positive power of 2 " "values can improve fp16 convergence. If None, dynamic loss scaling is used.", ) group.add_argument( "--loss-scale-window", type=float, default=1000, help="Window over which to raise/lower dynamic scale", ) group.add_argument( "--min-scale", type=float, default=1, help="Minimum loss scale for dynamic loss scale", ) return parser def add_training_args(parser: argparse.ArgumentParser): """Training arguments.""" group = parser.add_argument_group("train", "training configurations") group.add_argument("--do-train", action="store_true", help="whether do training") group.add_argument("--do-valid", action="store_true", help="whether do validation") group.add_argument("--do-valid-and-eval", action="store_true") group.add_argument("--do-eval", action="store_true", help="whether do testing") group.add_argument( "--do-infer", action="store_true", help="whether do inference (testing without labels)", ) group.add_argument( "--train-ratio", type=float, default=1.0, help="the ratio of the training set used for training", ) group.add_argument( "--train-num", type=int, default=-1, help="the number of training samples, -1 for all sample", ) group.add_argument( "--dev-ratio", type=float, default=1.0, help="the ratio of the training set used for validation", ) group.add_argument( "--dev-num", type=int, default=-1, help="the number of validation samples, -1 for all sample", ) group.add_argument( "--test-ratio", type=float, default=1.0, help="the ratio of the training set used for testing", ) group.add_argument( "--test-num", type=int, default=-1, help="the number of testing samples, -1 for all sample", ) group.add_argument("--epochs", type=int, default=1, help="the epochs for training") group.add_argument( "--batch-size", type=int, default=4, help="Data Loader batch size" ) group.add_argument( "--dev-batch-size", type=int, default=2, help="Data Loader batch size" ) group.add_argument( "--gradient-accumulation-steps", type=int, default=1, help="gradient accumulation steps", ) group.add_argument( "--weight-decay", type=float, default=0.01, help="weight decay coefficient for L2 regularization", ) group.add_argument( "--checkpoint-activations", action="store_true", help="checkpoint activation to allow for training " "with larger models and sequences", ) group.add_argument( "--checkpoint-num-layers", type=int, default=1, help="chunk size (number of layers) for checkpointing", ) group.add_argument( "--num-checkpoints", type=int, default=24, help="For activation checkpointing" ) group.add_argument( "--deepspeed-activation-checkpointing", action="store_true", help="uses activation checkpointing from deepspeed", ) group.add_argument("--clip-grad", type=float, default=1.0, help="gradient clipping") group.add_argument( "--train-iters", type=int, default=1000000, help="total number of iterations to train over all training runs", ) group.add_argument("--log-interval", type=int, default=100, help="report interval") group.add_argument( "--max-save", type=int, default=-1, help="max checkpoints to save" ) group.add_argument("--seed", type=int, default=1234, help="random seed") group.add_argument("--few-data-num", type=int, default=None) group.add_argument("--few-data-names", type=str, default=None) group.add_argument("--data-aug", type=int, default=None) group.add_argument("--rand-real-label", action="store_true") group.add_argument("--rand-pseudo-label", action="store_true") # Learning rate. group.add_argument( "--lr-decay-iters", type=int, default=None, help="number of iterations to decay LR over," " If None defaults to `--train-iters`*`--epochs`", ) group.add_argument( "--lr-decay-style", type=str, default="linear", choices=["constant", "linear", "cosine", "exponential", "noam"], help="learning rate decay function", ) group.add_argument("--lr", type=float, default=1.0e-4, help="initial learning rate") group.add_argument( "--warmup", type=float, default=0.0, help="percentage of data to warmup on (.01 = 1% of all " "training iters). Default 0.01", ) group.add_argument("--warmup-iter", type=int, default=0) # save group.add_argument( "--save", type=str, default=None, help="Output directory to save checkpoints to.", ) group.add_argument( "--save-interval", type=int, default=5000, help="number of iterations between saves", ) group.add_argument( "--no-save-optim", action="store_true", help="Do not save current optimizer." ) # load group.add_argument( "--load", type=str, default=None, help="Path to a directory containing a model checkpoint.", ) group.add_argument( "--load-oprimizer-states", action="store_true", help="whether to load optimizer states", ) group.add_argument( "--load-lr-scheduler-states", action="store_true", help="whether to load learning rate scheduler states", ) group.add_argument( "--no-load-optim", action="store_true", help="Do not load optimizer when loading checkpoint.", ) group.add_argument( "--log-file", type=str, default=None, help="the path to save log.txt file" ) # distributed training args group.add_argument( "--distributed-backend", default="nccl", help="which backend to use for distributed training. One of [gloo, nccl]", ) group.add_argument( "--local_rank", type=int, default=None, help="local rank passed from distributed launcher", ) return parser def add_prompt_args(parser: argparse.ArgumentParser): group = parser.add_argument_group("prompt", "prompt configurations") group.add_argument( "--load_prompt", type=str, default=None, help="the path to load prompt from" ) group.add_argument( "--prompt-tune", action="store_true", help="whether to do prompt tuning" ) group.add_argument( "--prompt-config", type=str, default=None, help="the path of the prompt configuration", ) group.add_argument( "--save-prompt-only", action="store_true", help="whether to save the prompt only. If true, only prompts will be saved otherwise, " "the whole model together with the prompt will be saved.", ) return parser def add_evaluation_args(parser: argparse.ArgumentParser): """Evaluation arguments.""" group = parser.add_argument_group("validation", "validation configurations") group.add_argument( "--eval-batch-size", type=int, default=None, help="Data Loader batch size for evaluation datasets. Defaults to `--batch-size`", ) group.add_argument( "--eval-iters", type=int, default=100, help="number of iterations to run for evaluation validation/test for", ) group.add_argument( "--eval-interval", type=int, default=1000, help="interval between running evaluation on validation set", ) group.add_argument("--eval-per-prompt", action="store_true") group.add_argument("--no-norm-cand-loss", action="store_true") return parser def add_text_generate_args(parser: argparse.ArgumentParser): """Text generate arguments.""" group = parser.add_argument_group("Text generation", "configurations") group.add_argument("--sampling", action="store_true") group.add_argument( "--temperature", type=float, default=1.2, help="The temperature of sampling." ) group.add_argument("--top_p", type=float, default=0.9, help="Top-p sampling.") group.add_argument("--top_k", type=int, default=0, help="Top-k sampling.") group.add_argument( "--max-generation-length", type=int, default=64, help="The maximum sequence length to generate.", ) group.add_argument( "--min-generation-length", type=int, default=0, help="The minimum sequence length to generate.", ) group.add_argument( "--num-beams", type=int, default=1, help="The beam number of beam search." ) group.add_argument( "--no-repeat-ngram-size", type=int, default=0, help="The n-gram whose length is less than this option will appear at most once in the whole dialog.", ) group.add_argument( "--repetition-penalty", type=float, default=1, help="Repetition penalty, to prevent repeated words.", ) group.add_argument( "--early-stopping", action="store_true", help="Early-stopping while generating." ) group.add_argument( "--length-penalty", type=float, default=0, help="Length penalty, to prevent short generation.", ) group.add_argument( "--rule-path", type=str, default=None, help="The directory that contains hand-written rules.", ) return parser def add_data_args(parser: argparse.ArgumentParser): """Train/valid/test data arguments.""" group = parser.add_argument_group("data", "data configurations") group.add_argument( "--model-parallel-size", type=int, default=1, help="size of the model parallel." ) group.add_argument( "--data-path", nargs="+", type=str, default=None, help="Path to combined dataset to split.", ) group.add_argument( "--data-ext", type=str, default=".json", help="the extension of the data file" ) group.add_argument( "--data-name", type=str, default=None, help="the name of the dataset" ) group.add_argument( "--data-names", type=str, default=None, help="the name of the dataset" ) group.add_argument( "--data-prefix", type=str, default=None, help="the prefix to add before each data sample", ) group.add_argument( "--num-workers", type=int, default=2, help="Number of workers to use for dataloading", ) group.add_argument( "--tokenizer-path", type=str, default="tokenizer.model", help="path used to save/load sentencepiece tokenization models", ) group.add_argument( "--enc-seq-length", type=int, default=512, help="Maximum sequence length to process", ) group.add_argument( "--dec-seq-length", type=int, default=256, help="Maximum sequence length to process", ) group.add_argument("--pad-token", type=str, default="<pad>") group.add_argument("--FiD", action="store_true") group.add_argument( "--passage_num", type=int, default=10, help="Number of passages to use for FiD" ) return parser def add_flan_args(parser: argparse.ArgumentParser): group = parser.add_argument_group("flan", "data configurations") group.add_argument("--flan-sample", action="store_true") group.add_argument("--flan-sample-max", type=float, default=1000000) return parser def add_debug_args(parser: argparse.ArgumentParser): group = parser.add_argument_group("debug", "data configurations") group.add_argument("--debug-option", type=int, default=-1) group.add_argument("--shuff-cand-idx", action="store_true") return parser def get_args(): """Parse all the args.""" parser = argparse.ArgumentParser(description="PyTorch BERT Model") parser = add_model_config_args(parser) parser = add_fp16_config_args(parser) parser = add_training_args(parser) parser = add_evaluation_args(parser) parser = add_data_args(parser) parser = add_prompt_args(parser) parser = add_text_generate_args(parser) parser = add_flan_args(parser) parser = add_debug_args(parser) # Include DeepSpeed configuration arguments parser = deepspeed.add_config_arguments(parser) args = parser.parse_args() if not args.data_path: print("WARNING: No training data specified") args.cuda = torch.cuda.is_available() args.rank = int(os.getenv("RANK", "0")) args.world_size = int(os.getenv("WORLD_SIZE", "1")) args.local_rank = int(os.getenv("LOCAL_RANK", "0")) args.model_parallel_size = min(args.model_parallel_size, args.world_size) if args.rank == 0: print( "using world size: {} and model-parallel size: {} ".format( args.world_size, args.model_parallel_size ) ) args.dynamic_loss_scale = False if args.loss_scale is None: args.dynamic_loss_scale = True if args.rank == 0: print(" > using dynamic loss scaling") if args.data_path is not None and len(args.data_path) == 1: args.data_path = args.data_path[0] return args
15,323
29.344554
110
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/learning_rates.py
# coding=utf-8 """PyTorch DataLoader for TFRecords""" import torch from torch.optim.lr_scheduler import _LRScheduler import math class AnnealingLR(_LRScheduler): """Anneals the learning rate from start to zero along a cosine curve.""" DECAY_STYLES = ['linear', 'cosine', 'exponential', 'constant', 'None', 'noam'] def __init__(self, optimizer, start_lr, warmup_iter, num_iters, decay_style=None, last_iter=-1, gradient_accumulation_steps=1): self.optimizer = optimizer self.start_lr = start_lr self.warmup_iter = (warmup_iter // gradient_accumulation_steps) + 1 self.num_iters = last_iter + 1 self.end_iter = num_iters self.gradient_accumulation_steps = gradient_accumulation_steps self.decay_style = decay_style.lower() if isinstance(decay_style, str) else None self.step(self.num_iters) if torch.distributed.get_rank() == 0: print('learning rate decaying', decay_style) def get_lr(self): # https://openreview.net/pdf?id=BJYwwY9ll pg. 4 if self.warmup_iter > 0 and self.num_iters <= self.warmup_iter: if self.decay_style != self.DECAY_STYLES[5]: return float(self.start_lr) * self.num_iters / self.warmup_iter else: return float(self.start_lr) / math.sqrt(self.warmup_iter) * self.num_iters / self.warmup_iter #* self.num_iters / self.warmup_iter / math.sqrt(self.warmup_iter) else: if self.decay_style == self.DECAY_STYLES[0]: return self.start_lr*((self.end_iter-(self.num_iters-self.warmup_iter))/self.end_iter) elif self.decay_style == self.DECAY_STYLES[1]: return self.start_lr / 2.0 * (math.cos(math.pi * (self.num_iters - self.warmup_iter) / self.end_iter) + 1) elif self.decay_style == self.DECAY_STYLES[2]: #TODO: implement exponential decay return self.start_lr elif self.decay_style == self.DECAY_STYLES[5]: return self.start_lr / math.sqrt(self.num_iters + 1) else: return self.start_lr def step(self, step_num=None): if step_num is None: step_num = self.num_iters + 1 self.num_iters = step_num new_lr = self.get_lr() for group in self.optimizer.param_groups: group['lr'] = new_lr def state_dict(self): sd = { 'start_lr': self.start_lr, 'warmup_iter': self.warmup_iter, 'num_iters': self.num_iters, 'decay_style': self.decay_style, 'end_iter': self.end_iter } return sd def load_state_dict(self, sd): self.start_lr = sd['start_lr'] self.warmup_iter = sd['warmup_iter'] self.num_iters = sd['num_iters'] self.end_iter = sd['end_iter'] self.decay_style = sd['decay_style'] self.step(self.num_iters)
2,974
40.901408
176
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/utils.py
# coding=utf-8 """Utilities for logging and serialization""" import os import random import numpy as np import torch from fp16 import FP16_Optimizer import mpu import deepspeed from apex.optimizers import FusedAdam as Adam from fp16 import FP16_Module from fp16 import FP16_Optimizer from learning_rates import AnnealingLR from model import EncDecModel, EncDecConfig from model import enc_dec_get_params_for_weight_decay_optimization, enc_dec_get_params_for_prompt_optimization from model import DistributedDataParallel as DDP def print_rank_0(message): if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: print(message, flush=True) else: print(message, flush=True) def print_args(args): """Print arguments.""" print('arguments:', flush=True) for arg in vars(args): dots = '.' * (29 - len(arg)) print(' {} {} {}'.format(arg, dots, getattr(args, arg)), flush=True) def save_rank_0(args, message): if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: with open(args.log_file, "a") as f: f.write(message + "\n") f.flush() else: with open(args.log_file, "a") as f: f.write(message + "\n") f.flush() def save_preds_t0(args, name, prompt_names, step, all_res_prompt, all_preds_prompt, all_labels_prompt): s = np.mean([np.mean([vv for vv in v.values()]) for v in all_res_prompt]) if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: os.makedirs(os.path.join(args.save, "preds", name), exist_ok=True) with open(os.path.join(args.save, "preds", name, "{:.2f}_{}.txt".format(s, step)), "w") as f: f.write(str(all_res_prompt) + "\n") for pid in range(len(prompt_names)): f.write("\n" + str(prompt_names[pid]) + "\n") for p, l in zip(all_preds_prompt[pid], all_labels_prompt[pid]): f.write(str(p) + "\t\t" + str(l) + "\n") def save_preds_prompts(args, name, dataset, step, res, all_preds_prompts, all_labels_prompts): s = np.mean([v for v in res[0].values()]) if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: os.makedirs(os.path.join(args.save, "preds", name), exist_ok=True) with open(os.path.join(args.save, "preds", name, "{:.2f}_{}.txt".format(s, step)), "w") as f: f.write(str(res) + "\n") for pid in dataset.all_data[name]["prompt_ids"]: f.write("\n" + str(dataset.all_data[name]["prompt_templates"][pid]) + "\n") for p, l in zip(all_preds_prompts[pid], all_labels_prompts[pid]): f.write(str(p) + "\t\t" + str(l) + "\n") def save_preds(args, name, step, res, all_preds, all_labels): s = np.mean([v for v in res[0].values()]) if torch.distributed.is_initialized(): if torch.distributed.get_rank() == 0: os.makedirs(os.path.join(args.save, "preds", name), exist_ok=True) with open(os.path.join(args.save, "preds", name, "{:.2f}_{}.txt".format(s, step)), "w") as f: f.write(str(res) + "\n") for p, l in zip(all_preds, all_labels): f.write(str(p) + "\t\t" + str(l) + "\n") def get_model(args, vocab_size, prompt_config=None): """Build the model.""" print_rank_0('building Enc-Dec model ...') config = EncDecConfig.from_json_file(args.model_config) config.vocab_size = vocab_size model = EncDecModel(config, parallel_output=True, checkpoint_activations=args.checkpoint_activations, checkpoint_num_layers=args.checkpoint_num_layers, prompt_config=prompt_config, args=args) if mpu.get_data_parallel_rank() == 0: print(' > number of parameters on model parallel rank {}: {}'.format( mpu.get_model_parallel_rank(), sum([p.nelement() for p in model.parameters()])), flush=True) # To prevent OOM for model sizes that cannot fit in GPU memory in full precision if args.deepspeed and args.fp16: model.half() # GPU allocation. model.cuda(torch.cuda.current_device()) if args.prompt_tune and prompt_config["init_scratch"]: model.init_prompt_embeds() # Fp16 conversion. if args.fp16: model = FP16_Module(model) # Wrap model for distributed training. model = DDP(model) return model def get_optimizer(model, args, prompt_config=None): """Set up the optimizer.""" # Build parameter groups (weight decay and non-decay). while isinstance(model, (DDP, FP16_Module)): model = model.module if args.prompt_tune and prompt_config["fix_model"]: param_groups = enc_dec_get_params_for_prompt_optimization(model) else: param_groups = enc_dec_get_params_for_weight_decay_optimization(model) # Add model parallel attribute if it is not set. for param_group in param_groups: for param in param_group['params']: if not hasattr(param, 'model_parallel'): param.model_parallel = False if args.cpu_optimizer: if args.cpu_torch_adam: cpu_adam_optimizer = torch.optim.Adam else: from deepspeed.ops.adam import DeepSpeedCPUAdam cpu_adam_optimizer = DeepSpeedCPUAdam optimizer = cpu_adam_optimizer(param_groups, lr=args.lr, weight_decay=args.weight_decay) else: # Use FusedAdam. optimizer = Adam(param_groups, lr=args.lr, weight_decay=args.weight_decay) print(f'Optimizer = {optimizer.__class__.__name__}') if args.deepspeed: # fp16 wrapper is not required for DeepSpeed. return optimizer # Wrap into fp16 optimizer. if args.fp16: optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale, dynamic_loss_scale=args.dynamic_loss_scale, dynamic_loss_args={ 'scale_window': args.loss_scale_window, 'min_scale': args.min_scale, 'delayed_shift': args.hysteresis}) if torch.distributed.get_rank() == 0: print(optimizer.param_groups) return optimizer def get_learning_rate_scheduler(optimizer, args): """Build the learning rate scheduler.""" # Add linear learning rate scheduler. if args.lr_decay_iters is not None: num_iters = args.lr_decay_iters else: num_iters = args.train_iters num_iters = max(1, num_iters) init_step = -1 if args.warmup_iter > 0: warmup_iter = args.warmup_iter else: warmup_iter = args.warmup * num_iters lr_scheduler = AnnealingLR(optimizer, start_lr=args.lr, warmup_iter=warmup_iter, num_iters=num_iters, decay_style=args.lr_decay_style, last_iter=init_step, gradient_accumulation_steps=args.gradient_accumulation_steps) return lr_scheduler def setup_model_and_optimizer(args, vocab_size, ds_config, prompt_config=None, set_optim=True): """Setup model and optimizer.""" model = get_model(args, vocab_size, prompt_config) if set_optim: optimizer = get_optimizer(model, args, prompt_config) lr_scheduler = get_learning_rate_scheduler(optimizer, args) else: optimizer, lr_scheduler = None, None if args.deepspeed: print_rank_0("DeepSpeed is enabled.") model, optimizer, _, lr_scheduler = deepspeed.initialize( model=model, optimizer=optimizer, args=args, lr_scheduler=lr_scheduler, mpu=mpu, dist_init_required=False, config_params=ds_config ) print(args.load) if args.load is not None: args.iteration = load_checkpoint(model, optimizer, lr_scheduler, args, prompt_config) else: args.iteration = 0 return model, optimizer, lr_scheduler def set_deepspeed_activation_checkpointing(args): deepspeed.checkpointing.configure(mpu, deepspeed_config=args.deepspeed_config, num_checkpoints=args.num_checkpoints) mpu.checkpoint = deepspeed.checkpointing.checkpoint mpu.get_cuda_rng_tracker = deepspeed.checkpointing.get_cuda_rng_tracker mpu.model_parallel_cuda_manual_seed = deepspeed.checkpointing.model_parallel_cuda_manual_seed def initialize_distributed(args): """Initialize torch.distributed.""" # Manually set the device ids. device = args.rank % torch.cuda.device_count() if args.local_rank is not None: device = args.local_rank torch.cuda.set_device(device) # Call the init process deepspeed.init_distributed() # Set the model-parallel / data-parallel communicators. mpu.initialize_model_parallel(args.model_parallel_size) # Optional DeepSpeed Activation Checkpointing Features if args.deepspeed and args.deepspeed_activation_checkpointing: set_deepspeed_activation_checkpointing(args) def set_random_seed(seed): """Set random seed for reproducability.""" if seed is not None and seed > 0: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) mpu.model_parallel_cuda_manual_seed(seed) def save_checkpoint(iteration, model, optimizer, lr_scheduler, args, save_dir=None): """Save a model checkpoint.""" save_ds_checkpoint(iteration, model, args, save_dir) # Wait so everyone is done (necessary) torch.distributed.barrier() # And update the latest iteration if torch.distributed.get_rank() == 0: tracker_filename = os.path.join(args.save if save_dir is None else save_dir, 'latest_checkpointed_iteration.txt') with open(tracker_filename, 'w') as f: f.write(str(iteration)) # Wait so everyone is done (not necessary) torch.distributed.barrier() def save_ds_checkpoint(iteration, model, args, save_dir=None): """Save a model checkpoint.""" sd = {} sd['iteration'] = iteration if args.save_prompt_only: prompt = model.module.module.module.get_prompt_embeds() save_prompt(args.save if save_dir is None else save_dir, iteration, prompt["encoder"]) else: model.save_checkpoint(args.save if save_dir is None else save_dir, str(iteration), client_state = sd, save_zero=False) def save_prompt(save_dir, iteration, prompt_embeds): save_path = os.path.join(save_dir, "prompt-{}.pt".format(iteration)) if torch.distributed.get_rank() == 0: torch.save(prompt_embeds, save_path) def get_checkpoint_iteration(args): # Read the tracker file and set the iteration. tracker_filename = os.path.join(args.load, 'latest_checkpointed_iteration.txt') if not os.path.isfile(tracker_filename): print_rank_0('WARNING: could not find the metadata file {} '.format( tracker_filename)) print_rank_0(' will not load any checkpoints and will start from ' 'random') return 0, False, False iteration = 0 release = False with open(tracker_filename, 'r') as f: metastring = f.read().strip() try: iteration = int(metastring) except ValueError: release = metastring == 'release' if not release: print_rank_0('ERROR: Invalid metadata file {}. Exiting'.format( tracker_filename)) exit() assert iteration > 0 or release, 'error parsing metadata file {}'.format( tracker_filename) return iteration, release, True def load_prompt(load_dir): prompt = torch.load(load_dir, map_location=lambda storage, loc: storage) return prompt def load_checkpoint(model, optimizer, lr_scheduler, args, prompt_config=None): """Load a model checkpoint.""" iteration, release, success = get_checkpoint_iteration(args) if not success: return 0 mp_rank = mpu.get_model_parallel_rank() checkpoint_name = os.path.join(args.load, str(iteration), 'mp_rank_{:02d}'.format(mp_rank) + '_model_states.pt') if not os.path.exists(checkpoint_name): print('Client provided checkpoint load path: {} does not exist ... skip checkpoint load'.format(checkpoint_name)) if mpu.get_data_parallel_rank() == 0: print("Unable to load checkpoint.") return iteration print('loading checkpoint: {}'.format(checkpoint_name)) sd = torch.load(checkpoint_name, map_location=lambda storage, loc: storage) if args.prompt_tune: load_prompt_path = prompt_config.get("load_prompt") if load_prompt_path is not None and len(load_prompt_path) > 0: prompt_embeds = load_prompt(load_prompt_path) sd["module"]["encoder.prompt_embeds.weight"] = prompt_embeds model.module.load_state_dict(sd["module"], strict=False) iteration = sd['iteration'] torch.distributed.barrier() if mpu.get_data_parallel_rank() == 0: print(' successfully loaded {}'.format(checkpoint_name)) return iteration
13,650
35.209549
126
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/generation_utils.py
# coding=utf-8 import os import torch import torch.nn.functional as F from collections import defaultdict from tokenization_t5 import EncDecTokenizer class BeamHypotheses(object): def __init__( self, num_beams, max_length, length_penalty, early_stopping, tokenizer=None ): """ Initialize n-best list of hypotheses. """ self.max_length = max_length - 1 # ignoring bos_token self.length_penalty = length_penalty self.early_stopping = early_stopping self.num_beams = num_beams self.length_fact = [] self.beams = [] self.worst_score = 1e9 self.raw_worst_score = 1e9 self.tokenizer = tokenizer def __len__(self): """ Number of hypotheses in the list. """ return len(self.beams) def add(self, hyp, sum_logprobs): """ Add a new hypothesis to the list. """ score = sum_logprobs / len(hyp) ** self.length_penalty if len(self) < self.num_beams or score > self.worst_score: self.beams.append((score, hyp)) self.length_fact.append(len(hyp) ** self.length_penalty) if len(self) > self.num_beams: sorted_scores = sorted( [(s, idx, _) for idx, (s, _) in enumerate(self.beams)] ) del self.beams[sorted_scores[0][1]] self.worst_score = sorted_scores[1][0] self.raw_worst_score = self.worst_score * ( len(sorted_scores[1][2]) ** self.length_penalty ) else: self.worst_score = min(score, self.worst_score) self.raw_worst_score = sum_logprobs def is_done(self, best_sum_logprobs, cur_len): """ If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst one in the heap, then we are done with this sentence. """ if len(self) < self.num_beams: return False elif self.early_stopping: return True else: cur_score = best_sum_logprobs / cur_len ** self.length_penalty ret = self.worst_score >= cur_score return ret def construct_antonym_dict(args): if args.rule_path is None: return None with open(os.path.join(args.rule_path, "./antonym/antonym.txt"), "r") as f: data = f.read().split("\n") data = [eval(item) for item in data if item] antonym_dict = defaultdict(list) for first, second in data: antonym_dict[first].append(second) antonym_dict[second].append(first) return antonym_dict def calc_banned_antonym_words_ids(input_tokens, tokenizer, antonym_dict): if antonym_dict is None: return [] antonym_words = [set()] * len(input_tokens) # only consider tokens occurring in current sentence for idx, tokens in enumerate(input_tokens): for word in tokenizer.convert_ids_to_tokens(reversed(tokens.tolist())): if word == "<sep>": break antonym_words[idx].update( tokenizer.convert_tokens_to_ids(antonym_dict[word]) ) return [list(tokens) for tokens in antonym_words] def calc_banned_ngram_tokens( prev_input_ids, num_hypos: int, no_repeat_ngram_size: int, tokenizer: EncDecTokenizer, ) -> None: """Copied from fairseq for no_repeat_ngram in beam_search""" generated_ngrams = [{} for _ in range(num_hypos)] for idx in range(num_hypos): gen_words = prev_input_ids[idx] generated_ngram = generated_ngrams[idx] for ngram in zip(*[gen_words[i:] for i in range(no_repeat_ngram_size)]): ngram = tuple(ngram) generated_ngram[ngram] = generated_ngram.get(ngram, set()) | set([ngram]) def _get_generated_ngrams(hypo_idx): # Before decoding the next token, prevent decoding of ngrams that have already appeared cur_len = len(prev_input_ids[hypo_idx]) generated_ngram_idx = [] for prefix_len in range(no_repeat_ngram_size): ngram_words = tuple(prev_input_ids[hypo_idx][cur_len - prefix_len :]) generated_ngram_words = generated_ngrams[hypo_idx].get(ngram_words, []) generated_ngram_idx += tokenizer.convert_tokens_to_ids( generated_ngram_words ) return generated_ngram_idx banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)] return banned_tokens def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-10000): # This function has been mostly taken from huggingface conversational ai code at # https://medium.com/huggingface/how-to-build-a-state-of-the-art-conversational-ai-with-transfer-learning-2d818ac26313 if top_k > 0: # Remove all tokens with a probability less than the last token of the top-k indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] logits[indices_to_remove] = filter_value batch_size = logits.size()[0] if top_p > 0.0: # logits : (batch_size, vocab_size) logits = logits.view(batch_size, -1).contiguous() # logits : (batch_size, vocab_size) for logit in logits: # logit: (vocab_size) sorted_logits, sorted_indices = torch.sort(logit, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) # Remove tokens with cumulative probability above the threshold sorted_indices_to_remove = cumulative_probs > top_p # Shift the indices to the right to keep also the first token above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[ ..., :-1 ].clone() sorted_indices_to_remove[..., 0] = 0 indices_to_remove = sorted_indices[sorted_indices_to_remove] logit[indices_to_remove] = filter_value logits = logits.view(batch_size, -1).contiguous() return logits def calc_banned_bad_words_ids(prev_input_ids, bad_words_ids): banned_tokens = [] def _tokens_match(prev_tokens, tokens): if len(tokens) == 0: # if bad word tokens is just one token always ban it return True if len(tokens) > len(prev_input_ids): # if bad word tokens are longer then prev input_ids they can't be equal return False if prev_tokens[-len(tokens) :] == tokens: # if tokens match return True else: return False for prev_input_ids_slice in prev_input_ids: banned_tokens_slice = [] for banned_token_seq in bad_words_ids: assert ( len(banned_token_seq) > 0 ), "Banned words token sequences {} cannot have an empty list".format( bad_words_ids ) if ( _tokens_match(prev_input_ids_slice.tolist(), banned_token_seq[:-1]) is False ): # if tokens do not match continue continue banned_tokens_slice.append(banned_token_seq[-1]) banned_tokens.append(banned_tokens_slice) return banned_tokens def enforce_repetition_penalty_( tokenizer, lprobs, batch_size, num_beams, prev_output_tokens, repetition_penalty ): """repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858).""" for i in range(batch_size * num_beams): for previous_token in set(prev_output_tokens[i].tolist()): if previous_token != tokenizer.eos_id: # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability if lprobs[i, previous_token] < 0: lprobs[i, previous_token] *= repetition_penalty else: lprobs[i, previous_token] /= repetition_penalty def postprocess_next_token_scores( tokenizer: EncDecTokenizer, scores, input_ids, no_repeat_ngram_size, bad_words_ids, cur_len, min_length, max_length, eos_token_id, repetition_penalty, batch_size, num_beams, antonym_dict, ): # repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858) if repetition_penalty != 1.0: enforce_repetition_penalty_( tokenizer, scores, batch_size, num_beams, input_ids, repetition_penalty, ) # set eos token prob to zero if min_length is not reached if eos_token_id is not None and cur_len < min_length: scores[:, eos_token_id] = -10000 if no_repeat_ngram_size > 0: # calculate a list of banned tokens to prevent repetitively generating the same ngrams num_batch_hypotheses = batch_size * num_beams # from fairseq: https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345 banned_batch_tokens = calc_banned_ngram_tokens( input_ids, num_batch_hypotheses, no_repeat_ngram_size, tokenizer=tokenizer ) for i, banned_tokens in enumerate(banned_batch_tokens): scores[i, banned_tokens] = -10000 if bad_words_ids is not None: # calculate a list of banned tokens according to bad words banned_tokens = calc_banned_bad_words_ids(input_ids, bad_words_ids) for i, banned_tokens in enumerate(banned_tokens): scores[i, banned_tokens] = -10000 # add antonym banned list banned_tokens = calc_banned_antonym_words_ids(input_ids, tokenizer, antonym_dict) for i, banned_tokens in enumerate(banned_tokens): scores[i, banned_tokens] = -10000 scores[:, 0] = -50000 return scores def generate_no_beam( model_batch, full_context, model, tokenizer: EncDecTokenizer, args, device ): batch_size = args.batch_size target_length = args.max_generation_length dec_init_length = 1 # +1 for s_0 if args.FiD: model.module.module.module.reset_score_storage() batch_size, _, sequence_length = model_batch["passage_input_ids"].size() enc_input_ids = model_batch["passage_input_ids"].view( batch_size * args.passage_num, sequence_length ) enc_attention_mask = model_batch["passage_attention_mask"].view( batch_size * args.passage_num, 1, sequence_length, sequence_length ) enc_outputs = model( enc_input_ids=enc_input_ids, enc_attention_mask=enc_attention_mask, only_encoder=True, ) enc_hidden_states = enc_outputs["encoder_last_hidden_state"].view( batch_size, sequence_length * args.passage_num, -1 ) else: enc_input_ids = model_batch["enc_input_ids"] enc_attention_mask = model_batch["enc_attention_mask"] enc_outputs = model( enc_input_ids=enc_input_ids, enc_attention_mask=enc_attention_mask, only_encoder=True, ) enc_hidden_states = enc_outputs["encoder_last_hidden_state"] # for generating responses # we only use the <go> token, so truncate other tokens dec_input_ids = model_batch["dec_input_ids"][..., :dec_init_length] dec_attention_mask = model_batch["dec_attention_mask"][ ..., :dec_init_length, :dec_init_length ] # we use past_key_values, so only the current token mask is needed cross_attention_mask = model_batch["cross_attention_mask"][..., :dec_init_length, :] unfinished_sents = enc_input_ids.new(enc_hidden_states.size(0)).fill_(1) output_ids = enc_input_ids.new_zeros( [enc_hidden_states.size(0), 0] ) # not include the prompt prob_idx = torch.arange(batch_size) past_key_values = None gen_len = 0 # construct antonym dict antonym_dict = None while gen_len < target_length: if unfinished_sents.max() == 0: tokens_to_add = tokenizer.eos_id * (1 - unfinished_sents) output_ids = torch.cat([output_ids, tokens_to_add.unsqueeze(-1)], dim=-1) else: dec_outputs = model( dec_input_ids=dec_input_ids, dec_attention_mask=dec_attention_mask, cross_attention_mask=cross_attention_mask, enc_hidden_states=enc_hidden_states, past_key_values=past_key_values, ) past_key_values = dec_outputs["past_key_values"] lm_logits = dec_outputs["lm_logits"] logits = lm_logits[:, -1, :] / args.temperature prev_output_tokens = torch.cat([full_context, output_ids], dim=-1) logits = postprocess_next_token_scores( tokenizer=tokenizer, scores=logits, input_ids=prev_output_tokens, no_repeat_ngram_size=args.no_repeat_ngram_size, bad_words_ids=[[0]], cur_len=gen_len, min_length=args.min_generation_length, max_length=args.max_generation_length, eos_token_id=tokenizer.eos_id, repetition_penalty=args.repetition_penalty, batch_size=batch_size, num_beams=1, antonym_dict=antonym_dict, ) if args.sampling: logits = top_k_logits(logits, top_k=args.top_k, top_p=args.top_p) probs = F.softmax(logits.float(), dim=-1) next_token = torch.multinomial(probs, num_samples=1).squeeze(1) else: next_token = torch.argmax(logits, -1) tokens_to_add = next_token * unfinished_sents + tokenizer.pad_id * ( 1 - unfinished_sents ) dec_input_ids = tokens_to_add.unsqueeze(-1) output_ids = torch.cat([output_ids, tokens_to_add.unsqueeze(-1)], dim=-1) # let the current token attend to all previous tokens dec_attention_mask = torch.cat( [dec_attention_mask[:, :, -1:, :], dec_attention_mask[:, :, -1:, -1:]], dim=-1, ) cross_attention_mask = cross_attention_mask[:, :, -1:, :] gen_len += 1 unfinished_sents.mul_(tokens_to_add.ne(tokenizer.eos_id).long()) output_ids = output_ids.cpu().tolist() generation_token_ids_list = [] generation_str_list = [] for e in output_ids: generation_token_ids = ( e[: e.index(tokenizer.eos_id)] if tokenizer.eos_id in e else e ) generation_token_ids_list.append(generation_token_ids) generation_str_list.append(tokenizer.decode(generation_token_ids)) return generation_str_list, generation_token_ids_list def generate_beam( model_batch, full_context, model, tokenizer: EncDecTokenizer, args, device ): """ Since the context in model batch is truncated, we need full_context to store the tokens in the entire context. """ batch_size = args.batch_size num_beams = args.num_beams target_length = args.max_generation_length do_sample = args.sampling and (args.top_p > 0 or args.top_k > 0) vocab_size = tokenizer.vocab_size enc_input_ids = model_batch["enc_input_ids"] enc_attention_mask = model_batch["enc_attention_mask"] enc_input_length = enc_input_ids.size(-1) enc_input_ids = enc_input_ids.unsqueeze(1).expand( batch_size, num_beams, enc_input_length ) enc_attention_mask = enc_attention_mask.unsqueeze(1).expand( batch_size, num_beams, 1, enc_input_length, enc_input_length ) enc_input_ids = enc_input_ids.contiguous().view( batch_size * num_beams, enc_input_length ) enc_attention_mask = enc_attention_mask.contiguous().view( batch_size * num_beams, 1, enc_input_length, enc_input_length ) full_context = full_context.unsqueeze(1).expand( batch_size, num_beams, full_context.size(-1) ) full_context = full_context.contiguous().view( batch_size * num_beams, full_context.size(-1) ) enc_outputs = model( enc_input_ids=enc_input_ids, enc_attention_mask=enc_attention_mask, only_encoder=True, ) enc_hidden_states = enc_outputs["encoder_last_hidden_state"] dec_init_length = 1 # 1 for s_0 # for generating responses dec_input_ids = model_batch["dec_input_ids"][..., :dec_init_length] dec_attention_mask = model_batch["dec_attention_mask"][ ..., :dec_init_length, :dec_init_length ] # we use past_key_values, so only the current token mask is needed cross_attention_mask = model_batch["cross_attention_mask"][..., :dec_init_length, :] dec_input_ids = dec_input_ids.unsqueeze(1).expand( batch_size, num_beams, dec_init_length ) dec_attention_mask = dec_attention_mask.unsqueeze(1).expand( batch_size, num_beams, 1, dec_init_length, dec_init_length ) cross_attention_mask = cross_attention_mask.unsqueeze(1).expand( batch_size, num_beams, 1, dec_init_length, enc_input_length ) dec_input_ids = dec_input_ids.contiguous().view( batch_size * num_beams, dec_init_length ) dec_attention_mask = dec_attention_mask.contiguous().view( batch_size * num_beams, 1, dec_init_length, dec_init_length ) cross_attention_mask = cross_attention_mask.contiguous().view( batch_size * num_beams, 1, dec_init_length, enc_input_length ) done = [False for _ in range(batch_size)] output_ids = enc_input_ids.new_zeros( [enc_input_ids.size(0), 0] ) # not include the prompt past_key_values = None gen_len = 0 # construct antonym dict antonym_dict = None # generated hypotheses generated_hyps = [ BeamHypotheses( num_beams, target_length, args.length_penalty, early_stopping=args.early_stopping, tokenizer=tokenizer, ) for _ in range(batch_size) ] beam_scores = torch.zeros( (batch_size, num_beams), dtype=torch.float, device=dec_input_ids.device ) beam_scores = beam_scores.view(-1) # shape (batch_size * num_beams,) while gen_len < target_length: dec_outputs = model( dec_input_ids=dec_input_ids, dec_attention_mask=dec_attention_mask, cross_attention_mask=cross_attention_mask, enc_hidden_states=enc_hidden_states, past_key_values=past_key_values, ) past_key_values = dec_outputs["past_key_values"] lm_logits = dec_outputs["lm_logits"] logits = lm_logits[:, -1, :] / args.temperature scores = F.log_softmax(logits, dim=-1) prev_output_tokens = torch.cat([full_context, output_ids], dim=-1) scores = postprocess_next_token_scores( tokenizer=tokenizer, scores=scores, input_ids=prev_output_tokens, no_repeat_ngram_size=args.no_repeat_ngram_size, bad_words_ids=None, cur_len=gen_len, min_length=args.min_generation_length, max_length=args.max_generation_length, eos_token_id=tokenizer.eos_id, repetition_penalty=args.repetition_penalty, batch_size=batch_size, num_beams=num_beams, antonym_dict=antonym_dict, ) if do_sample: _scores = scores + beam_scores[:, None].expand_as(scores) if args.temperature != 1.0: _scores = _scores / args.temperature _scores = top_k_logits(_scores, top_k=args.top_k, top_p=args.top_p) _scores = _scores.contiguous().view(batch_size, num_beams * vocab_size) # Sample 2 next tokens for each beam (so we have some spare tokens and match output of greedy beam search) probs = F.softmax(_scores, dim=-1) next_tokens = torch.multinomial( probs, num_samples=2 * num_beams ) # (batch_size, num_beams * 2) # Compute next scores next_scores = torch.gather( _scores, -1, next_tokens ) # (batch_size, num_beams * 2) # sort the sampled vector to make sure that the first num_beams samples are the best next_scores, next_scores_indices = torch.sort( next_scores, descending=True, dim=1 ) next_tokens = torch.gather( next_tokens, -1, next_scores_indices ) # (batch_size, num_beams * 2) else: next_scores = scores + beam_scores[:, None].expand_as( scores ) # (batch_size * num_beams, vocab_size) # re-organize to group the beam together (we are keeping top hypothesis accross beams) next_scores = next_scores.view( batch_size, num_beams * vocab_size ) # (batch_size, num_beams * vocab_size) next_scores, next_tokens = torch.topk( next_scores, 2 * num_beams, dim=1, largest=True, sorted=True ) assert next_scores.size() == next_tokens.size() == (batch_size, 2 * num_beams) # next batch beam content next_batch_beam = [] for batch_idx in range(batch_size): # if we are done with this sentence, add a pad token if done[batch_idx]: assert ( len(generated_hyps[batch_idx]) >= num_beams ), "Batch can only be done if at least {} beams have been generated".format( num_beams ) next_batch_beam.extend( [(0, tokenizer.pad_id, 0)] * num_beams ) # pad the batch continue # next sentence beam content, this will get added to next_batch_beam next_sent_beam = [] # next tokens for this sentence for beam_token_rank, (beam_token_id, beam_token_score) in enumerate( zip(next_tokens[batch_idx], next_scores[batch_idx]) ): # get beam and token IDs beam_id = beam_token_id // vocab_size token_id = beam_token_id % vocab_size effective_beam_id = batch_idx * num_beams + beam_id # add to generated hypotheses if end of sentence if token_id.item() == tokenizer.eos_id: # if beam_token does not belong to top num_beams tokens, it should not be added is_beam_token_worse_than_top_num_beams = ( beam_token_rank >= num_beams ) if is_beam_token_worse_than_top_num_beams: continue generated_hyps[batch_idx].add( output_ids[effective_beam_id].clone(), beam_token_score.item(), ) else: # add next predicted token since it is not eos_token next_sent_beam.append( (beam_token_score, token_id, effective_beam_id) ) # once the beam for next step is full, don't add more tokens to it. if len(next_sent_beam) == num_beams: break # Check if we are done so that we can save a pad step if all(done) done[batch_idx] = done[batch_idx] or generated_hyps[batch_idx].is_done( next_scores[batch_idx].max().item(), gen_len ) # update next beam content assert len(next_sent_beam) == num_beams, "Beam should always be full" next_batch_beam.extend(next_sent_beam) assert len(next_batch_beam) == num_beams * ( batch_idx + 1 ), "We should have added num_beams each step" # stop when we are done with each sentence if all(done): break # sanity check / prepare next batch assert len(next_batch_beam) == batch_size * num_beams beam_scores = torch.tensor( [x[0] for x in next_batch_beam], device=dec_input_ids.device ) beam_tokens = torch.tensor( [x[1] for x in next_batch_beam], device=dec_input_ids.device ) beam_idx = torch.tensor( [x[2] for x in next_batch_beam], device=dec_input_ids.device ) # re-order batch and update current length output_ids = output_ids[beam_idx, :] output_ids = torch.cat([output_ids, beam_tokens.unsqueeze(1)], dim=-1) dec_input_ids = beam_tokens.unsqueeze(1) dec_attention_mask = torch.cat( [dec_attention_mask[:, :, -1:, :], dec_attention_mask[:, :, -1:, -1:]], dim=-1, ) cross_attention_mask = cross_attention_mask[:, :, -1:, :] # past_key_values = num_layer * 2 * (2, beam_size, 32, prefix_len, 64) first 2: self/cross attention, second 2: key/value past_key_values = [ [ torch.index_select(layer_past_type, 1, beam_idx) for layer_past_type in layer_past ] for layer_past in past_key_values ] gen_len += 1 # finalize all open beam hypotheses and add to generated hypotheses for batch_idx in range(batch_size): if done[batch_idx]: continue # need to add best num_beams hypotheses to generated hyps for beam_id in range(num_beams): effective_beam_id = batch_idx * num_beams + beam_id final_score = beam_scores[effective_beam_id].item() final_tokens = output_ids[effective_beam_id] generated_hyps[batch_idx].add(final_tokens, final_score) best = [] best_ids = [] # retrieve best hypotheses for i, hypotheses in enumerate(generated_hyps): sorted_hyps = sorted(hypotheses.beams, key=lambda x: x[0]) best_hyp = sorted_hyps.pop()[1] best.append(tokenizer.decode(best_hyp.cpu().tolist())) best_ids.append(best_hyp.cpu().tolist()) return best, best_ids
26,394
36.439716
139
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/train_t0.py
# coding=utf-8 """Training Enc-Dec""" import os import torch import json import numpy as np from arguments import get_args from data_utils.T0Datasets import T0Dataset from data_utils.data_config import ( DATA_GROUP_CONFIG, DATA_NO_EVAL, DATA_NO_VALID, DATA_NO_TRAIN, DATA_EVAL_GEN, DATA_RETRIEVAL_AUGMENTATION, RA_PASSAGE_NUM, ) from data_utils import ANSWER_POST_FN from tokenization_t5 import EncDecTokenizer import mpu from utils import save_checkpoint from utils import print_args from utils import print_rank_0, save_rank_0 from utils import save_preds_t0 from utils import setup_model_and_optimizer, set_random_seed, initialize_distributed from samplers import DistributedBatchSampler, RandomSampler from data_utils import * from metrics import * from torch.utils.data import DataLoader, SequentialSampler from generation_utils import generate_beam, generate_no_beam from promptsource.templates import TemplateCollection from tqdm import tqdm def forward_step( args, model_batch, no_model_batch, model, device, keep_enc_hidden=False, do_infer=False, ): for k in model_batch: model_batch[k] = model_batch[k].to(device) for k in no_model_batch: no_model_batch[k] = no_model_batch[k].to(device) if args.FiD: batch_size, _, sequence_length = model_batch["passage_input_ids"].size() enc_outputs = model( enc_input_ids=model_batch["passage_input_ids"].view( batch_size * args.passage_num, sequence_length ), enc_attention_mask=model_batch["passage_attention_mask"].view( batch_size * args.passage_num, 1, sequence_length, sequence_length ), only_encoder=True, ) enc_hidden_states = enc_outputs["encoder_last_hidden_state"].view( batch_size, sequence_length * args.passage_num, -1 ) new_model_batch = {} for k in model_batch: if k not in ["passage_input_ids", "passage_attention_mask"]: new_model_batch[k] = model_batch[k] output = model(**new_model_batch, enc_hidden_states=enc_hidden_states) else: if keep_enc_hidden: enc_outputs = model(**model_batch, only_encoder=True) enc_hidden_states = enc_outputs["encoder_last_hidden_state"] output = model(**model_batch, enc_hidden_states=enc_hidden_states) else: output = model(**model_batch) logits = output["lm_logits"] forw_out = {"logits": logits} if keep_enc_hidden: forw_out["enc_hidden_states"] = enc_hidden_states if not do_infer: losses = mpu.vocab_parallel_cross_entropy( logits.contiguous().float(), no_model_batch["labels"] ) loss_mask = no_model_batch["loss_mask"] losses = (losses * loss_mask).sum(-1) / loss_mask.sum(-1) loss = losses.mean() forw_out["loss"] = loss forw_out["loss_batch"] = losses return forw_out def backward_step(args, loss, model, optimizer): # backward if args.deepspeed: model.backward(loss) else: optimizer.zero_grad() if args.fp16: optimizer.backward(loss, update_master_grads=False) else: loss.backward() # Update master gradients. if not args.deepspeed: if args.fp16: optimizer.update_master_grads() # Clipping gradients helps prevent the exploding gradient. if args.clip_grad > 0: if not args.fp16: mpu.clip_grad_norm(model.parameters(), args.clip_grad) else: optimizer.clip_master_grads(args.clip_grad) def train( args, data_names, tokenizer: EncDecTokenizer, model, optimizer, lr_scheduler, train_data_utils, dev_data_utils, device, ): """Train the model.""" train_dataloader, train_dataset, random_sampler = train_data_utils # Turn on training mode which enables dropout. model.train() # Tracking loss. total_loss = 0.0 step, global_step = 1, 1 best_scores = [] for e in range(args.epochs): model.train() random_sampler.set_epoch(e) train_dataset.set_epoch(e) for model_batch, no_model_batch, _, _ in train_dataloader: forw_out = forward_step(args, model_batch, no_model_batch, model, device) loss = forw_out["loss"] if torch.distributed.get_rank() == 0: print(loss) backward_step(args, loss, model, optimizer) # Update losses. total_loss += loss.item() if args.deepspeed: model.step() else: optimizer.step() if not (args.fp16 and optimizer.overflow): lr_scheduler.step() # Logging. if ( global_step % args.log_interval == 0 and step % args.gradient_accumulation_steps == 0 ): learning_rate = optimizer.param_groups[0]["lr"] avg_lm_loss = total_loss / ( args.log_interval * args.gradient_accumulation_steps ) log_string = "epoch {:3d}/{:3d} |".format(e, args.epochs) log_string += " global iteration {:8d}/{:8d} |".format( global_step, args.train_iters ) log_string += " learning rate {:.3} |".format(learning_rate) log_string += " lm loss {:.6} |".format(avg_lm_loss) if args.fp16: log_string += " loss scale {:.1f} |".format( optimizer.cur_scale if args.deepspeed else optimizer.loss_scale ) print_rank_0(log_string) save_rank_0(args, log_string) total_loss = 0.0 # Checkpointing if ( args.save and args.save_interval and global_step % args.save_interval == 0 and step % args.gradient_accumulation_steps == 0 ): save_dir_path = os.path.join(args.save, str(global_step)) if torch.distributed.get_rank() == 0: os.makedirs(save_dir_path, exist_ok=True) save_checkpoint( global_step, model, optimizer, lr_scheduler, args, save_dir=save_dir_path, ) # Evaluation if ( args.eval_interval and global_step % args.eval_interval == 0 and step % args.gradient_accumulation_steps == 0 and args.do_valid ): prefix = "iteration {} | ".format(global_step) metric_values = [] for name, dev_data_util_prompt in dev_data_utils.items(): if DATA_CONFIG[name].get("selfsup", False): if DATA_CONFIG[name]["type"] == "gen": dev_dataloader, dev_dataset, _ = dev_data_util_prompt[0] dev_loss = evaluate_lm( args, tokenizer, name, dev_dataset, dev_dataloader, model, device, mode="dev", train_step=global_step, save_res=True, ) log_string = ( prefix + name + " | dev_loss: " + str(np.mean(dev_loss)) ) print_rank_0(log_string) save_rank_0(args, log_string) else: dev_dataloader, dev_dataset, _ = dev_data_util_prompt[0] dev_loss, dev_res, dev_preds, dev_labels = evaluate_rank( args, tokenizer, name, dev_dataset, dev_dataloader, model, device, mode="dev", train_step=global_step, save_res=True, ) log_string = ( prefix + name + " | dev_loss: " + str(np.mean(dev_loss)) + " | dev res: " + str(dev_res) ) print_rank_0(log_string) save_rank_0(args, log_string) else: dev_res_prompt = [] dev_loss_prompt = [] dev_preds_prompt = [] dev_labels_prompt = [] dev_prompt_names = [] for pid, dev_data_util in enumerate(dev_data_util_prompt): dev_dataloader, dev_dataset, _ = dev_data_util dev_prompt_names.append( dev_dataset.all_data[name]["prompt_names"][0] ) if ( dev_dataset.data_prompts[name][0].answer_choices is not None ): eval_func = evaluate_rank else: eval_func = evaluate_gen dev_loss, dev_res, dev_preds, dev_labels = eval_func( args, tokenizer, name, dev_dataset, dev_dataloader, model, device, mode="dev", train_step=global_step, save_res=True, ) dev_loss_prompt.append(dev_loss) dev_res_prompt.append(dev_res) dev_preds_prompt.append(dev_preds) dev_labels_prompt.append(dev_labels) log_string = ( prefix + name + " | dev_loss: " + str(np.mean(dev_loss_prompt)) + " | dev res: " + str(dev_res_prompt) ) print_rank_0(log_string) save_rank_0(args, log_string) save_preds_t0( args, name, dev_prompt_names, global_step, dev_res_prompt, dev_preds_prompt, dev_labels_prompt, ) values = [ v for dev_res in dev_res_prompt for v in dev_res.values() ] metric_values.extend(values) if len(metric_values) != 0: metric_avg = sum(metric_values) / len(metric_values) log_string = prefix + "Average: " + str(metric_avg) print_rank_0(log_string) save_rank_0(args, log_string) model.train() step += 1 if step % args.gradient_accumulation_steps == 0: global_step += 1 return global_step def evaluate_lm( args, tokenizer: EncDecTokenizer, name, eval_dataset: T0Dataset, eval_data_loader, model, device, mode="dev", train_step=0, save_res=False, ): model.eval() total_loss = 0.0 step = 0 with torch.no_grad(): for model_batch, no_model_batch, _, _ in eval_data_loader: for k in model_batch: model_batch[k] = model_batch[k].to(device) for k in no_model_batch: no_model_batch[k] = no_model_batch[k].to(device) forw_out = forward_step( args, model_batch, no_model_batch, model, device, keep_enc_hidden=True ) loss = forw_out["loss"].item() if "loss" in forw_out else 0 total_loss += loss step += 1 if step == 0: if torch.distributed.get_rank() == 0: print(name) print(eval_dataset.data_prompts[name][0].name) print(len(eval_dataset)) total_loss /= step return total_loss def evaluate_gen( args, tokenizer: EncDecTokenizer, name, eval_dataset: T0Dataset, eval_data_loader, model, device, mode="dev", train_step=0, save_res=False, ): # Turn on evaluation mode which disables dropout. model.eval() total_loss = 0.0 step = 0 all_output_ids = [] all_idxs = [] if args.FiD: all_scores = [] with torch.no_grad(): if not args.FiD: for model_batch, no_model_batch, _, _ in eval_data_loader: for k in model_batch: model_batch[k] = model_batch[k].to(device) for k in no_model_batch: no_model_batch[k] = no_model_batch[k].to(device) forw_out = forward_step( args, model_batch, no_model_batch, model, device, keep_enc_hidden=True, ) loss = forw_out["loss"].item() if "loss" in forw_out else 0 total_loss += loss step += 1 if step == 0: if torch.distributed.get_rank() == 0: print(name) print(eval_dataset.data_prompts[name][0].name) print(len(eval_dataset)) total_loss /= step for e, (model_batch, no_model_batch, _, _) in tqdm( enumerate(eval_data_loader), desc="Evaluating" ): for k in model_batch: model_batch[k] = model_batch[k].to(device) for k in no_model_batch: no_model_batch[k] = no_model_batch[k].to(device) if args.num_beams == 1: generation_str_list, generation_id_list = generate_no_beam( model_batch, model_batch["enc_input_ids"], model, tokenizer, args, device, ) if args.FiD: scores = model.module.module.module.get_crossattention_scores( model_batch["passage_attention_mask"][:, :, 0, 0, :].bool() ) all_scores.append(scores) else: generation_str_list, generation_id_list = generate_beam( model_batch, model_batch["enc_input_ids"], model, tokenizer, args, device, ) output_ids = [ x + [tokenizer.pad_id] + (args.max_generation_length - len(x)) * [tokenizer.pad_id] for x in generation_id_list ] output_ids = torch.tensor(output_ids).to(device) tmp_idxs = [ torch.zeros_like(no_model_batch["idxs"]).to(device) for _ in range(mpu.get_data_parallel_world_size()) ] torch.distributed.all_gather( tmp_idxs, no_model_batch["idxs"].data, group=mpu.get_data_parallel_group(), ) tmp_output_ids = [ torch.zeros_like(output_ids).to(device) for _ in range(mpu.get_data_parallel_world_size()) ] torch.distributed.all_gather( tmp_output_ids, output_ids.data, group=mpu.get_data_parallel_group() ) all_idxs.extend(tmp_idxs) all_output_ids.extend(tmp_output_ids) all_output_ids = torch.cat(all_output_ids, dim=0).cpu().tolist() all_idxs = torch.cat(all_idxs, dim=0).tolist() if args.FiD: all_scores = torch.cat(all_scores, dim=0) print(all_scores.size()) torch.save( all_scores, os.path.join(args.save, f"stored_FiD_scores.pt"), ) all_preds_real = [] all_labels_real = [] eval_res = {} for idxs, output_ids in zip(all_idxs, all_output_ids): _, _, sid = idxs output_ids = ( output_ids[: output_ids.index(tokenizer.pad_id)] if tokenizer.pad_id in output_ids else output_ids ) all_preds_real.append(tokenizer.decode(output_ids)) all_labels_real.append(eval_dataset.all_data[name]["data"][sid]["answer"]) metric_names = eval_dataset.data_prompts[name][0].metadata.metrics for metric_name in metric_names: if (name, metric_name) in ANSWER_POST_FN: all_labels_real, all_preds_real = ANSWER_POST_FN[(name, metric_name)]( all_labels_real, all_preds_real ) res = T0_METRICS[metric_name](all_labels_real, all_preds_real) eval_res.update(res) # if save_res: # save_preds_t0(args, name, eval_dataset, train_step, eval_res, all_preds_real, all_labels_real) return total_loss, eval_res, all_preds_real, all_labels_real def evaluate_rank( args, tokenizer: EncDecTokenizer, name, eval_dataset: T0Dataset, eval_data_loader, model, device, mode="dev", train_step=0, save_res=False, ): """Evaluation.""" # Turn on evaluation mode which disables dropout. model.eval() total_loss = 0.0 step = 0 all_idxs = [] all_preds = [] if args.prompt_tune: all_prompt = torch.load( f"data/{args.data_names}/cache/stored_dembeds.pt", map_location=lambda storage, loc: storage, ) if args.FiD: all_scores = [] tmp_pos_index = torch.arange(1, eval_dataset.max_cand_len + 1, device=device) with torch.no_grad(): for ( model_batch, no_model_batch, cand_model_batch, cand_no_model_batch, ) in tqdm(eval_data_loader, desc="Evaluating"): for k in model_batch: model_batch[k] = model_batch[k].to(device) for k in no_model_batch: no_model_batch[k] = no_model_batch[k].to(device) for k in cand_model_batch: cand_model_batch[k] = cand_model_batch[k].to(device) for k in cand_no_model_batch: cand_no_model_batch[k] = cand_no_model_batch[k].to(device) if args.prompt_tune: prompt = all_prompt[step] model.module.module.module.encoder.load_prompt_embeds(prompt) if args.FiD: model.module.module.module.reset_score_storage() batch_size, _, sequence_length = model_batch["passage_input_ids"].size() enc_outputs = model( enc_input_ids=model_batch["passage_input_ids"].view( batch_size * args.passage_num, sequence_length ), enc_attention_mask=model_batch["passage_attention_mask"].view( batch_size * args.passage_num, 1, sequence_length, sequence_length, ), only_encoder=True, ) enc_hidden_states = enc_outputs["encoder_last_hidden_state"].view( batch_size, sequence_length * args.passage_num, -1 ) else: enc_outputs = model(**model_batch, only_encoder=True) enc_hidden_states = enc_outputs["encoder_last_hidden_state"] # enc_hidden_states[0, :10, :] = prompt output = model(**cand_model_batch, enc_hidden_states=enc_hidden_states) if args.FiD: scores = model.module.module.module.get_crossattention_scores( model_batch["passage_attention_mask"][:, :, 0, 0, :].bool() ) all_scores.append(scores) logits = output["lm_logits"] losses = mpu.vocab_parallel_cross_entropy( logits.contiguous().float(), cand_no_model_batch["target_ids"] ) loss_mask = cand_no_model_batch["loss_mask"] losses = losses * loss_mask gold_loss = 0 preds = [] for samp_loss, cand_pos, cand_label in zip( losses, cand_no_model_batch["pos"], cand_no_model_batch["labels"] ): cum_loss = torch.cumsum(samp_loss, dim=0) # print(samp_loss) sum_loss = torch.masked_select(cum_loss, cand_pos) cand_loss = torch.diff( sum_loss, dim=0, prepend=torch.zeros(1, device=device) ) # print("cand loss", cand_loss) # print("samp loss", samp_loss) cand_pos_idx = torch.masked_select(tmp_pos_index, cand_pos) cand_lens = torch.diff( cand_pos_idx, dim=0, prepend=torch.zeros(1, device=device) ) # print("cand_lens", cand_lens) if args.no_norm_cand_loss: normed_cand_loss = cand_loss else: normed_cand_loss = cand_loss / cand_lens # print(normed_cand_loss) # exit(0) max_res = torch.min(normed_cand_loss, dim=0) preds.append(max_res.indices.item()) gold_loss += normed_cand_loss[cand_label.item()].item() gold_loss /= len(losses) total_loss += gold_loss preds = torch.tensor(preds, dtype=torch.long, device=device) gathered_preds = [ torch.zeros_like(preds) for _ in range(mpu.get_data_parallel_world_size()) ] torch.distributed.all_gather( gathered_preds, preds.contiguous(), mpu.get_data_parallel_group() ) all_preds.extend(gathered_preds) gathered_idx = [ torch.zeros_like(no_model_batch["idxs"]) for _ in range(mpu.get_data_parallel_world_size()) ] torch.distributed.all_gather( gathered_idx, no_model_batch["idxs"].contiguous(), mpu.get_data_parallel_group(), ) all_idxs.extend(gathered_idx) step += 1 if step == 0: if torch.distributed.get_rank() == 0: print(name) print(eval_dataset.data_prompts[name][0].name) print(len(eval_dataset)) total_loss /= step all_idxs = torch.cat(all_idxs, dim=0).cpu().tolist() all_preds = torch.cat(all_preds, dim=0).cpu().tolist() if args.FiD: all_scores = torch.cat(all_scores, dim=0) print(all_scores.size()) torch.save( all_scores, os.path.join(args.save, f"stored_FiD_scores.pt"), ) all_preds_real = [] all_labels_real = [] eval_res = {} for idxs, pred in zip(all_idxs, all_preds): _, _, sid = idxs sample = eval_dataset.all_data[name]["data"][sid] all_preds_real.append(sample["options"][pred]) all_labels_real.append(sample["answer"]) if eval_dataset.data_prompts[name] is None: # selfsup metric_names = ["Other"] else: metric_names = eval_dataset.data_prompts[name][0].metadata.metrics for metric_name in metric_names: if (name, metric_name) in ANSWER_POST_FN: all_labels_real, all_preds_real = ANSWER_POST_FN[(name, metric_name)]( all_labels_real, all_preds_real ) res = T0_METRICS[metric_name](all_labels_real, all_preds_real) eval_res.update(res) # if save_res: # save_preds_t0(args, name, eval_dataset, train_step, eval_res, all_preds_real, all_labels_real) return total_loss, eval_res, all_preds_real, all_labels_real def load_data( args, data_prompts, split, tokenizer, ratio=1, num=-1, few_data_names=None, drop_last=True, ): # Data parallel arguments. world_size = mpu.get_data_parallel_world_size() rank = mpu.get_data_parallel_rank() if args.eval_batch_size is None: args.eval_batch_size = args.batch_size if split == "train": global_batch_size = args.batch_size * world_size elif split == "validation": global_batch_size = args.dev_batch_size * world_size else: global_batch_size = args.eval_batch_size * world_size num_workers = args.num_workers dataset = T0Dataset( args, tokenizer, data_prompts, split, ratio=ratio, few_data_names=few_data_names, num=num, ) if split == "train": sampler = RandomSampler(dataset) sampler.set_seed(args.seed) else: sampler = SequentialSampler(dataset) batch_sampler = DistributedBatchSampler( sampler=sampler, batch_size=global_batch_size, drop_last=drop_last, rank=rank, world_size=world_size, ) data_loader = DataLoader( dataset, batch_sampler=batch_sampler, num_workers=num_workers, pin_memory=True, collate_fn=dataset.collate, ) # Torch dataloader. return data_loader, dataset, sampler def main(): """Main training program.""" # Disable CuDNN. torch.backends.cudnn.enabled = False # Arguments. args = get_args() os.makedirs(args.save, exist_ok=True) # Pytorch distributed. initialize_distributed(args) if torch.distributed.get_rank() == 0: print("Training Enc-Dec model") print_args(args) with open(os.path.join(args.save, "args.json"), "w") as f: json.dump(vars(args), f) # Random seeds for reproducability. set_random_seed(args.seed) device = torch.cuda.current_device() # setup tokenizer tokenizer = EncDecTokenizer( os.path.join(args.tokenizer_path, "spiece.model"), pad_token=args.pad_token ) with open(args.deepspeed_config, "r") as f: ds_config = json.load(f) ds_config["gradient_accumulation_steps"] = args.gradient_accumulation_steps ds_config["train_micro_batch_size_per_gpu"] = args.batch_size data_group_names = args.data_names.split("-") data_names = [] for name in data_group_names: if name in DATA_GROUP_CONFIG: data_names.extend(DATA_GROUP_CONFIG[name]) else: data_names.append(name) few_data_names = None if args.few_data_names is not None: few_data_group_names = args.few_data_names.split("-") few_data_names = [] for name in few_data_group_names: if name in DATA_GROUP_CONFIG: few_data_names.extend(DATA_GROUP_CONFIG[name]) else: few_data_names.append(name) data_prompts = {} for name in data_names: for ra_name in DATA_RETRIEVAL_AUGMENTATION: if ra_name in name: DATA_CONFIG[name] = DATA_CONFIG[ra_name] DATA_CONFIG[name]["data_dir"] = f"data/{name}/cache" break if name in RA_PASSAGE_NUM: args.passage_num = RA_PASSAGE_NUM[name] if DATA_CONFIG[name].get("selfsup", False): data_prompts[name] = None else: collection = TemplateCollection() if "name" in DATA_CONFIG[name]: templates = collection.get_dataset( DATA_CONFIG[name]["name"][0], DATA_CONFIG[name]["name"][1] ) else: templates = collection.get_dataset(name, None) data_prompts[name] = [] for template_name in templates.all_template_names: if "mmlu" in name or "ai2_arc" in name: if template_name == "heres_a_problem": data_prompts[name].append(templates[template_name]) continue if ( "popQA" in name or "marco_qa" in name or "kilt" in name ) and template_name != "question_with_instruction": continue if (name, template_name) not in DATA_NO_TRAIN: if "popQA" in name: prompt = templates[template_name] prompt.metadata.metrics = ["popQA"] data_prompts[name].append(prompt) elif "marco_qa" in name: prompt = templates[template_name] prompt.metadata.metrics = ["BLEU", "ROUGE"] data_prompts[name].append(prompt) elif "kilt" in name: prompt = templates[template_name] prompt.metadata.metrics = ["Trivia QA"] data_prompts[name].append(prompt) else: data_prompts[name].append(templates[template_name]) print("All Data group:", data_group_names, "All Data:", data_names) if args.do_train: train_data_utils = load_data( args, data_prompts, "train", tokenizer, ratio=args.train_ratio, few_data_names=few_data_names, num=args.train_num, ) dev_data_utils = {} for name in data_prompts: if DATA_CONFIG[name].get("selfsup", False): dev_data_utils[name] = [ load_data( args, {name: None}, "validation", tokenizer, ratio=args.dev_ratio, few_data_names=few_data_names, num=args.dev_num, ) ] else: if (name, None) not in DATA_NO_VALID: dev_data_utils[name] = [] for template in data_prompts[name]: if (name, template.name) not in DATA_NO_VALID: dev_data_utils[name].append( load_data( args, {name: [template]}, "validation", tokenizer, ratio=args.dev_ratio, few_data_names=few_data_names, num=args.dev_num, ) ) if args.train_iters == -1: args.train_iters = ( len(train_data_utils[1]) * args.epochs // ( mpu.get_data_parallel_world_size() * args.batch_size * args.gradient_accumulation_steps ) ) if args.save_interval == -1: args.save_interval = len(train_data_utils[1]) // ( mpu.get_data_parallel_world_size() * args.batch_size * args.gradient_accumulation_steps ) if args.eval_interval == -1: args.eval_interval = len(train_data_utils[1]) // ( mpu.get_data_parallel_world_size() * args.batch_size * args.gradient_accumulation_steps ) else: args.train_iters = 10 # a magic number log_string = "Total train epochs {} | Total train iters {} | ".format( args.epochs, args.train_iters ) print_rank_0(log_string) save_rank_0(args, log_string) # Model, optimizer, and learning rate. prompt_config = None if args.prompt_tune: with open(args.prompt_config, "r") as f: prompt_config = json.load(f) model, optimizer, lr_scheduler = setup_model_and_optimizer( args, tokenizer.vocab_size, ds_config, set_optim=args.do_train, prompt_config=prompt_config, ) if args.do_train: train( args, data_names, tokenizer, model, optimizer, lr_scheduler, train_data_utils, dev_data_utils, device, ) if args.do_eval: for name in data_names: if (name, None) not in DATA_NO_EVAL: eval_loss_prompt = [] eval_res_prompt = [] eval_preds_prompt = [] eval_labels_prompt = [] eval_prompt_names = [] for template in data_prompts[name]: if (name, template.name) not in DATA_NO_EVAL: eval_data_utils = load_data( args, {name: [template]}, "validation", tokenizer, ratio=args.test_ratio, few_data_names=few_data_names, num=args.test_num, ) eval_dataloader, eval_dataset, _ = eval_data_utils eval_prompt_names.append( eval_dataset.all_data[name]["prompt_names"][0] ) if ( eval_dataset.data_prompts[name][0].answer_choices is not None and (name, template.name) not in DATA_EVAL_GEN ): eval_func = evaluate_rank else: eval_func = evaluate_gen eval_loss, eval_res, eval_preds, eval_labels = eval_func( args, tokenizer, name, eval_dataset, eval_dataloader, model, device, mode="test", save_res=True, ) eval_loss_prompt.append(eval_loss) eval_res_prompt.append(eval_res) eval_preds_prompt.append(eval_preds) eval_labels_prompt.append(eval_labels) avg_eval_res = { k: np.mean([res[k] for res in eval_res_prompt]) for k in eval_res_prompt[0] } log_string = ( "Eval result: loss: {:.6} | avg_res: {} | all_res: {}".format( np.mean(eval_loss_prompt), avg_eval_res, eval_res_prompt ) ) print_rank_0(log_string) save_rank_0(args, log_string) save_preds_t0( args, name, eval_prompt_names, 0, eval_res_prompt, eval_preds_prompt, eval_labels_prompt, ) if __name__ == "__main__": main()
36,843
34.022814
104
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/metrics.py
from sklearn.metrics import f1_score import collections import numpy as np from generation_metrics import Metric from t5.evaluation import metrics def popqa(all_labels_real, all_preds_real): assert len(all_labels_real) == len(all_preds_real) accuracy = [] for possible_answers, pred in zip(all_labels_real, all_preds_real): is_correct = False for pa in possible_answers: if pa in pred or pa.lower() in pred or pa.capitalize() in pred: is_correct = True accuracy.append(is_correct) return {"accuracy": 100 * np.mean(accuracy)} T0_METRICS = { "BLEU": metrics.bleu, "ROUGE": metrics.rouge, "Span Squad": metrics.span_squad, "Squad": metrics.squad, "Trivia QA": metrics.trivia_qa, "Accuracy": metrics.accuracy, "Spearman Correlation": metrics.spearman_corrcoef, "Other": metrics.accuracy, "popQA": popqa } def _metric_max_over_ground_truths(metric_fn, ground_truths, prediction): """Computes the maximum of the metric over all ground truths.""" return max( [metric_fn(ground_truth, prediction) for ground_truth in ground_truths] ) def _str_em(target, prediction): return target == prediction def _str_f1(target, prediction): """Computes token f1 score for a single target and prediction.""" prediction_tokens = prediction.split() target_tokens = target.split() common = (collections.Counter(prediction_tokens) & collections.Counter(target_tokens)) num_same = sum(common.values()) if num_same == 0: return 0 precision = 1.0 * num_same / len(prediction_tokens) recall = 1.0 * num_same / len(target_tokens) f1 = 100 * (2 * precision * recall) / (precision + recall) return f1 def acc_single_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[Int] ''' acc = 100 * np.mean([int(p == l) for p, l in zip(all_preds, all_labels)]) return {"acc": acc} def acc_multi_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[List[Int]] ''' acc = 100 * np.mean([int(any([p == ll for ll in l])) for p, l in zip(all_preds, all_labels)]) return {"acc": acc} def f1_single_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[Int] ''' f1_macro = 100 * f1_score(all_labels, all_preds, average="macro") return {"f1": f1_macro} def str_em_single_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[Int] ''' em = 100 * np.mean([_str_em(p, l) for p, l in zip(all_preds, all_labels)]) return {"em": em} def str_em_multi_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[List[Int]] ''' em = 100 * np.mean([_metric_max_over_ground_truths(_str_em, l, p) for p, l in zip(all_preds, all_labels)]) return {"em": em} def str_f1_single_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[Int] ''' f1 = 100 * np.mean([_str_f1(p, l) for p, l in zip(all_preds, all_labels)]) return {"f1": f1} def str_f1_multi_ref(all_preds, all_labels): ''' all_preds: List[Int] all_labels: List[List[Int]] ''' f1 = 100 * np.mean([_metric_max_over_ground_truths(_str_f1, l, p) for p, l in zip(all_preds, all_labels)]) return {"f1": f1} def rouge_single_ref(all_preds, all_labels): metric = Metric() for l, p in zip(all_labels, all_preds): metric.forword([l.split()], p.split()) metric_res, *_ = metric.close() return metric_res def rouge_multi_ref(all_preds, all_labels): metric = Metric() for l, p in zip(all_labels, all_preds): metric.forword([ll.split() for ll in l], p.split()) metric_res, *_ = metric.close() return metric_res # Multi-rouge/multi-bleu. When there are multiple references, we want to get the # rouge score that is highest. According to the authors, this is how it was done # in the GEM paper. # Source: https://github.com/google/BIG-bench/blob/main/bigbench/api/task_metrics.py def rouge_fn(targets, predictions): """Computes ROUGE by taking the max ROUGE-N per reference and N.""" # Following strategy from https://www.aclweb.org/anthology/W04-1013/. # Identify best reference per response and ROUGE type. rouge_types = ["rouge1", "rouge2", "rougeLsum"] max_references = {rouge_type: [] for rouge_type in rouge_types} for targ_for_resp, resp in zip(targets, predictions): # Compute individual scores per example/ref pair. resp_scores = [metrics.rouge([t], [resp]) for t in targ_for_resp] # Find best scoring references for generated output and ROUGE type. for rouge_type in rouge_types: best_score_index = max(range(len(resp_scores)), key=lambda x: resp_scores[x][rouge_type]) best_ref = targ_for_resp[best_score_index] # Add the reference to the new reference list. max_references[rouge_type].append(best_ref) # Compute metric for each of the reference lists for a ref type. results = {} for rouge_type in rouge_types: results[rouge_type] = metrics.rouge(max_references[rouge_type], predictions)[rouge_type] return results
5,252
31.226994
110
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/samplers.py
# coding=utf-8 """Batch samplers that work with either random or sequential data samplers.""" import torch from torch.utils import data class RandomSampler(data.sampler.Sampler): """Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler, but this class lets the user set an epoch like DistributedSampler Samples elements randomly. If without replacement, then sample from a shuffled dataset. If with replacement, then user can specify ``num_samples`` to draw. Arguments: data_source (Dataset): dataset to sample from num_samples (int): number of samples to draw, default=len(dataset) replacement (bool): samples are drawn with replacement if ``True``, default=False """ def __init__(self, data_source, replacement=False, num_samples=None, diff_order=False): self.data_source = data_source self.replacement = replacement self._num_samples = num_samples self.epoch = -1 self.seed = -1 self.diff_order = diff_order if self._num_samples is not None and replacement is False: raise ValueError("With replacement=False, num_samples should not " "be specified, since a random permute will be " "performed.") if not isinstance(self.num_samples, int) or self.num_samples <= 0: raise ValueError("num_samples should be a positive integer " "value, but got num_samples={}".format( self.num_samples)) if not isinstance(self.replacement, bool): raise ValueError("replacement should be a boolean value, but got " "replacement={}".format(self.replacement)) @property def num_samples(self): # dataset size might change at runtime if self._num_samples is None: return len(self.data_source) return self._num_samples def __iter__(self): n = len(self.data_source) g = torch.Generator() if self.diff_order: if self.epoch >= 0 and self.seed >= 0: g.manual_seed(self.epoch + self.seed) elif self.epoch >= 0: g.manual_seed(self.epoch) elif self.seed >= 0: g.manual_seed(self.seed) else: if self.seed >= 0 and self.seed != 1234: # hack g.manual_seed(self.seed) if self.replacement: return iter(torch.randint(high=n, size=(self.num_samples,), dtype=torch.int64, generator=g).tolist()) return iter(torch.randperm(n, generator=g).tolist()) def __len__(self): return self.num_samples def set_epoch(self, epoch): self.epoch = epoch def set_seed(self, seed): self.seed = seed class DistributedBatchSampler(data.sampler.BatchSampler): """Similar to normal implementation of distributed sampler, except implementation is at the batch sampler level, instead of just the sampler level. This allows wrapping of arbitrary data samplers (sequential, random, WeightedRandomSampler, etc.) with this batch sampler. The `interleave` argument specifies how to distribute a batch. A value of True combined with the above random sampler is equivalent to pytorch's torch.utils.data.distributed.DistributedSampler. For the following batch [0,1,2,3,4,5,6,7] and data parallelism of 2 specifying True will result in the following samples for each gpu: GPU0: [0,2,4,6] GPU1: [1,3,5,7] specifying False will result in the following samples: GPU0: [0,1,2,3] GPU1: [4,5,6,7]""" def __init__(self, sampler, batch_size, drop_last, rank=-1, world_size=2, wrap_last=False, interleave=False): super(DistributedBatchSampler, self).__init__(sampler, batch_size, drop_last) if rank == -1: assert False, 'should not be here' rank = torch.distributed.get_rank() self.rank = rank self.world_size = world_size self.sampler.wrap_around = 0 self.wrap_around = 0 self.wrap_last = wrap_last self.start_iter = 0 self.interleave = interleave def __iter__(self): batch = [] i = 0 for idx in self.data_iterator(self.sampler, wrap_around=False): batch.append(idx) if len(batch) == self.batch_size: tbatch = self._batch(batch) if i >= self.start_iter: yield tbatch self.start_iter = 0 i += 1 batch = [] batch_len = len(batch) if batch_len > 0 and not self.drop_last: if self.wrap_last: self.sampler.wrap_around -= (self.batch_size) self.wrap_around += (len(batch)) self.wrap_around %= self.batch_size yield self._batch(batch) if self.wrap_last: self.sampler.wrap_around += self.batch_size def data_iterator(self, _iter, wrap_around=False): """iterates through data and handles wrap around""" for i, idx in enumerate(_iter): if i < self.wrap_around % self.batch_size: continue if wrap_around: self.wrap_around += 1 self.wrap_around %= self.batch_size yield idx def _batch(self, batch): """extracts samples only pertaining to this worker's batch""" if self.interleave: return batch[self.rank:self.batch_size:self.world_size] start = self.rank * self.batch_size // self.world_size end = (self.rank + 1) * self.batch_size // self.world_size return batch[start:end]
5,911
38.677852
91
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/tokenization_t5.py
# coding=utf-8 """ Tokenization class for model T5. Taken from Huggingface Transformers""" import os import re import warnings from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"} PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": { "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", } } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { "t5-small": 512, "t5-base": 512, "t5-large": 512, "t5-3b": 512, "t5-11b": 512, } class EncDecTokenizer(): """ Construct a T5 tokenizer. Based on `SentencePiece <https://github.com/google/sentencepiece>`__. This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab_file (:obj:`str`): `SentencePiece <https://github.com/google/sentencepiece>`__ file (generally has a `.spm` extension) that contains the vocabulary necessary to instantiate a tokenizer. eos_token (:obj:`str`, `optional`, defaults to :obj:`"</s>"`): The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the :obj:`sep_token`. unk_token (:obj:`str`, `optional`, defaults to :obj:`"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. pad_token (:obj:`str`, `optional`, defaults to :obj:`"<pad>"`): The token used for padding, for example when batching sequences of different lengths. extra_ids (:obj:`int`, `optional`, defaults to 100): Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary like in T5 preprocessing see `here <https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117>`__). additional_special_tokens (:obj:`List[str]`, `optional`): Additional special tokens used by the tokenizer. sp_model_kwargs (:obj:`dict`, `optional`): Will be passed to the ``SentencePieceProcessor.__init__()`` method. The `Python wrapper for SentencePiece <https://github.com/google/sentencepiece/tree/master/python>`__ can be used, among other things, to set: - ``enable_sampling``: Enable subword regularization. - ``nbest_size``: Sampling parameters for unigram. Invalid for BPE-Dropout. - ``nbest_size = {0,1}``: No sampling is performed. - ``nbest_size > 1``: samples from the nbest_size results. - ``nbest_size < 0``: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm. - ``alpha``: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout. Attributes: sp_model (:obj:`SentencePieceProcessor`): The `SentencePiece` processor that is used for every conversion (string, tokens and IDs). """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids", "attention_mask"] def __init__( self, vocab_file, eos_token="</s>", unk_token="<unk>", pad_token="<pad>", extra_ids=100, extra_extra_ids=28, additional_special_tokens=None, sp_model_kwargs: Optional[Dict[str, Any]] = None, **kwargs ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens))) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are provided to T5Tokenizer. " "In this case the additional_special_tokens must include the extra_ids tokens" ) self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs self.eos_token = eos_token self.unk_token = unk_token self.pad_token = pad_token self.extra_ids = extra_ids self.additional_sepcial_tokens = additional_special_tokens self.vocab_file = vocab_file self._extra_ids = extra_ids self._extra_extra_ids = extra_extra_ids self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(vocab_file) self.eos_id = self.convert_token_to_id(self.eos_token) self.unk_id = self.convert_token_to_id(self.unk_token) self.pad_id = self.convert_token_to_id(self.pad_token) self.special_tokens = [self.eos_token, self.unk_token, self.pad_token] @property def real_vocab_size(self): return self.sp_model.get_piece_size() + self._extra_ids @property def vocab_size(self): return self.sp_model.get_piece_size() + self._extra_ids + self._extra_extra_ids def get_vocab(self): vocab = {self.convert_ids_to_tokens(i): i for i in range(self.real_vocab_size)} return vocab def __getstate__(self): state = self.__dict__.copy() state["sp_model"] = None return state def __setstate__(self, d): self.__dict__ = d # for backward compatibility if not hasattr(self, "sp_model_kwargs"): self.sp_model_kwargs = {} self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def tokenize(self, text: str) -> List[str]: """Take as input a string and return a list of strings (tokens) for words/sub-words""" return self.sp_model.encode(text, out_type=str) def convert_token_to_id(self, token): """Converts a token (str) in an id using the vocab.""" if token.startswith("<extra_id_"): match = re.match(r"<extra_id_(\d+)>", token) num = int(match.group(1)) return self.real_vocab_size - num - 1 return self.sp_model.piece_to_id(token) def convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" if index < self.sp_model.get_piece_size(): token = self.sp_model.IdToPiece(index) else: token = f"<extra_id_{self.real_vocab_size - 1 - index}>" return token def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" current_sub_tokens = [] out_string = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.additional_sepcial_tokens or token in self.special_tokens: out_string += self.sp_model.decode_pieces(current_sub_tokens) + token + " " current_sub_tokens = [] else: current_sub_tokens.append(token) out_string += self.sp_model.decode_pieces(current_sub_tokens) return out_string.strip() def convert_tokens_to_ids(self, tokens): return [self.convert_token_to_id(x) for x in tokens] def convert_ids_to_tokens(self, ids): return [self.convert_id_to_token(x) for x in ids] def encode(self, text): return self.convert_tokens_to_ids(self.tokenize(text)) def decode(self, ids): return self.convert_tokens_to_string(self.convert_ids_to_tokens(ids)) def get_sentinel_id(self, idx): return self.real_vocab_size - idx - 1 def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: if not os.path.isdir(save_directory): return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): copyfile(self.vocab_file, out_vocab_file) return (out_vocab_file,)
9,482
41.334821
164
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/generation_metrics.py
# coding=utf-8 import warnings import numpy as np from typing import List from collections import Counter from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction from copy import deepcopy class Ngrams(object): """ Ngrams datastructure based on `set` or `list` depending in `exclusive` """ def __init__(self, ngrams={}, exclusive=True): if exclusive: self._ngrams = set(ngrams) else: self._ngrams = list(ngrams) self.exclusive = exclusive def add(self, o): if self.exclusive: self._ngrams.add(o) else: self._ngrams.append(o) def __len__(self): return len(self._ngrams) def intersection(self, o): if self.exclusive: inter_set = self._ngrams.intersection(o._ngrams) return Ngrams(inter_set, exclusive=True) else: other_list = deepcopy(o._ngrams) inter_list = [] for e in self._ngrams: try: i = other_list.index(e) except ValueError: continue other_list.pop(i) inter_list.append(e) return Ngrams(inter_list, exclusive=False) def union(self, *ngrams): if self.exclusive: union_set = self._ngrams for o in ngrams: union_set = union_set.union(o._ngrams) return Ngrams(union_set, exclusive=True) else: union_list = deepcopy(self._ngrams) for o in ngrams: union_list.extend(o._ngrams) return Ngrams(union_list, exclusive=False) def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my_lcs only gives length of the longest common subsequence, not the actual LCS """ if len(string) < len(sub): sub, string = string, sub lengths = [[0 for _ in range(0,len(sub)+1)] for _ in range(0,len(string)+1)] for j in range(1,len(sub)+1): for i in range(1, len(string) + 1): if string[i - 1] == sub[j - 1]: lengths[i][j] = lengths[i-1][j-1] + 1 else: lengths[i][j] = max(lengths[i-1][j] , lengths[i][j-1]) return lengths[len(string)][len(sub)] class Metric(object): def __init__(self): self.refs = [] self.hyps = [] def forword(self, refs: List[List[str]], hyp: List[str]): self.refs.append(refs) self.hyps.append(hyp) def forstr(self, refs: List[str], hyp: str): self.refs.append(refs) self.hyps.append(hyp) def calc_bleu_k(self, k): weights = [1. / k] * k + (4 - k) * [0.] try: bleu = corpus_bleu(self.refs, self.hyps, weights=weights, smoothing_function=SmoothingFunction().method3) except ZeroDivisionError as _: warnings.warn('the bleu is invalid') bleu = 0. return bleu def calc_distinct_k(self, k): d = {} tot = 0 for sen in self.hyps: for i in range(0, len(sen)-k): key = tuple(sen[i:i+k]) d[key] = 1 tot += 1 if tot > 0: dist = len(d) / tot else: warnings.warn('the distinct is invalid') dist = 0. return dist def calc_unigram_f1(self): f1_scores = [] for hyp, refs in zip(self.hyps, self.refs): scores = [] for ref in refs: cross = Counter(hyp) & Counter(ref) cross = sum(cross.values()) p = cross / max(len(hyp), 1e-10) r = cross / len(ref) f1 = 2 * p * r / max(p + r, 1e-10) scores.append(f1) f1_scores.append(max(scores)) return np.mean(f1_scores), f1_scores def calc_rouge_l(self, beta=1.2): scores = [] for hyp, refs in zip(self.hyps, self.refs): prec = [] rec = [] for ref in refs: lcs = my_lcs(ref, hyp) prec.append(lcs / max(len(hyp), 1e-10)) rec.append(lcs / len(ref)) prec_max = max(prec) rec_max = max(rec) if prec_max != 0 and rec_max !=0: score = ((1 + beta**2)*prec_max*rec_max)/float(rec_max + beta**2*prec_max) else: score = 0.0 scores.append(score) return np.mean(scores), scores def _get_ngrams(self, n, text, exclusive=True): """Calcualtes n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = Ngrams(exclusive=exclusive) text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(text[i:i + n])) return ngram_set def _get_word_ngrams(self, n, sentences, exclusive=True): """Calculates word n-grams for multiple sentences. """ assert len(sentences) > 0 assert n > 0 words = [x for y in sentences for x in y] # flatten the sentences return self._get_ngrams(n, words, exclusive=exclusive) def f_r_p_rouge_n(self, evaluated_count, reference_count, overlapping_count): # Handle edge case. This isn't mathematically correct, but it's good enough if reference_count == 0: recall = 0.0 else: recall = overlapping_count / reference_count return recall def calc_rouge_n(self, n=2, exclusive=True): """ Computes ROUGE-N of two text collections of sentences. Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/ papers/rouge-working-note-v1.3.1.pdf Args: evaluated_sentences: The sentences that have been picked by the summarizer reference_sentences: The sentences from the referene set n: Size of ngram. Defaults to 2. Returns: A tuple (f1, precision, recall) for ROUGE-N Raises: ValueError: raises exception if a param has len <= 0 """ if len(self.hyps) <= 0: raise ValueError("Hypothesis is empty.") if len(self.refs) <= 0: raise ValueError("Reference is empty.") evaluated_ngrams = self._get_word_ngrams(n, self.hyps, exclusive=exclusive) refs = [x[0] for x in self.refs] reference_ngrams = self._get_word_ngrams(n, refs, exclusive=exclusive) reference_count = len(reference_ngrams) evaluated_count = len(evaluated_ngrams) # Gets the overlapping ngrams between evaluated and reference overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams) overlapping_count = len(overlapping_ngrams) return self.f_r_p_rouge_n(evaluated_count, reference_count, overlapping_count) def close(self): result = {} # result = { # **{f"dist-{k}": 100 * self.calc_distinct_k(k) for k in range(3, 5)}, # **{f"bleu-{k}": 100 * self.calc_bleu_k(k) for k in range(4, 5)} # } # f1, scores = self.calc_unigram_f1() # result['f1'] = 100 * f1 # result_list = { # 'f1': scores # } rl, scores = self.calc_rouge_l() result['rouge-l'] = 100 * rl result["rouge-1"] = 100 * self.calc_rouge_n(n=1) result["rouge-2"] = 100 * self.calc_rouge_n(n=2) return result
7,988
32.426778
100
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16util.py
# coding=utf-8 import torch import torch.nn as nn from torch.autograd import Variable from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors import mpu class tofp16(nn.Module): """ Utility module that implements:: def forward(self, input): return input.half() """ def __init__(self): super(tofp16, self).__init__() def forward(self, input): return input.half() def BN_convert_float(module): """ Utility function for network_to_half(). Retained for legacy purposes. """ if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: module.float() for child in module.children(): BN_convert_float(child) return module def network_to_half(network): """ Convert model to half precision in a batchnorm-safe way. Retained for legacy purposes. It is recommended to use FP16Model. """ return nn.Sequential(tofp16(), BN_convert_float(network.half())) def convert_module(module, dtype): """ Converts a module's immediate parameters and buffers to dtype. """ for param in module.parameters(recurse=False): if param is not None: if param.data.dtype.is_floating_point: param.data = param.data.to(dtype=dtype) if param._grad is not None and param._grad.data.dtype.is_floating_point: param._grad.data = param._grad.data.to(dtype=dtype) for buf in module.buffers(recurse=False): if buf is not None and buf.data.dtype.is_floating_point: buf.data = buf.data.to(dtype=dtype) def convert_network(network, dtype): """ Converts a network's parameters and buffers to dtype. """ for module in network.modules(): if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: continue convert_module(module, dtype) return network class FP16Model(nn.Module): """ Convert model to half precision in a batchnorm-safe way. """ def __init__(self, network): super(FP16Model, self).__init__() self.network = convert_network(network, dtype=torch.half) def forward(self, *inputs): inputs = tuple(t.half() for t in inputs) return self.network(*inputs) def backwards_debug_hook(grad): raise RuntimeError("master_params recieved a gradient in the backward pass!") def prep_param_lists(model, flat_master=False): """ Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a performance optimization. Returns: A tuple (``model_params``, ``master_params``). ``model_params`` is a list of the model's parameters for later use with :func:`model_grads_to_master_grads` and :func:`master_params_to_model_params`. ``master_params`` is a list of FP32 master gradients. If ``flat_master=True``, ``master_params`` will be a list with one element. Example:: model_params, master_params = prep_param_lists(model) .. warning:: Currently, if ``flat_master=True``, all the model's parameters must be the same type. If the model has parameters of different types, use ``flat_master=False``, or use :class:`FP16_Optimizer`. .. _`Training Neural Networks with Mixed Precision: Real Examples`: http://on-demand.gputechconf.com/gtc/2018/video/S81012/ """ model_params = [param for param in model.parameters() if param.requires_grad] if flat_master: # Give the user some more useful error messages try: # flatten_dense_tensors returns a contiguous flat array. # http://pytorch.org/docs/master/_modules/torch/_utils.html master_params = _flatten_dense_tensors([param.data for param in model_params]).float() except: print("Error in prep_param_lists: model may contain a mixture of parameters " "of different types. Use flat_master=False, or use F16_Optimizer.") raise master_params = torch.nn.Parameter(master_params) master_params.requires_grad = True # master_params.register_hook(backwards_debug_hook) if master_params.grad is None: master_params.grad = master_params.new(*master_params.size()) return model_params, [master_params] else: master_params = [param.clone().float().detach() for param in model_params] for param in master_params: param.requires_grad = True return model_params, master_params def model_grads_to_master_grads(model_params, master_params, flat_master=False): """ Copy model gradients to master gradients. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`model_grads_to_master_grads`. """ if flat_master: # The flattening may incur one more deep copy than is necessary. master_params[0].grad.data.copy_( _flatten_dense_tensors([p.grad.data for p in model_params])) else: for model, master in zip(model_params, master_params): if model.grad is not None: if master.grad is None: master.grad = Variable(master.data.new(*master.data.size())) master.grad.data.copy_(model.grad.data) else: master.grad = None def master_params_to_model_params(model_params, master_params, flat_master=False): """ Copy master parameters to model parameters. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`master_params_to_model_params`. """ if flat_master: for model, master in zip(model_params, _unflatten_dense_tensors(master_params[0].data, model_params)): model.data.copy_(master) else: for model, master in zip(model_params, master_params): model.data.copy_(master.data) # Backward compatibility fixes def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) clip_grad_norm = mpu.clip_grad_norm #elif TORCH_MAJOR == 0 and TORCH_MINOR <= 4: # clip_grad_norm = torch.nn.utils.clip_grad_norm #else: # clip_grad_norm = torch.nn.utils.clip_grad_norm_
7,072
35.647668
337
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/__init__.py
# coding=utf-8 from .fp16util import ( BN_convert_float, network_to_half, prep_param_lists, model_grads_to_master_grads, master_params_to_model_params, tofp16, to_python_float, clip_grad_norm, convert_module, convert_network, FP16Model, ) from .fp16 import * from .loss_scaler import *
332
16.526316
34
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/loss_scaler.py
import torch import mpu # item() is a recent addition, so this helps with backward compatibility. def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] class LossScaler: """ Class that manages a static loss scale. This class is intended to interact with :class:`FP16_Optimizer`, and should not be directly manipulated by the user. Use of :class:`LossScaler` is enabled via the ``static_loss_scale`` argument to :class:`FP16_Optimizer`'s constructor. Args: scale (float, optional, default=1.0): The loss scale. """ def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) class DynamicLossScaler: """ Class that manages dynamic loss scaling. It is recommended to use :class:`DynamicLossScaler` indirectly, by supplying ``dynamic_loss_scale=True`` to the constructor of :class:`FP16_Optimizer`. However, it's important to understand how :class:`DynamicLossScaler` operates, because the default options can be changed using the the ``dynamic_loss_args`` argument to :class:`FP16_Optimizer`'s constructor. Loss scaling is designed to combat the problem of underflowing gradients encountered at long times when training fp16 networks. Dynamic loss scaling begins by attempting a very high loss scale. Ironically, this may result in OVERflowing gradients. If overflowing gradients are encountered, :class:`DynamicLossScaler` informs :class:`FP16_Optimizer` that an overflow has occurred. :class:`FP16_Optimizer` then skips the update step for this particular iteration/minibatch, and :class:`DynamicLossScaler` adjusts the loss scale to a lower value. If a certain number of iterations occur without overflowing gradients detected, :class:`DynamicLossScaler` increases the loss scale once more. In this way :class:`DynamicLossScaler` attempts to "ride the edge" of always using the highest loss scale possible without incurring overflow. Args: init_scale (float, optional, default=2**32): Initial loss scale attempted by :class:`DynamicLossScaler.` scale_factor (float, optional, default=2.0): Factor used when adjusting the loss scale. If an overflow is encountered, the loss scale is readjusted to loss scale/``scale_factor``. If ``scale_window`` consecutive iterations take place without an overflow, the loss scale is readjusted to loss_scale*``scale_factor``. scale_window (int, optional, default=1000): Number of consecutive iterations without an overflow to wait before increasing the loss scale. """ def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000, min_scale=1, delayed_shift=1, consecutive_hysteresis=False): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window self.min_scale = min_scale self.delayed_shift = delayed_shift self.cur_hysteresis = delayed_shift self.consecutive_hysteresis = consecutive_hysteresis # `params` is a list / generator of torch.Variable def has_overflow_serial(self, params): for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False def has_overflow(self, params): overflow = self.has_overflow_serial(params) # Since each model parallel GPU carries only part of the model, # make sure overflow flag is synced across all the model parallel GPUs overflow_gpu = torch.cuda.ByteTensor([overflow]) torch.distributed.all_reduce(overflow_gpu, op=torch.distributed.ReduceOp.MAX, group=mpu.get_model_parallel_group()) overflow = overflow_gpu[0].item() return bool(overflow) # `x` is a torch.Tensor def _has_inf_or_nan(x): try: # if x is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as x # (which is true for some recent version of pytorch). cpu_sum = float(x.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # cpu_sum = float(x.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False # `overflow` is boolean indicating whether the gradient overflowed def update_scale(self, overflow): if not hasattr(self, 'min_scale'): self.min_scale = 1 if not hasattr(self, 'delayed_shift'): self.delayed_shift = 1 if not hasattr(self, 'cur_hysteresis'): self.cur_hysteresis = 1 if not hasattr(self, 'consecutive_hysteresis'): self.consecutive_hysteresis = True if overflow: # self.cur_scale /= self.scale_factor if self.delayed_shift == 1 or self.cur_hysteresis == 1: self.cur_scale = max(self.cur_scale/self.scale_factor, self.min_scale) else: self.cur_hysteresis -= 1 self.last_overflow_iter = self.cur_iter else: if self.consecutive_hysteresis: self.cur_hysteresis = self.delayed_shift if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: if not self.consecutive_hysteresis: self.cur_hysteresis = self.delayed_shift self.cur_scale *= self.scale_factor self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) ############################################################## # Example usage below here -- assuming it's in a separate file ############################################################## """ TO-DO separate out into an example. if __name__ == "__main__": import torch from torch.autograd import Variable from dynamic_loss_scaler import DynamicLossScaler # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables. x = Variable(torch.randn(N, D_in), requires_grad=False) y = Variable(torch.randn(N, D_out), requires_grad=False) w1 = Variable(torch.randn(D_in, H), requires_grad=True) w2 = Variable(torch.randn(H, D_out), requires_grad=True) parameters = [w1, w2] learning_rate = 1e-6 optimizer = torch.optim.SGD(parameters, lr=learning_rate) loss_scaler = DynamicLossScaler() for t in range(500): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale)) print('Iter {} scaled loss: {}'.format(t, loss.data[0])) print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale)) # Run backprop optimizer.zero_grad() loss.backward() # Check for overflow has_overflow = DynamicLossScaler.has_overflow(parameters) # If no overflow, unscale grad and update as usual if not has_overflow: for param in parameters: param.grad.data.mul_(1. / loss_scaler.loss_scale) optimizer.step() # Otherwise, don't do anything -- ie, skip iteration else: print('OVERFLOW!') # Update loss scale for next iteration loss_scaler.update_scale(has_overflow) """
9,150
40.035874
326
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16.py
# coding=utf-8 """Stable version of apex FP16 Optimizer""" import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from .loss_scaler import DynamicLossScaler, LossScaler from .fp16util import model_grads_to_master_grads, master_params_to_model_params, clip_grad_norm FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor) def conversion_helper(val, conversion): """Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): rtn = tuple(rtn) return rtn def fp32_to_fp16(val): """Convert fp32 `val` to fp16""" def half_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, FLOAT_TYPES): val = val.half() return val return conversion_helper(val, half_conversion) def fp16_to_fp32(val): """Convert fp16 `val` to fp32""" def float_conversion(val): val_typecheck = val if isinstance(val_typecheck, (Parameter, Variable)): val_typecheck = val.data if isinstance(val_typecheck, HALF_TYPES): val = val.float() return val return conversion_helper(val, float_conversion) class FP16_Module(nn.Module): def __init__(self, module): super(FP16_Module, self).__init__() self.add_module('module', module.half()) def forward(self, *inputs, **kwargs): return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs)) def state_dict(self, destination=None, prefix='', keep_vars=False): return self.module.state_dict(destination, prefix, keep_vars) def load_state_dict(self, state_dict, strict=True): self.module.load_state_dict(state_dict, strict=strict) # TODO: Update overflow check + downscale to use Carl's fused kernel. class FP16_Optimizer(object): """ :class:`FP16_Optimizer` is designed to wrap an existing PyTorch optimizer, and manage static or dynamic loss scaling and master weights in a manner transparent to the user. For standard use, only two lines must be changed: creating the :class:`FP16_Optimizer` instance, and changing the call to ``backward``. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) # Name the FP16_Optimizer instance to replace the existing optimizer # (recommended but not required): optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... # loss.backward() becomes: optimizer.backward(loss) ... Example with dynamic loss scaling:: ... optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True) # optional arg to control dynamic loss scaling behavior # dynamic_loss_args={'scale_window' : 500}) # Usually, dynamic_loss_args is not necessary. Args: init_optimizer (torch.optim.optimizer): Existing optimizer created with the parameters to optimize. Internally, :class:`FP16_Optimizer` replaces the passed optimizer's fp16 parameters, if any, with fp32 master parameters copied from the original ones. :class:`FP16_Optimizer` also stores references to the original fp16 parameters, and updates these fp16 parameters from the master fp32 copy at the end of each :attr:`step`. static_loss_scale (float, optional, default=1.0): Loss scale used internally to scale gradients computed by the model. Any fp16 gradients will be copied to fp32, then downscaled before being applied to the fp32 master params, so ``static_loss_scale`` should not affect learning rate. dynamic_loss_scale (bool, optional, default=False): Use dynamic loss scaling. If True, this will override any ``static_loss_scale`` option. dynamic_loss_args (dict, optional, default=None): Dict of kwargs that will be forwarded to the internal :class:`DynamicLossScaler` instance's constructor. Keys of this dict must match kwargs accepted by :class:`DynamicLossScaler`'s constructor. If ``dynamic_loss_args`` is unspecified, :class:`DynamicLossScaler`'s defaults will be used. verbose (bool, optional, default=True): By default, FP16_Optimizer's constructor prints out the parameters and parameter groups it is ingesting, as a sanity check. If this becomes annoying (e.g. for large models), it can be disabled by passing ``verbose=False``. ``verbose=False`` will not disable printing when the loss scale is readjusted during dynamic loss scaling. ``init_optimizer`` is expected to have been constructed in the ordinary way. It is recommended (although not required) that the newly constructed :class:`FP16_Optimizer` instance be named to replace ``init_optimizer``, for two reasons: First, it means that references to the same name later in the file will not have to change. Second, :class:`FP16_Optimizer` reserves the right (as an implementation detail) to modify ``init_optimizer``. If you do choose a unique name for the new :class:`FP16_Optimizer` instance, you should only work with this new instance, because the preexisting optimizer might no longer behave as expected. ``init_optimizer`` may be any Pytorch optimizer. It may contain a mixture of fp16 and fp32 parameters organized into any number of ``param_groups`` with different hyperparameters. The :class:`FP16_Optimizer` constructor will ingest these ``param_groups`` and remember them. Calls to :: loss.backward() must be replaced with :: optimizer.backward(loss) because :class:`FP16_Optimizer` requires ownership of the backward pass to implement loss scaling and copies to master gradients. .. note:: Loss scaling, either static or dynamic, is orthogonal to learning rate, because gradients are downscaled before being applied. This means that adjusting the loss scale, or using dynamic loss scaling, should not require retuning the learning rate or any other hyperparameters. **Advanced options** **Closures**: :class:`FP16_Optimizer` can wrap a Pytorch optimizer that receives a closure. See docstring for :attr:`step`. **Gradient clipping**: Use :attr:`clip_master_grads`. **Multiple losses**: If your model accumulates gradients from multiple losses, this can be made more efficient by supplying ``update_master_grads=False`` to :attr:`backward`. See docstring for :attr:`backward`. **Manually adjusting loss scale**: The current loss scale can be retrieved or set via :: print(optimizer.loss_scale) optimizer.loss_scale = new_loss_scale For static loss scaling, manually adjusting the loss scale over time is a reasonable thing to do. During later epochs, gradients may become smaller, and a higher loss scale may be required, analogous to scheduling the learning rate. Dynamic loss scaling is more subtle (see :class:`DynamicLossScaler`) and in this case, manually adjusting the loss scale is not recommended. **Multi_GPU training**: If the wrapped ``init_optimizer`` was created from a model wrapped in Pytorch DistributedDataParallel or Apex DistributedDataParallel, :class:`FP16_Optimizer` should still work as intended. """ def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=False): if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.verbose = verbose self.optimizer = init_optimizer # init_state_dict sets up an alternative way to cast per-param state tensors. # Stashing here in case https://github.com/pytorch/pytorch/issues/7733 makes it necessary. # init_state_dict = init_optimizer.state_dict() self.fp16_groups = [] self.fp32_from_fp16_groups = [] self.fp32_from_fp32_groups = [] for i, param_group in enumerate(self.optimizer.param_groups): self.maybe_print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(param_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': self.maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}" .format(param.size())) fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True # Copythe model parallel flag. master_param.model_parallel = param.model_parallel param_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) # Reset existing state dict key to the new master param. # We still need to recast per-param state tensors, if any, to FP32. if param in self.optimizer.state: self.optimizer.state[master_param] = self.optimizer.state.pop(param) elif param.type() == 'torch.cuda.FloatTensor': self.maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}" .format(param.size())) fp32_params_this_group.append(param) param_group['params'][i] = param else: raise TypeError("Wrapped parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) self.fp16_groups.append(fp16_params_this_group) self.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) self.fp32_from_fp32_groups.append(fp32_params_this_group) # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors self.optimizer.load_state_dict(self.optimizer.state_dict()) # alternative way to cast per-param state tensors: # self.optimizer.load_state_dict(init_state_dict) if dynamic_loss_scale: self.dynamic_loss_scale = True if dynamic_loss_args is not None: self.loss_scaler = DynamicLossScaler(**dynamic_loss_args) else: self.loss_scaler = DynamicLossScaler() else: self.dynamic_loss_scale = False self.loss_scaler = LossScaler(static_loss_scale) self.overflow = False self.first_closure_call_this_step = True self.clip_grad_norm = clip_grad_norm def maybe_print(self, msg): if self.verbose: print(msg) def __getstate__(self): raise RuntimeError("FP16_Optimizer should be serialized using state_dict().") def __setstate__(self, state): raise RuntimeError("FP16_Optimizer should be deserialized using load_state_dict().") def zero_grad(self, set_grads_to_None=False): """ Zero fp32 and fp16 parameter grads. """ # In principle, only the .grad attributes of the model params need to be zeroed, # because gradients are copied into the FP32 master params. However, we zero # all gradients owned by the optimizer, just to be safe: for group in self.optimizer.param_groups: for p in group['params']: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() # Zero fp16 gradients owned by the model: for fp16_group in self.fp16_groups: for param in fp16_group: if set_grads_to_None: param.grad = None else: if param.grad is not None: param.grad.detach_() # as in torch.optim.optimizer.zero_grad() param.grad.zero_() def _check_overflow(self): params = [] for group in self.fp16_groups: for param in group: params.append(param) for group in self.fp32_from_fp32_groups: for param in group: params.append(param) self.overflow = self.loss_scaler.has_overflow(params) def _update_scale(self, has_overflow=False): self.loss_scaler.update_scale(has_overflow) def _master_params_to_model_params(self): for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): master_params_to_model_params(fp16_group, fp32_from_fp16_group) def _model_params_to_master_params(self): for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): master_params_to_model_params(fp32_from_fp16_group, fp16_group) # To consider: Integrate distributed with this wrapper by registering a hook on each variable # that does the overflow check, gradient copy + downscale, and fp32 allreduce in a different stream. def _model_grads_to_master_grads(self): for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): model_grads_to_master_grads(fp16_group, fp32_from_fp16_group) def _downscale_master(self): if self.loss_scale != 1.0: for group in self.optimizer.param_groups: for param in group['params']: if param.grad is not None: param.grad.data.mul_(1./self.loss_scale) def clip_master_grads(self, max_norm, norm_type=2): """ Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the current fp32 gradients (viewed as a single vector). .. warning:: Returns -1 if the most recently computed fp16 gradients overflowed (that is, if ``self.overflow`` is ``True``). """ if not self.overflow: fp32_params = [] for param_group in self.optimizer.param_groups: for param in param_group['params']: fp32_params.append(param) return self.clip_grad_norm(fp32_params, max_norm, norm_type) else: return -1 def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step state_dict['optimizer_state_dict'] = self.optimizer.state_dict() state_dict['fp32_from_fp16'] = self.fp32_from_fp16_groups return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] self.first_closure_call_this_step = state_dict['first_closure_call_this_step'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) # At this point, the optimizer's references to the model's fp32 parameters are up to date. # The optimizer's hyperparameters and internal buffers are also up to date. # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still # out of date. There are two options. # 1: Refresh the master params from the model's fp16 params. # This requires less storage but incurs precision loss. # 2: Save and restore the fp32 master copies separately. # We choose option 2. # # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device # of their associated parameters, because it's possible those buffers might not exist yet in # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been # constructed in the same way as the one whose state_dict we are loading, the same master params # are guaranteed to exist, so we can just copy_() from the saved master params. for current_group, saved_group in zip(self.fp32_from_fp16_groups, state_dict['fp32_from_fp16']): for current, saved in zip(current_group, saved_group): current.data.copy_(saved.data) def step(self, closure=None): # could add clip option. """ If no closure is supplied, :attr:`step` should be called after ``fp16_optimizer_obj.backward(loss)``. :attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to :class:`FP16_Optimizer`'s constructor, then copies the updated fp32 params into the fp16 params originally referenced by :class:`FP16_Optimizer`'s constructor, so the user may immediately run another forward pass using their model. If a closure is supplied, :attr:`step` may be called without a prior call to :attr:`backward(loss)`. This control flow is identical to `ordinary Pytorch optimizer use`_ with closures. However, the user should take care that any ``loss.backward()`` call within the closure has been replaced by ``fp16_optimizer_obj.backward(loss)``. Args: closure (optional): Closure that will be supplied to the underlying optimizer originally passed to :class:`FP16_Optimizer`'s constructor. closure should call :attr:`zero_grad()` on the :class:`FP16_Optimizer` object, compute the loss, call :attr:`backward(loss)`, and return the loss. Example with closure:: # optimizer is assumed to be an FP16_Optimizer object, previously constructed from an # existing pytorch optimizer. for input, target in dataset: def closure(): optimizer.zero_grad() output = model(input) loss = loss_fn(output, target) # loss.backward() becomes: optimizer.backward(loss) return loss optimizer.step(closure) .. warning:: Currently, calling :attr:`step` with a closure is not compatible with dynamic loss scaling. .. _`ordinary Pytorch optimizer use`: http://pytorch.org/docs/master/optim.html#optimizer-step-closure """ scale = self.loss_scaler.loss_scale self._update_scale(self.overflow) if self.overflow: self.maybe_print("OVERFLOW! Skipping step. Attempted loss scale: {}, reducing to {}" .format(scale, self.loss_scale)) return if closure is not None: retval = self._step_with_closure(closure) else: retval = self.optimizer.step() self._master_params_to_model_params() return retval def _step_with_closure(self, closure): def wrapped_closure(): # helpful for debugging # print("Calling wrapped_closure, first_closure_call_this_step = {}" # .format(self.first_closure_call_this_step)) if self.first_closure_call_this_step: # We expect that the fp16 params are initially fresh on entering self.step(), # so _master_params_to_model_params() is unnecessary the first time wrapped_closure() # is called within self.optimizer.step(). self.first_closure_call_this_step = False else: # If self.optimizer.step() internally calls wrapped_closure more than once, # it may update the fp32 params after each call. However, self.optimizer # doesn't know about the fp16 params at all. If the fp32 params get updated, # we can't rely on self.optimizer to refresh the fp16 params. We need # to handle that manually: self._master_params_to_model_params() # Our API expects the user to give us ownership of the backward() call by # replacing all calls to loss.backward() with optimizer.backward(loss). # This requirement holds whether or not the call to backward() is made within a closure. # If the user is properly calling optimizer.backward(loss) within "closure," # calling closure() here will give the fp32 master params fresh gradients # for the optimizer to play with, so all wrapped_closure needs to do is call # closure() and return the loss. temp_loss = closure() while(self.overflow): scale = self.loss_scaler.loss_scale self._update_scale(self.overflow) self.maybe_print("OVERFLOW within closure! Skipping step. Attempted loss scale: {}, " "reducing to {}".format(scale, self.loss_scale)) temp_loss = closure() return temp_loss retval = self.optimizer.step(wrapped_closure) self.first_closure_call_this_step = True return retval def backward(self, loss, update_master_grads=True, retain_graph=False): """ :attr:`backward` performs the following conceptual steps: 1. fp32_loss = loss.float() (see first Note below) 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's leaves (which may be fp16, fp32, or a mixture, depending how your model was defined). 4. fp16 grads are then copied to the master params' ``.grad`` attributes (see second Note), which are guaranteed to be fp32. 5. Finally, master grads are divided by loss_scale. In this way, after :attr:`backward`, the master params have fresh gradients, and :attr:`step` may be called. .. note:: :attr:`backward` internally converts the loss to fp32 before applying the loss scale. This provides some additional safety against overflow if the user has supplied an fp16 loss value. However, for maximum overflow safety, the user should compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to :attr:`backward`. .. warning:: The gradients found in a model's leaves after the call to :attr:`backward` should not be regarded as valid in general, because it's possible they have been scaled (and in the case of dynamic loss scaling, the scale factor may change over time). If the user wants to inspect gradients after a call to :attr:`backward`, only the master gradients should be regarded as valid. These can be retrieved via :attr:`inspect_master_grad_data()`. Args: loss: The loss output by the user's model. loss may be either float or half (but see first Note above). update_master_grads (bool, optional, default=True): Option to copy fp16 grads to fp32 grads on this call. By setting this to False, the user can delay the copy, which is useful to eliminate redundant fp16->fp32 grad copies if :attr:`backward` is being called on multiple losses in one iteration. If set to False, the user becomes responsible for calling :attr:`update_master_grads` before calling :attr:`step`. retain_graph (bool, optional, default=False): Forwards the usual ``retain_graph=True`` option to the internal call to ``loss.backward``. If ``retain_graph`` is being used to accumulate gradient values from multiple backward passes before calling ``optimizer.step``, passing ``update_master_grads=False`` is also recommended (see Example below). Example:: # Ordinary operation: optimizer.backward(loss) # Naive operation with multiple losses (technically valid, but less efficient): # fp32 grads will be correct after the second call, but # the first call incurs an unnecessary fp16->fp32 grad copy. optimizer.backward(loss1) optimizer.backward(loss2) # More efficient way to handle multiple losses: # The fp16->fp32 grad copy is delayed until fp16 grads from all # losses have been accumulated. optimizer.backward(loss1, update_master_grads=False) optimizer.backward(loss2, update_master_grads=False) optimizer.update_master_grads() """ # To consider: try multiple backward passes using retain_grad=True to find # a loss scale that works. After you find a loss scale that works, do a final dummy # backward pass with retain_graph=False to tear down the graph. Doing this would avoid # discarding the iteration, but probably wouldn't improve overall efficiency. self.loss_scaler.backward(loss.float(), retain_graph=retain_graph) if update_master_grads: self.update_master_grads() def update_master_grads(self): """ Copy the ``.grad`` attribute from stored references to fp16 parameters to the ``.grad`` attribute of the fp32 master parameters that are directly updated by the optimizer. :attr:`update_master_grads` only needs to be called if ``fp16_optimizer_obj.backward`` was called with ``update_master_grads=False``. """ if self.dynamic_loss_scale: self._check_overflow() if self.overflow: return self._model_grads_to_master_grads() self._downscale_master() def inspect_master_grad_data(self): """ When running with :class:`FP16_Optimizer`, ``.grad`` attributes of a model's fp16 leaves should not be regarded as truthful, because they might be scaled. After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was encountered, the fp32 master params' ``.grad`` attributes will contain valid gradients properly divided by the loss scale. However, because :class:`FP16_Optimizer` flattens some parameters, accessing them may be nonintuitive. :attr:`inspect_master_grad_data` allows those gradients to be viewed with shapes corresponding to their associated model leaves. Returns: List of lists (one list for each parameter group). The list for each parameter group is a list of the ``.grad.data`` attributes of the fp32 master params belonging to that group. """ if self.overflow: print("Warning: calling FP16_Optimizer.inspect_master_grad_data while in an overflow state. " "Gradients are currently invalid (may be inf, nan, or stale). Returning None.") return None else: # The optimizer owns only references to master params. master_grads_data = [] for param_group in self.optimizer.param_groups: master_grads_this_group = [] for param in param_group['params']: if param.grad is not None: master_grads_this_group.append(param.grad.data) else: master_grads_this_group.append(None) master_grads_data.append(master_grads_this_group) return master_grads_data # Promote loss scale so it can be retrieved or set via "fp16_optimizer_instance.loss_scale" def _get_loss_scale(self): return self.loss_scaler.loss_scale def _set_loss_scale(self, value): self.loss_scaler.cur_scale = value loss_scale = property(_get_loss_scale, _set_loss_scale) # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups)
31,108
49.338188
437
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/mappings.py
# coding=utf-8 import torch from .initialize import get_model_parallel_group from .utils import split_tensor_along_last_dim def _reduce(input_): """All-reduce the the input tensor across model parallel group.""" group = get_model_parallel_group() # Bypass the function if we are using only 1 GPU. if torch.distributed.get_world_size(group=group) == 1: return input_ # All-reduce. torch.distributed.all_reduce(input_, group=group) return input_ def _split(input_): """Split the tensor along its last dimension and keep the corresponding slice.""" group = get_model_parallel_group() # Bypass the function if we are using only 1 GPU. if torch.distributed.get_world_size(group=group) == 1: return input_ # Split along last dimension. world_size = torch.distributed.get_world_size(group=group) input_list = split_tensor_along_last_dim(input_, world_size) # Note: torch.split does not create contiguous tensors by default. rank = torch.distributed.get_rank(group=group) output = input_list[rank].contiguous() return output def _gather(input_): """Gather tensors and concatinate along the last dimension.""" group = get_model_parallel_group() # Bypass the function if we are using only 1 GPU. if torch.distributed.get_world_size(group=group) == 1: return input_ # Size and dimension. last_dim = input_.dim() - 1 rank = torch.distributed.get_rank(group=group) world_size = torch.distributed.get_world_size(group=group) tensor_list = [torch.empty_like(input_) for _ in range(world_size)] tensor_list[rank] = input_ torch.distributed.all_gather(tensor_list, input_, group=group) # Note: torch.cat already creates a contiguous tensor. output = torch.cat(tensor_list, dim=last_dim).contiguous() return output class _CopyToModelParallelRegion(torch.autograd.Function): """Pass the input to the model parallel region.""" @staticmethod def forward(ctx, input_): return input_ @staticmethod def backward(ctx, grad_output): return _reduce(grad_output) class _ReduceFromModelParallelRegion(torch.autograd.Function): """All-redcue the input from the model parallel region.""" @staticmethod def forward(ctx, input_): return _reduce(input_) @staticmethod def backward(ctx, grad_output): return grad_output class _ScatterToModelParallelRegion(torch.autograd.Function): """Split the input and keep only the corresponding chuck to the rank.""" @staticmethod def forward(ctx, input_): return _split(input_) @staticmethod def backward(ctx, grad_output): return _gather(grad_output) class _GatherFromModelParallelRegion(torch.autograd.Function): """Gather the input from model parallel region and concatinate.""" @staticmethod def forward(ctx, input_): return _gather(input_) @staticmethod def backward(ctx, grad_output): return _split(grad_output) # ----------------- # Helper functions. # ----------------- def copy_to_model_parallel_region(input_): return _CopyToModelParallelRegion.apply(input_) def reduce_from_model_parallel_region(input_): return _ReduceFromModelParallelRegion.apply(input_) def scatter_to_model_parallel_region(input_): return _ScatterToModelParallelRegion.apply(input_) def gather_from_model_parallel_region(input_): return _GatherFromModelParallelRegion.apply(input_)
3,527
26.138462
76
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/initialize.py
# coding=utf-8 """Model and data parallel groups.""" import torch from .utils import ensure_divisibility # Model parallel group that the current rank belongs to. _MODEL_PARALLEL_GROUP = None # Data parallel group that the current rank belongs to. _DATA_PARALLEL_GROUP = None def initialize_model_parallel(model_parallel_size_): """ Initialize model data parallel groups. Arguments: model_parallel_size: number of GPUs used to parallelize model. Let's say we have a total of 8 GPUs denoted by g0 ... g7 and we use 2 GPUs to parallelize the model. The present function will create 4 model parallel groups and 2 data parallel grous as: 4 model parallel groups: [g0, g1], [g2, g3], [g4, g5], [g6, g7] 2 data parallel groups: [g0, g2, g4, g6], [g1, g3, g5, g7] Note that for efficiency, the caller should make sure adjacent ranks are on the same DGX box. For example if we are using 2 DGX-1 boxes with a total of 16 GPUs, rank 0 to 7 belong to the first box and ranks 8 to 15 belong to the second box. """ if torch.distributed.get_rank() == 0: print('> initializing model parallel with size {}'.format( model_parallel_size_)) # Get world size and rank. Ensure some consistencies. assert torch.distributed.is_initialized() world_size = torch.distributed.get_world_size() model_parallel_size = min(model_parallel_size_, world_size) ensure_divisibility(world_size, model_parallel_size) rank = torch.distributed.get_rank() # Build the data parallel groups. global _DATA_PARALLEL_GROUP assert _DATA_PARALLEL_GROUP is None, \ 'data parallel group is already initialized' for i in range(model_parallel_size): ranks = range(i, world_size, model_parallel_size) group = torch.distributed.new_group(ranks) if i == (rank % model_parallel_size): _DATA_PARALLEL_GROUP = group # Build the model parallel groups. global _MODEL_PARALLEL_GROUP assert _MODEL_PARALLEL_GROUP is None, \ 'model parallel group is already initialized' for i in range(world_size // model_parallel_size): ranks = range(i * model_parallel_size, (i + 1) * model_parallel_size) group = torch.distributed.new_group(ranks) if i == (rank // model_parallel_size): _MODEL_PARALLEL_GROUP = group def model_parallel_is_initialized(): """Check if model and data parallel groups are initialized.""" if _MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None: return False return True def get_model_parallel_group(): """Get the model parallel group the caller rank belongs to.""" assert _MODEL_PARALLEL_GROUP is not None, \ 'model parallel group is not initialized' return _MODEL_PARALLEL_GROUP def get_data_parallel_group(): """Get the data parallel group the caller rank belongs to.""" assert _DATA_PARALLEL_GROUP is not None, \ 'data parallel group is not initialized' return _DATA_PARALLEL_GROUP def get_model_parallel_world_size(): """Return world size for the model parallel group.""" return torch.distributed.get_world_size(group=get_model_parallel_group()) def get_model_parallel_rank(): """Return my rank for the model parallel group.""" return torch.distributed.get_rank(group=get_model_parallel_group()) def get_model_parallel_src_rank(): """Calculate the global rank corresponding to a local rank zeor in the model parallel group.""" global_rank = torch.distributed.get_rank() local_world_size = get_model_parallel_world_size() return (global_rank // local_world_size) * local_world_size def get_data_parallel_world_size(): """Return world size for the data parallel group.""" return torch.distributed.get_world_size(group=get_data_parallel_group()) def get_data_parallel_rank(): """Return my rank for the data parallel group.""" return torch.distributed.get_rank(group=get_data_parallel_group()) def destroy_model_parallel(): """Set the groups to none.""" global _MODEL_PARALLEL_GROUP _MODEL_PARALLEL_GROUP = None global _DATA_PARALLEL_GROUP _DATA_PARALLEL_GROUP = None
4,274
33.475806
77
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/cross_entropy.py
# coding=utf-8 import torch from .initialize import get_model_parallel_group from .initialize import get_model_parallel_rank from .initialize import get_model_parallel_world_size from .utils import VocabUtility class _VocabParallelCrossEntropy(torch.autograd.Function): @staticmethod def forward(ctx, vocab_parallel_logits, target): # Copy so the input remains unchanged. logits = vocab_parallel_logits.clone() # Maximum value along vocab dimension across all GPUs. logits_max = torch.max(logits, dim=-1)[0] torch.distributed.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel_group()) # Subtract the maximum value. logits.sub_(logits_max.unsqueeze(dim=-1)) # Sum of exponential of logits along vocab dimension across all GPUs. exp_logits = logits.exp() sum_exp_logits = exp_logits.sum(dim=-1) torch.distributed.all_reduce(sum_exp_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) # Get the partition's vocab indecies get_vocab_range = VocabUtility.vocab_range_from_per_partition_vocab_size partition_vocab_size = vocab_parallel_logits.size()[-1] rank = get_model_parallel_rank() world_size = get_model_parallel_world_size() vocab_start_index, vocab_end_index = get_vocab_range( partition_vocab_size, rank, world_size) # Create a mask of valid vocab ids (1 means it needs to be masked). target_mask = (target < vocab_start_index) | (target >= vocab_end_index) masked_target = target.clone() - vocab_start_index masked_target[target_mask] = 0 # Get predicted-logits = logits[target]. # For Simplicity, we convert logits to a 2-D tensor with size # [*, partition-vocab-size] and target to a 1-D tensor of size [*]. logits_2d = logits.view(-1, partition_vocab_size) masked_target_1d = masked_target.view(-1) arange_1d = torch.arange(start=0, end=logits_2d.size()[0], device=logits_2d.device) predicted_logits_1d = logits_2d[arange_1d, masked_target_1d] predicted_logits = predicted_logits_1d.view_as(target) predicted_logits[target_mask] = 0.0 # All reduce is needed to get the chunks from other GPUs. torch.distributed.all_reduce(predicted_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) # Loss = log(sum(exp(logits))) - predicted-logit. loss = torch.log(sum_exp_logits) - predicted_logits # Store softmax, target-mask and masked-target for backward pass. exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1)) ctx.save_for_backward(exp_logits, target_mask, masked_target_1d) return loss @staticmethod def backward(ctx, grad_output): # Retreive tensors from the forward path. softmax, target_mask, masked_target_1d = ctx.saved_tensors # All the inputs have softmax as thier gradient. grad_input = softmax # For simplicity, work with the 2D gradient. partition_vocab_size = softmax.size()[-1] grad_2d = grad_input.view(-1, partition_vocab_size) # Add the gradient from matching classes. arange_1d = torch.arange(start=0, end=grad_2d.size()[0], device=grad_2d.device) grad_2d[arange_1d, masked_target_1d] -= ( 1.0 - target_mask.view(-1).float()) # Finally elementwise multiplication with the output gradients. grad_input.mul_(grad_output.unsqueeze(dim=-1)) return grad_input, None def vocab_parallel_cross_entropy(vocab_parallel_logits, target): """Helper function for the cross entropy.""" return _VocabParallelCrossEntropy.apply(vocab_parallel_logits, target) class _ParallelKLLoss(torch.autograd.Function): @staticmethod def forward(cls, logits: torch.Tensor, targets: torch.Tensor): # Maximum value along vocab dimension across all GPUs. logits_max = torch.max(logits, dim=-1)[0] torch.distributed.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel_group()) # Subtract the maximum value. logits.sub_(logits_max.unsqueeze(dim=-1)) # Sum of exponential of logits along vocab dimension across all GPUs. exp_logits = logits.exp() sum_exp_logits = exp_logits.sum(dim=-1) torch.distributed.all_reduce(sum_exp_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) targets_max = torch.max(targets, dim=-1)[0] torch.distributed.all_reduce(targets_max, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel_group()) # Subtract the maximum value. targets.sub_(targets_max.unsqueeze(dim=-1)) # Sum of exponential of logits along vocab dimension across all GPUs. exp_targets = targets.exp() sum_exp_targets = exp_targets.sum(dim=-1) torch.distributed.all_reduce(sum_exp_targets, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) # targets_softmax: [b, s, v_p] targets_softmax = torch.div(exp_targets, sum_exp_targets.unsqueeze(-1)) # sum_targets_softmax_logits: [b, s] sum_targets_softmax_logits = torch.matmul( targets_softmax.unsqueeze(-2), logits.unsqueeze(-1)).squeeze(-1).squeeze(-1) torch.distributed.all_reduce(sum_targets_softmax_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) log_targets_softmax = torch.log(targets_softmax) sum_log_targets_softmax = torch.matmul( targets_softmax.unsqueeze(-2), log_targets_softmax.unsqueeze(-1)).squeeze(-1).squeeze(-1) torch.distributed.all_reduce(sum_log_targets_softmax, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) loss = torch.log(sum_exp_logits) - sum_targets_softmax_logits + sum_log_targets_softmax logits_softmax = torch.div(exp_logits, sum_exp_logits.unsqueeze(-1)) cls.save_for_backward(logits_softmax, targets_softmax) return loss @staticmethod def backward(cls, grad_output: torch.Tensor): logits_softmax, targets_softmax = cls.saved_tensors grad_input = (logits_softmax - targets_softmax) * grad_output.unsqueeze(-1) return grad_input, None def parallel_KL_loss(logits, targets): return _ParallelKLLoss.apply(logits, targets) class _ParallelSoftCrossEntropyLoss(torch.autograd.Function): @staticmethod def forward(cls, logits: torch.Tensor, targets: torch.Tensor): # Maximum value along vocab dimension across all GPUs. logits_max = torch.max(logits, dim=-1)[0] torch.distributed.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel_group()) # Subtract the maximum value. logits.sub_(logits_max.unsqueeze(dim=-1)) # Sum of exponential of logits along vocab dimension across all GPUs. exp_logits = logits.exp() sum_exp_logits = exp_logits.sum(dim=-1) torch.distributed.all_reduce(sum_exp_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) # sum_targets_softmax_logits: [b, s] sum_targets_softmax_logits = torch.matmul( targets.unsqueeze(-2), logits.unsqueeze(-1)).squeeze(-1).squeeze(-1) torch.distributed.all_reduce(sum_targets_softmax_logits, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) loss = torch.log(sum_exp_logits) - sum_targets_softmax_logits logits_softmax = torch.div(exp_logits, sum_exp_logits.unsqueeze(-1)) cls.save_for_backward(logits_softmax, targets) return loss @staticmethod def backward(cls, grad_output: torch.Tensor): logits_softmax, targets = cls.saved_tensors grad_input = (logits_softmax - targets) * grad_output.unsqueeze(-1) return grad_input, None def parallel_soft_cross_entropy_loss(logits, targets): return _ParallelSoftCrossEntropyLoss.apply(logits, targets)
9,078
41.425234
101
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/utils.py
# coding=utf-8 import torch def ensure_divisibility(numerator, denominator): """Ensure that numerator is divisible by the denominator.""" assert numerator % denominator == 0, '{} is not divisible by {}'.format( numerator, denominator) def divide(numerator, denominator): """Ensure that numerator is divisible by the denominator and return the division value.""" ensure_divisibility(numerator, denominator) return numerator // denominator def split_tensor_along_last_dim(tensor, num_partitions, contiguous_split_chunks=False): """Split a tensor along its last dimension. Arguments: tensor: input tensor. num_partitions: number of partitions to split the tensor contiguous_split_chunks: If True, make each chunk contiguous in memory. """ # Get the size and dimension. last_dim = tensor.dim() - 1 last_dim_size = divide(tensor.size()[last_dim], num_partitions) # Split. tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) # Note: torch.split does not create contiguous tensors by default. if contiguous_split_chunks: return tuple(chunk.contiguous() for chunk in tensor_list) return tensor_list class VocabUtility: """Split the vocabulary into `world_size` chunks amd return the first and last index of the vocabulary belonging to the `rank` partition: Note that indecies in [fist, last)""" @staticmethod def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank, world_size): index_f = rank * per_partition_vocab_size index_l = index_f + per_partition_vocab_size return index_f, index_l @staticmethod def vocab_range_from_global_vocab_size(global_vocab_size, rank, world_size): per_partition_vocab_size = divide(global_vocab_size, world_size) return VocabUtility.vocab_range_from_per_partition_vocab_size( per_partition_vocab_size, rank, world_size)
2,102
34.644068
80
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/data.py
# coding=utf-8 import torch from .initialize import get_model_parallel_group from .initialize import get_model_parallel_rank from .initialize import get_model_parallel_src_rank _MAX_DATA_DIM = 4 def _check_data_types(keys, data, target_dtype): """Check that all the keys have the same target data type.""" for key in keys: assert data[key].dtype == target_dtype, '{} has data type {} which '\ 'is different than {}'.format(key, data[key].dtype, target_dtype) def _build_key_size_numel_dictionaries(keys, data): """Build the size on rank 0 and broadcast.""" max_dim = _MAX_DATA_DIM sizes = [0 for _ in range(max_dim) for _ in keys] # Pack the sizes on rank zero. if get_model_parallel_rank() == 0: offset = 0 for key in keys: assert data[key].dim() < max_dim, 'you should increase MAX_DATA_DIM' size = data[key].size() for i, s in enumerate(size): sizes[i + offset] = s offset += max_dim # Move to GPU and broadcast. sizes_cuda = torch.cuda.LongTensor(sizes) torch.distributed.broadcast(sizes_cuda, get_model_parallel_src_rank(), group=get_model_parallel_group()) # Move back to cpu and unpack. sizes_cpu = sizes_cuda.cpu() key_size = {} key_numel = {} total_numel = 0 offset = 0 for key in keys: i = 0 size = [] numel = 1 while sizes_cpu[offset + i] > 0: this_size = sizes_cpu[offset + i] size.append(this_size) numel *= this_size i += 1 key_size[key] = size key_numel[key] = numel total_numel += numel offset += max_dim return key_size, key_numel, total_numel def broadcast_data(keys, data, datatype): """Broadcast data from rank zero of each model parallel group to the members of the same model parallel group. Arguments: keys: list of keys in the data disctionary to be broadcasted data: data dictionary of string keys and cpu tensor values. datatype: torch data type of all tensors in data associated with keys. """ # Build (key, size) and (key, number of elements) dictionaries along # with the total number of elements on all ranks. key_size, key_numel, total_numel = _build_key_size_numel_dictionaries(keys, data) # Pack on rank zero. if get_model_parallel_rank() == 0: # Check that all keys have the same data type. _check_data_types(keys, data, datatype) # Flatten the data associated with the keys flatten_data = torch.cat( [data[key].contiguous().view(-1) for key in keys], dim=0).cuda() else: flatten_data = torch.empty(total_numel, device=torch.cuda.current_device(), dtype=datatype) # Boradcast torch.distributed.broadcast(flatten_data, get_model_parallel_src_rank(), group=get_model_parallel_group()) # Unpack output = {} offset = 0 for key in keys: size = key_size[key] numel = key_numel[key] output[key] = flatten_data.narrow(0, offset, numel).view(size) offset += numel return output
3,409
31.47619
80
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/grads.py
# coding=utf-8 # Parts of the code here are adapted from PyTorch # repo: https://github.com/pytorch/pytorch import torch from torch._six import inf from .initialize import get_model_parallel_group from .initialize import get_model_parallel_rank def clip_grad_norm(parameters, max_norm, norm_type=2): """Clips gradient norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Arguments: parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a single Tensor that will have gradients normalized max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the parameters (viewed as a single vector). """ if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = list(filter(lambda p: p.grad is not None, parameters)) max_norm = float(max_norm) norm_type = float(norm_type) if norm_type == inf: total_norm = max(p.grad.data.abs().max() for p in parameters) total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]) # Take max across all GPUs. torch.distributed.all_reduce(total_norm_cuda, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel_group()) total_norm = total_norm_cuda[0].item() else: total_norm = 0 for p in parameters: if p.model_parallel or (get_model_parallel_rank() == 0): param_norm = p.grad.data.norm(norm_type) total_norm += param_norm.item() ** norm_type # Sum across all model parallel GPUs. total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]) torch.distributed.all_reduce(total_norm_cuda, op=torch.distributed.ReduceOp.SUM, group=get_model_parallel_group()) total_norm = total_norm_cuda[0].item() ** (1. / norm_type) clip_coef = max_norm / (total_norm + 1e-6) if clip_coef < 1: for p in parameters: p.grad.data.mul_(clip_coef) return total_norm
2,406
37.206349
79
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/layers.py
# coding=utf-8 # Parts of the code here are adapted from PyTorch # repo: https://github.com/pytorch/pytorch import math import torch import torch.nn.functional as F import torch.nn.init as init from torch.nn.parameter import Parameter from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm from .initialize import get_model_parallel_rank from .initialize import get_model_parallel_world_size from .mappings import copy_to_model_parallel_region from .mappings import gather_from_model_parallel_region from .mappings import reduce_from_model_parallel_region from .mappings import scatter_to_model_parallel_region from .random import get_cuda_rng_tracker from .utils import divide from .utils import split_tensor_along_last_dim from .utils import VocabUtility def _initialize_affine_weight(weight, output_size, input_size, per_partition_size, partition_dim, init_method, stride=1, return_master_weight=False): """Initialize affine weight for model parallel. Build the master weight on all processes and scatter the relevant chunk.""" # If we only use 1 process for model parallelism, bypass scatter. world_size = get_model_parallel_world_size() if world_size == 1: init_method(weight) if return_master_weight: return weight return None # Initialize master weight master_weight = torch.empty(output_size, input_size, dtype=weight.dtype, requires_grad=False) init_method(master_weight) # Split and copy per_partition_per_stride_size = divide(per_partition_size, stride) weight_list = torch.split(master_weight, per_partition_per_stride_size, dim=partition_dim) rank = get_model_parallel_rank() my_weight_list = weight_list[rank::world_size] with torch.no_grad(): torch.cat(my_weight_list, dim=partition_dim, out=weight) if return_master_weight: return master_weight return None class VocabParallelEmbedding(torch.nn.Module): """Embedding parallelized in the vocabulary dimension. This is mainly adapted from torch.nn.Embedding and all the default values are kept. Arguments: num_embeddings: vocabulary size. embedding_dim: size of hidden state. init_method: method to initialize weights. """ def __init__(self, num_embeddings, embedding_dim, init_method=init.xavier_normal_): super(VocabParallelEmbedding, self).__init__() # Keep the input dimensions. self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim # Set the detauls for compatibility. self.padding_idx = None self.max_norm = None self.norm_type = 2. self.scale_grad_by_freq = False self.sparse = False self._weight = None # Divide the weight matrix along the vocaburaly dimension. self.vocab_start_index, self.vocab_end_index = \ VocabUtility.vocab_range_from_global_vocab_size( self.num_embeddings, get_model_parallel_rank(), get_model_parallel_world_size()) self.num_embeddings_per_partition = self.vocab_end_index - \ self.vocab_start_index # Allocate weights. self.weight = Parameter(torch.Tensor(self.num_embeddings_per_partition, self.embedding_dim)) self.weight.model_parallel = True # And initialize. _initialize_affine_weight( self.weight, self.num_embeddings, self.embedding_dim, self.num_embeddings_per_partition, 0, init_method) def forward(self, input_): # Build the mask. input_mask = (input_ < self.vocab_start_index) | \ (input_ >= self.vocab_end_index) # Mask the input. masked_input = input_.clone() - self.vocab_start_index masked_input[input_mask] = 0 # Get the embeddings. output_parallel = F.embedding(masked_input, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse) # Mask the output embedding. output_parallel[input_mask, :] = 0.0 # Reduce across all the model parallel GPUs. output = reduce_from_model_parallel_region(output_parallel) return output class ParallelEmbedding(torch.nn.Module): """Embedding parallelized in the embedding dimension. This is mainly adapted from torch.nn.Embedding and all the default values are kept. Arguments: num_embeddings: vocabulary size. embedding_dim: size of hidden state. init_method: method to initialize weights. """ def __init__(self, num_embeddings, embedding_dim, init_method=init.xavier_normal_, keep_master_weight_for_test=False): super(ParallelEmbedding, self).__init__() # Keep the input dimensions. self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim # Set some detauls for compatibility. self.padding_idx = None self.max_norm = None self.norm_type = 2. self.scale_grad_by_freq = False self.sparse = False self._weight = None # Divide the weight matrix along the embedding dimension. world_size = get_model_parallel_world_size() self.embedding_dim_per_partition = divide(self.embedding_dim, world_size) # Allocate weights. self.weight = Parameter(torch.Tensor(self.num_embeddings, self.embedding_dim_per_partition)) self.weight.model_parallel = True # And initialize. split the weights to different model parallel devices _initialize_affine_weight( self.weight, self.num_embeddings, self.embedding_dim, self.embedding_dim_per_partition, 1, init_method, stride=1, return_master_weight=False) def forward(self, input_): input_parallel = copy_to_model_parallel_region(input_) output_parallel = F.embedding(input_parallel, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse) output = gather_from_model_parallel_region(output_parallel) return output class ColumnParallelLinear(torch.nn.Module): """Linear layer with column parallelism. NOTE: This function will NOT do all-reduce unless gather_output is True The linear layer is defined as Y = XA + b. A is parallelized along its second dimension as A = [A_1, ..., A_p]. Arguments: input_size: first dimension of matrix A. output_size: second dimension of matrix A. bias: If true, add bias gather_output: If true, call all-gether on output and make Y avaiable to all GPUs, otherwise, every GPU will have its output which is Y_i = XA_i init_method: method to initialize weights. Note that bias is always set to zero. stride: For the strided linear layers. keep_master_weight_for_test: This was added for testing and should be set to False. It returns the master weights used for initialization. """ def __init__(self, input_size, output_size, bias=True, gather_output=True, init_method=init.xavier_normal_, stride=1, keep_master_weight_for_test=False): super(ColumnParallelLinear, self).__init__() # Keep input parameters self.input_size = input_size self.output_size = output_size self.gather_output = gather_output # Divide the weight matrix along the last dimension. world_size = get_model_parallel_world_size() self.output_size_per_partition = divide(output_size, world_size) # Parameters. # Note: torch.nn.functional.linear performs XA^T + b and as a result # we allocate the transpose. self.weight = Parameter(torch.Tensor(self.output_size_per_partition, self.input_size)) self.weight.model_parallel = True if bias: self.bias = Parameter(torch.Tensor(self.output_size_per_partition)) self.bias.model_parallel = True # Always initialize bias to zero. with torch.no_grad(): self.bias.zero_() else: self.register_parameter('bias', None) # Initialize weight. self.master_weight = _initialize_affine_weight( self.weight, self.output_size, self.input_size, self.output_size_per_partition, 0, init_method, stride=stride, return_master_weight=keep_master_weight_for_test) def forward(self, input_): # Set up backprop all-reduce. input_parallel = copy_to_model_parallel_region(input_) # Matrix multiply. output_parallel = F.linear(input_parallel, self.weight, self.bias) if self.gather_output: # All-gather across the partitions. output = gather_from_model_parallel_region(output_parallel) else: output = output_parallel return output class RowParallelLinear(torch.nn.Module): """Linear layer with row parallelism. NOTE: This function will do all-reduce The linear layer is defined as Y = XA + b. A is parallelized along its first dimension and X along its second dimension as: - - | A_1 | | . | A = | . | X = [X_1, ..., X_p] | . | | A_p | - - Arguments: input_size: first dimension of matrix A. output_size: second dimension of matrix A. bias: If true, add bias. Note that bias is not parallelized. input_is_parallel: If true, we assume that the input is already split across the GPUs and we do not split again. init_method: method to initialize weights. Note that bias is always set to zero. stride: For the strided linear layers. keep_master_weight_for_test: This was added for testing and should be set to False. It returns the master weights used for initialization. """ def __init__(self, input_size, output_size, bias=True, input_is_parallel=False, init_method=init.xavier_normal_, stride=1, keep_master_weight_for_test=False): super(RowParallelLinear, self).__init__() # Keep input parameters self.input_size = input_size self.output_size = output_size self.input_is_parallel = input_is_parallel # Divide the weight matrix along the last dimension. world_size = get_model_parallel_world_size() self.input_size_per_partition = divide(input_size, world_size) # Parameters. # Note: torch.nn.functional.linear performs XA^T + b and as a result # we allocate the transpose. self.weight = Parameter(torch.Tensor(self.output_size, self.input_size_per_partition)) self.weight.model_parallel = True if bias: self.bias = Parameter(torch.Tensor(self.output_size)) # Always initialize bias to zero. with torch.no_grad(): self.bias.zero_() else: self.register_parameter('bias', None) # Initialize weight. self.master_weight = _initialize_affine_weight( self.weight, self.output_size, self.input_size, self.input_size_per_partition, 1, init_method, stride=stride, return_master_weight=keep_master_weight_for_test) def forward(self, input_): # Set up backprop all-reduce. if self.input_is_parallel: input_parallel = input_ else: input_parallel = scatter_to_model_parallel_region(input_) # Matrix multiply. output_parallel = F.linear(input_parallel, self.weight) # All-reduce across all the partitions. output_ = reduce_from_model_parallel_region(output_parallel) if self.bias is not None: output = output_ + self.bias else: output = output_ return output
12,967
39.652038
80
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/random.py
# coding=utf-8 #Modified by Samyam Rajbhandari #Used to partition the activations stored for backward propagation #Therefore reduces the memory consumption # Parts of the code here are adapted from PyTorch # repo: https://github.com/pytorch/pytorch import contextlib import torch.distributed as dist import torch from torch import _C from torch.cuda import _lazy_call, device as device_ctx_manager #from torch.utils.checkpoint import detach_variable import torch.distributed as dist PARTITION_ACTIVATIONS = False PA_CORRECTNESS_TEST= False def see_memory_usage(message, force=False): if not force: return dist.barrier() if dist.get_rank() == 0: print(message) print("Memory Allocated ", torch.cuda.memory_allocated()/(1024*1024*1024), "GigaBytes") print("Max Memory Allocated ", torch.cuda.max_memory_allocated()/(1024*1024*1024), "GigaBytes") print("Cache Allocated ", torch.cuda.memory_cached()/(1024*1024*1024), "GigaBytes") print("Max cache Allocated ", torch.cuda.max_memory_cached()/(1024*1024*1024), "GigaBytes") print(" ") #input("Press Any Key To Continue ..") from .initialize import get_data_parallel_rank from .initialize import get_model_parallel_rank from .initialize import get_model_parallel_world_size from .initialize import get_model_parallel_group mp_rank = None #get_model_parallel_rank() mp_size = None #get_model_parallel_world_size() mp_group = None #get_model_parallel_group() # Default name for the model parallel rng tracker. _MODEL_PARALLEL_RNG_TRACKER_NAME = 'model-parallel-rng' transport_stream = None cuda_device=None def detach_variable(inputs, device=None): if isinstance(inputs, tuple): out = [] for inp in inputs: if not isinstance(inp, torch.Tensor): out.append(inp) continue requires_grad = inp.requires_grad if device is not None: x = inp.to(device=device) else: x = inp x = x.detach() x.requires_grad = requires_grad out.append(x) return tuple(out) else: raise RuntimeError( "Only tuple of tensors is supported. Got Unsupported input type: ", type(inputs).__name__) def _set_cuda_rng_state(new_state, device=-1): """Sets the random number generator state of the current GPU. Argumentss: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cases. """ if hasattr(_C, '_cuda_setRNGState') and callable(_C._cuda_setRNGState): # older PyTorch def cb(): with device_ctx_manager(device): _C._cuda_setRNGState(new_state) else: # newer PyTorch if device == -1: device = torch.device('cuda') elif isinstance(device, str): device = torch.device(device) elif isinstance(device, int): device = torch.device('cuda', device) def cb(): idx = device.index if idx is None: idx = torch.cuda.current_device() default_generator = torch.cuda.default_generators[idx] default_generator.set_state(new_state) _lazy_call(cb) class CudaRNGStatesTracker: """Tracker for the cuda RNG states. Using the `add` method, a cuda rng state is initialized based on the input `seed` and is assigned to `name`. Later, by forking the rng state, we can perform operations and return to our starting cuda state. """ def __init__(self): # Map from a string name to the cuda rng state. self.states_ = {} # Seeds are just for book keeping and ensure no seed is set twice. self.seeds_ = set() def reset(self): """Set to the initial state (no tracker).""" self.states_ = {} self.seeds_ = set() def get_states(self): """Get rng states. Copy the dictionary so we have direct pointers to the states, not just a pointer to the dictionary.""" states = {} for name in self.states_: states[name] = self.states_[name] return states def set_states(self, states): """Set the rng states. For efficiency purposes, we do not check the size of seed for compatibility.""" self.states_ = states def add(self, name, seed): """Track the rng state.""" # Check seed is not already used. if seed in self.seeds_: raise Exception('seed {} already exists'.format(seed)) self.seeds_.add(seed) # Check that state is not already defined. if name in self.states_: raise Exception('cuda rng state {} already exists'.format(name)) # Get the current rng state. orig_rng_state = torch.cuda.get_rng_state() # Set the new state and store it. torch.cuda.manual_seed(seed) self.states_[name] = torch.cuda.get_rng_state() # Reset rng state to what it was. _set_cuda_rng_state(orig_rng_state) @contextlib.contextmanager def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME): """Fork the cuda rng state, perform operations, and exit with the original state.""" # Check if we have added the state if name not in self.states_: raise Exception('cuda rng state {} is not added'.format(name)) # Store current rng state. orig_cuda_rng_state = torch.cuda.get_rng_state() # Set rng state to the desired one _set_cuda_rng_state(self.states_[name]) # Do the stuff we wanted to do. try: yield finally: # Update the current rng state for later use. self.states_[name] = torch.cuda.get_rng_state() # And set the state to the original state we started with. _set_cuda_rng_state(orig_cuda_rng_state) # RNG tracker object. _CUDA_RNG_STATE_TRACKER = CudaRNGStatesTracker() def get_cuda_rng_tracker(): """Get cuda rng tracker.""" return _CUDA_RNG_STATE_TRACKER def model_parallel_cuda_manual_seed(seed): """Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for data parallelism and is the same among a set of model parallel GPUs but different across different model paralle groups. This is used for example for dropout in the non-model-parallel regions. model-parallel state: This state is different among a set of model parallel GPUs, but the same across data parallel groups. This is used for example for dropout in model parallel regions. """ # 2718 is just for fun and any POSITIVE value will work. offset = seed + 2718 model_parallel_seed = offset + get_model_parallel_rank() # Data parallel gets the original sedd. data_parallel_seed = seed if torch.distributed.get_rank() == 0: print('> initializing model parallel cuda seeds on global rank {}, ' 'model parallel rank {}, and data parallel rank {} with ' 'model parallel seed: {} and data parallel seed: {}'.format( torch.distributed.get_rank(), get_model_parallel_rank(), get_data_parallel_rank(), model_parallel_seed, data_parallel_seed), flush=True) _CUDA_RNG_STATE_TRACKER.reset() # Set the default state. torch.cuda.manual_seed(data_parallel_seed) # and model parallel state. _CUDA_RNG_STATE_TRACKER.add(_MODEL_PARALLEL_RNG_TRACKER_NAME, model_parallel_seed) def get_partition_start(item): global mp_rank, mp_size, mp_group partition_size = get_partition_size(item) start = partition_size * mp_rank return int(start) def get_partition_size(item): global mp_rank, mp_size, mp_group size = item.numel() partition_size = size/mp_size return int(partition_size) def get_full_inputs(tensors): inputs=[] for i in range(int(len(tensors)/2)-1): item = tensors[2 * i] size = tensors[2* i + 1] partition_size = item.numel() tensor_size = partition_size * mp_size flat_tensor = torch.zeros([tensor_size], dtype=item.dtype, device=item.device) partitions=[] for i in range(mp_size): part_i = flat_tensor.narrow(0, partition_size * i , partition_size) if i == mp_rank: part_i.copy_(item) partitions.append(part_i) dist.all_gather(partitions,partitions[mp_rank], group=mp_group) input_tensor = flat_tensor.view(list(size.numpy())) item.data=input_tensor.data inputs.append(item) inputs.append(tensors[-2]) return tuple(inputs) class CheckpointFunction(torch.autograd.Function): """This function is adapted from torch.utils.checkpoint with two main changes: 1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state` 2) the states in the model parallel tracker are also properly tracked/set/reset. """ @staticmethod def forward(ctx, run_function, *args): ctx.run_function = run_function global mp_rank, mp_size, mp_group if mp_rank is None: mp_rank = get_model_parallel_rank() mp_size = get_model_parallel_world_size() mp_group = get_model_parallel_group() global cuda_device, transport_stream, PARTITION_ACTIVATIONS if cuda_device is None: if dist.get_rank() == 0: print(f"Partition Activations {PARTITION_ACTIVATIONS} and Correctness Check {PA_CORRECTNESS_TEST}") cuda_device = torch.cuda.current_device() #The transport stream is used to overlap the allgather communication for the activations #with the computation in the backward pass transport_stream = torch.cuda.Stream(device=cuda_device) if PARTITION_ACTIVATIONS: inputs = [item.detach().contiguous().view(-1).narrow(0, get_partition_start(item), get_partition_size(item)).clone() for item in args[:-1]] inputs.append(args[-1]) #just in case something funky is happening such as reuse of inputs inputs_cuda = [item.to(cuda_device) if isinstance(item, torch.Tensor) else item for item in args] # Copy the rng states. ctx.fwd_cpu_rng_state = torch.get_rng_state() ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state() ctx.fwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() #ctx.save_for_backward(*args) with torch.no_grad(): outputs = run_function(*inputs_cuda) del inputs_cuda if PARTITION_ACTIVATIONS: new_args = [] for arg, inp in zip(args,inputs): size= torch.tensor(arg.size()) arg.data = inp.data new_args.append(arg) new_args.append(size) ctx.save_for_backward(*new_args) else: ctx.save_for_backward(*args) return outputs @staticmethod def backward(ctx, *args): if not torch.autograd._is_checkpoint_valid(): raise RuntimeError("Checkpointing is not compatible with .grad(), " "please use .backward() if possible") global cuda_device, transport_stream, PARTITION_ACTIVATIONS if PARTITION_ACTIVATIONS: with torch.cuda.stream(transport_stream): inputs = get_full_inputs(ctx.saved_tensors) detached_inputs = detach_variable(inputs) else: inputs = ctx.saved_tensors detached_inputs = detach_variable(inputs) # Store the current states. bwd_cpu_rng_state = torch.get_rng_state() bwd_cuda_rng_state = torch.cuda.get_rng_state() bwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states() # Set the states to what it used to be before the forward pass. torch.set_rng_state(ctx.fwd_cpu_rng_state) _set_cuda_rng_state(ctx.fwd_cuda_rng_state) get_cuda_rng_tracker().set_states(ctx.fwd_cuda_rng_state_tracker) if PARTITION_ACTIVATIONS: current_stream=torch.cuda.current_stream() current_stream.wait_stream(transport_stream) with torch.enable_grad(): outputs = ctx.run_function(*detached_inputs) # Set the states back to what it was at the start of this function. torch.set_rng_state(bwd_cpu_rng_state) _set_cuda_rng_state(bwd_cuda_rng_state) get_cuda_rng_tracker().set_states(bwd_cuda_rng_state_tracker) if isinstance(outputs, torch.Tensor): outputs = (outputs,) torch.autograd.backward(outputs, args) return (None,) + tuple(inp.grad if isinstance(inp, torch.Tensor) else None for inp in detached_inputs) def checkpoint(function, *args): """Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint.""" return CheckpointFunction.apply(function, *args) def partition_activations_in_checkpoint(partition_activation): global PARTITION_ACTIVATIONS PARTITION_ACTIVATIONS=partition_activation if dist.get_rank() == 0: print(f"**************Partition Activations {PARTITION_ACTIVATIONS}************")
14,040
36.442667
151
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/transformer_enc_dec.py
from audioop import cross import math from numpy.lib.function_base import insert import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F # from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm from .initialize import get_model_parallel_world_size from .layers import ColumnParallelLinear from .layers import RowParallelLinear from .mappings import gather_from_model_parallel_region import deepspeed import pickle from .random import checkpoint from .random import get_cuda_rng_tracker from .utils import divide from .utils import split_tensor_along_last_dim from model.configuration_enc_dec import EncDecConfig from .layers import VocabParallelEmbedding from typing import Callable, Optional, List class LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Construct a layernorm module in the T5 style No bias and no subtraction of mean. """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) # self.bias = nn.Parameter(torch.zeros(hidden_size)) self.eps = eps def forward(self, hidden_states): # layer norm should always be calculated in float32 variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.eps) # convert into float16 if necessary if self.weight.dtype == torch.float16: hidden_states = hidden_states.to(torch.float16) return self.weight * hidden_states @torch.jit.script def gelu_impl(x): """OpenAI's gelu implementation.""" return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x))) def gelu(x): return gelu_impl(x) def unscaled_init_method(sigma): """Init method based on N(0, sigma).""" def init_(tensor): return torch.nn.init.normal_(tensor, mean=0.0, std=sigma) return init_ def scaled_init_method(sigma, num_layers): """Init method based on N(0, sigma/sqrt(2*num_layers).""" std = sigma / math.sqrt(2.0 * num_layers) def init_(tensor): return torch.nn.init.normal_(tensor, mean=0.0, std=std) return init_ def init_method_normal(std): """Init method based on normal distribution. This is only used for embeddings. The transformer has its own initializer. """ def init_(tensor): return torch.nn.init.normal_(tensor, mean=0.0, std=std) return init_ class ParallelDenseReluDense(nn.Module): def __init__(self, config: EncDecConfig, init_method: Callable, output_layer_init_method: Optional[Callable] = None): super(ParallelDenseReluDense, self).__init__() self.wi_0 = ColumnParallelLinear( config.d_model, config.d_ff, gather_output=False, bias=False, init_method=init_method) self.wi_1 = ColumnParallelLinear( config.d_model, config.d_ff, gather_output=False, bias=False, init_method=init_method) self.wo = RowParallelLinear( config.d_ff, config.d_model, bias=False, input_is_parallel=True, init_method=output_layer_init_method) self.dropout = nn.Dropout(config.dropout_rate) # self.do_dim_trick = config.do_dim_trick # if torch.distributed.get_rank() % 5 == 4: # self.ff_mask = nn.Parameter(torch.tensor([1.0] * 13104 + [0.0] * 4), requires_grad=False) # else: # self.ff_mask = nn.Parameter(torch.tensor([1.0] * 13108), requires_grad=False) def forward(self, hidden_states): # hidden_states: [b, s, hp] hidden_gelu = gelu(self.wi_0(hidden_states)) hidden_linear = self.wi_1(hidden_states) hidden_states = hidden_gelu * hidden_linear # hidden_states: [b, s, d_ff_p] # if self.do_dim_trick: # ff_mask = self.ff_mask.view(1, 1, self.ff_mask.size(0)) # hidden_states = ff_mask * hidden_states # hidden_states = F.relu(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.wo(hidden_states) # hidden_states: [b, s, hp] return hidden_states class ParallelAttention(nn.Module): def __init__( self, config: EncDecConfig, init_method: Callable, is_decoder: bool = False, is_cross_attn: bool = False, output_layer_init_method: Optional[Callable] = None, has_relative_attention_bias: bool = False): super(ParallelAttention, self).__init__() self.is_decoder = is_decoder self.is_cross_attn = is_cross_attn self.output_attention = config.output_attention self.has_relative_attention_bias = has_relative_attention_bias self.relative_attention_num_buckets = config.relative_attention_num_buckets # Set output layer initialization if not provided. if output_layer_init_method is None: output_layer_init_method = init_method d_attn_out = config.d_kv * config.num_heads # h # Per attention head and per partition values. world_size = get_model_parallel_world_size() # p self.hidden_size_per_partition = divide(d_attn_out, world_size) # h_p self.hidden_size_per_attention_head = config.d_kv # h_i self.num_attention_heads_per_partition = divide(config.num_heads, world_size) # n_p # Strided linear layer. if is_cross_attn: self.project_q = ColumnParallelLinear(config.d_model, d_attn_out, stride=1, # NOTE: modify stride bias=False, gather_output=False, init_method=init_method) self.project_kv = ColumnParallelLinear(config.d_model, 2 * d_attn_out, stride=2, # NOTE: modify stride bias=False, gather_output=False, init_method=init_method) else: self.project = ColumnParallelLinear(config.d_model, 3 * d_attn_out, stride=3, bias=False, gather_output=False, init_method=init_method) if self.has_relative_attention_bias: self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.num_attention_heads_per_partition) # Dropout. Note that for a single iteration, this layer will generate # different outputs on different number of parallel partitions but # on average it should not be partition dependent. self.attention_dropout = nn.Dropout(config.dropout_rate) # Output. self.dense = RowParallelLinear(d_attn_out, config.d_model, input_is_parallel=True, bias=False, init_method=output_layer_init_method) self.output_dropout = nn.Dropout(config.dropout_rate) if deepspeed.checkpointing.is_configured(): global get_cuda_rng_tracker, checkpoint get_cuda_rng_tracker = deepspeed.checkpointing.get_cuda_rng_tracker checkpoint = deepspeed.checkpointing.checkpoint def _transpose_for_scores(self, tensor): """Transpose a 3D tensor [b, s, h_p=n_p*h_i] into a 4D tensor with size [b, np, s, hn]. """ new_tensor_shape = tensor.size()[:-1] + \ (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head) # [b, s, n_p, h_i] tensor = tensor.view(*new_tensor_shape) # tensor: [b, n_p, s, h_i] return tensor.permute(0, 2, 1, 3) @staticmethod def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128): """ Adapted from Mesh Tensorflow: https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593 Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for small absolute relative_position and larger buckets for larger absolute relative_positions. All relative positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket. This should allow for more graceful generalization to longer sequences than the model has been trained on Args: relative_position: an int32 Tensor bidirectional: a boolean - whether the attention is bidirectional num_buckets: an integer max_distance: an integer Returns: a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets) """ relative_buckets = 0 if bidirectional: num_buckets //= 2 relative_buckets += (relative_position > 0).to(torch.long) * num_buckets relative_position = torch.abs(relative_position) else: relative_position = -torch.min(relative_position, torch.zeros_like(relative_position)) # now relative_position is in the range [0, inf) # half of the buckets are for exact increments in positions max_exact = num_buckets // 2 is_small = relative_position < max_exact # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance relative_postion_if_large = max_exact + ( torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact) ).to(torch.long) relative_postion_if_large = torch.min( relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1) ) relative_buckets += torch.where(is_small, relative_position, relative_postion_if_large) return relative_buckets def compute_bias(self, query_length, key_length): """ Compute binned relative position bias """ context_position = torch.arange(query_length, dtype=torch.long)[:, None] memory_position = torch.arange(key_length, dtype=torch.long)[None, :] relative_position = memory_position - context_position # shape (query_length, key_length) relative_position_bucket = self._relative_position_bucket( relative_position, # shape (query_length, key_length) bidirectional=(not self.is_decoder), num_buckets=self.relative_attention_num_buckets, ) relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device) values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads) values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length) return values def forward( self, hidden_states, attention_mask=None, key_value_states=None, position_bias=None, query_length=None, past_key_value=None,): batch_size, seq_length = hidden_states.shape[:2] real_seq_length = seq_length if past_key_value is not None: assert ( len(past_key_value) == 2 ), "past_key_value should have 2 past states: keys and values. Got {} past states".format( len(past_key_value) ) real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length key_length = real_seq_length if key_value_states is None else key_value_states.shape[1] # hidden_states: [b, s, d_model] if key_value_states is not None: assert self.is_cross_attn is True # mixed_query_layer: [b, s, h_p] mixed_query_layer = self.project_q(hidden_states) # mixed_key_value_layer: [b, s, 2 * h_p] mixed_key_value_layer = self.project_kv(key_value_states) (mixed_key_layer, mixed_value_layer) = split_tensor_along_last_dim(mixed_key_value_layer, 2) else: assert self.is_cross_attn is False # hidden_states: [b, s, h] mixed_x_layer = self.project(hidden_states) # mixed_x_layer: [b, s, 3 * h_p] (mixed_query_layer, mixed_key_layer, mixed_value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3) # mixed_***_layer: [b, s, h_p] # ***_layer [b, n_p, s, h_i] query_layer = self._transpose_for_scores(mixed_query_layer) key_layer = self._transpose_for_scores(mixed_key_layer) value_layer = self._transpose_for_scores(mixed_value_layer) if past_key_value is not None and not self.is_cross_attn: assert self.is_decoder is True # decoder # ***_layer: [b, n_p, 1, h_i] past_key_layer, past_value_layer = past_key_value # past_***_layer: [b, n_p, s-1, h_i] key_layer = torch.cat([past_key_layer, key_layer], dim=2) value_layer = torch.cat([past_value_layer, value_layer], dim=2) # ***_layer: [b, n_p, s_k, h_i] # Raw attention scores. [b, n_p, s_q, s_k] compute every head alone attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) # NOTE: We follow the implementation of Transformers to remove the scale of attention+acores # attention_scores = attention_scores / math.sqrt( # self.hidden_size_per_attention_head) # relative positional bias if position_bias is None: if not self.has_relative_attention_bias: position_bias = torch.zeros( (1, self.num_attention_heads_per_partition, real_seq_length, key_length), device=attention_scores.device, dtype=attention_scores.dtype ) else: position_bias = self.compute_bias(real_seq_length, key_length) # if key and values are already calculated # we want only the last query position bias if past_key_value is not None: position_bias = position_bias[:, :, -seq_length:, :] # if torch.distributed.get_rank() == 0: # print(real_seq_length, key_length, position_bias[0, 0, 0]) no_pos_bias_attn_probs = nn.Softmax(dim=-1)(attention_scores) # Apply the attention mask [b, 1, s_q, s_k] and relative position_bias # NOTE: 10000 can't be larger otherwise may cause fp16 overflow (max in fp16 = 65504) attention_scores = torch.mul(attention_scores, attention_mask) + (-10000.0 * (1.0 - attention_mask) + position_bias) # attention_scores = torch.mul(attention_scores, attention_mask) - 10000.0 * (1.0 - attention_mask) if hasattr(self, "score_storage"): if self.score_storage is None: self.score_storage = attention_scores[:, :, 0:1, :] # Attention probabilities. [b, n_p, s_q, s_k] attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. with get_cuda_rng_tracker().fork(): attention_probs = self.attention_dropout(attention_probs) # Context layer. context_layer = torch.matmul(attention_probs, value_layer) # context_layer: [b, n_p, s, h_i] context_layer = context_layer.permute(0, 2, 1, 3).contiguous() # context_layer: [b, s, n_p, h_i] # if self.do_dim_trick: # head_mask = self.head_mask.view(1, 1, self.head_mask.size(0), 1).expand_as(context_layer) # context_layer = context_layer * head_mask new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,) context_layer = context_layer.view(*new_context_layer_shape) # context_layer: [b, s, h_p] attn_output = self.dense(context_layer) # attn_output: [b, s, d_model] attn_output = self.output_dropout(attn_output) present_key_value_state = torch.stack((key_layer, value_layer), dim=0) if self.is_decoder else None outputs = (attn_output,) + (present_key_value_state,) + (position_bias,) if self.output_attention: outputs += (no_pos_bias_attn_probs,) else: outputs += (None,) return outputs # attn_output, present_key_value_state, position_bias, attention_probs class ParallelSelfAttention(nn.Module): def __init__( self, config: EncDecConfig, init_method: Callable, is_decoder: bool = False, output_layer_init_method: Optional[Callable] = None, has_relative_attention_bias: bool = False): super(ParallelSelfAttention, self).__init__() self.self_attn = ParallelAttention( config, init_method, is_decoder=is_decoder, is_cross_attn=False, output_layer_init_method=output_layer_init_method, has_relative_attention_bias=has_relative_attention_bias) self.layer_norm = LayerNorm(config.d_model, eps=config.layer_norm_epsilon) self.dropout = nn.Dropout(config.dropout_rate) def forward( self, hidden_states, attention_mask=None, position_bias=None, past_key_value=None): normed_hidden_states = self.layer_norm(hidden_states) attention_output = self.self_attn( normed_hidden_states, attention_mask=attention_mask, position_bias=position_bias, past_key_value=past_key_value, ) hidden_states = hidden_states + self.dropout(attention_output[0]) # add attentions if we output them outputs = (hidden_states,) + attention_output[1:] return outputs # hidden_states, present_key_value_state, position_bias, (attention_probs) class ParallelCrossAttention(nn.Module): def __init__( self, config: EncDecConfig, init_method: Callable, is_decoder: bool = True, output_layer_init_method: Optional[Callable] = None): super(ParallelCrossAttention, self).__init__() self.cross_attn = ParallelAttention( config, init_method, is_decoder=is_decoder, is_cross_attn=True, output_layer_init_method=output_layer_init_method, has_relative_attention_bias=False) self.layer_norm = LayerNorm(config.d_model, eps=config.layer_norm_epsilon) self.dropout = nn.Dropout(config.dropout_rate) def forward( self, hidden_states, key_value_states, attention_mask=None, position_bias=None, query_length=None, past_key_value=None): normed_hidden_states = self.layer_norm(hidden_states) attention_output = self.cross_attn( normed_hidden_states, key_value_states=key_value_states, attention_mask=attention_mask, position_bias=position_bias, query_length=query_length, past_key_value=past_key_value ) hidden_states = hidden_states + self.dropout(attention_output[0]) # add attentions if we output them outputs = (hidden_states,) + attention_output[1:] return outputs # hidden_states, present_key_value_state, position_bias, (attention_probs) class ParallelFF(nn.Module): def __init__( self, config: EncDecConfig, init_method: Callable, output_layer_init_method: Callable = None): super(ParallelFF, self).__init__() self.dense_relu_dense = ParallelDenseReluDense(config, init_method, output_layer_init_method) self.layer_norm = LayerNorm(config.d_model, eps=config.layer_norm_epsilon) self.dropout = nn.Dropout(config.dropout_rate) def forward(self, hidden_states): # hidden_states [b, s, d_model] forwarded_states = self.layer_norm(hidden_states) forwarded_states = self.dense_relu_dense(forwarded_states) hidden_states = hidden_states + self.dropout(forwarded_states) return hidden_states class ParallelBlock(nn.Module): def __init__( self, config: EncDecConfig, init_method: Callable, output_layer_init_method: Optional[Callable] = None, has_relative_attention_bias: bool = False, is_decoder: bool = False): super(ParallelBlock, self).__init__() if output_layer_init_method is None: output_layer_init_method = init_method self.is_decoder = is_decoder self.self_attn = ParallelSelfAttention( config, init_method, is_decoder=is_decoder, output_layer_init_method=output_layer_init_method, has_relative_attention_bias=has_relative_attention_bias) if is_decoder: self.cross_attn = ParallelCrossAttention( config, init_method, is_decoder=is_decoder, output_layer_init_method=output_layer_init_method) self.ff = ParallelFF( config, init_method, output_layer_init_method=output_layer_init_method) def forward( self, hidden_states, attention_mask=None, position_bias=None, enc_hidden_states=None, cross_attention_mask=None, enc_dec_position_bias=None, past_key_value=None,): if past_key_value is not None: self_attn_past_key_value = past_key_value[0] cross_attn_past_key_value = past_key_value[1] else: self_attn_past_key_value, cross_attn_past_key_value = None, None self_attn_outputs = self.self_attn( hidden_states, attention_mask=attention_mask, position_bias=position_bias, past_key_value=self_attn_past_key_value, ) hidden_states, self_attn_present_key_value = self_attn_outputs[:2] position_bias = (self_attn_outputs[2],) attention_probs = (self_attn_outputs[3],) present_key_value = (self_attn_present_key_value,) # cross attn if self.is_decoder: if self_attn_present_key_value is not None: query_length = self_attn_present_key_value[0].shape[2] else: query_length = None cross_attn_outputs = self.cross_attn( hidden_states, key_value_states=enc_hidden_states, attention_mask=cross_attention_mask, position_bias=enc_dec_position_bias, past_key_value=cross_attn_past_key_value, query_length=query_length, ) hidden_states, cross_attn_present_key_value = cross_attn_outputs[:2] present_key_value += (cross_attn_present_key_value,) # Keep cross-attention outputs and relative position weights position_bias = position_bias + (cross_attn_outputs[2],) attention_probs = attention_probs + (cross_attn_outputs[3],) hidden_states = self.ff(hidden_states) outputs = (hidden_states,) outputs = outputs + (present_key_value,) + position_bias + attention_probs # (for encoder) hidden_states, present_key_value_states, self-attention position bias, attention_probs # (for decoder) hidden_states, present_key_value_states, self-attention position bias, cross-attention position bias, self_attention_probs, cross_attention_probs return outputs class ParallelTransformer(nn.Module): def __init__(self, config: EncDecConfig, word_embeds: VocabParallelEmbedding, prompt_config=None, is_decoder=False, checkpoint_activations=False, checkpoint_num_layers=1, args=None): super(ParallelTransformer, self).__init__() self.word_embeds = word_embeds self.config = config self.args = args self.prompt_config = prompt_config if self.prompt_config is not None and self.prompt_config["prompt_len"] > 0: prompt_dim = prompt_config.get("prompt_dim", config.d_model) self.prompt_embeds = nn.Embedding(prompt_config["prompt_len"], prompt_dim) self.dropout = nn.Dropout(config.dropout_rate) self.final_layernorm = LayerNorm(config.d_model, eps=config.layer_norm_epsilon) self.checkpoint_activations = checkpoint_activations self.checkpoint_num_layers = checkpoint_num_layers self.is_decoder = is_decoder output_layer_init_method = None if config.use_scaled_init_for_output_weights: output_layer_init_method = scaled_init_method(config.init_method_std, config.num_layers) self.blocks = nn.ModuleList( [ParallelBlock( config, unscaled_init_method(sigma=config.init_method_std), has_relative_attention_bias=bool(i == 0), output_layer_init_method=output_layer_init_method, is_decoder=is_decoder) for i in range(config.num_layers)] ) if deepspeed.checkpointing.is_configured(): global get_cuda_rng_tracker, checkpoint get_cuda_rng_tracker = deepspeed.checkpointing.get_cuda_rng_tracker checkpoint = deepspeed.checkpointing.checkpoint def init_prompt_embeds(self): if self.prompt_config is not None and self.prompt_config["prompt_len"] > 0: prompt_weights = self.word_embeds(self.prompt_config["init_ids"]).detach() self.prompt_embeds.weight.data = prompt_weights def load_prompt_embeds(self, prompt_embeds): if self.prompt_config is not None and self.prompt_config["prompt_len"] > 0: prompt_embeds = prompt_embeds.to(self.prompt_embeds.weight.data.device) print("loading prompts") self.prompt_embeds.weight.data = prompt_embeds def get_prompt(self): if self.prompt_config is not None and self.prompt_config["prompt_len"] > 0: return self.prompt_embeds.weight.data else: return None def get_input_embeds(self, input_ids): if self.prompt_config is None: return self.word_embeds(input_ids) p_embeds = None if self.prompt_config is not None and self.prompt_config["prompt_len"] > 0 and self.prompt_config.get("insert_input", True): prompt_mask = (input_ids < 0).long() prompt_ids = (-(input_ids * prompt_mask)) - prompt_mask p_embeds = self.prompt_embeds(prompt_ids) * prompt_mask.half().unsqueeze(-1) word_mask = (0 <= input_ids).long() word_ids = word_mask * input_ids w_embeds = self.word_embeds(word_ids) * word_mask.float().unsqueeze(-1) if p_embeds is not None: w_embeds = w_embeds + p_embeds return w_embeds # bs * seq_len * hidden def forward( self, input_ids=None, attention_mask=None, cross_attention_mask=None, enc_hidden_states=None, past_key_values=None,): bs = input_ids.size(0) inputs_embeds = self.get_input_embeds(input_ids) hidden_states = self.dropout(inputs_embeds) position_bias = None enc_dec_position_bias = None present_key_value_states = [] # initialize past_key_values with `None` if past does not exist if past_key_values is None: past_key_values = [None] * len(self.blocks) all_self_attention_probs = [] all_cross_attention_probs = [] def custom(start, end): def custom_forward(*inputs): layer_modules_ = self.blocks[start:end] past_key_values_ = past_key_values[start:end] self_attn_present_key_values_ = [] cross_attn_present_key_values_ = [] position_bias_, enc_dec_position_bias_ = None, None hidden_states_ = inputs[0] if len(inputs) > 2: position_bias_ = inputs[1] if len(inputs) > 3: enc_dec_position_bias_ = inputs[2] if enc_hidden_states is not None: enc_hidden_states_ = inputs[-1] else: enc_hidden_states_ = None _l = start for layer_, past_key_value_ in zip(layer_modules_, past_key_values_): attention_mask_ = attention_mask cross_attention_mask_ = cross_attention_mask layer_outputs_ = layer_(hidden_states_, attention_mask_, position_bias_, enc_hidden_states_, cross_attention_mask_, enc_dec_position_bias_, past_key_value=past_key_value_) hidden_states_, present_key_value_ = layer_outputs_[:2] if self.is_decoder: self_attn_present_key_values_.append(present_key_value_[0]) cross_attn_present_key_values_.append(present_key_value_[1]) all_self_attention_probs.append(layer_outputs_[-2]) all_cross_attention_probs.append(layer_outputs_[-1]) else: self_attn_present_key_values_.append(present_key_value_[0]) all_self_attention_probs.append(layer_outputs_[-1]) position_bias_ = layer_outputs_[2] if self.is_decoder and enc_hidden_states is not None: enc_dec_position_bias_ = layer_outputs_[3] _l += 1 outputs_ = (hidden_states_,) if position_bias_ is not None: outputs_ += (position_bias_,) if enc_dec_position_bias_ is not None: outputs_ += (enc_dec_position_bias_,) if self.is_decoder: self_attn_present_key_values_ = torch.stack(self_attn_present_key_values_, dim=0) cross_attn_present_key_values_ = torch.stack(cross_attn_present_key_values_, dim=0) outputs_ += (self_attn_present_key_values_, cross_attn_present_key_values_,) return outputs_ return custom_forward if self.checkpoint_activations: l = 0 num_layers = len(self.blocks) chunk_length = self.checkpoint_num_layers while l < num_layers: arg_list = (hidden_states,) if position_bias is not None: arg_list += (position_bias,) if enc_dec_position_bias is not None: arg_list += (enc_dec_position_bias,) if enc_hidden_states is not None: arg_list += (enc_hidden_states,) tmp_outputs = checkpoint(custom(l, l+chunk_length), *arg_list) else: arg_list += (attention_mask,) tmp_outputs = checkpoint(custom(l, l+chunk_length), *arg_list) hidden_states = tmp_outputs[0] if self.is_decoder: if len(tmp_outputs) > 3: position_bias = tmp_outputs[1] if len(tmp_outputs) > 4: enc_dec_position_bias = tmp_outputs[2] present_key_value_states.extend([(s, c) for s, c in zip(tmp_outputs[-2], tmp_outputs[-1])]) else: if len(tmp_outputs) > 1: position_bias = tmp_outputs[1] if len(tmp_outputs) > 2: enc_dec_position_bias = tmp_outputs[2] present_key_value_states.extend([None] * chunk_length) l += chunk_length else: for i, (layer_module, past_key_value) in enumerate(zip(self.blocks, past_key_values)): layer_outputs = layer_module( hidden_states, attention_mask=attention_mask, position_bias=position_bias, enc_hidden_states=enc_hidden_states, cross_attention_mask=cross_attention_mask, enc_dec_position_bias=enc_dec_position_bias, past_key_value=past_key_value ) # layer_outputs is a tuple with: # hidden-states, key-value-states, self-attention position bias, cross-attention position bias, attention_probs hidden_states, present_key_value_state = layer_outputs[:2] if self.is_decoder: all_self_attention_probs.append(layer_outputs[-2]) all_cross_attention_probs.append(layer_outputs[-1]) else: all_self_attention_probs.append(layer_outputs[-1]) position_bias = layer_outputs[2] if self.is_decoder and enc_hidden_states is not None: enc_dec_position_bias = layer_outputs[3] present_key_value_states.append(present_key_value_state) # We share the position biases between the layers - the first layer store them # layer_outputs = hidden-states, key-value-states (self-attention weights), # (self-attention position bias), (cross-attention weights), (cross-attention position bias) # position_bias = layer_outputs[2] hidden_states = self.final_layernorm(hidden_states) hidden_states = self.dropout(hidden_states) # exit(0) outputs = { "last_hidden_state": hidden_states, "past_key_values": present_key_value_states, "hidden_states": None, "attentions": all_self_attention_probs, "cross_attentions": all_cross_attention_probs } return outputs
35,723
41.427553
186
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/__init__.py
# coding=utf-8 """Model parallel utility interface.""" from .cross_entropy import vocab_parallel_cross_entropy from .cross_entropy import parallel_soft_cross_entropy_loss from .data import broadcast_data from .grads import clip_grad_norm from .initialize import destroy_model_parallel from .initialize import get_data_parallel_group from .initialize import get_data_parallel_rank from .initialize import get_data_parallel_world_size from .initialize import get_model_parallel_group from .initialize import get_model_parallel_rank from .initialize import get_model_parallel_src_rank from .initialize import get_model_parallel_world_size from .initialize import initialize_model_parallel from .initialize import model_parallel_is_initialized from .layers import ColumnParallelLinear from .layers import ParallelEmbedding from .layers import RowParallelLinear from .layers import VocabParallelEmbedding from .mappings import copy_to_model_parallel_region from .mappings import gather_from_model_parallel_region from .mappings import reduce_from_model_parallel_region from .mappings import scatter_to_model_parallel_region from .random import checkpoint from .random import partition_activations_in_checkpoint from .random import get_cuda_rng_tracker from .random import model_parallel_cuda_manual_seed from .transformer_enc_dec import LayerNorm from .transformer_enc_dec import ParallelTransformer
1,406
32.5
59
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/enc_dec_modeling.py
import copy import torch import torch.nn as nn import torch.nn.functional as F import mpu from .configuration_enc_dec import EncDecConfig def init_method_normal(std): """Init method based on normal distribution. This is only used for embeddings. The transformer has its own initializer. """ def init_(tensor): return torch.nn.init.normal_(tensor, mean=0.0, std=std) return init_ class EncDecModel(nn.Module): def __init__( self, config: EncDecConfig, parallel_output=True, checkpoint_activations=False, checkpoint_num_layers=1, prompt_config=None, args=None): super(EncDecModel, self).__init__() if config.vocab_size is None: raise RuntimeError("Should set vocab size") self.enc_config = copy.deepcopy(config) self.dec_config = copy.deepcopy(config) self.parallel_output = parallel_output init_method = init_method_normal(std=config.init_method_std) # NOTE: good? self.word_embeds = mpu.VocabParallelEmbedding(config.vocab_size, config.d_model, init_method=init_method) self.prompt_config = prompt_config self.args = args self.lm_head = mpu.VocabParallelEmbedding(config.vocab_size, config.d_model, init_method=init_method) self.encoder = mpu.ParallelTransformer(self.enc_config, word_embeds=self.word_embeds, is_decoder=False, prompt_config=prompt_config["enc"] if prompt_config is not None else None, checkpoint_activations=checkpoint_activations, checkpoint_num_layers=checkpoint_num_layers, args=args) self.decoder = mpu.ParallelTransformer(self.dec_config, word_embeds=self.word_embeds, is_decoder=True, prompt_config=prompt_config["dec"] if prompt_config is not None else None, checkpoint_activations=checkpoint_activations, checkpoint_num_layers=checkpoint_num_layers, args=args) if config.tie_weights: self.tie_weights() def init_prompt_embeds(self): self.encoder.init_prompt_embeds() self.decoder.init_prompt_embeds() def load_prompt_embeds(self, prompt_embeds): self.encoder.load_prompt_embeds(prompt_embeds) self.decoder.load_prompt_embeds(prompt_embeds) def get_prompt_embeds(self): return { "encoder": self.encoder.get_prompt(), "decoder": self.decoder.get_prompt() } def tie_weights(self): self.lm_head.weight = self.word_embeds.weight def reset_score_storage(self): for mod in self.decoder.blocks: mod.cross_attn.cross_attn.score_storage = None def get_crossattention_scores(self, context_mask): scores = [] n_passages = context_mask.size(1) for mod in self.decoder.blocks: scores.append(mod.cross_attn.cross_attn.score_storage) scores = torch.cat(scores, dim=2) # FiD n_layers beacuse dec seq = 1, auto regressive bsz, n_heads, n_layers, _ = scores.size() # batch_size, n_head, n_layers, n_passages, text_maxlength scores = scores.view(bsz, n_heads, n_layers, n_passages, -1) # batch_size, 1, 1, n_passages, text_maxlength scores = scores.masked_fill(~context_mask[:, None, None], 0.).float() # batch_size, n_passages scores = scores.sum(dim=[1, 2, 4]) ntokens = context_mask.sum(dim=[2]) * n_layers * n_heads scores = scores / ntokens return scores def forward( self, enc_input_ids=None, enc_position_ids=None, enc_attention_mask=None, dec_input_ids=None, dec_position_ids=None, dec_attention_mask=None, cross_attention_mask=None, enc_hidden_states=None, past_key_values=None, only_encoder=False,): provided_hidden = (enc_hidden_states is not None) if enc_hidden_states is None: enc_outputs = self.encoder( input_ids=enc_input_ids, attention_mask=enc_attention_mask, ) enc_hidden_states = enc_outputs["last_hidden_state"] if only_encoder: outputs = { "encoder_last_hidden_state": enc_hidden_states, "encoder_hidden_states": enc_outputs["hidden_states"], "encoder_attentions": enc_outputs["attentions"], } return outputs dec_outputs = self.decoder( input_ids=dec_input_ids, attention_mask=dec_attention_mask, cross_attention_mask=cross_attention_mask, enc_hidden_states=enc_hidden_states, past_key_values=past_key_values, ) last_hidden_state_parallel = mpu.copy_to_model_parallel_region(dec_outputs["last_hidden_state"]) logits_parallel = F.linear(last_hidden_state_parallel, self.lm_head.weight) if self.parallel_output: lm_logits = logits_parallel else: lm_logits = mpu.gather_from_model_parallel_region(logits_parallel) outputs = { "lm_logits": lm_logits, "last_hidden_state": dec_outputs["last_hidden_state"], "past_key_values": dec_outputs["past_key_values"], "encoder_last_hidden_state": enc_hidden_states, "encoder_attentions": enc_outputs["attentions"] if not provided_hidden else None, "decoder_self_attentions": dec_outputs["attentions"], "decoder_cross_attentions": dec_outputs["cross_attentions"] } return outputs def enc_dec_get_params_for_weight_decay_optimization(module): weight_decay_params = {'params': []} no_weight_decay_params = {'params': [], 'weight_decay': 0.0} for module_ in module.modules(): if isinstance(module_, (mpu.LayerNorm, nn.LayerNorm, mpu.transformer_enc_dec.LayerNorm)): no_weight_decay_params['params'].extend( [p for p in list(module_._parameters.values()) if p is not None]) else: weight_decay_params['params'].extend( [p for n, p in list(module_._parameters.items()) if p is not None and n != 'bias']) no_weight_decay_params['params'].extend( [p for n, p in list(module_._parameters.items()) if p is not None and n == 'bias']) return weight_decay_params, no_weight_decay_params def enc_dec_get_params_for_prompt_optimization(module: nn.Module): params = [{'params': []}] for t in module.named_modules(): if "prompt" in t[0]: if torch.distributed.get_rank() == 0: print("Update params", t[0]) params[0]['params'].extend([p for p in list(t[1]._parameters.values()) if p is not None]) for t in module.named_parameters(): if "prompt" not in t[0]: t[1].requires_grad_(False) if torch.distributed.get_rank() == 0: print("print params", params) return params
7,115
35.492308
186
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/distributed.py
# coding=utf-8 import torch from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors import torch.distributed as dist from torch.nn.modules import Module from torch.autograd import Variable import mpu class DistributedDataParallel(Module): def __init__(self, module): super(DistributedDataParallel, self).__init__() self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False self.module = module self.data_parallel_group = mpu.get_data_parallel_group() src_rank = mpu.get_model_parallel_rank() for p in self.module.parameters(): if torch.is_tensor(p): dist.broadcast(p, src_rank, group=self.data_parallel_group) def allreduce_params(reduce_after=True, no_scale=False, fp32_allreduce=False): if(self.needs_reduction): self.needs_reduction = False buckets = {} for name, param in self.module.named_parameters(): if param.requires_grad and param.grad is not None: tp = (param.data.type()) if tp not in buckets: buckets[tp] = [] buckets[tp].append(param) if self.warn_on_half: if torch.cuda.HalfTensor in buckets: print("WARNING: gloo dist backend for half parameters may be extremely slow." + " It is recommended to use the NCCL backend in this case.") self.warn_on_half = False for tp in buckets: bucket = buckets[tp] grads = [param.grad.data for param in bucket] coalesced = _flatten_dense_tensors(grads) if fp32_allreduce: coalesced = coalesced.float() if not no_scale and not reduce_after: coalesced /= dist.get_world_size(group=self.data_parallel_group) dist.all_reduce(coalesced, group=self.data_parallel_group) torch.cuda.synchronize() if not no_scale and reduce_after: coalesced /= dist.get_world_size(group=self.data_parallel_group) for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)): buf.copy_(synced) self.hook_handles = [] self.hooks = [] for param in list(self.module.parameters()): def allreduce_hook(*unused): Variable._execution_engine.queue_callback(allreduce_params) # handle = param.register_hook(allreduce_hook) #self.hooks.append(allreduce_hook) #self.hook_handles.append(handle) self.allreduce_params = allreduce_params def forward(self, *inputs, **kwargs): self.needs_reduction = True return self.module(*inputs, **kwargs) def state_dict(self, destination=None, prefix='', keep_vars=False): #[h.remove() for h in self.hook_handles] sd = self.module.state_dict(destination, prefix, keep_vars) # for handle, hook in zip(self.hook_handles, self.hooks): # d = handle.hooks_dict_ref() # d[handle.id] = hook return sd def load_state_dict(self, state_dict, strict=True): self.module.load_state_dict(state_dict, strict=strict) ''' def _sync_buffers(self): buffers = list(self.module._all_buffers()) if len(buffers) > 0: # cross-node buffer sync flat_buffers = _flatten_dense_tensors(buffers) dist.broadcast(flat_buffers, 0) for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)): buf.copy_(synced) def train(self, mode=True): # Clear NCCL communicator and CUDA event cache of the default group ID, # These cache will be recreated at the later call. This is currently a # work-around for a potential NCCL deadlock. if dist._backend == dist.dist_backend.NCCL: dist._clear_group_cache() super(DistributedDataParallel, self).train(mode) self.module.train(mode) '''
4,286
42.30303
103
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/__init__.py
# coding=utf-8 from .distributed import * from .enc_dec_modeling import EncDecModel from .enc_dec_modeling import enc_dec_get_params_for_weight_decay_optimization from .enc_dec_modeling import enc_dec_get_params_for_prompt_optimization from .configuration_enc_dec import EncDecConfig
287
27.8
78
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/configuration_enc_dec.py
""" enc_dec model configuration """ import json import os import copy from typing import Any, Dict, Tuple, Union class EncDecConfig(object): def __init__( self, d_model=768, d_kv=64, d_ff=256, num_layers=12, num_decoder_layers=12, num_heads=12, relative_attention_num_buckets=32, dropout_rate=0.1, layer_norm_epsilon=1e-6, initializer_factor=1.0, feed_forward_proj="relu", use_cache=True, use_scaled_init_for_output_weights=True, init_method_std=0.02, max_position_embeddings=1024, do_dim_trick=False, output_attention=False, tie_weights=False, **kwargs ): super().__init__() self.d_model = d_model self.d_kv = d_kv self.d_ff = d_ff self.num_layers = num_layers self.num_decoder_layers = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry self.num_heads = num_heads self.relative_attention_num_buckets = relative_attention_num_buckets self.dropout_rate = dropout_rate self.layer_norm_epsilon = layer_norm_epsilon self.initializer_factor = initializer_factor self.feed_forward_proj = feed_forward_proj self.use_cache = use_cache self.use_scaled_init_for_output_weights = use_scaled_init_for_output_weights self.init_method_std = init_method_std self.max_position_embeddings = max_position_embeddings self.vocab_size = None self.do_dim_trick = do_dim_trick self.output_attention = output_attention self.tie_weights = tie_weights @classmethod def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike]) -> "EncDecConfig": return cls.from_json_file(pretrained_model_name_or_path) @classmethod def from_json_file(cls, json_file: Union[str, os.PathLike]) -> "EncDecConfig": config_dict = cls._dict_from_json_file(json_file) return cls(**config_dict) @classmethod def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]): with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return json.loads(text) def to_json_file(self, json_file_path: Union[str, os.PathLike]): with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) def to_dict(self) -> Dict[str, Any]: output = copy.deepcopy(self.__dict__) if hasattr(self.__class__, "model_type"): output["model_type"] = self.__class__.model_type return output def to_json_string(self) -> str: config_dict = self.to_dict() return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
2,881
34.146341
103
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/__init__.py
from .data_config import DATA_CONFIG from .postprocess import ANSWER_POST_FN
77
25
39
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/data_config.py
import os BASE_DATA_DIR = "data" def string_to_float(preds, labels): return [float(p) for p in preds], [float(l) for l in labels] DATA_GROUP_CONFIG = { "MCQA": [ "dream", "quail", "quartz", "social_i_qa", "wiqa", "cosmos_qa", "qasc", "quarel", "sciq", "wiki_hop", ], "MCQA_PSEUDO": [ "quail_pseudo", "quartz_pseudo", "social_i_qa_pseudo", "cosmos_qa_pseudo", "quarel_pseudo", ], "EXQA": ["adversarial_qa", "quoref", "ropes", "duorc_self", "duorc_para"], "EXQA_PSEUDO": ["adversarial_qa_pseudo", "quoref_pseudo", "ropes_pseudo"], "CBQA": ["hotpot_qa_distractor", "hotpot_qa_fullwiki", "wiki_qa"], "CBQA_PSEUDO": ["wiki_qa_pseudo"], "SENT": [ "yelp_polarity", "rotten_tomatoes", "imdb", "app_reviews", "amazon_polarity", ], "SENT_PSEUDO": ["yelp_polarity_pseudo", "rotten_tomatoes_pseudo", "imdb_pseudo"], "TC": ["ag_news", "dbpedia_14", "trec"], "TC_PSEUDO": ["ag_news_pseudo", "dbpedia_14_pseudo"], "S2T": ["wiki_bio", "common_gen"], "S2T_PSEUDO": ["common_gen_pseudo"], "SUM": ["xsum", "gigaword", "multi_news", "samsum", "cnn_dailymail"], "SUM_PSEUDO": ["xsum_pseudo", "gigaword_pseudo", "cnn_dailymail_pseudo"], "PARA": ["mrpc", "qqp", "paws_labeled_final"], "PARA_PSEUDO": ["mrpc_pseudo", "qqp_pseudo", "paws_labeled_final_pseudo"], "SC": ["copa", "hellaswag", "story_cloze_2016"], "NLI": ["rte", "cb", "anli_r1", "anli_r2", "anli_r3"], "COREF": ["wsc", "winorande_xl", "winogrande_debiased"], "WIC": ["wic"], "DATA_0.1": [ "sciq", "duorc_self", "hotpot_qa_fullwiki", "app_reviews", "trec", "wiki_bio", "multi_news", "qqp", ], "DATA_0.4": ["qasc", "quarel", "wiki_hop", "quoref", "imdb", "xsum"], "DATA_0.7": [ "wiqa", "quartz", "dream", "ropes", "duorc_para", "hotpot_qa_distractor", "amazon_polarity", "rotten_tomatoes", "ag_news", "samsum", "cnn_dailymail", "mrpc", ], "DATA_1.0": [ "cosmos_qa", "social_i_qa", "quail", "adversarial_qa", "wiki_qa", "yelp_polarity", "dbpedia_14", "common_gen", "gigaword", "paws_labeled_final", ], "DATA_0.4_PSEUDO": ["quarel_pseudo", "quoref_pseudo", "imdb_pseudo", "xsum_pseudo"], "DATA_0.7_PSEUDO": [ "quartz_pseudo", "ropes_pseudo", "rotten_tomatoes_pseudo", "ag_news_pseudo", "cnn_dailymail_pseudo", "mrpc_pseudo", ], "DATA_1.0_PSEUDO": [ "cosmos_qa_pseudo", "social_i_qa_pseudo", "quail_pseudo", "adversarial_qa_pseudo", "wiki_qa_pseudo", "yelp_polarity_pseudo", "dbpedia_14_pseudo", "common_gen_pseudo", "gigaword_pseudo", "paws_labeled_final_pseudo", ], "MMLU": [ "abstract_algebra", "anatomy", "astronomy", "business_ethics", "clinical_knowledge", "college_biology", "college_chemistry", "college_computer_science", "college_mathematics", "college_medicine", "college_physics", "computer_security", "conceptual_physics", "econometrics", "electrical_engineering", "elementary_mathematics", "formal_logic", "global_facts", "high_school_biology", "high_school_chemistry", "high_school_computer_science", "high_school_european_history", "high_school_geography", "high_school_government_and_politics", "high_school_macroeconomics", "high_school_mathematics", "high_school_microeconomics", "high_school_physics", "high_school_psychology", "high_school_statistics", "high_school_us_history", "high_school_world_history", "human_aging", "human_sexuality", "international_law", "jurisprudence", "logical_fallacies", "machine_learning", "management", "marketing", "medical_genetics", "miscellaneous", "moral_disputes", "moral_scenarios", "nutrition", "philosophy", "prehistory", "professional_accounting", "professional_law", "professional_medicine", "professional_psychology", "public_relations", "security_studies", "sociology", "us_foreign_policy", "virology", "world_religions", ], } DATA_NO_VALID = [ ("hotpot_qa_distractor", None), ("hotpot_qa_fullwiki", None), ("paws_labeled_final", None), ("paws_labeled_final_pseudo", None), ("adversarial_qa", None), ("adversarial_qa_pseudo", None), ("duorc_ParaphraseRC", None), ("dream", None), ("amazon_polarity", None), ("app_reviews", None), ("app_reviews_pseudo", None), ("imdb", None), ("imdb_pseudo", None), ("wiki_bio", None), ("gigaword", None), ("gigaword_pseudo", None), ("multi_news", None), ("samsum", None), ("dbpedia_14", None), ("dbpedia_14_pseudo", None), ("trec", None), ] DATA_NO_EVAL = [ ("story_cloze_2016", "Generate Ending"), ("story_gen", "Answer Given options"), ("story_gen", "Choose Story Ending"), ("story_gen", "Movie What Happens Next"), ("story_gen", "Novel Correct Ending"), ("story_gen", "Story Continuation and Options"), ("squad_qg", "answer_given_context_and_question"), ("squad_qg", "answer_question_given_context"), ("squad_qg", "answer_the_question"), ("squad_qg", "given_context_answer_question_variation"), ("hellaswag", "Open-ended completion"), ("hellaswag", "Open-ended start"), ("hellaswag", "Topic of the context"), ("hellaswag", "Reversed appropriate continuation - Yes or No"), ("hellaswag", "Appropriate continuation - Yes or No"), ("hellaswag", "Topic without the ending answer"), ] DATA_NO_TRAIN = { ("wiki_qa_pseudo", "Topic Prediction - Answer Only"), ("wiki_qa_pseudo", "Topic Prediction - Question Only"), ("wiki_qa_pseudo", "Topic Prediction - Question and Answer Pair"), ("app_reviews", "convert_to_star_rating"), } DATA_EVAL_GEN = {("story_gen", "Generate Ending")} DATA_RETRIEVAL_AUGMENTATION = ["mmlu", "ai2_arc", "popQA", "marco_qa", "kilt"] RA_PASSAGE_NUM = { "mmlu_msmarco_ra_contriever_aar": 10, "popQA_kilt_wikipedia_ra_ance_aar": 3, "popQA_kilt_wikipedia_ra_contriever_aar": 3, } DATA_CONFIG = { "mmlu": { "name": ["ai2_arc", "ARC-Challenge"], "type": "rank", "do_cache": False, "data_dir": os.path.join(BASE_DATA_DIR, "mmlu/cache"), }, "ai2_arc": { "name": ["ai2_arc", "ARC-Challenge"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "ai2_arc/cache"), }, "popQA": { "name": ["trivia_qa", "unfiltered"], "type": "gen", "do_cache": False, "data_dir": os.path.join(BASE_DATA_DIR, "popQA/cache"), }, "marco_qa": { "name": ["trivia_qa", "unfiltered"], "type": "gen", "do_cache": False, "data_dir": os.path.join(BASE_DATA_DIR, "marco_qa/cache"), }, "kilt": { "name": ["trivia_qa", "unfiltered"], "type": "gen", "do_cache": False, "data_dir": os.path.join(BASE_DATA_DIR, "kilt/cache"), }, "commonsense_qa": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "commonsense_qa/cache"), }, "dream": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "dream/cache"), }, "quail": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quail/cache"), }, "quail_pseudo": { "name": ["quail", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quail/pseudo"), }, "quartz": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quartz/cache"), }, "quartz_pseudo": { "name": ["quartz", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quartz/pseudo"), }, "social_i_qa": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "social_i_qa/cache"), }, "social_i_qa_pseudo": { "name": ["social_i_qa", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "social_i_qa/pseudo"), }, "social_i_qa_pseudo": { "name": ["social_i_qa", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "social_i_qa/pseudo"), }, "wiqa": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wiqa/cache"), }, "cosmos_qa": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "cosmos_qa/cache"), }, "cosmos_qa_pseudo": { "name": ["cosmos_qa", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "cosmos_qa/pseudo"), }, "qasc": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "qasc/cache"), }, "quarel": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quarel/cache"), }, "quarel_pseudo": { "name": ["quarel", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quarel/pseudo"), }, "sciq": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "sciq/cache"), }, "sciq_sciq": { "name": ["sciq", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "sciq/from_sciq"), }, "wiki_hop": { "name": ["wiki_hop", "original"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wiki_hop/cache/"), "split": ["train", "validation"], }, "adversarial_qa": { "name": ["adversarial_qa", "adversarialQA"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "adversarial_qa/cache/adversarialQA"), }, "adversarial_qa_pseudo": { "name": ["adversarial_qa", "adversarialQA"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "adversarial_qa/pseudo/adversarialQA"), }, "quoref": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quoref/cache"), }, "quoref_pseudo": { "name": ["quoref", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quoref/pseudo"), }, "quoref_duorc": { "name": ["quoref", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "quoref/from_duorc"), }, "ropes": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "ropes/cache"), }, "ropes_pseudo": { "name": ["ropes", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "ropes/pseudo"), }, "duorc_self": { "name": ["duorc", "SelfRC"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "duorc/cache/SelfRC"), }, "duorc_para": { "name": ["duorc", "ParaphraseRC"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "duorc/cache/ParaphraseRC"), }, "duorc_para_duorc": { "name": ["duorc", "ParaphraseRC"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "duorc/from_duorc/ParaphraseRC"), }, "hotpot_qa_distractor": { "name": ["hotpot_qa", "distractor"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "hotpot_qa/cache/distractor"), }, "hotpot_qa_fullwiki": { "name": ["hotpot_qa", "fullwiki"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "hotpot_qa/cache/fullwiki"), }, "hotpot_qa_fullwiki_hotpot": { "name": ["hotpot_qa", "fullwiki"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "hotpot_qa/from_hotpot_qa/fullwiki"), }, "wiki_qa": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wiki_qa/cache"), }, "wiki_qa_pseudo": { "name": ["wiki_qa", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wiki_qa/pseudo"), }, "amazon_polarity": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "amazon_polarity/cache"), }, "app_reviews": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "app_reviews/cache"), }, "app_reviews_pseudo": { "name": ["app_reviews", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "app_reviews/pseudo"), }, "imdb": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "imdb/cache"), }, "imdb_pseudo": { "name": ["imdb", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "imdb/pseudo"), }, "rotten_tomatoes": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "rotten_tomatoes/cache"), }, "rotten_tomatoes_pseudo": { "name": ["rotten_tomatoes", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "rotten_tomatoes/pseudo"), }, "yelp_polarity": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "yelp_polarity/cache"), }, "yelp_polarity_pseudo": { "name": ["yelp_polarity", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "yelp_polarity/pseudo"), }, "ag_news": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "ag_news/cache"), }, "ag_news_pseudo": { "name": ["ag_news", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "ag_news/pseudo"), }, "dbpedia_14": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "dbpedia_14/cache"), }, "dbpedia_14_pseudo": { "name": ["dbpedia_my", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "dbpedia_14/pseudo"), }, "trec": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "trec/cache"), }, "common_gen": { "type": "gen", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "common_gen/cache"), }, "common_gen_pseudo": { "name": ["common_gen", None], "type": "gen", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "common_gen/pseudo"), }, "wiki_bio": { "type": "gen", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wiki_bio/cache"), }, "cnn_dailymail": { "name": ["cnn_dailymail", "3.0.0"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "cnn_dailymail/cache/3.0.0"), }, "cnn_dailymail_pseudo": { "name": ["cnn_dailymail", "3.0.0"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "cnn_dailymail/pseudo/3.0.0"), }, "gigaword": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "gigaword/cache"), }, "gigaword_pseudo": { "name": ["gigaword", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "gigaword/pseudo"), }, "multi_news": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "multi_news/cache"), }, "samsum": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "samsum/cache"), }, "xsum": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "xsum/cache"), }, "xsum_pseudo": { "name": ["xsum", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "xsum/pseudo"), }, "mrpc": { "name": ["glue", "mrpc"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "mrpc/cache"), }, "mrpc_pseudo": { "name": ["glue", "mrpc"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "mrpc/pseudo"), }, "paws_labeled_final": { "name": ["paws", "labeled_final"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "paws/cache/labeled_final"), }, "paws_labeled_final_pseudo": { "name": ["paws", "labeled_final"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "paws/pseudo/labeled_final"), }, "paws_labeled_final_qqp": { "name": ["paws", "labeled_final"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "paws/from_qqp/labeled_final"), }, "qqp": { "name": ["glue", "qqp"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "qqp/cache"), }, "qqp_pseudo": { "name": ["glue", "qqp"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "qqp/pseudo"), }, "copa": { "name": ["super_glue", "copa"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "copa/cache"), }, "hellaswag": { "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "hellaswag/cache"), }, "story_cloze_2016": { "name": ["story_cloze", "2016"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "story_cloze/cache/2016"), "split": ["validation"], }, "story_gen": { "name": ["story_cloze", "2016"], "type": "gen", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "story_cloze/cache/2016"), "split": ["validation"], }, "squad_qg": { "name": ["squad", None], "type": "gen", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "squad/cache/"), "split": ["validation"], }, "anli_r1": { "name": ["anli", None], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "anli/cache/r1"), }, "cb": { "name": ["super_glue", "cb"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "cb/cache"), }, "rte": { "name": ["super_glue", "rte"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "rte/cache"), }, "wsc": { "name": ["super_glue", "wsc.fixed"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wsc_balance/cache"), }, "winogrande_xl": { "name": ["winogrande", "winogrande_xl"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "winogrande/cache/winogrande_xl"), }, "winogrande_debiased": { "name": ["winogrande", "winogrande_debiased"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "winogrande/cache/winogrande_debiased"), }, "wic": { "name": ["super_glue", "wic"], "type": "rank", "do_cache": True, "data_dir": os.path.join(BASE_DATA_DIR, "wic/cache"), }, "nsg": { "type": "gen", "selfsup": True, "do_cache": True, "flan_sample_max": 30000, "data_dir": os.path.join(BASE_DATA_DIR, "selfsup/merge/nsg"), "metric": None, }, "mwp": { "type": "gen", "selfsup": True, "do_cache": True, "flan_sample_max": 30000, "data_dir": os.path.join(BASE_DATA_DIR, "selfsup/merge/mwp"), "metric": None, }, "lpp_gen": { "type": "gen", "selfsup": True, "do_cache": True, "flan_sample_max": 30000, "data_dir": os.path.join(BASE_DATA_DIR, "selfsup/merge/lpp_gen"), "metric": None, }, "lpp_cls": { "type": "rank", "selfsup": True, "do_cache": True, "flan_sample_max": 30000, "data_dir": os.path.join(BASE_DATA_DIR, "selfsup/merge/lpp_cls"), "metric": None, }, }
22,045
29.035422
88
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/T0Datasets.py
import json import re import os import torch import math import numpy as np import pickle from torch.utils.data import Dataset from utils import print_rank_0, save_rank_0 from tokenization_t5 import EncDecTokenizer from .data_config import DATA_GROUP_CONFIG, DATA_CONFIG import datasets from promptsource.templates import TemplateCollection from datasets import load_dataset from .postprocess import OPTION_POST_FN datasets.disable_caching() class T0Dataset(Dataset): def __init__( self, args, tokenizer: EncDecTokenizer, data_prompts, split, ratio=1, few_data_names=None, num=-1, ): self.args = args self.tokenizer = tokenizer self.ratio = ratio self.data_prompts = data_prompts self.pad_id = tokenizer.pad_id self.split = split self.sample_num = num self.idx_size = 3 self.few_data_names = few_data_names self.selfsup_sample_num = {"train": 100000, "validation": 1000} self.all_data = {name: {} for name in data_prompts} self.all_enc_sizes = [] self.all_dec_sizes = [] self.all_cand_sizes = [] if self.args.FiD: self.all_passage_sizes = [] for name in self.data_prompts: if DATA_CONFIG[name].get("selfsup", False): data, enc_sizes, dec_sizes, cand_sizes = self.load_from_cache_self(name) self.all_data[name] = { "prompt_num": 1, "prompt_names": ["merged"], "data": data, } else: if DATA_CONFIG[name]["do_cache"]: ( data, enc_sizes, dec_sizes, cand_sizes, passage_sizes, ) = self.load_from_cache(name) else: ( data, enc_sizes, dec_sizes, cand_sizes, passage_sizes, ) = self.process_data(name) self.all_data[name] = { "prompt_num": len(data_prompts[name]), "prompt_names": [prompt.name for prompt in data_prompts[name]], "data": data, } print("len data", len(data)) self.all_enc_sizes.extend(enc_sizes) self.all_dec_sizes.extend(dec_sizes) self.all_cand_sizes.extend(cand_sizes) if self.args.FiD: self.all_passage_sizes.extend(passage_sizes) self.max_enc_len = max(self.all_enc_sizes) self.max_dec_len = max(self.all_dec_sizes) self.max_cand_len = max(self.all_cand_sizes) if self.args.FiD: self.max_passage_len = max(self.all_passage_sizes) self.max_enc_len = self.max_passage_len * self.args.passage_num self.flan_sample_num = { name: min( DATA_CONFIG[name].get("flan_sample_max", args.flan_sample_max) * d["prompt_num"], len(d["data"]), ) for name, d in self.all_data.items() } self.idxs = self.build_idx() self.cur_epoch = 0 print_str = "" for name in self.data_prompts: print_str += "Data: {}_{}".format(name, split) print_str += " | Ratio: {}".format(ratio) print_str += " | Max enc len: {}".format(self.max_enc_len) print_str += " | Max dec len: {}".format(self.max_dec_len) print_str += " | Max cand len: {}".format(self.max_cand_len) print_str += " | Prompt num: {}".format(self.all_data[name]["prompt_num"]) print_str += " | All data num: {}".format(len(self.all_data[name]["data"])) print_str += " | Sample num: {}".format(self.flan_sample_num[name]) print_str += " | Idx one epoch num: {}\n".format(len(self.idxs[0])) print_str = print_str[:-1] print_rank_0(print_str) save_rank_0(args, print_str) def set_epoch(self, e): self.cur_epoch = e def build_idx(self): epochs = self.args.epochs idx_repo = {} for (name, d), (name, sample_num) in zip( self.all_data.items(), self.flan_sample_num.items() ): data_idx = [i for i in range(len(d["data"]))] repeat_num = math.ceil(epochs * sample_num / len(data_idx)) tmp_data_idx = [] for i in range(repeat_num): if self.split == "train": np.random.shuffle(data_idx) tmp_data_idx.extend(data_idx) idx_repo[name] = tmp_data_idx print( name, "| repeat num:", repeat_num, "| sample num:", sample_num, "| data_idx len:", len(data_idx), "| tmp_data_idx:", len(tmp_data_idx), ) idxs = [] for e in range(epochs): samp_idx = [] for name, d in self.all_data.items(): sample_num = self.flan_sample_num[name] l = idx_repo[name][e * sample_num : (e + 1) * sample_num] l = [(name, x) for x in l] samp_idx.extend(l) idxs.append(samp_idx) first_len = len(idxs[0]) for e, x in enumerate(idxs): assert len(x) == first_len, (e, len(x), first_len) return idxs def load_from_cache_self(self, name): cache_path = os.path.join( DATA_CONFIG[name]["data_dir"], "cache_{}_{}.pkl".format(self.split, self.selfsup_sample_num[self.split]), ) with open(cache_path, "rb") as f: data, enc_sizes, dec_sizes, cand_sizes = pickle.load(f) return data, enc_sizes, dec_sizes, cand_sizes def load_from_cache(self, name): data_dir = DATA_CONFIG[name]["data_dir"] if self.split == "train": if self.args.few_data_num is not None: assert self.few_data_names is not None if name in self.few_data_names: sample_num = self.args.few_data_num else: sample_num = self.sample_num else: sample_num = self.sample_num cache_path = os.path.join( data_dir, "cache_{}_{}_{}.pkl".format(self.split, self.ratio, sample_num), ) else: prompt_name = self.data_prompts[name][0].name.replace("/", "_") cache_path = os.path.join( data_dir, "cache_{}_{}_{}_{}.pkl".format( self.split, self.ratio, self.sample_num, prompt_name ), ) print("cache path", cache_path) if os.path.exists(cache_path): with open(cache_path, "rb") as f: data, enc_sizes, dec_sizes, cand_sizes, passage_sizes = pickle.load(f) else: data, enc_sizes, dec_sizes, cand_sizes, passage_sizes = self.process_data( name ) with open(cache_path, "wb") as f: pickle.dump((data, enc_sizes, dec_sizes, cand_sizes, passage_sizes), f) return data, enc_sizes, dec_sizes, cand_sizes, passage_sizes def process_data(self, name): print_rank_0("Processing " + name) if self.split == "train": if self.args.few_data_num is not None: assert self.few_data_names is not None if name in self.few_data_names: sample_num = self.args.few_data_num else: sample_num = self.sample_num else: sample_num = DATA_CONFIG[name].get("train_num", self.sample_num) if self.args.data_aug is not None: sample_num += self.args.data_aug else: sample_num = DATA_CONFIG[name].get("dev_num", self.sample_num) data_dir = DATA_CONFIG[name]["data_dir"] data_files = {self.split: os.path.join(data_dir, "{}.jsonl".format(self.split))} dataset = load_dataset("json", data_files=data_files) data = [] enc_sizes = [] dec_sizes = [] cand_sizes = [] passage_sizes = [] sid, lid = 0, 0 skip = 0 for pid, prompt in enumerate(self.data_prompts[name]): print_rank_0(prompt.name) for sample in dataset[self.split]: if lid % 500 == 0: print_rank_0( "{}, {}, {}, {}, {}".format( name, self.split, prompt.name, lid, skip ) ) # genread_template = "{} Generate a background document from Wikipedia to help answer the given question:" answers = None if "popQA" in name: enc_str = sample["prompt"] # enc_str = genread_template.format(enc_str) dec_str = sample["answers"][0] answers = sample["answers"] else: applied_sample = prompt.apply(sample) if len(applied_sample) != 2: # print_rank_0("sample num out") skip += 1 continue enc_str, dec_str = applied_sample # enc_str = genread_template.format(enc_str) if "mmlu_demo" in sample: enc_str = sample["mmlu_demo"] + enc_str passages = None if "passages" in sample: passages = [] for i in range(self.args.passage_num): max_question_len = 1250 if self.split == "train" else 10000 max_passage_len = ( max(1250 - len(enc_str), 0) if self.split == "train" else 500 ) # Can last if self.args.prompt_tune: passage_str = enc_str[:max_question_len] passages.append( [-(i + 1)] + self.tokenizer.encode(passage_str) + [1] ) else: passage_str = ( sample["passages"][i][:max_passage_len] + enc_str[:max_question_len] ) passages.append(self.tokenizer.encode(passage_str) + [1]) if self.args.prompt_tune: context = ( [-(i + 1) for i in range(self.args.passage_num)] + self.tokenizer.encode(enc_str) + [1] ) else: context = self.tokenizer.encode(enc_str) + [1] target = [0] + self.tokenizer.encode(dec_str) + [1] # if len(enc_str) > 5000: # # print_rank_0("pre-check out " + str(len(enc_str))) # skip += 1 # continue # if len(context) > self.args.enc_seq_length: # skip += 1 # # print_rank_0("enc out " + str(len(context))) # continue # if len(target) > self.args.dec_seq_length: # skip += 1 # # print_rank_0("dec out " + str(len(target))) # continue options = prompt.get_answer_choices_list(sample) options = OPTION_POST_FN.get((name, prompt.name), lambda x: x)(options) if self.split != "train" and options is not None: cands = [ [0] + self.tokenizer.encode(option) + [1] for option in options ] else: cands = None if len(dec_str) == 0: # print_rank_0("dec str out " + str(len(dec_str))) skip += 1 continue if options is not None and dec_str not in options: print_rank_0(str(applied_sample)) print_rank_0( name + " " + prompt.name + " " + "Skip bug sample " + str(dec_str) + " " + str(options) ) continue data.append( { "idxs": [pid, lid, sid], "enc_input_ids": context, "dec_input_ids": target[:-1], "label_ids": target[1:], "answer": dec_str if answers is None else answers, "options": options, "cands": { "input_ids": [c[:-1] for c in cands], "target_ids": [c[1:] for c in cands], "label": options.index(dec_str), } if cands is not None else None, "passage_input_ids": passages, } ) enc_sizes.append(len(context)) dec_sizes.append(len(target) - 1) if cands is not None: cand_sizes.append(sum([len(c) - 1 for c in cands])) else: cand_sizes.append(0) if passages is not None: passage_sizes.extend([len(p) for p in passages]) else: passage_sizes.append(0) sid += 1 lid += 1 if sample_num > 0 and lid >= sample_num: break lid = 0 return data, enc_sizes, dec_sizes, cand_sizes, passage_sizes def __len__(self): return len(self.idxs[0]) def __getitem__(self, idx): name, sid = self.idxs[self.cur_epoch][idx] d = self.all_data[name]["data"][sid] return d, name def collate(self, samples): bs = len(samples) model_data = { "enc_input_ids": torch.ones(bs, self.max_enc_len, dtype=torch.long) * self.pad_id, "enc_attention_mask": torch.zeros( bs, 1, self.max_enc_len, self.max_enc_len ), "dec_attention_mask": torch.zeros( bs, 1, self.max_dec_len, self.max_dec_len ), "cross_attention_mask": torch.zeros( bs, 1, self.max_dec_len, self.max_enc_len ), "dec_input_ids": torch.ones(bs, self.max_dec_len, dtype=torch.long) * self.pad_id, } if self.args.FiD: model_data["passage_input_ids"] = ( torch.ones( bs, self.args.passage_num, self.max_passage_len, dtype=torch.long ) * self.pad_id ) model_data["passage_attention_mask"] = torch.zeros( bs, self.args.passage_num, 1, self.max_passage_len, self.max_passage_len ) no_model_data = { "idxs": torch.zeros(bs, self.idx_size, dtype=torch.long), "labels": torch.ones(bs, self.max_dec_len, dtype=torch.long) * self.pad_id, "loss_mask": torch.zeros(bs, self.max_dec_len), } name_list = [] for i, samp in enumerate(samples): samp, name = samp name_list.append(name) enc_len, dec_len = len(samp["enc_input_ids"]), len(samp["dec_input_ids"]) model_data["enc_input_ids"][i][:enc_len] = torch.tensor( samp["enc_input_ids"], dtype=torch.long ) model_data["enc_attention_mask"][i][0, :enc_len, :enc_len] = samp.get( "enc_attention_mask", 1.0 ) model_data["dec_input_ids"][i][:dec_len] = torch.tensor( samp["dec_input_ids"], dtype=torch.long ) model_data["dec_attention_mask"][i][0, :dec_len, :dec_len] = torch.tril( torch.ones(dec_len, dec_len) ) if self.args.FiD: enc_len = self.max_enc_len samp["cross_attention_mask"] = torch.zeros(enc_len) for j in range(self.args.passage_num): passage_len = len(samp["passage_input_ids"][j]) samp["cross_attention_mask"][ j * self.max_passage_len : j * self.max_passage_len + passage_len ] = 1.0 model_data["cross_attention_mask"][i][0, :dec_len, :enc_len] = samp.get( "cross_attention_mask", 1.0 ) if self.args.FiD: for j in range(self.args.passage_num): passage_len = len(samp["passage_input_ids"][j]) model_data["passage_input_ids"][i][j][:passage_len] = torch.tensor( samp["passage_input_ids"][j], dtype=torch.long ) model_data["passage_attention_mask"][i][j][ 0, :passage_len, :passage_len ] = 1.0 no_model_data["idxs"][i] = torch.tensor(samp["idxs"], dtype=torch.long) no_model_data["labels"][i][: len(samp["label_ids"])] = torch.tensor( samp["label_ids"], dtype=torch.long ) no_model_data["loss_mask"][i][: len(samp["label_ids"])] = 1.0 if self.args.fp16: model_data["enc_attention_mask"] = model_data["enc_attention_mask"].half() model_data["dec_attention_mask"] = model_data["dec_attention_mask"].half() model_data["cross_attention_mask"] = model_data[ "cross_attention_mask" ].half() if self.args.FiD: model_data["passage_attention_mask"] = model_data[ "passage_attention_mask" ].half() if samp["cands"] is not None: cand_model_data = { "dec_input_ids": torch.ones(bs, self.max_cand_len, dtype=torch.long) * self.pad_id, "dec_attention_mask": torch.zeros( bs, 1, self.max_cand_len, self.max_cand_len ), "cross_attention_mask": torch.zeros( bs, 1, self.max_cand_len, self.max_enc_len ), } cand_no_model_data = { "labels": torch.zeros(bs, dtype=torch.long), "target_ids": torch.ones(bs, self.max_cand_len, dtype=torch.long) * self.pad_id, "pos": torch.zeros(bs, self.max_cand_len, dtype=torch.bool), "loss_mask": torch.zeros(bs, self.max_cand_len), } for i, samp in enumerate(samples): samp, _ = samp start = 0 enc_len = len(samp["enc_input_ids"]) if self.args.FiD: enc_len = self.max_enc_len for input_ids, target_ids in zip( samp["cands"]["input_ids"], samp["cands"]["target_ids"] ): cand_model_data["dec_input_ids"][i][ start : start + len(input_ids) ] = torch.tensor(input_ids, dtype=torch.long) cand_no_model_data["target_ids"][i][ start : start + len(target_ids) ] = torch.tensor(target_ids, dtype=torch.long) cand_model_data["dec_attention_mask"][i][ 0, start : start + len(input_ids), start : start + len(input_ids), ] = torch.tril(torch.ones(len(input_ids), len(input_ids))) cand_model_data["cross_attention_mask"][i][ 0, start : start + len(input_ids), :enc_len ] = samp.get("cross_attention_mask", 1.0) cand_no_model_data["loss_mask"][i][ start : start + len(input_ids) ] = 1 start = start + len(input_ids) cand_no_model_data["pos"][i][start - 1] = True cand_no_model_data["labels"][i] = samp["cands"]["label"] if self.args.fp16: cand_model_data["dec_attention_mask"] = cand_model_data[ "dec_attention_mask" ].half() cand_model_data["cross_attention_mask"] = cand_model_data[ "cross_attention_mask" ].half() else: cand_model_data, cand_no_model_data = {}, {} # print(name_list) return model_data, no_model_data, cand_model_data, cand_no_model_data
21,571
38.29326
122
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/postprocess.py
OPTION_POST_FN = { ("imdb", "Negation template for positive and negative"): lambda x: ["negative review.", "positive review."], ("imdb_pseudo", "Negation template for positive and negative"): lambda x: ["negative review.", "positive review."], ("wiqa", "which_of_the_following_is_the_supposed_perturbation"): lambda x: ['directly impacting a step of the process', 'indirectly impacting a step of the process', 'not impacting any step of the process'] } ANSWER_POST_FN = { ("quoref", "Squad"): lambda labels, preds: ([[l] for l in labels], preds), ("quoref_pseudo", "Squad"): lambda labels, preds: ([[l] for l in labels], preds), ("ropes", "Squad"): lambda labels, preds: ([[l] for l in labels], preds), ("ropes_pseudo", "Squad"): lambda labels, preds: ([[l] for l in labels], preds), }
814
66.916667
210
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/arguments.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) from dataclasses import dataclass, field from typing import Optional, List from transformers import TrainingArguments @dataclass class ModelArguments: model_name_or_path: str = field( metadata={ "help": "Path to pretrained model or model identifier from huggingface.co/models" } ) target_model_path: str = field( default=None, metadata={"help": "Path to pretrained reranker target model"} ) config_name: Optional[str] = field( default=None, metadata={ "help": "Pretrained config name or path if not the same as model_name" }, ) tokenizer_name: Optional[str] = field( default=None, metadata={ "help": "Pretrained tokenizer name or path if not the same as model_name" }, ) cache_dir: Optional[str] = field( default=None, metadata={ "help": "Where do you want to store the pretrained models downloaded from s3" }, ) # modeling untie_encoder: bool = field( default=False, metadata={"help": "no weight sharing between qry passage encoders"}, ) feature: str = field( default="last_hidden_state", metadata={"help": "What feature to be extracted from the HF PLM"}, ) pooling: str = field( default="first", metadata={"help": "How to pool the features from the HF PLM"} ) # out projection add_linear_head: bool = field(default=False) projection_in_dim: int = field(default=768) projection_out_dim: int = field(default=768) # for Jax training dtype: Optional[str] = field( default="float32", metadata={ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one " "of `[float32, float16, bfloat16]`. " }, ) encoder_only: bool = field( default=False, metadata={"help": "Whether to only use the encoder of T5"} ) pos_token: Optional[str] = field( default=None, metadata={"help": "Token that indicates a relevant document"} ) neg_token: Optional[str] = field( default=None, metadata={"help": "Token that indicates a irrelevant document"} ) normalize: bool = field( default=False, metadata={"help": "Whether to normalize the embeddings"} ) param_efficient_method: Optional[str] = field( default=None, metadata={"help": "Param efficient method used in model training"} ) @dataclass class DataArguments: train_dir: str = field(default=None, metadata={"help": "Path to train directory"}) train_path: str = field( default=None, metadata={"help": "Path to single train file"} ) eval_path: str = field(default=None, metadata={"help": "Path to eval file"}) query_path: str = field(default=None, metadata={"help": "Path to query file"}) corpus_path: str = field(default=None, metadata={"help": "Path to corpus file"}) train_n_passages: int = field(default=8) use_all_positive_passages: bool = field( default=False, metadata={"help": "use all positive passages"} ) positive_passage_no_shuffle: bool = field( default=False, metadata={"help": "always use the first positive passage"} ) negative_passage_no_shuffle: bool = field( default=False, metadata={"help": "always use the first negative passages"} ) q_max_len: int = field( default=32, metadata={ "help": "The maximum total input sequence length after tokenization for query. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) p_max_len: int = field( default=128, metadata={ "help": "The maximum total input sequence length after tokenization for passage. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) data_cache_dir: Optional[str] = field( default=None, metadata={ "help": "Where do you want to store the data downloaded from huggingface" }, ) query_template: str = field(default=None, metadata={"help": "template for query"}) query_column_names: str = field( default=None, metadata={"help": "column names for the tsv data format"} ) doc_template: str = field(default=None, metadata={"help": "template for doc"}) doc_column_names: str = field( default=None, metadata={"help": "column names for the tsv data format"} ) all_markers: str = field( default=None, metadata={"help": "all markers in the template"} ) @dataclass class BEIRDataArguments(DataArguments): data_dir: str = field( default=None, metadata={"help": "Path to BEIR data directory"} ) @dataclass class DRTrainingArguments(TrainingArguments): warmup_ratio: float = field(default=0.1) remove_unused_columns: Optional[bool] = field( default=False, metadata={ "help": "Remove columns not required by the model when using an nlp.Dataset." }, ) negatives_x_device: bool = field( default=False, metadata={"help": "share negatives across devices"} ) do_encode: bool = field(default=False, metadata={"help": "run the encoding loop"}) use_mapping_dataset: bool = field( default=False, metadata={ "help": "Use mapping dataset instead of iterable dataset in training" }, ) grad_cache: bool = field( default=False, metadata={"help": "Use gradient cache update"} ) gc_q_chunk_size: int = field(default=4) gc_p_chunk_size: int = field(default=32) drop_last: bool = field( default=False, metadata={ "help": "Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)or not. DRTrainers' behaviour depends on this setting instead of dataloader_drop_last." }, ) @dataclass class DRPretrainingDataArguments(DataArguments): train_n_passages: int = field(default=1) pretrain_strategies: str = field( default="crop", metadata={"help": "pretraining strategies"} ) pretrain_target_field: str = field( default="text", metadata={"help": "pretraining target field"} ) cropping_ratio_min: float = field( default=0.1, metadata={ "help": "Minimum ratio of the cropped span to the original document span" }, ) cropping_ratio_max: float = field( default=0.5, metadata={ "help": "Maximum ratio of the cropped span to the original document span" }, ) @dataclass class RRTrainingArguments(TrainingArguments): warmup_ratio: float = field(default=0.1) remove_unused_columns: Optional[bool] = field( default=False, metadata={ "help": "Remove columns not required by the model when using an nlp.Dataset." }, ) use_mapping_dataset: bool = field( default=False, metadata={ "help": "Use mapping dataset instead of iterable dataset in training" }, ) margin: float = field(default=1.0) loss_fn: str = field(default="bce", metadata={"help": "loss function to use"}) @dataclass class InferenceArguments(TrainingArguments): use_gpu: bool = field( default=False, metadata={"help": "Use GPU for Faiss retrieval"} ) encoded_save_path: str = field( default=None, metadata={"help": "where to save the encode"} ) trec_save_path: str = field( default=None, metadata={"help": "where to save the trec file"} ) encode_query_as_passage: bool = field( default=False, metadata={ "help": "Treat input queries as passages instead of queries for encoding. Use corpus_path, doc_template and doc_column_names instead if you used this option." }, ) trec_run_path: str = field( default=None, metadata={"help": "previous stage TrecRun file"} ) id_key_name: str = field(default="id", metadata={"help": "key name for id"}) remove_identical: bool = field( default=False, metadata={"help": "remove identical passages"} ) reranking_depth: int = field(default=None, metadata={"help": "re-ranking depth"}) retrieve_depth: int = field( default=100, metadata={"help": "number of documents to retrieve in retriever"} ) max_inmem_docs: int = field( default=1000000, metadata={"help": "max number of docs to keep in memory"} )
8,692
33.496032
215
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/qa_utils.py
import copy import logging import re import unicodedata import regex logger = logging.getLogger(__name__) class Tokens(object): """A class to represent a list of tokenized text.""" TEXT = 0 TEXT_WS = 1 SPAN = 2 POS = 3 LEMMA = 4 NER = 5 def __init__(self, data, annotators, opts=None): self.data = data self.annotators = annotators self.opts = opts or {} def __len__(self): """The number of tokens.""" return len(self.data) def slice(self, i=None, j=None): """Return a view of the list of tokens from [i, j).""" new_tokens = copy.copy(self) new_tokens.data = self.data[i: j] return new_tokens def untokenize(self): """Returns the original text (with whitespace reinserted).""" return ''.join([t[self.TEXT_WS] for t in self.data]).strip() def words(self, uncased=False): """Returns a list of the text of each token Args: uncased: lower cases text """ if uncased: return [t[self.TEXT].lower() for t in self.data] else: return [t[self.TEXT] for t in self.data] def offsets(self): """Returns a list of [start, end) character offsets of each token.""" return [t[self.SPAN] for t in self.data] def pos(self): """Returns a list of part-of-speech tags of each token. Returns None if this annotation was not included. """ if 'pos' not in self.annotators: return None return [t[self.POS] for t in self.data] def lemmas(self): """Returns a list of the lemmatized text of each token. Returns None if this annotation was not included. """ if 'lemma' not in self.annotators: return None return [t[self.LEMMA] for t in self.data] def entities(self): """Returns a list of named-entity-recognition tags of each token. Returns None if this annotation was not included. """ if 'ner' not in self.annotators: return None return [t[self.NER] for t in self.data] def ngrams(self, n=1, uncased=False, filter_fn=None, as_strings=True): """Returns a list of all ngrams from length 1 to n. Args: n: upper limit of ngram length uncased: lower cases text filter_fn: user function that takes in an ngram list and returns True or False to keep or not keep the ngram as_string: return the ngram as a string vs list """ def _skip(gram): if not filter_fn: return False return filter_fn(gram) words = self.words(uncased) ngrams = [(s, e + 1) for s in range(len(words)) for e in range(s, min(s + n, len(words))) if not _skip(words[s:e + 1])] # Concatenate into strings if as_strings: ngrams = ['{}'.format(' '.join(words[s:e])) for (s, e) in ngrams] return ngrams def entity_groups(self): """Group consecutive entity tokens with the same NER tag.""" entities = self.entities() if not entities: return None non_ent = self.opts.get('non_ent', 'O') groups = [] idx = 0 while idx < len(entities): ner_tag = entities[idx] # Check for entity tag if ner_tag != non_ent: # Chomp the sequence start = idx while (idx < len(entities) and entities[idx] == ner_tag): idx += 1 groups.append((self.slice(start, idx).untokenize(), ner_tag)) else: idx += 1 return groups class Tokenizer(object): """Base tokenizer class. Tokenizers implement tokenize, which should return a Tokens class. """ def tokenize(self, text): raise NotImplementedError def shutdown(self): pass def __del__(self): self.shutdown() class SimpleTokenizer(Tokenizer): ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+' NON_WS = r'[^\p{Z}\p{C}]' def __init__(self, **kwargs): """ Args: annotators: None or empty set (only tokenizes). """ self._regexp = regex.compile( '(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS), flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE ) if len(kwargs.get('annotators', {})) > 0: logger.warning('%s only tokenizes! Skipping annotators: %s' % (type(self).__name__, kwargs.get('annotators'))) self.annotators = set() def tokenize(self, text): data = [] matches = [m for m in self._regexp.finditer(text)] for i in range(len(matches)): # Get text token = matches[i].group() # Get whitespace span = matches[i].span() start_ws = span[0] if i + 1 < len(matches): end_ws = matches[i + 1].span()[0] else: end_ws = span[1] # Format data data.append(( token, text[start_ws: end_ws], span, )) return Tokens(data, self.annotators) def regex_match(text, pattern): """Test if a regex pattern is contained within a text.""" try: pattern = re.compile( pattern, flags=re.IGNORECASE + re.UNICODE + re.MULTILINE, ) except BaseException: return False return pattern.search(text) is not None def _normalize(text): return unicodedata.normalize('NFD', text) def has_answers(text, answers, tokenizer, regex=False): text = _normalize(text) if regex: for ans in answers: ans = _normalize(ans) if regex_match(text, ans): return True else: text = tokenizer.tokenize(text).words(uncased=True) for ans in answers: ans = _normalize(ans) ans = tokenizer.tokenize(ans).words(uncased=True) for i in range(0, len(text) - len(ans) + 1): if ans == text[i: i + len(ans)]: return True return False
6,346
28.52093
77
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/loss.py
import torch from torch import Tensor from torch.nn import functional as F from torch import distributed as dist class SimpleContrastiveLoss: def __call__(self, x: Tensor, y: Tensor, target: Tensor = None, reduction: str = 'mean'): if target is None: target_per_qry = y.size(0) // x.size(0) target = torch.arange( 0, x.size(0) * target_per_qry, target_per_qry, device=x.device, dtype=torch.long) logits = torch.matmul(x, y.transpose(0, 1)) return F.cross_entropy(logits, target, reduction=reduction) class DistributedContrastiveLoss(SimpleContrastiveLoss): def __init__(self, n_target: int = 0, scale_loss: bool = True): assert dist.is_initialized(), "Distributed training has not been properly initialized." super().__init__() self.word_size = dist.get_world_size() self.rank = dist.get_rank() self.scale_loss = scale_loss def __call__(self, x: Tensor, y: Tensor, **kwargs): dist_x = self.gather_tensor(x) dist_y = self.gather_tensor(y) loss = super().__call__(dist_x, dist_y, **kwargs) if self.scale_loss: loss = loss * self.word_size return loss def gather_tensor(self, t): gathered = [torch.empty_like(t) for _ in range(self.word_size)] dist.all_gather(gathered, t) gathered[self.rank] = t return torch.cat(gathered, dim=0) class MarginRankingLoss: def __init__(self, margin: float = 1.0): self.margin = margin def __call__(self, pos_scores: Tensor, neg_scores: Tensor): return torch.mean(F.relu(self.margin - pos_scores + neg_scores)) class SoftMarginRankingLoss: def __init__(self, margin: float = 1.0): self.margin = margin def __call__(self, pos_scores: Tensor, neg_scores: Tensor): return torch.mean(F.softplus(self.margin - pos_scores + neg_scores)) class BinaryCrossEntropyLoss: def __call__(self, pos_scores: Tensor, neg_scores: Tensor): return (F.binary_cross_entropy_with_logits(pos_scores, torch.ones_like(pos_scores)) + F.binary_cross_entropy_with_logits(neg_scores, torch.zeros_like(neg_scores))) class CrossEntropyLoss: def __call__(self, pos_scores: Tensor, neg_scores: Tensor): return (F.cross_entropy(pos_scores, torch.ones(pos_scores.shape[0], dtype=torch.long).to(pos_scores.device)) + F.cross_entropy(neg_scores, torch.zeros(neg_scores.shape[0], dtype=torch.long).to(pos_scores.device))) rr_loss_functions = { "mr": MarginRankingLoss, "smr": SoftMarginRankingLoss, "bce": BinaryCrossEntropyLoss, "ce": CrossEntropyLoss, }
2,694
35.418919
118
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/utils.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import csv import json import warnings from dataclasses import dataclass from typing import Dict, List import datasets import torch from transformers import PreTrainedTokenizer try: from opendelta import BitFitModel, AdapterModel, PrefixModel, LoraModel _opendelta_available = True except ModuleNotFoundError: _opendelta_available = False @dataclass class SimpleTrainPreProcessor: query_file: str collection_file: str tokenizer: PreTrainedTokenizer doc_max_len: int = 128 query_max_len: int = 32 columns = ['text_id', 'title', 'text'] title_field = 'title' text_field = 'text' query_field = 'text' doc_template: str = None query_template: str = None allow_not_found: bool = False def __post_init__(self): self.queries = self.read_queries(self.query_file) self.collection = datasets.load_dataset( 'csv', data_files=self.collection_file, column_names=self.columns, delimiter='\t', )['train'] @staticmethod def read_queries(queries): qmap = {} if queries[-3:] == "csv": with open(queries) as f: reader = csv.DictReader(f, fieldnames=["qid", "qry"], delimiter="\t") for row in reader: qid = row.pop("qid") qry = row.pop("qry") qmap[qid] = qry else: with open(queries) as f: for l in f: qid, qry = l.strip().split('\t') qmap[qid] = qry return qmap @staticmethod def read_qrel(relevance_file): qrel = {} with open(relevance_file, encoding='utf8') as f: tsvreader = csv.reader(f, delimiter="\t") for [topicid, _, docid, rel] in tsvreader: assert rel == "1" if topicid in qrel: qrel[topicid].append(docid) else: qrel[topicid] = [docid] return qrel def get_query(self, q): if self.query_template is None: query = self.queries[q] else: query = fill_template(self.query_template, data={self.query_field: self.queries[q]}, allow_not_found=self.allow_not_found) query_encoded = self.tokenizer.encode( query, add_special_tokens=False, max_length=self.query_max_len, truncation=True ) return query_encoded def get_passage(self, p): entry = self.collection[int(p)] title = entry[self.title_field] title = "" if title is None else title body = entry[self.text_field] if self.doc_template is None: content = title + self.tokenizer.sep_token + body else: content = fill_template(self.doc_template, data=entry, allow_not_found=self.allow_not_found) passage_encoded = self.tokenizer.encode( content, add_special_tokens=False, max_length=self.doc_max_len, truncation=True ) return passage_encoded def process_one(self, train): q, pp, nn = train train_example = { 'query': self.get_query(q), 'positives': [self.get_passage(p) for p in pp], 'negatives': [self.get_passage(n) for n in nn], } return json.dumps(train_example) @dataclass class SimpleCollectionPreProcessor: tokenizer: PreTrainedTokenizer separator: str = '\t' max_length: int = 128 def process_line(self, line: str): xx = line.strip().split(self.separator) text_id, text = xx[0], xx[1:] text_encoded = self.tokenizer.encode( self.tokenizer.sep_token.join(text), add_special_tokens=False, max_length=self.max_length, truncation=True ) encoded = { 'text_id': text_id, 'text': text_encoded } return json.dumps(encoded) def save_as_trec(rank_result: Dict[str, Dict[str, float]], output_path: str, run_id: str = "OpenMatch"): """ Save the rank result as TREC format: <query_id> Q0 <doc_id> <rank> <score> <run_id> """ with open(output_path, "w") as f: for qid in rank_result: # sort the results by score sorted_results = sorted(rank_result[qid].items(), key=lambda x: x[1], reverse=True) for i, (doc_id, score) in enumerate(sorted_results): f.write("{} Q0 {} {} {} {}\n".format(qid, doc_id, i + 1, score, run_id)) def load_from_trec(input_path: str, as_list: bool = False, max_len_per_q: int = None): """ Load the rank result from TREC format: <query_id> Q0 <doc_id> <rank> <score> <run_id> or <query_id> <doc_id> <score> """ rank_result = {} cnt = 0 with open(input_path, "r") as f: for line in f: content = line.strip().split() if len(content) == 6: qid, _, doc_id, _, score, _ = content elif len(content) == 3: qid, doc_id, score = content else: raise ValueError("Invalid run format") if not as_list: if qid not in rank_result: rank_result[qid] = {} cnt = 0 if max_len_per_q is None or cnt < max_len_per_q: rank_result[qid][doc_id] = float(score) else: if qid not in rank_result: rank_result[qid] = [] cnt = 0 if max_len_per_q is None or cnt < max_len_per_q: rank_result[qid].append((doc_id, float(score))) cnt += 1 return rank_result def find_all_markers(template: str): """ Find all markers' names (quoted in "<>") in a template. """ markers = [] start = 0 while True: start = template.find("<", start) if start == -1: break end = template.find(">", start) if end == -1: break markers.append(template[start + 1:end]) start = end + 1 return markers def fill_template(template: str, data: Dict, markers: List[str] = None, allow_not_found: bool = False): """ Fill a template with data. """ if markers is None: markers = find_all_markers(template) for marker in markers: marker_hierarchy = marker.split(".") found = True content = data for marker_level in marker_hierarchy: content = content.get(marker_level, None) if content is None: found = False break if not found: if allow_not_found: warnings.warn("Marker '{}' not found in data. Replacing it with an empty string.".format(marker), RuntimeWarning) content = "" else: raise ValueError("Cannot find the marker '{}' in the data".format(marker)) template = template.replace("<{}>".format(marker), str(content)) return template def merge_retrieval_results_by_score(results: List[Dict[str, Dict[str, float]]], topk: int = 100): """ Merge retrieval results from multiple partitions of document embeddings and keep topk. """ merged_results = {} for result in results: for qid in result: if qid not in merged_results: merged_results[qid] = {} for doc_id in result[qid]: if doc_id not in merged_results[qid]: merged_results[qid][doc_id] = result[qid][doc_id] for qid in merged_results: merged_results[qid] = {k: v for k, v in sorted(merged_results[qid].items(), key=lambda x: x[1], reverse=True)[:topk]} return merged_results # Mean Pooling - Take attention mask into account for correct averaging def mean_pooling(token_embeddings, attention_mask): input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9) def get_delta_model_class(model_type): if not _opendelta_available: raise ValueError( 'OpenDelta package not available. You can obtain it from https://github.com/thunlp/OpenDelta.') delta_models = { 'bitfit': BitFitModel, 'adapter': AdapterModel, 'prefix': PrefixModel, 'lora': LoraModel } return delta_models[model_type]
8,668
32.087786
134
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/data_augmentation_strategy.py
import random from typing import List class DataAugmentationStrategy: def augment(self, data: List[int]) -> List[int]: raise NotImplementedError def __call__(self, data: List[int]) -> List[int]: return self.augment(data) class NullStrategy(DataAugmentationStrategy): def augment(self, data: List[int]) -> List[int]: return data class Cropping(DataAugmentationStrategy): def __init__(self, ratio_min: float = 0.1, ratio_max: float = 0.5): self.ratio_min = ratio_min self.ratio_max = ratio_max def augment(self, data: List[int]) -> List[int]: ratio = random.uniform(self.ratio_min, self.ratio_max) length = int(len(data) * ratio) start = random.randint(0, len(data) - length) end = start + length crop = data[start:end] return crop class SequentialStrategies(DataAugmentationStrategy): def __init__(self, *strategies: DataAugmentationStrategy): self.strategies = strategies def add_strategy(self, strategy: DataAugmentationStrategy): self.strategies.append(strategy) def augment(self, data: List[int]) -> List[int]: for strategy in self.strategies: data = strategy(data) return data
1,261
25.851064
71
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/__init__.py
0
0
0
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/trainer/dense_trainer.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import logging import os from itertools import repeat from typing import Any, Dict, List, Optional, Tuple, Union import datasets import torch import torch.distributed as dist from torch.utils.data import DataLoader from transformers.file_utils import is_datasets_available from transformers.trainer import Trainer, TRAINING_ARGS_NAME from transformers.trainer_pt_utils import IterableDatasetShard from ..loss import DistributedContrastiveLoss, SimpleContrastiveLoss logger = logging.getLogger(__name__) try: from grad_cache import GradCache _grad_cache_available = True except ModuleNotFoundError: _grad_cache_available = False class DRTrainer(Trainer): def __init__(self, delta_model=None, *args, **kwargs): super(DRTrainer, self).__init__(*args, **kwargs) self.delta_model = delta_model self._dist_loss_scale_factor = dist.get_world_size() if self.args.negatives_x_device else 1 def _save(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info("Saving model checkpoint to %s", output_dir) self.model.save(output_dir) if self.tokenizer is not None: self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME)) if self.delta_model: logger.info("Saving delta model to %s", output_dir + "/delta_model") self.delta_model.save_finetuned(output_dir + "/delta_model") def _prepare_inputs( self, inputs: Tuple[Dict[str, Union[torch.Tensor, Any]], ...] ) -> List[Dict[str, Union[torch.Tensor, Any]]]: prepared = [] for x in inputs: if isinstance(x, torch.Tensor): prepared.append(x.to(self.args.device)) else: prepared.append(super()._prepare_inputs(x)) return prepared def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `self.train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_dataset = self.train_dataset if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): train_dataset = self._remove_unused_columns(train_dataset, description="training") if isinstance(train_dataset, torch.utils.data.IterableDataset): if self.args.world_size > 1: train_dataset = IterableDatasetShard( train_dataset, batch_size=self.args.train_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( train_dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) train_sampler = self._get_train_sampler() return DataLoader( train_dataset, batch_size=self.args.train_batch_size, sampler=train_sampler, collate_fn=self.data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def compute_loss(self, model, inputs, return_outputs=False): query, passage = inputs outputs = model(query=query, passage=passage) return (outputs.loss, outputs) if return_outputs else outputs.loss def training_step(self, *args): return super(DRTrainer, self).training_step(*args) / self._dist_loss_scale_factor def split_dense_inputs(model_input: dict, chunk_size: int): assert len(model_input) == 1 arg_key = list(model_input.keys())[0] arg_val = model_input[arg_key] keys = list(arg_val.keys()) chunked_tensors = [arg_val[k].split(chunk_size, dim=0) for k in keys] chunked_arg_val = [dict(zip(kk, tt)) for kk, tt in zip(repeat(keys), zip(*chunked_tensors))] return [{arg_key: c} for c in chunked_arg_val] def get_dense_rep(x): if x.q_reps is None: return x.p_reps else: return x.q_reps class GCDenseTrainer(DRTrainer): def __init__(self, *args, **kwargs): logger.info('Initializing Gradient Cache Trainer') if not _grad_cache_available: raise ValueError( 'Grad Cache package not available. You can obtain it from https://github.com/luyug/GradCache.') super(GCDenseTrainer, self).__init__(*args, **kwargs) loss_fn_cls = DistributedContrastiveLoss if self.args.negatives_x_device else SimpleContrastiveLoss loss_fn = loss_fn_cls() self.gc = GradCache( models=[self.model, self.model], chunk_sizes=[self.args.gc_q_chunk_size, self.args.gc_p_chunk_size], loss_fn=loss_fn, split_input_fn=split_dense_inputs, get_rep_fn=get_dense_rep, fp16=self.args.fp16, scaler=self.scaler ) def training_step(self, model, inputs) -> torch.Tensor: model.train() queries, passages = self._prepare_inputs(inputs) queries, passages = {'query': queries}, {'passage': passages} _distributed = self.args.local_rank > -1 self.gc.models = [model, model] loss = self.gc(queries, passages, no_sync_except_last=_distributed) return loss / self._dist_loss_scale_factor
6,280
36.837349
111
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/trainer/__init__.py
from .dense_trainer import DRTrainer, GCDenseTrainer from .reranker_trainer import RRTrainer
92
45.5
52
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/trainer/reranker_trainer.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import logging import os from typing import Any, Dict, List, Optional, Tuple, Union import torch import torch.nn as nn from transformers.trainer import Trainer from transformers.trainer_pt_utils import nested_detach logger = logging.getLogger(__name__) class RRTrainer(Trainer): def __init__(self, *args, **kwargs): super(RRTrainer, self).__init__(*args, **kwargs) def _save(self, output_dir: Optional[str] = None): output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info("Saving model checkpoint to %s", output_dir) self.model.save(output_dir) def _prepare_inputs( self, inputs: Tuple[Dict[str, Union[torch.Tensor, Any]], ...] ) -> List[Dict[str, Union[torch.Tensor, Any]]]: prepared = [] for x in inputs: if isinstance(x, torch.Tensor): prepared.append(x.to(self.args.device)) else: prepared.append(super()._prepare_inputs(x)) return prepared def prediction_step( self, model: nn.Module, inputs, prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] with torch.no_grad(): with self.autocast_smart_context_manager(): loss, outputs = self.compute_loss(model, inputs, return_outputs=True) loss = loss.mean().detach() if isinstance(outputs, dict): logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"]) else: logits = outputs[1:] if prediction_loss_only: return (loss, None, None) logits = nested_detach(logits) if len(logits) == 1: logits = logits[0] return (loss, logits, None) def compute_loss(self, model, inputs, return_outputs=False): pos_pairs, neg_pairs = inputs outputs = model(pos_pairs=pos_pairs, neg_pairs=neg_pairs) return (outputs.loss, outputs) if return_outputs else outputs.loss
2,539
32.866667
96
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/dataset/inference_dataset.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import os from functools import lru_cache from typing import List, Union, Callable from datasets import load_dataset from torch.utils.data import Dataset, IterableDataset from transformers import PreTrainedTokenizer from ..arguments import DataArguments from ..utils import fill_template, find_all_markers def get_idx(obj): example_id = obj.get("_id", None) or obj.get("id", None) or obj.get("text_id", None) example_id = str(example_id) if example_id is not None else None return example_id class InferenceDataset(): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], is_query: bool = False, full_tokenization: bool = True, mode: str = "processed", batch_size: int = 1, num_processes: int = 1, process_index: int = 0, filter_fn: Callable = lambda x: True, cache_dir: str = None ): self.cache_dir = cache_dir self.is_query = is_query self.data_files = data_files self.tokenizer = tokenizer self.max_len = data_args.q_max_len if self.is_query else data_args.p_max_len self.template = data_args.query_template if self.is_query else data_args.doc_template self.all_markers = find_all_markers(self.template) if data_args.all_markers is None else data_args.all_markers.split(",") self.full_tokenization = full_tokenization modes = ["raw", "dict_processed", "processed"] if mode not in modes: raise ValueError(f"mode must be one of {modes}") self.mode = mode self.batch_size = batch_size self.num_processes = num_processes self.process_index = process_index self.filter_fn = filter_fn self._prepare_data(data_args) def _prepare_data(self, data_args): raise NotImplementedError @classmethod def load( cls, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]] = None, is_query: bool = False, full_tokenization: bool = True, mode: str = "processed", stream: bool = True, batch_size: int = 1, num_processes: int = 1, process_index: int = 0, filter_fn: Callable = lambda x: True, cache_dir: str = None ): if data_files is None: data_files = [data_args.query_path] if is_query else [data_args.corpus_path] else: data_files = [data_files] if isinstance(data_files, str) else data_files ext = os.path.splitext(data_files[0])[1] ext_to_cls = { ".json": StreamJsonlDataset if stream else MappingJsonlDataset, ".csv": StreamTsvDataset if stream else MappingTsvDataset, ".jsonl": StreamJsonlDataset if stream else MappingJsonlDataset, ".tsv": StreamTsvDataset if stream else MappingTsvDataset, ".txt": StreamTsvDataset if stream else MappingTsvDataset, } cls_ = ext_to_cls.get(ext, None) if cls_ is None: raise ValueError("Unsupported dataset file extension {}".format(ext)) return cls_( tokenizer=tokenizer, data_args=data_args, data_files=data_files, is_query=is_query, full_tokenization=full_tokenization, mode=mode, batch_size=batch_size, num_processes=num_processes, process_index=process_index, filter_fn=filter_fn, cache_dir=cache_dir ) def _tokenize(self, example: str): return self.tokenizer( example, add_special_tokens=self.full_tokenization, padding='max_length' if self.full_tokenization else False, truncation=True, max_length=self.max_len, return_attention_mask=self.full_tokenization, return_token_type_ids=False ) def process_one(self, example): if self.mode == "raw": return example elif self.mode == "dict_processed": example_id = get_idx(example) tokenized = {} for marker in self.all_markers: tokenized[marker] = dict(self._tokenize(example[marker])) if (marker in example and example[marker] is not None) else None return {"text_id": example_id, **tokenized} else: example_id = get_idx(example) full_text = fill_template(self.template, example, self.all_markers, allow_not_found=True) tokenized = self._tokenize(full_text) return {"text_id": example_id, **tokenized} class StreamInferenceDataset(InferenceDataset, IterableDataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(StreamInferenceDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) def __iter__(self): real_batch_size = self.batch_size * self.num_processes process_slice = range(self.process_index * self.batch_size, (self.process_index + 1) * self.batch_size) current_batch = [] for element in self.dataset: current_batch.append(element) # Wait to have a full batch before yielding elements. if len(current_batch) == real_batch_size: for i in process_slice: yield self.process_one(current_batch[i]) current_batch = [] if len(current_batch) > 0: for i in process_slice: if i < len(current_batch): yield self.process_one(current_batch[i]) class StreamJsonlDataset(StreamInferenceDataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(StreamJsonlDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) def _prepare_data(self, data_args): self.dataset = load_dataset( "json", data_files=self.data_files, streaming=True, cache_dir=self.cache_dir )["train"].filter(self.filter_fn) sample = list(self.dataset.take(1))[0] self.all_columns = sample.keys() class StreamTsvDataset(StreamInferenceDataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(StreamTsvDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) def _prepare_data(self, data_args): self.all_columns = data_args.query_column_names if self.is_query else data_args.doc_column_names if self.all_columns is not None: self.all_columns = self.all_columns.split(',') self.dataset = load_dataset( "csv", data_files=self.data_files, streaming=True, column_names=self.all_columns, delimiter='\t', cache_dir=self.cache_dir )["train"].filter(self.filter_fn) class MappingInferenceDataset(InferenceDataset, Dataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(MappingInferenceDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) @lru_cache(maxsize=None) def __getitem__(self, index): return self.process_one(self.dataset[index]) def get_raw(self, index): return self.dataset[index] def __len__(self): return len(self.dataset) class MappingJsonlDataset(MappingInferenceDataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(MappingJsonlDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) def _prepare_data(self, data_args): hf_dataset = load_dataset( "json", data_files=self.data_files, streaming=True, cache_dir=self.cache_dir )["train"].filter(self.filter_fn) sample = list(self.dataset.take(1))[0] self.all_columns = sample.keys() self.dataset = {} for item in hf_dataset: self.dataset[get_idx(item)] = item class MappingTsvDataset(MappingInferenceDataset): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, data_files: Union[str, List[str]], **kwargs ): super(MappingTsvDataset, self).__init__(tokenizer, data_args, data_files, **kwargs) def _prepare_data(self, data_args): self.all_columns = data_args.query_column_names if self.is_query else data_args.doc_column_names if self.all_columns is not None: self.all_columns = self.all_columns.split(',') hf_dataset = load_dataset( "csv", data_files=self.data_files, streaming=True, column_names=self.all_columns, delimiter='\t', cache_dir=self.cache_dir )["train"].filter(self.filter_fn) self.dataset = {} for item in hf_dataset: self.dataset[get_idx(item)] = item
9,674
32.947368
138
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/dataset/data_collator.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) from dataclasses import dataclass from transformers import DataCollatorWithPadding, DefaultDataCollator @dataclass class QPCollator(DataCollatorWithPadding): """ Wrapper that does conversion from List[Tuple[encode_qry, encode_psg]] to List[qry], List[psg] and pass batch separately to the actual collator. Abstract out data detail for the model. """ max_q_len: int = 32 max_p_len: int = 128 def __call__(self, features): qq = [f["query_"] for f in features] dd = [f["passages"] for f in features] if isinstance(qq[0], list): qq = sum(qq, []) if isinstance(dd[0], list): dd = sum(dd, []) q_collated = self.tokenizer.pad( qq, padding='max_length', max_length=self.max_q_len, return_tensors="pt", ) d_collated = self.tokenizer.pad( dd, padding='max_length', max_length=self.max_p_len, return_tensors="pt", ) return q_collated, d_collated @dataclass class PairCollator(DataCollatorWithPadding): """ Wrapper that does conversion from List[Tuple[encode_qry, encode_psg]] to List[qry], List[psg] and pass batch separately to the actual collator. Abstract out data detail for the model. """ max_q_len: int = 32 max_p_len: int = 128 def __call__(self, features): pos_pairs = [f["pos_pair"] for f in features] neg_pairs = [f["neg_pair"] for f in features] if isinstance(pos_pairs[0], list): pos_pairs = sum(pos_pairs, []) if isinstance(neg_pairs[0], list): neg_pairs = sum(neg_pairs, []) pos_pair_collated = self.tokenizer.pad( pos_pairs, padding='max_length', max_length=self.max_q_len + self.max_p_len + 2, return_tensors="pt", ) neg_pair_collated = self.tokenizer.pad( neg_pairs, padding='max_length', max_length=self.max_q_len + self.max_p_len + 2, return_tensors="pt", ) return pos_pair_collated, neg_pair_collated @dataclass class DRInferenceCollator(DefaultDataCollator): def __call__(self, features): text_ids = [x["text_id"] for x in features] collated_features = super().__call__(features) return text_ids, collated_features @dataclass class RRInferenceCollator(DefaultDataCollator): def __call__(self, features): query_ids = [x["query_id"] for x in features] doc_ids = [x["doc_id"] for x in features] collated_features = super().__call__(features) return query_ids, doc_ids, collated_features
2,786
29.293478
97
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/dataset/train_dataset.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import glob import logging import os import random from typing import Callable, Dict, List, Union from datasets import load_dataset from torch.utils.data import Dataset, IterableDataset from transformers import BatchEncoding, PreTrainedTokenizer from ..arguments import DataArguments, DRPretrainingDataArguments from ..data_augmentation_strategy import Cropping, NullStrategy, SequentialStrategies from ..trainer import DRTrainer logger = logging.getLogger(__name__) class TrainDatasetBase: """ Abstract base class for all train datasets in Openmatch.\n This implants arguments and data preparation, but should be mostly used for identifying an OpenMatch Train Dataset.\n All future dataset ABCs would subclass this and `(Iterable)Dataset`. """ def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DataArguments, trainer: DRTrainer = None, is_eval: bool = False, shuffle_seed: int = None, cache_dir: str = None, ) -> None: self.tokenizer = tokenizer self.data_args = data_args self.q_max_len = data_args.q_max_len self.p_max_len = data_args.p_max_len self.trainer = trainer self.is_eval = is_eval self._prepare_data(data_args, shuffle_seed, cache_dir) def _prepare_data(self, data_args, shuffle_seed, cache_dir): if not self.is_eval: self.data_files = ( [data_args.train_path] if data_args.train_dir is None else glob.glob(os.path.join(data_args.train_dir, "*.jsonl")) ) else: self.data_files = [data_args.eval_path] def get_process_fn(self, epoch, hashed_seed): raise NotImplementedError class StreamTrainDatasetMixin(IterableDataset): def _prepare_data(self, data_args, shuffle_seed, cache_dir): super()._prepare_data(data_args, shuffle_seed, cache_dir) self.dataset = load_dataset( "json", data_files=self.data_files, streaming=True, cache_dir=cache_dir )["train"] self.dataset = ( self.dataset.shuffle(seed=shuffle_seed, buffer_size=10_000) if shuffle_seed is not None else self.dataset ) sample = list(self.dataset.take(1))[0] self.all_columns = sample.keys() def __len__(self): concat_filenames = " ".join(self.data_files) count = 0 with os.popen("wc -l {}".format(concat_filenames)) as f: for line in f: lc, filename = line.strip().split() lc = int(lc) if filename != "total": count += lc return count def __iter__(self): if not self.is_eval: epoch = int(self.trainer.state.epoch) _hashed_seed = hash(self.trainer.args.seed) self.dataset.set_epoch(epoch) return iter( self.dataset.map( self.get_process_fn(epoch, _hashed_seed), remove_columns=self.all_columns, ) ) return iter( self.dataset.map( self.get_process_fn(0, None), remove_columns=self.all_columns ) ) class MappingTrainDatasetMixin(Dataset): def _prepare_data(self, data_args, shuffle_seed, cache_dir): super()._prepare_data(data_args, shuffle_seed, cache_dir) self.dataset = load_dataset( "json", data_files=self.data_files, streaming=False, cache_dir=cache_dir )["train"] sample = self.dataset[0] self.all_columns = sample.keys() def __len__(self): return len(self.dataset) def __getitem__(self, index): group = self.dataset[index] if not self.is_eval: epoch = int(self.trainer.state.epoch) _hashed_seed = hash(index + self.trainer.args.seed) return self.get_process_fn(epoch, _hashed_seed)(group) return self.get_process_fn(0, None)(group) class DRTrainDataset(TrainDatasetBase): def create_one_example( self, text_encoding: List[int], is_query=False ) -> BatchEncoding: item = self.tokenizer.encode_plus( text_encoding, truncation="only_first", max_length=self.data_args.q_max_len if is_query else self.data_args.p_max_len, padding=False, return_attention_mask=False, return_token_type_ids=False, ) return item def get_process_fn(self, epoch, hashed_seed): def process_fn(example): qry = example["query"] encoded_query = self.create_one_example(qry, is_query=True) encoded_passages = [] group_positives = example["positives"] group_negatives = example["negatives"] if not self.data_args.use_all_positive_passages: if self.data_args.positive_passage_no_shuffle or hashed_seed is None: pos_psg = group_positives[0] else: pos_psg = group_positives[ (hashed_seed + epoch) % len(group_positives) ] encoded_passages.append(self.create_one_example(pos_psg)) else: for pos_psg in group_positives: encoded_passages.append(self.create_one_example(pos_psg)) negative_size = self.data_args.train_n_passages - 1 if len(group_negatives) < negative_size: if hashed_seed is not None: negs = random.choices(group_negatives, k=negative_size) else: negs = [x for x in group_negatives] negs = negs * 2 negs = negs[:negative_size] elif self.data_args.train_n_passages == 1: negs = [] elif self.data_args.negative_passage_no_shuffle: negs = group_negatives[:negative_size] else: _offset = epoch * negative_size % len(group_negatives) negs = [x for x in group_negatives] if hashed_seed is not None: random.Random(hashed_seed).shuffle(negs) negs = negs * 2 negs = negs[_offset : _offset + negative_size] for neg_psg in negs: encoded_passages.append(self.create_one_example(neg_psg)) if not self.data_args.use_all_positive_passages: assert len(encoded_passages) == self.data_args.train_n_passages else: assert ( len(encoded_passages) == self.data_args.train_n_passages + len(group_positives) - 1 ) return { "query_": encoded_query, "passages": encoded_passages, } # Avoid name conflict with query in the original dataset return process_fn class StreamDRTrainDataset(StreamTrainDatasetMixin, DRTrainDataset): pass class MappingDRTrainDataset(MappingTrainDatasetMixin, DRTrainDataset): pass class DRPretrainDataset(TrainDatasetBase): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: DRPretrainingDataArguments, trainer: DRTrainer = None, is_eval: bool = False, shuffle_seed: int = None, cache_dir: str = None, ) -> None: super(DRPretrainDataset, self).__init__( tokenizer, data_args, trainer, is_eval, shuffle_seed, cache_dir ) pretrain_strategies_str = ( data_args.pretrain_strategies.split(",") if data_args.pretrain_strategies is not None else [] ) strategies = [] for strategy_str in pretrain_strategies_str: if strategy_str == "null": strategies.append(NullStrategy()) logger.info("Adding NullStrategy") elif strategy_str == "crop": strategies.append( Cropping( ratio_min=data_args.cropping_ratio_min, ratio_max=data_args.cropping_ratio_max, ) ) logger.info( "Adding Cropping, ratio_min={}, ratio_max={}".format( data_args.cropping_ratio_min, data_args.cropping_ratio_max ) ) else: raise ValueError( "Unknown pretraining strategy: {}".format(strategy_str) ) self.apply_strategy = SequentialStrategies(*strategies) def create_one_example( self, text_encoding: List[int], is_query=False ) -> BatchEncoding: text_encoding = self.apply_strategy(text_encoding) item = self.tokenizer.encode_plus( text_encoding, truncation="only_first", max_length=self.data_args.q_max_len if is_query else self.data_args.p_max_len, padding=False, return_attention_mask=False, return_token_type_ids=False, ) return item def get_process_fn(self, epoch, hashed_seed): def process_fn(example): content = example[self.data_args.pretrain_target_field] encoded_query = self.create_one_example(content, is_query=True) encoded_passages = [self.create_one_example(content)] return {"query": encoded_query, "passages": encoded_passages} return process_fn class StreamDRPretrainDataset(StreamTrainDatasetMixin, DRPretrainDataset): pass class MappingDRPretrainDataset(MappingTrainDatasetMixin, DRPretrainDataset): pass class RRTrainDataset(TrainDatasetBase): def create_one_example(self, qry_encoding, psg_encoding) -> BatchEncoding: item = self.tokenizer.encode_plus( qry_encoding + psg_encoding, truncation="longest_first", max_length=self.data_args.q_max_len + self.data_args.p_max_len + 2, padding=False, return_attention_mask=False, return_token_type_ids=False, ) return item def get_process_fn(self, epoch, hashed_seed): def process_fn(example): qry = example["query"] group_positives = example["positives"] group_negatives = example["negatives"] if self.data_args.positive_passage_no_shuffle or hashed_seed is None: pos_psg = group_positives[0] else: pos_psg = group_positives[(hashed_seed + epoch) % len(group_positives)] encoded_pos_pair = self.create_one_example(qry, pos_psg) if hashed_seed is None: neg_psg = group_negatives[0] else: neg_psg = group_negatives[(hashed_seed + epoch) % len(group_negatives)] encoded_neg_pair = self.create_one_example(qry, neg_psg) return {"pos_pair": encoded_pos_pair, "neg_pair": encoded_neg_pair} return process_fn class StreamRRTrainDataset(StreamTrainDatasetMixin, RRTrainDataset): pass class MappingRRTrainDataset(MappingTrainDatasetMixin, RRTrainDataset): pass
11,428
34.604361
121
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/dataset/beir_dataset.py
import csv import logging import os from transformers import PreTrainedTokenizer from ..arguments import BEIRDataArguments from .inference_dataset import InferenceDataset logger = logging.getLogger(__name__) def load_beir_qrels(qrels_file): qrels = {} with open(qrels_file) as f: tsvreader = csv.DictReader(f, delimiter="\t") for row in tsvreader: qid = row["query-id"] pid = row["corpus-id"] rel = int(row["score"]) if qid in qrels: qrels[qid][pid] = rel else: qrels[qid] = {pid: rel} return qrels class BEIRDataset(): def __init__( self, tokenizer: PreTrainedTokenizer, data_args: BEIRDataArguments, full_tokenization: bool = True, mode: str = "processed", stream: bool = True, batch_size: int = 1, num_processes: int = 1, process_index: int = 0, cache_dir: str = None ): logger.info("Loading corpus") self.corpus_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, data_files=os.path.join(data_args.data_dir, "corpus.jsonl"), is_query=False, full_tokenization=full_tokenization, mode=mode, stream=stream, batch_size=batch_size, num_processes=num_processes, process_index=process_index, cache_dir=cache_dir ) split_names = ["train", "dev", "test"] self.query_datasets = {} self.qrels = {} for split_name in split_names: qrels_path = os.path.join(data_args.data_dir, "qrels", f"{split_name}.tsv") if os.path.exists(qrels_path): logger.info(f"Loading {split_name} queries and qrels") qrels = load_beir_qrels(qrels_path) self.qrels[split_name] = qrels qids = list(qrels.keys()) self.query_datasets[split_name] = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, data_files=os.path.join(data_args.data_dir, "queries.jsonl"), is_query=True, full_tokenization=full_tokenization, mode=mode, stream=stream, batch_size=batch_size, num_processes=num_processes, process_index=process_index, filter_fn=lambda x: x["_id"] in qids, cache_dir=cache_dir ) else: logger.info(f"{split_name} queries and qrels not found") self.query_datasets[split_name] = None self.qrels[split_name] = None
2,840
32.821429
87
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/dataset/__init__.py
from .beir_dataset import BEIRDataset from .data_collator import DRInferenceCollator, QPCollator, PairCollator, RRInferenceCollator from .inference_dataset import StreamJsonlDataset, StreamTsvDataset, MappingJsonlDataset, MappingTsvDataset, InferenceDataset from .train_dataset import StreamDRTrainDataset, MappingDRTrainDataset, StreamDRPretrainDataset, MappingDRPretrainDataset, StreamRRTrainDataset, MappingRRTrainDataset
425
84.2
166
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/train_dr.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import logging import os import sys from ..arguments import DataArguments from ..arguments import DRTrainingArguments as TrainingArguments from ..arguments import ModelArguments from ..dataset import QPCollator, StreamDRTrainDataset, MappingDRTrainDataset from ..modeling import DRModel from ..trainer import DRTrainer as Trainer from ..trainer import GCDenseTrainer from ..utils import get_delta_model_class from transformers import AutoConfig, AutoTokenizer, HfArgumentParser, set_seed logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments training_args: TrainingArguments if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info("Training/evaluation parameters %s", training_args) logger.info("MODEL parameters %s", model_args) set_seed(training_args.seed) num_labels = 1 config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = DRModel.build( model_args, data_args, training_args, config=config, cache_dir=model_args.cache_dir, ) if model_args.param_efficient_method: model_class = get_delta_model_class(model_args.param_efficient_method) delta_model = model_class(model) logger.info("Using param efficient method: %s", model_args.param_efficient_method) train_dataset_cls = MappingDRTrainDataset if training_args.use_mapping_dataset else StreamDRTrainDataset train_dataset = train_dataset_cls( tokenizer, data_args, shuffle_seed=training_args.seed, cache_dir=data_args.data_cache_dir or model_args.cache_dir ) eval_dataset = train_dataset_cls( tokenizer, data_args, is_eval=True, cache_dir=data_args.data_cache_dir or model_args.cache_dir ) if data_args.eval_path is not None else None trainer_cls = GCDenseTrainer if training_args.grad_cache else Trainer trainer = trainer_cls( model=model, args=training_args, tokenizer=tokenizer, train_dataset=train_dataset, eval_dataset=eval_dataset, data_collator=QPCollator( tokenizer, max_p_len=data_args.p_max_len, max_q_len=data_args.q_max_len ), delta_model=delta_model if model_args.param_efficient_method else None ) train_dataset.trainer = trainer trainer.train() trainer.save_model() if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir) if __name__ == "__main__": main()
4,236
33.447154
133
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/pretrain_dr.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import logging import os import sys from openmatch.arguments import DRPretrainingDataArguments from openmatch.arguments import DRTrainingArguments as TrainingArguments from openmatch.arguments import ModelArguments from openmatch.dataset import QPCollator, StreamDRPretrainDataset, MappingDRPretrainDataset from openmatch.modeling import DRModel from openmatch.trainer import DRTrainer as Trainer from openmatch.trainer import GCDenseTrainer from transformers import AutoConfig, AutoTokenizer, HfArgumentParser, set_seed logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DRPretrainingDataArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DRPretrainingDataArguments training_args: TrainingArguments if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info("Training/evaluation parameters %s", training_args) logger.info("MODEL parameters %s", model_args) if data_args.train_n_passages != 1: logger.warning("train_n_passages is not 1, but %d, setting to 1", data_args.train_n_passages) data_args.train_n_passages = 1 set_seed(training_args.seed) num_labels = 1 config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = DRModel.build( model_args, data_args, training_args, config=config, cache_dir=model_args.cache_dir, ) train_dataset_cls = MappingDRPretrainDataset if training_args.use_mapping_dataset else StreamDRPretrainDataset train_dataset = train_dataset_cls( tokenizer, data_args, shuffle_seed=training_args.seed, cache_dir=data_args.data_cache_dir or model_args.cache_dir ) trainer_cls = GCDenseTrainer if training_args.grad_cache else Trainer trainer = trainer_cls( model=model, args=training_args, tokenizer=tokenizer, train_dataset=train_dataset, data_collator=QPCollator( tokenizer, max_p_len=data_args.p_max_len, max_q_len=data_args.q_max_len ), ) train_dataset.trainer = trainer trainer.train() trainer.save_model() if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir) if __name__ == "__main__": main()
3,895
33.785714
133
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/successive_retrieve.py
import logging import os import sys from openmatch.arguments import DataArguments from openmatch.arguments import InferenceArguments as EncodingArguments from openmatch.arguments import ModelArguments from openmatch.dataset import InferenceDataset from openmatch.modeling import DRModelForInference from openmatch.retriever import SuccessiveRetriever from openmatch.utils import save_as_trec from transformers import AutoConfig, AutoTokenizer, HfArgumentParser logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, EncodingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, encoding_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, encoding_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments encoding_args: EncodingArguments # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if encoding_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed inference: %s, 16-bits inference: %s", encoding_args.local_rank, encoding_args.device, encoding_args.n_gpu, bool(encoding_args.local_rank != -1), encoding_args.fp16, ) logger.info("Encoding parameters %s", encoding_args) logger.info("MODEL parameters %s", model_args) num_labels = 1 try: config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) except OSError: config = None tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = DRModelForInference.build( model_args=model_args, config=config, cache_dir=model_args.cache_dir, ) query_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, is_query=True, stream=True, batch_size=encoding_args.per_device_eval_batch_size, num_processes=encoding_args.world_size, process_index=encoding_args.process_index, cache_dir=model_args.cache_dir ) retriever = SuccessiveRetriever.from_embeddings(model, encoding_args) result = retriever.retrieve(query_dataset, encoding_args.retrieve_depth) if encoding_args.local_process_index == 0: save_as_trec(result, encoding_args.trec_save_path) if __name__ == '__main__': main()
2,927
33.447059
109
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/retrieve.py
import logging import os import sys from ..arguments import DataArguments from ..arguments import InferenceArguments as EncodingArguments from ..arguments import ModelArguments from ..dataset import InferenceDataset from ..modeling import DRModelForInference from ..retriever import Retriever from ..utils import save_as_trec, get_delta_model_class from transformers import AutoConfig, AutoTokenizer, HfArgumentParser logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, EncodingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, encoding_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, encoding_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments encoding_args: EncodingArguments # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if encoding_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed inference: %s, 16-bits inference: %s", encoding_args.local_rank, encoding_args.device, encoding_args.n_gpu, bool(encoding_args.local_rank != -1), encoding_args.fp16, ) logger.info("Encoding parameters %s", encoding_args) logger.info("MODEL parameters %s", model_args) num_labels = 1 try: config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) except OSError: config = None tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = DRModelForInference.build( model_args=model_args, config=config, cache_dir=model_args.cache_dir, ) if model_args.param_efficient_method: model_class = get_delta_model_class(model_args.param_efficient_method) delta_model = model_class.from_finetuned(model_args.model_name_or_path + '/delta_model', model, local_files_only=True) logger.info("Using param efficient method: %s", model_args.param_efficient_method) query_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, is_query=(not encoding_args.encode_query_as_passage), stream=True, batch_size=encoding_args.per_device_eval_batch_size, num_processes=encoding_args.world_size, process_index=encoding_args.process_index, cache_dir=model_args.cache_dir ) retriever = Retriever.from_embeddings(model, encoding_args) result = retriever.retrieve(query_dataset, encoding_args.retrieve_depth) if encoding_args.local_process_index == 0: save_as_trec(result, encoding_args.trec_save_path) if __name__ == '__main__': main()
3,253
35.155556
126
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/build_index.py
import logging import os from ..arguments import DataArguments from ..arguments import InferenceArguments as EncodingArguments from ..arguments import ModelArguments from ..dataset import InferenceDataset from ..modeling import DRModelForInference from ..retriever import Retriever from ..utils import get_delta_model_class from transformers import AutoConfig, AutoTokenizer, HfArgumentParser logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, EncodingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, encoding_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, encoding_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments encoding_args: EncodingArguments # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if encoding_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed inference: %s, 16-bits inference: %s", encoding_args.local_rank, encoding_args.device, encoding_args.n_gpu, bool(encoding_args.local_rank != -1), encoding_args.fp16, ) logger.info("Encoding parameters %s", encoding_args) logger.info("MODEL parameters %s", model_args) num_labels = 1 try: config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) except OSError: config = None tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) model = DRModelForInference.build( model_args=model_args, config=config, cache_dir=model_args.cache_dir, ) if model_args.param_efficient_method: model_class = get_delta_model_class(model_args.param_efficient_method) delta_model = model_class.from_finetuned(model_args.model_name_or_path + '/delta_model', model, local_files_only=True) logger.info("Using param efficient method: %s", model_args.param_efficient_method) corpus_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, is_query=False, stream=True, batch_size=encoding_args.per_device_eval_batch_size, num_processes=encoding_args.world_size, process_index=encoding_args.process_index, cache_dir=model_args.cache_dir ) Retriever.build_embeddings(model, corpus_dataset, encoding_args) if __name__ == '__main__': main()
2,993
34.223529
126
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/rerank.py
import logging import os import sys from openmatch.arguments import DataArguments from openmatch.arguments import InferenceArguments from openmatch.arguments import ModelArguments from openmatch.dataset import InferenceDataset from openmatch.modeling import RRModel from openmatch.retriever import Reranker from openmatch.utils import save_as_trec, load_from_trec from transformers import AutoConfig, AutoTokenizer, HfArgumentParser logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, InferenceArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, inference_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, inference_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments inference_args: InferenceArguments # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if inference_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", inference_args.local_rank, inference_args.device, inference_args.n_gpu, bool(inference_args.local_rank != -1), inference_args.fp16, ) logger.info("Encoding parameters %s", inference_args) logger.info("MODEL parameters %s", model_args) num_labels = 1 config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = RRModel.build( model_args=model_args, tokenizer=tokenizer, config=config, cache_dir=model_args.cache_dir, ) query_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, full_tokenization=False, is_query=True, stream=False, cache_dir=model_args.cache_dir ) corpus_dataset = InferenceDataset.load( tokenizer=tokenizer, data_args=data_args, full_tokenization=False, is_query=False, stream=False, cache_dir=model_args.cache_dir ) run = load_from_trec(inference_args.trec_run_path, max_len_per_q=inference_args.reranking_depth) reranker = Reranker(model, tokenizer, corpus_dataset, inference_args) result = reranker.rerank(query_dataset, run) if inference_args.local_process_index == 0: save_as_trec(result, inference_args.trec_save_path) if __name__ == '__main__': main()
3,032
31.967391
110
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/driver/train_rr.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import logging import os import sys from openmatch.arguments import DataArguments from openmatch.arguments import RRTrainingArguments as TrainingArguments from openmatch.arguments import ModelArguments from openmatch.dataset import PairCollator, StreamRRTrainDataset, MappingRRTrainDataset from openmatch.modeling import RRModel from openmatch.trainer import RRTrainer as Trainer from transformers import AutoConfig, AutoTokenizer, HfArgumentParser, set_seed logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() model_args: ModelArguments data_args: DataArguments training_args: TrainingArguments if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info("Training/evaluation parameters %s", training_args) logger.info("MODEL parameters %s", model_args) set_seed(training_args.seed) num_labels = 1 config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=False, ) model = RRModel.build( model_args, data_args, training_args, tokenizer=tokenizer, config=config, cache_dir=model_args.cache_dir, ) train_dataset_cls = MappingRRTrainDataset if training_args.use_mapping_dataset else StreamRRTrainDataset train_dataset = train_dataset_cls( tokenizer, data_args, shuffle_seed=training_args.seed, cache_dir=data_args.data_cache_dir or model_args.cache_dir ) eval_dataset = train_dataset_cls( tokenizer, data_args, is_eval=True, cache_dir=data_args.data_cache_dir or model_args.cache_dir ) if data_args.eval_path is not None else None trainer = Trainer( model=model, args=training_args, tokenizer=tokenizer, train_dataset=train_dataset, eval_dataset=eval_dataset, data_collator=PairCollator( tokenizer, max_p_len=data_args.p_max_len, max_q_len=data_args.q_max_len ), ) train_dataset.trainer = trainer trainer.train() trainer.save_model() if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir) if __name__ == "__main__": main()
3,825
32.561404
133
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/modeling/reranking_model.py
import copy import json import logging import os from dataclasses import dataclass from typing import Dict, Optional import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from torch import Tensor from transformers import (AutoModel, BatchEncoding, PreTrainedModel, T5EncoderModel, PreTrainedTokenizer, AutoConfig, T5ForConditionalGeneration) from transformers.modeling_outputs import ModelOutput from ..arguments import DataArguments from ..arguments import RRTrainingArguments as TrainingArguments from ..arguments import ModelArguments from ..loss import rr_loss_functions, CrossEntropyLoss from ..utils import mean_pooling from .linear import LinearHead logger = logging.getLogger(__name__) @dataclass class RROutput(ModelOutput): pos_pair_scores: Tensor = None neg_pair_scores: Tensor = None loss: Tensor = None class RRModel(nn.Module): def __init__( self, lm: PreTrainedModel, head: nn.Module, feature: str = "last_hidden_state", pooling: str = "first", pos_token: str = None, neg_token: str = None, tokenizer: PreTrainedTokenizer = None, model_args: ModelArguments = None, data_args: DataArguments = None, train_args: TrainingArguments = None, ): super().__init__() self.lm = lm self.head = head self.feature = feature self.pooling = pooling self.pos_token = pos_token self.neg_token = neg_token self.tokenizer = tokenizer self.pos_token_id = tokenizer.encode(self.pos_token, add_special_tokens=False)[0] if self.pos_token else None self.neg_token_id = tokenizer.encode(self.neg_token, add_special_tokens=False)[0] if self.neg_token else None self.model_args = model_args self.data_args = data_args self.train_args = train_args if train_args is not None: self.loss_fn_str = train_args.loss_fn self.loss_fn = rr_loss_functions[self.loss_fn_str]() self.margin = train_args.margin if "T5" in type(self.lm).__name__ and not self.model_args.encoder_only: self.loss_fn_str = "ce" self.loss_fn = CrossEntropyLoss() def _get_config_dict(self): config = { "plm_backbone": { "type": type(self.lm).__name__, "feature": self.feature, }, "pooling": self.pooling, "pos_token": self.pos_token, "neg_token": self.neg_token, } return config def forward( self, pos_pairs: Dict[str, Tensor] = None, neg_pairs: Dict[str, Tensor] = None, ): pos_pair_scores = self.encode(pos_pairs) neg_pair_scores = self.encode(neg_pairs) if self.loss_fn_str in ["mr", "smr"]: loss = self.loss_fn(pos_pair_scores, neg_pair_scores, margin=self.margin) else: loss = self.loss_fn(pos_pair_scores, neg_pair_scores) return RROutput( loss=loss, pos_pair_scores=pos_pair_scores, neg_pair_scores=neg_pair_scores, ) def encode(self, items): if items is None: return None, None items = BatchEncoding(items) if "T5" in type(self.lm).__name__ and not self.model_args.encoder_only: decoder_input_ids = torch.zeros((items.input_ids.shape[0], 1), dtype=torch.long).to(items.input_ids.device) items_out = self.lm(**items, decoder_input_ids=decoder_input_ids, return_dict=True) logits = items_out.logits scores = logits[:, 0, [self.neg_token_id, self.pos_token_id]] # batch_size * 2 else: items_out = self.lm(**items, return_dict=True) hidden = getattr(items_out, self.feature) if self.pooling == "first": reps = hidden[:, 0, :] elif self.pooling == "mean": reps = mean_pooling(hidden, items.attention_mask) else: raise ValueError("Unknown pooling type: {}".format(self.pooling)) scores = self.head(reps) # batch_size * 1 return scores @classmethod def build( cls, model_args: ModelArguments, data_args: DataArguments = None, train_args: TrainingArguments = None, tokenizer: PreTrainedTokenizer = None, **hf_kwargs, ): # load local config = None model_class = None hf_config = AutoConfig.from_pretrained(model_args.model_name_or_path, **hf_kwargs) if model_args.encoder_only: model_class = T5EncoderModel elif "T5" in hf_config.architectures[0]: # Pre-trained T5 model model_class = T5ForConditionalGeneration else: model_class = AutoModel if os.path.exists(os.path.join(model_args.model_name_or_path, "openmatch_config.json")): with open(os.path.join(model_args.model_name_or_path, "openmatch_config.json")) as f: config = json.load(f) if os.path.isdir(model_args.model_name_or_path) and config is not None: # not a raw Huggingface model logger.info(f'loading reranking model weight from {model_args.model_name_or_path}') lm = model_class.from_pretrained( model_args.model_name_or_path, **hf_kwargs ) head = LinearHead.load(ckpt_dir=model_args.model_name_or_path) else: # a Huggingface model lm = model_class.from_pretrained(model_args.model_name_or_path, **hf_kwargs) head = LinearHead(model_args.projection_in_dim, 1) model = cls( lm=lm, head=head, feature=model_args.feature if config is None else config["plm_backbone"]["feature"], pooling=model_args.pooling if config is None else config["pooling"], pos_token=model_args.pos_token if config is None else config["pos_token"], neg_token=model_args.neg_token if config is None else config["neg_token"], tokenizer=tokenizer, model_args=model_args, data_args=data_args, train_args=train_args, ) return model def save(self, output_dir: str): self.lm.save_pretrained(output_dir) self.head.save(output_dir) with open(os.path.join(output_dir, 'openmatch_config.json'), 'w') as f: json.dump(self._get_config_dict(), f, indent=4)
6,685
35.736264
119
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/modeling/linear.py
import logging import os import json import torch import torch.nn as nn from torch import Tensor logger = logging.getLogger(__name__) class LinearHead(nn.Module): def __init__( self, input_dim: int = 768, output_dim: int = 768, ): super(LinearHead, self).__init__() self.linear = nn.Linear(input_dim, output_dim, bias=False) self.config = {'input_dim': input_dim, 'output_dim': output_dim} def forward(self, rep: Tensor = None): return self.linear(rep) @classmethod def load(cls, ckpt_dir: str): logger.info(f'Loading linear head from {ckpt_dir}') model_path = os.path.join(ckpt_dir, 'linear.pt') config_path = os.path.join(ckpt_dir, 'head_config.json') with open(config_path, 'r') as f: config = json.load(f) model = cls(**config) model.load_state_dict(torch.load(model_path)) return model def save(self, save_path): torch.save(self.state_dict(), os.path.join(save_path, 'linear.pt')) with open(os.path.join(save_path, 'head_config.json'), 'w') as f: json.dump(self.config, f, indent=4)
1,182
29.333333
75
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/modeling/dense_retrieval_model.py
# Adapted from Tevatron (https://github.com/texttron/tevatron) import copy import importlib import json import logging import os from dataclasses import dataclass from typing import Dict, Optional import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from torch import Tensor from transformers import ( AutoConfig, AutoModel, BatchEncoding, PreTrainedModel, T5EncoderModel, ) from transformers.modeling_outputs import ModelOutput from ..arguments import DataArguments from ..arguments import DRTrainingArguments as TrainingArguments from ..arguments import ModelArguments from ..utils import mean_pooling from .linear import LinearHead logger = logging.getLogger(__name__) @dataclass class DROutput(ModelOutput): q_reps: Tensor = None p_reps: Tensor = None loss: Tensor = None scores: Tensor = None class DRModel(nn.Module): def __init__( self, lm_q: PreTrainedModel, lm_p: PreTrainedModel, tied: bool = True, feature: str = "last_hidden_state", pooling: str = "first", head_q: nn.Module = None, head_p: nn.Module = None, normalize: bool = False, model_args: ModelArguments = None, data_args: DataArguments = None, train_args: TrainingArguments = None, ): super().__init__() self.tied = tied self.lm_q = lm_q self.lm_p = lm_p self.head_q = head_q self.head_p = head_p self.loss_fn = nn.CrossEntropyLoss(reduction="mean") self.feature = feature self.pooling = pooling self.normalize = normalize self.model_args = model_args self.train_args = train_args self.data_args = data_args if train_args is not None and train_args.negatives_x_device: if not dist.is_initialized(): raise ValueError( "Distributed training has not been initialized for representation all gather." ) self.process_rank = dist.get_rank() self.world_size = dist.get_world_size() def _get_config_dict(self): config = { "tied": self.tied, "plm_backbone": { "type": type(self.lm_q).__name__, "feature": self.feature, }, "pooling": self.pooling, "linear_head": bool(self.head_q), "normalize": self.normalize, } return config def forward( self, query: Dict[str, Tensor] = None, passage: Dict[str, Tensor] = None, ): q_hidden, q_reps = self.encode_query(query) p_hidden, p_reps = self.encode_passage(passage) if q_reps is None or p_reps is None: return DROutput(q_reps=q_reps, p_reps=p_reps) # if self.training: if self.train_args.negatives_x_device: q_reps = self.dist_gather_tensor(q_reps) p_reps = self.dist_gather_tensor(p_reps) effective_bsz = ( self.train_args.per_device_train_batch_size * self.world_size if self.train_args.negatives_x_device else self.train_args.per_device_train_batch_size ) scores = torch.matmul(q_reps, p_reps.transpose(0, 1)) # scores = torch.matmul(q_reps, p_reps.transpose(0, 1)) / 0.05 # contriever if not self.data_args.use_all_positive_passages: target = torch.arange( scores.size(0), device=scores.device, dtype=torch.long ) target = target * self.data_args.train_n_passages loss = self.loss_fn(scores, target) else: batch_size = scores.size(0) n_total_passages = int(scores.size(1) / scores.size(0)) n_positive_passages = n_total_passages - ( self.data_args.train_n_passages - 1 ) losses = None num = 0 target = torch.arange(1, device=scores.device, dtype=torch.long) for i in range(batch_size): indices = [0] positive_indices = [ i * n_total_passages + j for j in range(n_positive_passages) ] for j in range(scores.size(1)): if j not in positive_indices: indices.append(j) for j in range(n_positive_passages): indices[0] = i * n_total_passages + j now_scores = scores[i][indices].unsqueeze(0) loss = self.loss_fn(now_scores, target) losses = losses + loss if losses != None else loss num += 1 loss = losses / num if self.training and self.train_args.negatives_x_device: loss = loss * self.world_size # counter average weight reduction return DROutput(loss=loss, scores=scores, q_reps=q_reps, p_reps=p_reps) def encode(self, items, model, head): if items is None: return None, None items = BatchEncoding(items) if "T5" in type(model).__name__ and not self.model_args.encoder_only: decoder_input_ids = torch.zeros( (items.input_ids.shape[0], 1), dtype=torch.long ).to(items.input_ids.device) items_out = model( **items, decoder_input_ids=decoder_input_ids, return_dict=True ) hidden = items_out.last_hidden_state reps = hidden[:, 0, :] else: items_out = model(**items, return_dict=True) hidden = getattr(items_out, self.feature) if self.pooling == "first": reps = hidden[:, 0, :] elif self.pooling == "mean": reps = mean_pooling(hidden, items.attention_mask) elif self.pooling == "no": reps = hidden else: raise ValueError("Unknown pooling type: {}".format(self.pooling)) if head is not None: reps = head(reps) # D * d if self.normalize: reps = F.normalize(reps, dim=1) return hidden, reps def encode_passage(self, psg): return self.encode(psg, self.lm_p, self.head_p) def encode_query(self, qry): return self.encode(qry, self.lm_q, self.head_q) @classmethod def build( cls, model_args: ModelArguments, data_args: DataArguments = None, train_args: TrainingArguments = None, **hf_kwargs, ): # load local config = None head_q = head_p = None if os.path.exists( os.path.join(model_args.model_name_or_path, "openmatch_config.json") ): with open( os.path.join(model_args.model_name_or_path, "openmatch_config.json") ) as f: config = json.load(f) if ( os.path.isdir(model_args.model_name_or_path) and config is not None ): # an OpenMatch model tied = config["tied"] if tied: logger.info( f"loading query model weight from {model_args.model_name_or_path}" ) model_name = config["plm_backbone"]["type"] model_class = getattr( importlib.import_module("transformers"), model_name ) lm_q = lm_p = model_class.from_pretrained( model_args.model_name_or_path, **hf_kwargs ) if config["linear_head"]: head_q = head_p = LinearHead.load(model_args.model_name_or_path) else: _qry_model_path = os.path.join( model_args.model_name_or_path, "query_model" ) _psg_model_path = os.path.join( model_args.model_name_or_path, "passage_model" ) _qry_head_path = os.path.join( model_args.model_name_or_path, "query_head" ) _psg_head_path = os.path.join( model_args.model_name_or_path, "passage_head" ) logger.info(f"loading query model weight from {_qry_model_path}") model_name = config["plm_backbone"]["lm_q_type"] model_class = getattr( importlib.import_module("transformers"), model_name ) if os.path.exists(os.path.join(_qry_model_path, "config.json")): logger.info(f"loading query model config from {_qry_model_path}") qry_model_config = AutoConfig.from_pretrained(_qry_model_path) hf_kwargs["config"] = qry_model_config lm_q = model_class.from_pretrained(_qry_model_path, **hf_kwargs) logger.info(f"loading passage model weight from {_psg_model_path}") model_name = config["plm_backbone"]["lm_p_type"] model_class = getattr( importlib.import_module("transformers"), model_name ) if os.path.exists(os.path.join(_psg_model_path, "config.json")): logger.info(f"loading passage model config from {_psg_model_path}") psg_model_config = AutoConfig.from_pretrained(_psg_model_path) hf_kwargs["config"] = psg_model_config lm_p = model_class.from_pretrained(_psg_model_path, **hf_kwargs) if config["linear_head"]: head_q = LinearHead.load(_qry_head_path) head_p = LinearHead.load(_psg_head_path) else: # a Huggingface model tied = not model_args.untie_encoder model_class = T5EncoderModel if model_args.encoder_only else AutoModel lm_q = model_class.from_pretrained( model_args.model_name_or_path, **hf_kwargs ) lm_p = copy.deepcopy(lm_q) if not tied else lm_q if model_args.add_linear_head: head_q = LinearHead( model_args.projection_in_dim, model_args.projection_out_dim ) head_p = copy.deepcopy(head_q) if not tied else head_q model = cls( lm_q=lm_q, lm_p=lm_p, tied=tied, feature=model_args.feature if config is None else config["plm_backbone"]["feature"], pooling=model_args.pooling if config is None else config["pooling"], head_q=head_q, head_p=head_p, normalize=model_args.normalize if config is None else config["normalize"], model_args=model_args, data_args=data_args, train_args=train_args, ) return model def save(self, output_dir: str): if not self.tied: os.makedirs(os.path.join(output_dir, "query_model")) os.makedirs(os.path.join(output_dir, "passage_model")) self.lm_q.save_pretrained(os.path.join(output_dir, "query_model")) self.lm_p.save_pretrained(os.path.join(output_dir, "passage_model")) if self.head_q is not None: self.head_q.save(os.path.join(output_dir, "query_head")) self.head_p.save(os.path.join(output_dir, "passage_head")) else: self.lm_q.save_pretrained(output_dir) if self.head_q is not None: self.head_q.save(output_dir) with open(os.path.join(output_dir, "openmatch_config.json"), "w") as f: json.dump(self._get_config_dict(), f, indent=4) def dist_gather_tensor(self, t: Optional[torch.Tensor]): if t is None: return None t = t.contiguous() all_tensors = [torch.empty_like(t) for _ in range(self.world_size)] dist.all_gather(all_tensors, t) all_tensors[self.process_rank] = t all_tensors = torch.cat(all_tensors, dim=0) return all_tensors class DRModelForInference(DRModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.eval() @torch.no_grad() def encode_passage(self, psg): return super(DRModelForInference, self).encode_passage(psg) @torch.no_grad() def encode_query(self, qry): return super(DRModelForInference, self).encode_query(qry) def forward( self, query: Dict[str, Tensor] = None, passage: Dict[str, Tensor] = None, ): q_hidden, q_reps = self.encode_query(query) p_hidden, p_reps = self.encode_passage(passage) return DROutput(q_reps=q_reps, p_reps=p_reps)
12,826
35.440341
98
py
Augmentation-Adapted-Retriever
Augmentation-Adapted-Retriever-main/src/Retriever/modeling/__init__.py
from .dense_retrieval_model import DRModel, DRModelForInference, DROutput from .reranking_model import RRModel, RROutput
120
59.5
73
py