├── .gitignore ├── KGQA ├── LSTM │ ├── dataloader.py │ ├── main.py │ └── model.py └── RoBERTa │ ├── dataloader.py │ ├── helpers.py │ ├── main.py │ └── model.py ├── LICENSE ├── README.md ├── config ├── simple-train-webqsp-full.yaml └── simple-train-webqsp-half.yaml ├── model.png ├── requirements.txt ├── scripts ├── download_artifacts.sh ├── initial_setup.sh ├── install_libkge.sh ├── preprocess_webqsp_dataset.sh ├── train_metaQA.sh └── train_webqsp.sh └── train_embeddings ├── README.md ├── load_data.py ├── main.py └── model.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | #data 132 | data/ 133 | 134 | #pretrained models 135 | pretrained_models/ 136 | 137 | #checkpoints 138 | checkpoints/ 139 | 140 | #kge 141 | kge/ 142 | 143 | #csv 144 | *.csv -------------------------------------------------------------------------------- /KGQA/LSTM/dataloader.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import random 3 | from torch.utils.data import Dataset, DataLoader 4 | from collections import defaultdict 5 | import os 6 | import unicodedata 7 | import re 8 | import time 9 | from collections import defaultdict 10 | from tqdm import tqdm 11 | import numpy as np 12 | 13 | 14 | class DatasetMetaQA(Dataset): 15 | def __init__(self, data, word2ix, relations, entities, entity2idx): 16 | self.data = data 17 | self.relations = relations 18 | self.entities = entities 19 | self.word_to_ix = {} 20 | self.entity2idx = entity2idx 21 | self.word_to_ix = word2ix 22 | self.pos_dict = defaultdict(list) 23 | self.neg_dict = defaultdict(list) 24 | self.index_array = list(self.entities.keys()) 25 | 26 | 27 | def __len__(self): 28 | return len(self.data) 29 | 30 | def toOneHot(self, indices): 31 | indices = torch.LongTensor(indices) 32 | batch_size = len(indices) 33 | vec_len = len(self.entity2idx) 34 | one_hot = torch.FloatTensor(vec_len) 35 | one_hot.zero_() 36 | one_hot.scatter_(0, indices, 1) 37 | return one_hot 38 | 39 | def __getitem__(self, index): 40 | data_point = self.data[index] 41 | question_text = data_point[1] 42 | question_ids = [self.word_to_ix[word] for word in question_text.split()] 43 | head_id = self.entity2idx[data_point[0].strip()] 44 | tail_ids = [] 45 | for tail_name in data_point[2]: 46 | tail_name = tail_name.strip() 47 | tail_ids.append(self.entity2idx[tail_name]) 48 | tail_onehot = self.toOneHot(tail_ids) 49 | return question_ids, head_id, tail_onehot 50 | 51 | 52 | 53 | 54 | def _collate_fn(batch): 55 | sorted_seq = sorted(batch, key=lambda sample: len(sample[0]), reverse=True) 56 | sorted_seq_lengths = [len(i[0]) for i in sorted_seq] 57 | longest_sample = sorted_seq_lengths[0] 58 | minibatch_size = len(batch) 59 | # print(minibatch_size) 60 | # aditay 61 | input_lengths = [] 62 | p_head = [] 63 | p_tail = [] 64 | inputs = torch.zeros(minibatch_size, longest_sample, dtype=torch.long) 65 | for x in range(minibatch_size): 66 | # data_a = x[0] 67 | sample = sorted_seq[x][0] 68 | p_head.append(sorted_seq[x][1]) 69 | tail_onehot = sorted_seq[x][2] 70 | p_tail.append(tail_onehot) 71 | seq_len = len(sample) 72 | input_lengths.append(seq_len) 73 | sample = torch.tensor(sample, dtype=torch.long) 74 | sample = sample.view(sample.shape[0]) 75 | inputs[x].narrow(0,0,seq_len).copy_(sample) 76 | 77 | return inputs, torch.tensor(input_lengths, dtype=torch.long), torch.tensor(p_head, dtype=torch.long), torch.stack(p_tail) 78 | 79 | class DataLoaderMetaQA(DataLoader): 80 | def __init__(self, *args, **kwargs): 81 | super(DataLoaderMetaQA, self).__init__(*args, **kwargs) 82 | self.collate_fn = _collate_fn 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /KGQA/LSTM/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import numpy as np 4 | from torch.utils.data import Dataset, DataLoader 5 | import torch.nn as nn 6 | import pickle 7 | from tqdm import tqdm 8 | import argparse 9 | from torch.nn import functional as F 10 | from dataloader import DatasetMetaQA, DataLoaderMetaQA 11 | from model import RelationExtractor 12 | from torch.optim.lr_scheduler import ExponentialLR 13 | import pandas as pd 14 | 15 | def str2bool(v): 16 | if isinstance(v, bool): 17 | return v 18 | if v.lower() in ('no', 'false', 'f', 'n', '0'): 19 | return False 20 | else: 21 | return True 22 | 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('--hops', type=str, default='1') 25 | parser.add_argument('--ls', type=float, default=0.0) 26 | parser.add_argument('--validate_every', type=int, default=5) 27 | parser.add_argument('--model', type=str, default='Rotat3') 28 | parser.add_argument('--kg_type', type=str, default='half') 29 | 30 | parser.add_argument('--mode', type=str, default='eval') 31 | parser.add_argument('--batch_size', type=int, default=1024) 32 | parser.add_argument('--dropout', type=float, default=0.1) 33 | parser.add_argument('--entdrop', type=float, default=0.0) 34 | parser.add_argument('--reldrop', type=float, default=0.0) 35 | parser.add_argument('--scoredrop', type=float, default=0.0) 36 | parser.add_argument('--l3_reg', type=float, default=0.0) 37 | parser.add_argument('--decay', type=float, default=1.0) 38 | parser.add_argument('--shuffle_data', type=bool, default=True) 39 | parser.add_argument('--num_workers', type=int, default=15) 40 | parser.add_argument('--lr', type=float, default=0.0001) 41 | parser.add_argument('--nb_epochs', type=int, default=90) 42 | parser.add_argument('--gpu', type=int, default=0) 43 | parser.add_argument('--neg_batch_size', type=int, default=128) 44 | parser.add_argument('--hidden_dim', type=int, default=200) 45 | parser.add_argument('--embedding_dim', type=int, default=256) 46 | parser.add_argument('--relation_dim', type=int, default=30) 47 | parser.add_argument('--use_cuda', type=bool, default=True) 48 | parser.add_argument('--patience', type=int, default=5) 49 | parser.add_argument('--freeze', type=str2bool, default=True) 50 | 51 | os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2,3,4,5,6,7" 52 | args = parser.parse_args() 53 | 54 | 55 | def prepare_embeddings(embedding_dict): 56 | entity2idx = {} 57 | idx2entity = {} 58 | i = 0 59 | embedding_matrix = [] 60 | for key, entity in embedding_dict.items(): 61 | entity2idx[key.strip()] = i 62 | idx2entity[i] = key.strip() 63 | i += 1 64 | embedding_matrix.append(entity) 65 | return entity2idx, idx2entity, embedding_matrix 66 | 67 | def get_vocab(data): 68 | word_to_ix = {} 69 | maxLength = 0 70 | idx2word = {} 71 | for d in data: 72 | sent = d[1] 73 | for word in sent.split(): 74 | if word not in word_to_ix: 75 | idx2word[len(word_to_ix)] = word 76 | word_to_ix[word] = len(word_to_ix) 77 | 78 | length = len(sent.split()) 79 | if length > maxLength: 80 | maxLength = length 81 | 82 | return word_to_ix, idx2word, maxLength 83 | 84 | def preprocess_entities_relations(entity_dict, relation_dict, entities, relations): 85 | e = {} 86 | r = {} 87 | 88 | f = open(entity_dict, 'r') 89 | for line in f: 90 | line = line.strip().split('\t') 91 | ent_id = int(line[0]) 92 | ent_name = line[1] 93 | e[ent_name] = entities[ent_id] 94 | f.close() 95 | 96 | f = open(relation_dict,'r') 97 | for line in f: 98 | line = line.strip().split('\t') 99 | rel_id = int(line[0]) 100 | rel_name = line[1] 101 | r[rel_name] = relations[rel_id] 102 | f.close() 103 | return e,r 104 | 105 | def inTopk(scores, ans, k): 106 | result = False 107 | topk = torch.topk(scores, k)[1] 108 | for x in topk: 109 | if x in ans: 110 | result = True 111 | return result 112 | 113 | def validate(data_path, device, model, word2idx, entity2idx, model_name, return_hits_at_k): 114 | model.eval() 115 | data = process_text_file(data_path) 116 | answers = [] 117 | data_gen = data_generator(data=data, word2ix=word2idx, entity2idx=entity2idx) 118 | total_correct = 0 119 | error_count = 0 120 | 121 | hit_at_1 = 0 122 | hit_at_5 = 0 123 | hit_at_10 = 0 124 | 125 | candidates_with_scores = [] 126 | writeCandidatesToFile=False 127 | 128 | for i in tqdm(range(len(data))): 129 | try: 130 | d = next(data_gen) 131 | head = d[0].to(device) 132 | question = d[1].to(device) 133 | ans = d[2] 134 | ques_len = d[3].unsqueeze(0) 135 | tail_test = torch.tensor(ans, dtype=torch.long).to(device) 136 | 137 | scores = model.get_score_ranked(head=head, sentence=question, sent_len=ques_len)[0] 138 | # candidates = qa_nbhood_list[i] 139 | # mask = torch.from_numpy(getMask(candidates, entity2idx)).to(device) 140 | # following 2 lines for no neighbourhood check 141 | mask = torch.zeros(len(entity2idx)).to(device) 142 | mask[head] = 1 143 | #reduce scores of all non-candidates 144 | new_scores = scores - (mask*99999) 145 | pred_ans = torch.argmax(new_scores).item() 146 | # new_scores = new_scores.cpu().detach().numpy() 147 | # scores_list.append(new_scores) 148 | if pred_ans == head.item(): 149 | print('Head and answer same') 150 | print(torch.max(new_scores)) 151 | print(torch.min(new_scores)) 152 | # pred_ans = getBest(scores, candidates) 153 | # if ans[0] not in candidates: 154 | # print('Answer not in candidates') 155 | # print(len(candidates)) 156 | # exit(0) 157 | 158 | if writeCandidatesToFile: 159 | entry = {} 160 | entry['question'] = d[-1] 161 | head_text = idx2entity[head.item()] 162 | entry['head'] = head_text 163 | s, c = torch.topk(new_scores, 200) 164 | s = s.cpu().detach().numpy() 165 | c = c.cpu().detach().numpy() 166 | cands = [] 167 | for cand in c: 168 | cands.append(idx2entity[cand]) 169 | entry['scores'] = s 170 | entry['candidates'] = cands 171 | correct_ans = [] 172 | for a in ans: 173 | correct_ans.append(idx2entity[a]) 174 | entry['answers'] = correct_ans 175 | candidates_with_scores.append(entry) 176 | 177 | 178 | if inTopk(new_scores, ans, 1): 179 | hit_at_1 += 1 180 | if inTopk(new_scores, ans, 5): 181 | hit_at_5 += 1 182 | if inTopk(new_scores, ans, 10): 183 | hit_at_10 += 1 184 | 185 | 186 | if type(ans) is int: 187 | ans = [ans] 188 | is_correct = 0 189 | if pred_ans in ans: 190 | total_correct += 1 191 | is_correct = 1 192 | else: 193 | num_incorrect += 1 194 | q_text = d[-1] 195 | answers.append(q_text + '\t' + str(pred_ans) + '\t' + str(is_correct)) 196 | except: 197 | error_count += 1 198 | 199 | accuracy = total_correct/len(data) 200 | # print('Error mean rank: %f' % (incorrect_rank_sum/num_incorrect)) 201 | # print('%d out of %d incorrect were not in top 50' % (not_in_top_50_count, num_incorrect)) 202 | 203 | if return_hits_at_k: 204 | return answers, accuracy, (hit_at_1/len(data)), (hit_at_5/len(data)), (hit_at_10/len(data)) 205 | else: 206 | return answers, accuracy 207 | 208 | def writeToFile(lines, fname): 209 | f = open(fname, 'w') 210 | for line in lines: 211 | f.write(line + '\n') 212 | f.close() 213 | print('Wrote to ', fname) 214 | return 215 | 216 | def set_bn_eval(m): 217 | classname = m.__class__.__name__ 218 | if classname.find('BatchNorm1d') != -1: 219 | m.eval() 220 | 221 | def get_chk_suffix(): 222 | return '.chkpt' 223 | 224 | def get_checkpoint_file_path(chkpt_path, model_name, num_hops, suffix, kg_type): 225 | return f"{chkpt_path}{model_name}_{num_hops}_{suffix}_{kg_type}" 226 | 227 | def perform_experiment(data_path, mode, entity_path, relation_path, entity_dict, relation_dict, neg_batch_size, batch_size, shuffle, num_workers, nb_epochs, embedding_dim, hidden_dim, relation_dim, gpu, use_cuda,patience, freeze, validate_every, num_hops, lr, entdrop, reldrop, scoredrop, l3_reg, model_name, decay, ls, w_matrix, bn_list, kg_type, valid_data_path=None, test_data_path=None): 228 | entities = np.load(entity_path) 229 | relations = np.load(relation_path) 230 | e,r = preprocess_entities_relations(entity_dict, relation_dict, entities, relations) 231 | entity2idx, idx2entity, embedding_matrix = prepare_embeddings(e) 232 | data = process_text_file(data_path, split=False) 233 | # data = pickle.load(open(data_path, 'rb')) 234 | word2ix,idx2word, max_len = get_vocab(data) 235 | hops = str(num_hops) 236 | device = torch.device(gpu if use_cuda else "cpu") 237 | 238 | dataset = DatasetMetaQA(data=data, word2ix=word2ix, relations=r, entities=e, entity2idx=entity2idx) 239 | 240 | model = RelationExtractor(embedding_dim=embedding_dim, hidden_dim=hidden_dim, vocab_size=len(word2ix), num_entities = len(idx2entity), relation_dim=relation_dim, pretrained_embeddings=embedding_matrix, freeze=freeze, device=device, entdrop = entdrop, reldrop = reldrop, scoredrop = scoredrop, l3_reg = l3_reg, model = model_name, ls = ls, w_matrix = w_matrix, bn_list=bn_list) 241 | 242 | checkpoint_path = '../../checkpoints/MetaQA/' 243 | if mode=='train': 244 | optimizer = torch.optim.Adam(model.parameters(), lr=lr) 245 | scheduler = ExponentialLR(optimizer, decay) 246 | optimizer.zero_grad() 247 | model.to(device) 248 | best_score = -float("inf") 249 | best_model = model.state_dict() 250 | no_update = 0 251 | data_loader = DataLoaderMetaQA(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers) 252 | for epoch in range(nb_epochs): 253 | phases = [] 254 | for i in range(validate_every): 255 | phases.append('train') 256 | phases.append('valid') 257 | for phase in phases: 258 | if phase == 'train': 259 | model.train() 260 | if freeze == True: 261 | # print('Freezing batch norm layers') 262 | model.apply(set_bn_eval) 263 | loader = tqdm(data_loader, total=len(data_loader), unit="batches") 264 | running_loss = 0 265 | for i_batch, a in enumerate(loader): 266 | model.zero_grad() 267 | question = a[0].to(device) 268 | sent_len = a[1].to(device) 269 | positive_head = a[2].to(device) 270 | positive_tail = a[3].to(device) 271 | 272 | loss = model(sentence=question, p_head=positive_head, p_tail=positive_tail, question_len=sent_len) 273 | loss.backward() 274 | optimizer.step() 275 | running_loss += loss.item() 276 | loader.set_postfix(Loss=running_loss/((i_batch+1)*batch_size), Epoch=epoch) 277 | loader.set_description('{}/{}'.format(epoch, nb_epochs)) 278 | loader.update() 279 | 280 | scheduler.step() 281 | 282 | elif phase=='valid': 283 | model.eval() 284 | eps = 0.0001 285 | answers, score = validate(model=model, data_path= valid_data_path, word2idx= word2ix, entity2idx= entity2idx, device=device, model_name=model_name, return_hits_at_k=False) 286 | if score > best_score + eps: 287 | best_score = score 288 | no_update = 0 289 | best_model = model.state_dict() 290 | print(hops + " hop Validation accuracy increased from previous epoch", score) 291 | _, test_score = validate(model=model, data_path= test_data_path, word2idx= word2ix, entity2idx= entity2idx, device=device, model_name=model_name, return_hits_at_k=False) 292 | print('Test score for best valid so far:', test_score) 293 | # writeToFile(answers, 'results_' + model_name + '_' + hops + '.txt') 294 | suffix = '' 295 | if freeze == True: 296 | suffix = '_frozen' 297 | checkpoint_file_name = get_checkpoint_file_path(checkpoint_path, model_name, num_hops, suffix, kg_type)+get_chk_suffix() 298 | print('Saving checkpoint to ', checkpoint_file_name) 299 | torch.save(model.state_dict(), checkpoint_file_name) 300 | elif (score < best_score + eps) and (no_update < patience): 301 | no_update +=1 302 | print("Validation accuracy decreases to %f from %f, %d more epoch to check"%(score, best_score, patience-no_update)) 303 | elif no_update == patience: 304 | print("Model has exceed patience. Saving best model and exiting") 305 | torch.save(best_model, get_checkpoint_file_path(checkpoint_path, model_name, num_hops, '', kg_type)+ '_' + 'best_score_model' + get_chk_suffix() ) 306 | exit() 307 | if epoch == nb_epochs-1: 308 | print("Final Epoch has reached. Stopping and saving model.") 309 | torch.save(best_model, get_checkpoint_file_path(checkpoint_path, model_name, num_hops, '', kg_type)+ '_' + 'best_score_model' + get_chk_suffix() ) 310 | exit() 311 | elif mode=='test': 312 | model_chkpt_file=get_checkpoint_file_path(checkpoint_path, model_name, num_hops, '', kg_type)+ '_' + 'best_score_model' + get_chk_suffix() 313 | 314 | print(model_chkpt_file) 315 | 316 | model.load_state_dict(torch.load(model_chkpt_file, map_location=lambda storage, loc: storage)) 317 | model.to(device) 318 | # for parameter in model.parameters(): 319 | # parameter.requires_grad = False 320 | 321 | answers, accuracy, hits_at_1, hits_at_5, hits_at_10 = validate(model=model, data_path= test_data_path, word2idx= word2ix, entity2idx= entity2idx, device=device, model_name=model_name, return_hits_at_k=True) 322 | 323 | d = { 324 | 'KG-Model': model_name, 325 | 'KG-Type': kg_type, 326 | 'hops': num_hops, 327 | 'Accuracy': [accuracy], 328 | 'Hits@1': [hits_at_1], 329 | 'Hits@5': [hits_at_5], 330 | 'Hits@10': [hits_at_10] 331 | } 332 | df = pd.DataFrame(data=d) 333 | df.to_csv(f"final_results.csv", mode='a', index=False, header=False) 334 | 335 | 336 | def process_text_file(text_file, split=False): 337 | data_file = open(text_file, 'r') 338 | data_array = [] 339 | for data_line in data_file.readlines(): 340 | data_line = data_line.strip() 341 | if data_line == '': 342 | continue 343 | data_line = data_line.strip().split('\t') 344 | question = data_line[0].split('[') 345 | question_1 = question[0] 346 | question_2 = question[1].split(']') 347 | head = question_2[0].strip() 348 | question_2 = question_2[1] 349 | question = question_1+'NE'+question_2 350 | ans = data_line[1].split('|') 351 | data_array.append([head, question.strip(), ans]) 352 | if split==False: 353 | return data_array 354 | else: 355 | data = [] 356 | for line in data_array: 357 | head = line[0] 358 | question = line[1] 359 | tails = line[2] 360 | for tail in tails: 361 | data.append([head, question, tail]) 362 | return data 363 | 364 | def data_generator(data, word2ix, entity2idx): 365 | for i in range(len(data)): 366 | data_sample = data[i] 367 | head = entity2idx[data_sample[0].strip()] 368 | question = data_sample[1].strip().split(' ') 369 | encoded_question = [word2ix[word.strip()] for word in question] 370 | if type(data_sample[2]) is str: 371 | ans = entity2idx[data_sample[2]] 372 | else: 373 | ans = [entity2idx[entity.strip()] for entity in list(data_sample[2])] 374 | 375 | yield torch.tensor(head, dtype=torch.long),torch.tensor(encoded_question, dtype=torch.long) , ans, torch.tensor(len(encoded_question), dtype=torch.long), data_sample[1] 376 | 377 | 378 | 379 | 380 | hops = args.hops 381 | if hops in ['1', '2', '3']: 382 | hops = hops + 'hop' 383 | if args.kg_type == 'half': 384 | data_path = '../../data/QA_data/MetaQA/qa_train_' + hops + '_half.txt' 385 | else: 386 | data_path = '../../data/QA_data/MetaQA/qa_train_' + hops + '.txt' 387 | 388 | valid_data_path = '../../data/QA_data/MetaQA/qa_dev_' + hops + '.txt' 389 | test_data_path = '../../data/QA_data/MetaQA/qa_test_' + hops + '.txt' 390 | 391 | model_name = args.model 392 | kg_type = args.kg_type 393 | print('KG type is', kg_type) 394 | embedding_folder = '../../pretrained_models/embeddings/' + model_name + '_MetaQA_' + kg_type 395 | 396 | entity_embedding_path = embedding_folder + '/E.npy' 397 | relation_embedding_path = embedding_folder + '/R.npy' 398 | entity_dict = embedding_folder + '/entities.dict' 399 | relation_dict = embedding_folder + '/relations.dict' 400 | w_matrix = embedding_folder + '/W.npy' 401 | 402 | bn_list = [] 403 | 404 | for i in range(3): 405 | bn = np.load(embedding_folder + '/bn' + str(i) + '.npy', allow_pickle=True) 406 | bn_list.append(bn.item()) 407 | 408 | perform_experiment(data_path=data_path, 409 | mode=args.mode, 410 | entity_path=entity_embedding_path, 411 | relation_path=relation_embedding_path, 412 | entity_dict=entity_dict, 413 | relation_dict=relation_dict, 414 | neg_batch_size=args.neg_batch_size, 415 | batch_size=args.batch_size, 416 | shuffle=args.shuffle_data, 417 | num_workers=args.num_workers, 418 | nb_epochs=args.nb_epochs, 419 | embedding_dim=args.embedding_dim, 420 | hidden_dim=args.hidden_dim, 421 | relation_dim=args.relation_dim, 422 | gpu=args.gpu, 423 | use_cuda=args.use_cuda, 424 | valid_data_path=valid_data_path, 425 | test_data_path=test_data_path, 426 | patience=args.patience, 427 | validate_every=args.validate_every, 428 | freeze=args.freeze, 429 | num_hops=args.hops, 430 | lr=args.lr, 431 | entdrop=args.entdrop, 432 | reldrop=args.reldrop, 433 | scoredrop = args.scoredrop, 434 | l3_reg = args.l3_reg, 435 | model_name=args.model, 436 | decay=args.decay, 437 | ls=args.ls, 438 | w_matrix=w_matrix, 439 | bn_list=bn_list, 440 | kg_type=kg_type) 441 | -------------------------------------------------------------------------------- /KGQA/LSTM/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.utils 5 | import torch.nn.functional as F 6 | from torch.autograd import Variable 7 | from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence 8 | import torch.nn.functional as F 9 | import numpy as np 10 | from torch.nn.init import xavier_normal_ 11 | 12 | class RelationExtractor(nn.Module): 13 | 14 | def __init__(self, embedding_dim, hidden_dim, vocab_size, relation_dim, num_entities, pretrained_embeddings, device, entdrop, reldrop, scoredrop, l3_reg, model, ls, w_matrix, bn_list, freeze=True): 15 | super(RelationExtractor, self).__init__() 16 | self.device = device 17 | self.bn_list = bn_list 18 | self.model = model 19 | self.freeze = freeze 20 | self.label_smoothing = ls 21 | self.l3_reg = l3_reg 22 | if self.model == 'DistMult': 23 | multiplier = 1 24 | self.getScores = self.DistMult 25 | elif self.model == 'SimplE': 26 | multiplier = 2 27 | self.getScores = self.SimplE 28 | elif self.model == 'ComplEx': 29 | multiplier = 2 30 | self.getScores = self.ComplEx 31 | elif self.model == 'Rotat3': 32 | multiplier = 3 33 | self.getScores = self.Rotat3 34 | elif self.model == 'TuckER': 35 | W_torch = torch.from_numpy(np.load(w_matrix)) 36 | self.W = nn.Parameter( 37 | torch.Tensor(W_torch), 38 | requires_grad = True 39 | ) 40 | # self.W = nn.Parameter(torch.tensor(np.random.uniform(-1, 1, (relation_dim, relation_dim, relation_dim)), 41 | # dtype=torch.float, device="cuda", requires_grad=True)) 42 | multiplier = 1 43 | self.getScores = self.TuckER 44 | elif self.model == 'RESCAL': 45 | self.getScores = self.RESCAL 46 | multiplier = 1 47 | else: 48 | print('Incorrect model specified:', self.model) 49 | exit(0) 50 | print('Model is', self.model) 51 | self.hidden_dim = hidden_dim 52 | self.relation_dim = relation_dim * multiplier 53 | if self.model == 'RESCAL': 54 | self.relation_dim = relation_dim * relation_dim 55 | self.word_embeddings = nn.Embedding(vocab_size, embedding_dim) 56 | self.n_layers = 1 57 | self.bidirectional = True 58 | 59 | self.num_entities = num_entities 60 | self.loss = torch.nn.BCELoss(reduction='sum') 61 | 62 | # best: all dropout 0 63 | self.rel_dropout = torch.nn.Dropout(reldrop) 64 | self.ent_dropout = torch.nn.Dropout(entdrop) 65 | self.score_dropout = torch.nn.Dropout(scoredrop) 66 | 67 | # The LSTM takes word embeddings as inputs, and outputs hidden states 68 | # with dimensionality hidden_dim. 69 | self.pretrained_embeddings = pretrained_embeddings 70 | print('Frozen:', self.freeze) 71 | self.embedding = nn.Embedding.from_pretrained(torch.FloatTensor(pretrained_embeddings), freeze=self.freeze) 72 | # self.embedding = nn.Embedding(self.num_entities, self.relation_dim) 73 | # xavier_normal_(self.embedding.weight.data) 74 | 75 | self.mid1 = 256 76 | self.mid2 = 256 77 | 78 | self.lin1 = nn.Linear(hidden_dim * 2, self.mid1, bias=False) 79 | self.lin2 = nn.Linear(self.mid1, self.mid2, bias=False) 80 | xavier_normal_(self.lin1.weight.data) 81 | xavier_normal_(self.lin2.weight.data) 82 | self.hidden2rel = nn.Linear(self.mid2, self.relation_dim) 83 | self.hidden2rel_base = nn.Linear(hidden_dim * 2, self.relation_dim) 84 | 85 | if self.model in ['DistMult', 'TuckER', 'RESCAL', 'SimplE']: 86 | self.bn0 = torch.nn.BatchNorm1d(self.embedding.weight.size(1)) 87 | self.bn2 = torch.nn.BatchNorm1d(self.embedding.weight.size(1)) 88 | else: 89 | self.bn0 = torch.nn.BatchNorm1d(multiplier) 90 | self.bn2 = torch.nn.BatchNorm1d(multiplier) 91 | 92 | for i in range(3): 93 | for key, value in self.bn_list[i].items(): 94 | self.bn_list[i][key] = torch.Tensor(value).to(device) 95 | 96 | 97 | self.bn0.weight.data = self.bn_list[0]['weight'] 98 | self.bn0.bias.data = self.bn_list[0]['bias'] 99 | self.bn0.running_mean.data = self.bn_list[0]['running_mean'] 100 | self.bn0.running_var.data = self.bn_list[0]['running_var'] 101 | 102 | self.bn2.weight.data = self.bn_list[2]['weight'] 103 | self.bn2.bias.data = self.bn_list[2]['bias'] 104 | self.bn2.running_mean.data = self.bn_list[2]['running_mean'] 105 | self.bn2.running_var.data = self.bn_list[2]['running_var'] 106 | 107 | self.logsoftmax = torch.nn.LogSoftmax(dim=-1) 108 | self.GRU = nn.LSTM(embedding_dim, self.hidden_dim, self.n_layers, bidirectional=self.bidirectional, batch_first=True) 109 | 110 | 111 | def applyNonLinear(self, outputs): 112 | outputs = self.lin1(outputs) 113 | outputs = F.relu(outputs) 114 | outputs = self.lin2(outputs) 115 | outputs = F.relu(outputs) 116 | outputs = self.hidden2rel(outputs) 117 | # outputs = self.hidden2rel_base(outputs) 118 | return outputs 119 | 120 | def TuckER(self, head, relation): 121 | head = self.bn0(head) 122 | head = self.ent_dropout(head) 123 | x = head.view(-1, 1, head.size(1)) 124 | 125 | W_mat = torch.mm(relation, self.W.view(relation.size(1), -1)) 126 | W_mat = W_mat.view(-1, head.size(1), head.size(1)) 127 | W_mat = self.rel_dropout(W_mat) 128 | x = torch.bmm(x, W_mat) 129 | x = x.view(-1, head.size(1)) 130 | x = self.bn2(x) 131 | x = self.score_dropout(x) 132 | 133 | x = torch.mm(x, self.embedding.weight.transpose(1,0)) 134 | pred = torch.sigmoid(x) 135 | return pred 136 | 137 | def RESCAL(self, head, relation): 138 | head = self.bn0(head) 139 | head = self.ent_dropout(head) 140 | ent_dim = head.size(1) 141 | head = head.view(-1, 1, ent_dim) 142 | relation = relation.view(-1, ent_dim, ent_dim) 143 | relation = self.rel_dropout(relation) 144 | x = torch.bmm(head, relation) 145 | x = x.view(-1, ent_dim) 146 | x = self.bn2(x) 147 | x = self.score_dropout(x) 148 | x = torch.mm(x, self.embedding.weight.transpose(1,0)) 149 | pred = torch.sigmoid(x) 150 | return pred 151 | 152 | def DistMult(self, head, relation): 153 | head = self.bn0(head) 154 | head = self.ent_dropout(head) 155 | relation = self.rel_dropout(relation) 156 | s = head * relation 157 | s = self.bn2(s) 158 | s = self.score_dropout(s) 159 | ans = torch.mm(s, self.embedding.weight.transpose(1,0)) 160 | pred = torch.sigmoid(ans) 161 | return pred 162 | 163 | def SimplE(self, head, relation): 164 | head = self.bn0(head) 165 | head = self.ent_dropout(head) 166 | relation = self.rel_dropout(relation) 167 | s = head * relation 168 | s_head, s_tail = torch.chunk(s, 2, dim=1) 169 | s = torch.cat([s_tail, s_head], dim=1) 170 | s = self.bn2(s) 171 | s = self.score_dropout(s) 172 | s = torch.mm(s, self.embedding.weight.transpose(1,0)) 173 | s = 0.5 * s 174 | pred = torch.sigmoid(s) 175 | return pred 176 | 177 | def ComplEx(self, head, relation): 178 | head = torch.stack(list(torch.chunk(head, 2, dim=1)), dim=1) 179 | head = self.bn0(head) 180 | head = self.ent_dropout(head) 181 | relation = self.rel_dropout(relation) 182 | head = head.permute(1, 0, 2) 183 | re_head = head[0] 184 | im_head = head[1] 185 | 186 | re_relation, im_relation = torch.chunk(relation, 2, dim=1) 187 | re_tail, im_tail = torch.chunk(self.embedding.weight, 2, dim =1) 188 | 189 | re_score = re_head * re_relation - im_head * im_relation 190 | im_score = re_head * im_relation + im_head * re_relation 191 | 192 | score = torch.stack([re_score, im_score], dim=1) 193 | score = self.bn2(score) 194 | score = self.score_dropout(score) 195 | score = score.permute(1, 0, 2) 196 | 197 | re_score = score[0] 198 | im_score = score[1] 199 | score = torch.mm(re_score, re_tail.transpose(1,0)) + torch.mm(im_score, im_tail.transpose(1,0)) 200 | pred = torch.sigmoid(score) 201 | return pred 202 | 203 | def Rotat3(self, head, relation): 204 | pi = 3.14159265358979323846 205 | relation = F.hardtanh(relation) * pi 206 | r = torch.stack(list(torch.chunk(relation, 3, dim=1)), dim=1) 207 | h = torch.stack(list(torch.chunk(head, 3, dim=1)), dim=1) 208 | h = self.bn0(h) 209 | h = self.ent_dropout(h) 210 | r = self.rel_dropout(r) 211 | 212 | r = r.permute(1, 0, 2) 213 | h = h.permute(1, 0, 2) 214 | 215 | x = h[0] 216 | y = h[1] 217 | z = h[2] 218 | 219 | # need to rotate h by r 220 | # r contains values in radians 221 | 222 | for i in range(len(r)): 223 | sin_r = torch.sin(r[i]) 224 | cos_r = torch.cos(r[i]) 225 | if i == 0: 226 | x_n = x.clone() 227 | y_n = y * cos_r - z * sin_r 228 | z_n = y * sin_r + z * cos_r 229 | elif i == 1: 230 | x_n = x * cos_r - y * sin_r 231 | y_n = x * sin_r + y * cos_r 232 | z_n = z.clone() 233 | elif i == 2: 234 | x_n = z * sin_r + x * cos_r 235 | y_n = y.clone() 236 | z_n = z * cos_r - x * sin_r 237 | 238 | x = x_n 239 | y = y_n 240 | z = z_n 241 | 242 | s = torch.stack([x, y, z], dim=1) 243 | s = self.bn2(s) 244 | s = self.score_dropout(s) 245 | s = s.permute(1, 0, 2) 246 | s = torch.cat([s[0], s[1], s[2]], dim = 1) 247 | ans = torch.mm(s, self.embedding.weight.transpose(1,0)) 248 | pred = torch.sigmoid(ans) 249 | return pred 250 | 251 | def forward(self, sentence, p_head, p_tail, question_len): 252 | embeds = self.word_embeddings(sentence) 253 | packed_output = pack_padded_sequence(embeds, question_len, batch_first=True) 254 | outputs, (hidden, cell_state) = self.GRU(packed_output) 255 | outputs, outputs_length = pad_packed_sequence(outputs, batch_first=True) 256 | outputs = torch.cat([hidden[0,:,:], hidden[1,:,:]], dim=-1) 257 | # outputs = self.drop1(outputs) 258 | # rel_embedding = self.hidden2rel(outputs) 259 | rel_embedding = self.applyNonLinear(outputs) 260 | p_head = self.embedding(p_head) 261 | pred = self.getScores(p_head, rel_embedding) 262 | actual = p_tail 263 | if self.label_smoothing: 264 | actual = ((1.0-self.label_smoothing)*actual) + (1.0/actual.size(1)) 265 | loss = self.loss(pred, actual) 266 | # reg = -0.001 267 | # best: reg is 1.0 268 | # self.l3_reg = 0.002 269 | # self.gamma1 = 1 270 | # self.gamma2 = 3 271 | if not self.freeze: 272 | if self.l3_reg: 273 | norm = torch.norm(self.embedding.weight, p=3, dim=-1) 274 | loss = loss + self.l3_reg * torch.sum(norm) 275 | return loss 276 | 277 | def get_relation_embedding(self, head, sentence, sent_len): 278 | embeds = self.word_embeddings(sentence.unsqueeze(0)) 279 | packed_output = pack_padded_sequence(embeds, sent_len, batch_first=True) 280 | outputs, (hidden, cell_state) = self.GRU(packed_output) 281 | outputs = torch.cat([hidden[0,:,:], hidden[1,:,:]], dim=-1) 282 | # rel_embedding = self.hidden2rel(outputs) 283 | rel_embedding = self.applyNonLinear(outputs) 284 | return rel_embedding 285 | 286 | def get_score_ranked(self, head, sentence, sent_len): 287 | embeds = self.word_embeddings(sentence.unsqueeze(0)) 288 | packed_output = pack_padded_sequence(embeds, sent_len, batch_first=True) 289 | outputs, (hidden, cell_state) = self.GRU(packed_output) 290 | outputs = torch.cat([hidden[0,:,:], hidden[1,:,:]], dim=-1) 291 | # rel_embedding = self.hidden2rel(outputs) 292 | rel_embedding = self.applyNonLinear(outputs) 293 | 294 | head = self.embedding(head).unsqueeze(0) 295 | scores = self.getScores(head, rel_embedding) 296 | 297 | # top2 = torch.topk(score, k=2, largest=True, sorted=True) 298 | # return top2 299 | 300 | return scores 301 | 302 | 303 | 304 | 305 | 306 | -------------------------------------------------------------------------------- /KGQA/RoBERTa/dataloader.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import random 3 | from torch.utils.data import Dataset, DataLoader 4 | from collections import defaultdict 5 | import os 6 | import unicodedata 7 | import re 8 | import time 9 | from collections import defaultdict 10 | from tqdm import tqdm 11 | import numpy as np 12 | from transformers import * 13 | from helpers import * 14 | 15 | class DatasetWebQSP(Dataset): 16 | def __init__(self, data, entities, entity2idx, transformer_name, kg_model): 17 | self.data = data 18 | self.entities = entities 19 | self.entity2idx = entity2idx 20 | self.pos_dict = defaultdict(list) 21 | self.neg_dict = defaultdict(list) 22 | self.index_array = list(self.entities.keys()) 23 | self.transformer_name = transformer_name 24 | self.pre_trained_model_name = get_pretrained_model_name(transformer_name) 25 | self.tokenizer = None 26 | self.set_tokenizer() 27 | self.max_length = 64 28 | self.kg_model = kg_model 29 | 30 | def set_tokenizer(self): 31 | if self.transformer_name == 'RoBERTa': 32 | self.tokenizer = RobertaTokenizer.from_pretrained(self.pre_trained_model_name) 33 | elif self.transformer_name == 'XLNet': 34 | self.tokenizer = XLNetTokenizer.from_pretrained(self.pre_trained_model_name) 35 | elif self.transformer_name == 'ALBERT': 36 | self.tokenizer = AlbertTokenizer.from_pretrained(self.pre_trained_model_name) 37 | elif self.transformer_name == 'SentenceTransformer': 38 | self.tokenizer = AutoTokenizer.from_pretrained(self.pre_trained_model_name) 39 | elif self.transformer_name == 'Longformer': 40 | self.tokenizer = LongformerTokenizer.from_pretrained(self.pre_trained_model_name) 41 | else: 42 | print('Incorrect transformer specified:', self.transformer_name) 43 | exit(0) 44 | 45 | def __len__(self): 46 | return len(self.data) 47 | 48 | def pad_sequence(self, arr, max_len=128): 49 | num_to_add = max_len - len(arr) 50 | for _ in range(num_to_add): 51 | arr.append('') 52 | return arr 53 | 54 | def toOneHot(self, indices): 55 | indices = torch.LongTensor(indices) 56 | batch_size = len(indices) 57 | vec_len = len(self.entity2idx) 58 | one_hot = torch.FloatTensor(vec_len) 59 | one_hot.zero_() 60 | # one_hot = -torch.ones(vec_len, dtype=torch.float32) 61 | one_hot.scatter_(0, indices, 1) 62 | return one_hot 63 | 64 | def __getitem__(self, index): 65 | data_point = self.data[index] 66 | question_text = data_point[1] 67 | question_tokenized, attention_mask = self.tokenize_question(question_text) 68 | head_id = self.entity2idx[data_point[0].strip()] 69 | tail_ids = [] 70 | for tail_name in data_point[2]: 71 | tail_name = tail_name.strip() 72 | #TODO: dunno if this is right way of doing things 73 | if tail_name in self.entity2idx: 74 | tail_ids.append(self.entity2idx[tail_name]) 75 | tail_onehot = self.toOneHot(tail_ids) 76 | return question_tokenized, attention_mask, head_id, tail_onehot 77 | 78 | def tokenize_question(self, question): 79 | if self.transformer_name != "SentenceTransformer": 80 | question = f"{question}" 81 | question_tokenized = self.tokenizer.tokenize(question) 82 | question_tokenized = self.pad_sequence(question_tokenized, self.max_length) 83 | 84 | question_tokenized = torch.tensor(self.tokenizer.encode( 85 | question_tokenized, # Question to encode 86 | add_special_tokens = False # Add '[CLS]' and '[SEP]', as per original paper 87 | )) 88 | 89 | attention_mask = [] 90 | for q in question_tokenized: 91 | # 1 means padding token 92 | if q == 1: 93 | attention_mask.append(0) 94 | else: 95 | attention_mask.append(1) 96 | 97 | return question_tokenized, torch.tensor(attention_mask, dtype=torch.long) 98 | else: 99 | 100 | encoded_que = self.tokenizer.encode_plus(question, padding='max_length', max_length=self.max_length, return_tensors='pt') 101 | return encoded_que['input_ids'][0], encoded_que['attention_mask'][0] 102 | 103 | # def _collate_fn(batch): 104 | # print(len(batch)) 105 | # exit(0) 106 | # question_tokenized = batch[0] 107 | # attention_mask = batch[1] 108 | # head_id = batch[2] 109 | # tail_onehot = batch[3] 110 | # question_tokenized = torch.stack(question_tokenized, dim=0) 111 | # attention_mask = torch.stack(attention_mask, dim=0) 112 | # return question_tokenized, attention_mask, head_id, tail_onehot 113 | 114 | class DataLoaderWebQSP(DataLoader): 115 | def __init__(self, *args, **kwargs): 116 | super(DataLoaderWebQSP, self).__init__(*args, **kwargs) 117 | # self.collate_fn = _collate_fn 118 | 119 | -------------------------------------------------------------------------------- /KGQA/RoBERTa/helpers.py: -------------------------------------------------------------------------------- 1 | # SentenceTransformer Mean Pooling - Take attention mask into account for correct averaging 2 | def mean_pooling(model_output, attention_mask): 3 | token_embeddings = model_output[0] #First element of model_output contains all token embeddings 4 | input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() 5 | sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) 6 | sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9) 7 | return sum_embeddings / sum_mask 8 | 9 | 10 | def get_pretrained_model_name(transformer_name): 11 | if transformer_name == 'RoBERTa': 12 | return 'roberta-base' 13 | elif transformer_name == 'XLNet': 14 | return 'xlnet-base-cased' 15 | elif transformer_name == 'ALBERT': 16 | return 'albert-base-v2' 17 | elif transformer_name == 'SentenceTransformer': 18 | return 'sentence-transformers/bert-base-nli-mean-tokens' 19 | elif transformer_name == 'Longformer': 20 | return 'allenai/longformer-base-4096' 21 | else: 22 | print('Incorrect pretrained model name specified:', transformer_name) 23 | exit(0) -------------------------------------------------------------------------------- /KGQA/RoBERTa/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import numpy as np 4 | from torch.utils.data import Dataset, DataLoader 5 | import torch.nn as nn 6 | import pickle 7 | from tqdm import tqdm 8 | import argparse 9 | import operator 10 | from torch.nn import functional as F 11 | from dataloader import DatasetWebQSP, DataLoaderWebQSP 12 | from model import RelationExtractor 13 | from torch.optim.lr_scheduler import ExponentialLR, ReduceLROnPlateau 14 | import networkx as nx 15 | import time 16 | import sys 17 | import pandas as pd 18 | sys.path.append("../..") # Adds higher directory to python modules path. 19 | from kge.model import KgeModel 20 | from kge.util.io import load_checkpoint 21 | from torch.nn.utils.rnn import pad_sequence 22 | 23 | def str2bool(v): 24 | if isinstance(v, bool): 25 | return v 26 | if v.lower() in ('no', 'false', 'f', 'n', '0'): 27 | return False 28 | else: 29 | return True 30 | 31 | parser = argparse.ArgumentParser() 32 | 33 | 34 | parser.add_argument('--hops', type=str, default='1') 35 | parser.add_argument('--load_from', type=str, default='') 36 | parser.add_argument('--ls', type=float, default=0.0) 37 | parser.add_argument('--validate_every', type=int, default=5) 38 | parser.add_argument('--model', type=str, default='ComplEx') 39 | parser.add_argument('--mode', type=str, default='eval') 40 | parser.add_argument('--outfile', type=str, default='best_score_model') 41 | parser.add_argument('--batch_size', type=int, default=1024) 42 | parser.add_argument('--dropout', type=float, default=0.1) 43 | parser.add_argument('--entdrop', type=float, default=0.0) 44 | parser.add_argument('--reldrop', type=float, default=0.0) 45 | parser.add_argument('--scoredrop', type=float, default=0.0) 46 | parser.add_argument('--l3_reg', type=float, default=0.0) 47 | parser.add_argument('--decay', type=float, default=1.0) 48 | parser.add_argument('--shuffle_data', type=bool, default=True) 49 | parser.add_argument('--num_workers', type=int, default=1) 50 | parser.add_argument('--lr', type=float, default=0.0001) 51 | parser.add_argument('--nb_epochs', type=int, default=90) 52 | parser.add_argument('--gpu', type=int, default=0) 53 | parser.add_argument('--neg_batch_size', type=int, default=128) 54 | parser.add_argument('--hidden_dim', type=int, default=200) 55 | parser.add_argument('--embedding_dim', type=int, default=256) 56 | parser.add_argument('--relation_dim', type=int, default=30) 57 | parser.add_argument('--use_cuda', type=bool, default=True) 58 | parser.add_argument('--patience', type=int, default=5) 59 | parser.add_argument('--freeze', type=str2bool, default=True) 60 | parser.add_argument('--do_batch_norm', type=str2bool, default=True) 61 | parser.add_argument('--que_embedding_model', type=str, default='RoBERTa') 62 | 63 | os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2,3,4,5,6,7" 64 | args = parser.parse_args() 65 | 66 | 67 | def prepare_embeddings(embedding_dict): 68 | entity2idx = {} 69 | idx2entity = {} 70 | i = 0 71 | embedding_matrix = [] 72 | for key, entity in embedding_dict.items(): 73 | entity2idx[key] = i 74 | idx2entity[i] = key 75 | i += 1 76 | embedding_matrix.append(entity) 77 | return entity2idx, idx2entity, embedding_matrix 78 | 79 | def get_vocab(data): 80 | word_to_ix = {} 81 | maxLength = 0 82 | idx2word = {} 83 | for d in data: 84 | sent = d[1] 85 | for word in sent.split(): 86 | if word not in word_to_ix: 87 | idx2word[len(word_to_ix)] = word 88 | word_to_ix[word] = len(word_to_ix) 89 | 90 | length = len(sent.split()) 91 | if length > maxLength: 92 | maxLength = length 93 | 94 | return word_to_ix, idx2word, maxLength 95 | 96 | def preprocess_entities_relations(entity_dict, relation_dict, entities, relations): 97 | e = {} 98 | r = {} 99 | f = open(entity_dict, 'r') 100 | for line in f: 101 | line = line[:-1].split('\t') 102 | ent_id = int(line[0]) 103 | ent_name = line[1] 104 | e[ent_name] = entities[ent_id] 105 | f.close() 106 | f = open(relation_dict,'r') 107 | for line in f: 108 | line = line.strip().split('\t') 109 | rel_id = int(line[0]) 110 | rel_name = line[1] 111 | r[rel_name] = relations[rel_id] 112 | f.close() 113 | return e,r 114 | 115 | def makeGraph(entity2idx): 116 | f = open('kb.txt', 'r') 117 | triples = [] 118 | for line in f: 119 | line = line.strip().split('|') 120 | triples.append(line) 121 | f.close() 122 | G = nx.Graph() 123 | for t in triples: 124 | e1 = entity2idx[t[0]] 125 | e2 = entity2idx[t[2]] 126 | G.add_node(e1) 127 | G.add_node(e2) 128 | G.add_edge(e1, e2) 129 | return G 130 | 131 | def getBest(scores, candidates): 132 | cand_scores_dict = {} 133 | highest = 0 134 | highest_key = '' 135 | for c in candidates: 136 | if scores[c] > highest: 137 | highest = scores[c] 138 | highest_key = c 139 | return highest_key 140 | 141 | 142 | def getNeighbourhood(graph, entity, radius=1): 143 | g = nx.ego_graph(graph, entity, radius, center=False) 144 | nodes = list(g.nodes) 145 | return nodes 146 | 147 | 148 | def getMask(candidates, entity2idx): 149 | max_len = len(entity2idx) 150 | x = np.ones(max_len) 151 | for c in candidates: 152 | if c not in entity2idx: 153 | c = c.strip() 154 | x[entity2idx[c]] = 0 155 | return x 156 | 157 | def inTopk(scores, ans, k): 158 | result = False 159 | topk = torch.topk(scores, k)[1] 160 | for x in topk: 161 | if x in ans: 162 | result = True 163 | return result 164 | 165 | def test(data_path, device, model, dataloader, entity2idx, model_name, return_hits_at_k): 166 | model.eval() 167 | data = process_text_file(data_path) 168 | idx2entity = {} 169 | for key, value in entity2idx.items(): 170 | idx2entity[value] = key 171 | answers = [] 172 | data_gen = data_generator(data=data, dataloader=dataloader, entity2idx=entity2idx) 173 | total_correct = 0 174 | error_count = 0 175 | num_incorrect = 0 176 | incorrect_rank_sum = 0 177 | not_in_top_50_count = 0 178 | 179 | # print('Loading nbhood file') 180 | # if 'webqsp' in data_path: 181 | # # with open('webqsp_test_candidate_list_only2hop.pickle', 'rb') as handle: 182 | # with open('webqsp_test_candidate_list_half.pickle', 'rb') as handle: 183 | # qa_nbhood_list = pickle.load(handle) 184 | # else: 185 | # with open('qa_dev_full_candidate_list.pickle', 'rb') as handle: 186 | # qa_nbhood_list = pickle.load(handle) 187 | 188 | scores_list = [] 189 | hit_at_1 = 0 190 | hit_at_5 = 0 191 | hit_at_10 = 0 192 | candidates_with_scores = [] 193 | writeCandidatesToFile = False 194 | for i in tqdm(range(len(data))): 195 | # try: 196 | d = next(data_gen) 197 | head = d[0].to(device) 198 | question_tokenized = d[1].to(device) 199 | attention_mask = d[2].to(device) 200 | ans = d[3] 201 | tail_test = torch.tensor(ans, dtype=torch.long).to(device) 202 | scores = model.get_score_ranked(head=head, question_tokenized=question_tokenized, attention_mask=attention_mask)[0] 203 | # candidates = qa_nbhood_list[i] 204 | # mask = torch.from_numpy(getMask(candidates, entity2idx)).to(device) 205 | # following 2 lines for no neighbourhood check 206 | mask = torch.zeros(len(entity2idx)).to(device) 207 | mask[head] = 1 208 | #reduce scores of all non-candidates 209 | new_scores = scores - (mask*99999) 210 | pred_ans = torch.argmax(new_scores).item() 211 | # new_scores = new_scores.cpu().detach().numpy() 212 | # scores_list.append(new_scores) 213 | if pred_ans == head.item(): 214 | print('Head and answer same') 215 | print(torch.max(new_scores)) 216 | print(torch.min(new_scores)) 217 | # pred_ans = getBest(scores, candidates) 218 | # if ans[0] not in candidates: 219 | # print('Answer not in candidates') 220 | # print(len(candidates)) 221 | # exit(0) 222 | 223 | if writeCandidatesToFile: 224 | entry = {} 225 | entry['question'] = d[-1] 226 | head_text = idx2entity[head.item()] 227 | entry['head'] = head_text 228 | s, c = torch.topk(new_scores, 200) 229 | s = s.cpu().detach().numpy() 230 | c = c.cpu().detach().numpy() 231 | cands = [] 232 | for cand in c: 233 | cands.append(idx2entity[cand]) 234 | entry['scores'] = s 235 | entry['candidates'] = cands 236 | correct_ans = [] 237 | for a in ans: 238 | correct_ans.append(idx2entity[a]) 239 | entry['answers'] = correct_ans 240 | candidates_with_scores.append(entry) 241 | 242 | 243 | if inTopk(new_scores, ans, 1): 244 | hit_at_1 += 1 245 | if inTopk(new_scores, ans, 5): 246 | hit_at_5 += 1 247 | if inTopk(new_scores, ans, 10): 248 | hit_at_10 += 1 249 | 250 | if type(ans) is int: 251 | ans = [ans] 252 | is_correct = 0 253 | if pred_ans in ans: 254 | total_correct += 1 255 | is_correct = 1 256 | else: 257 | num_incorrect += 1 258 | q_text = d[-1] 259 | answers.append(q_text + '\t' + str(pred_ans) + '\t' + str(is_correct)) 260 | # except: 261 | # error_count += 1 262 | 263 | if writeCandidatesToFile: 264 | # pickle.dump(candidates_with_scores, open('candidates_with_score_and_qe_half.pkl', 'wb')) 265 | pickle.dump(candidates_with_scores, open('webqsp_scores_finetune.pkl', 'wb')) 266 | print('wrote candidate file (for future answer processing)') 267 | # np.save("scores_webqsp_complex.npy", scores_list) 268 | # exit(0) 269 | # print(hit_at_10/len(data)) 270 | accuracy = total_correct/len(data) 271 | # print('Error mean rank: %f' % (incorrect_rank_sum/num_incorrect)) 272 | # print('%d out of %d incorrect were not in top 50' % (not_in_top_50_count, num_incorrect)) 273 | 274 | if return_hits_at_k: 275 | return answers, accuracy, (hit_at_1/len(data)), (hit_at_5/len(data)), (hit_at_10/len(data)) 276 | else: 277 | return answers, accuracy 278 | 279 | def writeToFile(lines, fname): 280 | f = open(fname, 'w') 281 | for line in lines: 282 | f.write(line + '\n') 283 | f.close() 284 | print('Wrote to ', fname) 285 | return 286 | 287 | def set_bn_eval(m): 288 | classname = m.__class__.__name__ 289 | if classname.find('BatchNorm1d') != -1: 290 | m.eval() 291 | 292 | def getEntityEmbeddings(model_name, kge_model, hops): 293 | e = {} 294 | model_dir = f"../../pretrained_models/embeddings/{model_name}" 295 | entity_dict = f"{model_dir}_fbwq_full/entity_ids.del" 296 | 297 | if 'half' in hops: 298 | entity_dict = f"{model_dir}_fbwq_half/entity_ids.del" 299 | print('Loading half entity_ids.del') 300 | embedder = kge_model._entity_embedder 301 | f = open(entity_dict, 'r') 302 | for line in f: 303 | line = line[:-1].split('\t') 304 | ent_id = int(line[0]) 305 | ent_name = line[1] 306 | e[ent_name] = embedder._embeddings(torch.LongTensor([ent_id]))[0] 307 | f.close() 308 | return e 309 | 310 | def get_chkpt_path(model_name, que_embedding_model, outfile): 311 | return f"../../checkpoints/WebQSP/{model_name}_{que_embedding_model}_{outfile}/best_score_model.pt" 312 | 313 | def custom_collate_fn(batch): 314 | print(len(batch)) 315 | print(batch) 316 | for i,a in enumerate(batch): 317 | for x in a: 318 | print(f"{i}: {x}: {batch}") 319 | question_tokenized = batch[0] 320 | attention_mask = batch[1] 321 | head_id = batch[2] 322 | tail_onehot = batch[3] 323 | question_tokenized = torch.stack(question_tokenized, dim=0) 324 | attention_mask = torch.stack(attention_mask, dim=0) 325 | return question_tokenized, attention_mask, head_id, tail_onehot 326 | 327 | def perform_experiment(data_path, mode, neg_batch_size, batch_size, shuffle, num_workers, nb_epochs, embedding_dim, hidden_dim, relation_dim, gpu, use_cuda,patience, freeze, validate_every, hops, lr, entdrop, reldrop, scoredrop, l3_reg, model_name, decay, ls, load_from, outfile, do_batch_norm, que_embedding_model, valid_data_path=None, test_data_path=None): 328 | webqsp_checkpoint_folder = f"../../checkpoints/WebQSP/{model_name}_{que_embedding_model}_{outfile}/" 329 | if not os.path.exists(webqsp_checkpoint_folder): 330 | os.makedirs(webqsp_checkpoint_folder) 331 | 332 | print('Loading entities and relations') 333 | kg_type = 'full' 334 | if 'half' in hops: 335 | kg_type = 'half' 336 | 337 | checkpoint_file = f"../../pretrained_models/embeddings/{model_name}_fbwq_{kg_type}/checkpoint_best.pt" 338 | 339 | print('Loading kg embeddings from', checkpoint_file) 340 | kge_checkpoint = load_checkpoint(checkpoint_file) 341 | kge_model = KgeModel.create_from(kge_checkpoint) 342 | kge_model.eval() 343 | e = getEntityEmbeddings(model_name, kge_model, hops) 344 | 345 | print('Loaded entities and relations') 346 | 347 | entity2idx, idx2entity, embedding_matrix = prepare_embeddings(e) 348 | 349 | # word2ix,idx2word, max_len = get_vocab(data) 350 | # hops = str(num_hops) 351 | device = torch.device(gpu if use_cuda else "cpu") 352 | model = RelationExtractor(embedding_dim=embedding_dim, num_entities = len(idx2entity), relation_dim=relation_dim, pretrained_embeddings=embedding_matrix, freeze=freeze, device=device, entdrop = entdrop, reldrop = reldrop, scoredrop = scoredrop, l3_reg = l3_reg, model = model_name, que_embedding_model=que_embedding_model, ls = ls, do_batch_norm=do_batch_norm) 353 | 354 | # time.sleep(10) 355 | if mode=='train': 356 | data = process_text_file(data_path) 357 | dataset = DatasetWebQSP(data, e, entity2idx, que_embedding_model, model_name) 358 | 359 | # if model_name=="ComplEx": 360 | # data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers) 361 | # else: 362 | # data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, collate_fn=custom_collate_fn) 363 | 364 | data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers) 365 | 366 | if load_from != '': 367 | # model.load_state_dict(torch.load("checkpoints/roberta_finetune/" + load_from + ".pt")) 368 | fname = f"checkpoints/{que_embedding_model}_finetune/{load_from}.pt" 369 | model.load_state_dict(torch.load(fname, map_location=lambda storage, loc: storage)) 370 | model.to(device) 371 | optimizer = torch.optim.Adam(model.parameters(), lr=lr) 372 | scheduler = ExponentialLR(optimizer, decay) 373 | optimizer.zero_grad() 374 | best_score = -float("inf") 375 | best_model = model.state_dict() 376 | no_update = 0 377 | for epoch in range(nb_epochs): 378 | phases = [] 379 | for i in range(validate_every): 380 | phases.append('train') 381 | phases.append('valid') 382 | for phase in phases: 383 | if phase == 'train': 384 | model.train() 385 | # model.apply(set_bn_eval) 386 | loader = tqdm(data_loader, total=len(data_loader), unit="batches") 387 | running_loss = 0 388 | for i_batch, a in enumerate(loader): 389 | model.zero_grad() 390 | question_tokenized = a[0].to(device) 391 | attention_mask = a[1].to(device) 392 | positive_head = a[2].to(device) 393 | positive_tail = a[3].to(device) 394 | loss = model(question_tokenized=question_tokenized, attention_mask=attention_mask, p_head=positive_head, p_tail=positive_tail) 395 | loss.backward() 396 | optimizer.step() 397 | running_loss += loss.item() 398 | loader.set_postfix(Loss=running_loss/((i_batch+1)*batch_size), Epoch=epoch) 399 | loader.set_description('{}/{}'.format(epoch, nb_epochs)) 400 | loader.update() 401 | 402 | scheduler.step() 403 | 404 | elif phase=='valid': 405 | model.eval() 406 | eps = 0.0001 407 | answers, score = test(model=model, data_path= valid_data_path, entity2idx=entity2idx, dataloader=dataset, device=device, model_name=model_name, return_hits_at_k=False) 408 | if score > best_score + eps: 409 | best_score = score 410 | no_update = 0 411 | best_model = model.state_dict() 412 | print(hops + " hop Validation accuracy (no relation scoring) increased from previous epoch", score) 413 | writeToFile(answers, f'results/{model_name}_{que_embedding_model}_{outfile}.txt') 414 | torch.save(best_model, get_chkpt_path(model_name, que_embedding_model, outfile)) 415 | elif (score < best_score + eps) and (no_update < patience): 416 | no_update +=1 417 | print("Validation accuracy decreases to %f from %f, %d more epoch to check"%(score, best_score, patience-no_update)) 418 | elif no_update == patience: 419 | print("Model has exceed patience. Saving best model and exiting") 420 | torch.save(best_model, get_chkpt_path(model_name, que_embedding_model, outfile)) 421 | exit(0) 422 | if epoch == nb_epochs-1: 423 | print("Final Epoch has reached. Stoping and saving model.") 424 | torch.save(best_model, get_chkpt_path(model_name, que_embedding_model, outfile)) 425 | exit() 426 | # torch.save(model.state_dict(), "checkpoints/roberta_finetune/"+str(epoch)+".pt") 427 | # torch.save(model.state_dict(), "checkpoints/roberta_finetune/x.pt") 428 | 429 | elif mode=='test': 430 | data = process_text_file(test_data_path) 431 | dataset = DatasetWebQSP(data, e, entity2idx, que_embedding_model, model_name) 432 | model_chkpt_file_path = get_chkpt_path(model_name, que_embedding_model, outfile) 433 | model.load_state_dict(torch.load(model_chkpt_file_path, map_location=lambda storage, loc: storage)) 434 | model.to(device) 435 | for parameter in model.parameters(): 436 | parameter.requires_grad = False 437 | model.eval() 438 | answers, accuracy, hits_at_1, hits_at_5, hits_at_10 = test(model=model, data_path= test_data_path, entity2idx=entity2idx, dataloader=dataset, device=device, model_name=model_name, return_hits_at_k=True) 439 | 440 | d = { 441 | 'KG-Model': model_name, 442 | 'KG-Type': kg_type, 443 | 'Que-Embedding-Model': que_embedding_model, 444 | 'Accuracy': [accuracy], 445 | 'Hits@1': [hits_at_1], 446 | 'Hits@5': [hits_at_5], 447 | 'Hits@10': [hits_at_10] 448 | } 449 | df = pd.DataFrame(data=d) 450 | df.to_csv(f"final_results.csv", mode='a', index=False, header=False) 451 | 452 | 453 | def process_text_file(text_file, split=False): 454 | data_file = open(text_file, 'r') 455 | data_array = [] 456 | for data_line in data_file.readlines(): 457 | data_line = data_line.strip() 458 | if data_line == '': 459 | continue 460 | data_line = data_line.strip().split('\t') 461 | # if no answer 462 | if len(data_line) != 2: 463 | continue 464 | question = data_line[0].split('[') 465 | question_1 = question[0] 466 | question_2 = question[1].split(']') 467 | head = question_2[0].strip() 468 | question_2 = question_2[1] 469 | question = question_1+'NE'+question_2 470 | ans = data_line[1].split('|') 471 | data_array.append([head, question.strip(), ans]) 472 | if split==False: 473 | return data_array 474 | else: 475 | data = [] 476 | for line in data_array: 477 | head = line[0] 478 | question = line[1] 479 | tails = line[2] 480 | for tail in tails: 481 | data.append([head, question, tail]) 482 | return data 483 | 484 | def data_generator(data, dataloader, entity2idx): 485 | for i in range(len(data)): 486 | data_sample = data[i] 487 | head = entity2idx[data_sample[0].strip()] 488 | question = data_sample[1] 489 | question_tokenized, attention_mask = dataloader.tokenize_question(question) 490 | if type(data_sample[2]) is str: 491 | ans = entity2idx[data_sample[2]] 492 | else: 493 | #TODO: not sure if this is the right way 494 | ans = [] 495 | for entity in list(data_sample[2]): 496 | if entity.strip() in entity2idx: 497 | ans.append(entity2idx[entity.strip()]) 498 | # ans = [entity2idx[entity.strip()] for entity in list(data_sample[2])] 499 | 500 | yield torch.tensor(head, dtype=torch.long), question_tokenized, attention_mask, ans, data_sample[1] 501 | 502 | 503 | 504 | 505 | hops = args.hops 506 | 507 | model_name = args.model 508 | 509 | if 'webqsp' in hops: 510 | data_path = '../../data/QA_data/WebQuestionsSP/qa_train_webqsp.txt' 511 | valid_data_path = '../../data/QA_data/WebQuestionsSP/qa_test_webqsp.txt' 512 | test_data_path = '../../data/QA_data/WebQuestionsSP/qa_test_webqsp.txt' 513 | 514 | 515 | 516 | perform_experiment( 517 | data_path=data_path, 518 | mode=args.mode, 519 | neg_batch_size=args.neg_batch_size, 520 | batch_size=args.batch_size, 521 | shuffle=args.shuffle_data, 522 | num_workers=args.num_workers, 523 | nb_epochs=args.nb_epochs, 524 | embedding_dim=args.embedding_dim, 525 | hidden_dim=args.hidden_dim, 526 | relation_dim=args.relation_dim, 527 | gpu=args.gpu, 528 | use_cuda=args.use_cuda, 529 | valid_data_path=valid_data_path, 530 | test_data_path=test_data_path, 531 | patience=args.patience, 532 | validate_every=args.validate_every, 533 | freeze=args.freeze, 534 | hops=args.hops, 535 | lr=args.lr, 536 | entdrop=args.entdrop, 537 | reldrop=args.reldrop, 538 | scoredrop = args.scoredrop, 539 | l3_reg = args.l3_reg, 540 | model_name=args.model, 541 | decay=args.decay, 542 | ls=args.ls, 543 | load_from=args.load_from, 544 | outfile=args.outfile, 545 | do_batch_norm=args.do_batch_norm, 546 | que_embedding_model=args.que_embedding_model 547 | ) 548 | -------------------------------------------------------------------------------- /KGQA/RoBERTa/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.utils 4 | import torch.nn.functional as F 5 | from torch.autograd import Variable 6 | import torch.nn.functional as F 7 | import numpy as np 8 | from torch.nn.init import xavier_normal_ 9 | from transformers import * 10 | import random 11 | from helpers import * 12 | 13 | class RelationExtractor(nn.Module): 14 | 15 | def __init__(self, embedding_dim, relation_dim, num_entities, pretrained_embeddings, device, entdrop, reldrop, scoredrop, l3_reg, model, que_embedding_model, ls, do_batch_norm, freeze=True): 16 | super(RelationExtractor, self).__init__() 17 | self.device = device 18 | self.model = model 19 | self.freeze = freeze 20 | self.label_smoothing = ls 21 | self.l3_reg = l3_reg 22 | self.do_batch_norm = do_batch_norm 23 | if not self.do_batch_norm: 24 | print('Not doing batch norm') 25 | self.pre_trained_model_name = get_pretrained_model_name(que_embedding_model) 26 | if que_embedding_model == 'RoBERTa': 27 | self.que_embedding_model = RobertaModel.from_pretrained(self.pre_trained_model_name) 28 | elif que_embedding_model == 'XLNet': 29 | self.que_embedding_model = XLNetModel.from_pretrained(self.pre_trained_model_name) 30 | elif que_embedding_model == 'ALBERT': 31 | self.que_embedding_model = AlbertModel.from_pretrained(self.pre_trained_model_name) 32 | elif que_embedding_model == 'SentenceTransformer': 33 | self.que_embedding_model = AutoModel.from_pretrained(self.pre_trained_model_name) 34 | elif que_embedding_model == 'Longformer': 35 | self.que_embedding_model = LongformerModel.from_pretrained(self.pre_trained_model_name) 36 | else: 37 | print('Incorrect question embeddding model specified:', que_embedding_model) 38 | exit(0) 39 | 40 | for param in self.que_embedding_model.parameters(): 41 | param.requires_grad = True 42 | if self.model == 'DistMult': 43 | multiplier = 1 44 | self.getScores = self.DistMult 45 | elif self.model == 'SimplE': 46 | multiplier = 2 47 | self.getScores = self.SimplE 48 | elif self.model == 'ComplEx': 49 | multiplier = 2 50 | self.getScores = self.ComplEx 51 | elif self.model == 'TuckER': 52 | # W_torch = torch.from_numpy(np.load(w_matrix)) 53 | # self.W = nn.Parameter( 54 | # torch.Tensor(W_torch), 55 | # requires_grad = not self.freeze 56 | # ) 57 | self.W = nn.Parameter(torch.tensor(np.random.uniform(-1, 1, (relation_dim, relation_dim, relation_dim)), 58 | dtype=torch.float, device="cuda", requires_grad=True)) 59 | multiplier = 1 60 | self.getScores = self.TuckER 61 | elif self.model == 'RESCAL': 62 | self.getScores = self.RESCAL 63 | multiplier = 1 64 | else: 65 | print('Incorrect model specified:', self.model) 66 | exit(0) 67 | print('Model is', self.model) 68 | self.hidden_dim = 768 69 | self.relation_dim = relation_dim * multiplier 70 | if self.model == 'RESCAL': 71 | self.relation_dim = relation_dim * relation_dim 72 | 73 | self.num_entities = num_entities 74 | # self.loss = torch.nn.BCELoss(reduction='sum') 75 | self.loss = self.kge_loss 76 | 77 | # best: all dropout 0 78 | self.rel_dropout = torch.nn.Dropout(reldrop) 79 | self.ent_dropout = torch.nn.Dropout(entdrop) 80 | self.score_dropout = torch.nn.Dropout(scoredrop) 81 | self.fcnn_dropout = torch.nn.Dropout(0.1) 82 | 83 | # self.pretrained_embeddings = pretrained_embeddings 84 | # random.shuffle(pretrained_embeddings) 85 | # print(pretrained_embeddings[0]) 86 | print('Frozen:', self.freeze) 87 | self.embedding = nn.Embedding.from_pretrained(torch.stack(pretrained_embeddings, dim=0), freeze=self.freeze) 88 | # self.embedding = nn.Embedding.from_pretrained(torch.FloatTensor(pretrained_embeddings), freeze=self.freeze) 89 | print(self.embedding.weight.shape) 90 | # self.embedding = nn.Embedding(self.num_entities, self.relation_dim) 91 | # self.embedding.weight.requires_grad = False 92 | # xavier_normal_(self.embedding.weight.data) 93 | 94 | self.mid1 = 512 95 | self.mid2 = 512 96 | self.mid3 = 512 97 | self.mid4 = 512 98 | 99 | # self.lin1 = nn.Linear(self.hidden_dim, self.mid1) 100 | # self.lin2 = nn.Linear(self.mid1, self.mid2) 101 | # self.lin3 = nn.Linear(self.mid2, self.mid3) 102 | # self.lin4 = nn.Linear(self.mid3, self.mid4) 103 | # self.hidden2rel = nn.Linear(self.mid4, self.relation_dim) 104 | self.hidden2rel = nn.Linear(self.hidden_dim, self.relation_dim) 105 | self.hidden2rel_base = nn.Linear(self.mid2, self.relation_dim) 106 | 107 | if self.model in ['DistMult', 'TuckER', 'RESCAL', 'SimplE']: 108 | self.bn0 = torch.nn.BatchNorm1d(self.embedding.weight.size(1)) 109 | self.bn2 = torch.nn.BatchNorm1d(self.embedding.weight.size(1)) 110 | else: 111 | self.bn0 = torch.nn.BatchNorm1d(multiplier) 112 | self.bn2 = torch.nn.BatchNorm1d(multiplier) 113 | 114 | 115 | 116 | self.logsoftmax = torch.nn.LogSoftmax(dim=-1) 117 | self._klloss = torch.nn.KLDivLoss(reduction='sum') 118 | 119 | def set_bn_eval(self): 120 | self.bn0.eval() 121 | self.bn2.eval() 122 | 123 | def kge_loss(self, scores, targets): 124 | # loss = torch.mean(scores*targets) 125 | return self._klloss( 126 | F.log_softmax(scores, dim=1), F.normalize(targets.float(), p=1, dim=1) 127 | ) 128 | 129 | def applyNonLinear(self, outputs): 130 | # outputs = self.fcnn_dropout(self.lin1(outputs)) 131 | # outputs = F.relu(outputs) 132 | # outputs = self.fcnn_dropout(self.lin2(outputs)) 133 | # outputs = F.relu(outputs) 134 | # outputs = self.lin3(outputs) 135 | # outputs = F.relu(outputs) 136 | # outputs = self.lin4(outputs) 137 | # outputs = F.relu(outputs) 138 | outputs = self.hidden2rel(outputs) 139 | # outputs = self.hidden2rel_base(outputs) 140 | return outputs 141 | 142 | def TuckER(self, head, relation): 143 | head = self.bn0(head) 144 | head = self.ent_dropout(head) 145 | x = head.view(-1, 1, head.size(1)) 146 | 147 | W_mat = torch.mm(relation, self.W.view(relation.size(1), -1)) 148 | W_mat = W_mat.view(-1, head.size(1), head.size(1)) 149 | W_mat = self.rel_dropout(W_mat) 150 | x = torch.bmm(x, W_mat) 151 | x = x.view(-1, head.size(1)) 152 | x = self.bn2(x) 153 | x = self.score_dropout(x) 154 | 155 | x = torch.mm(x, self.embedding.weight.transpose(1,0)) 156 | pred = torch.sigmoid(x) 157 | return pred 158 | 159 | def RESCAL(self, head, relation): 160 | head = self.bn0(head) 161 | head = self.ent_dropout(head) 162 | ent_dim = head.size(1) 163 | head = head.view(-1, 1, ent_dim) 164 | relation = relation.view(-1, ent_dim, ent_dim) 165 | relation = self.rel_dropout(relation) 166 | x = torch.bmm(head, relation) 167 | x = x.view(-1, ent_dim) 168 | x = self.bn2(x) 169 | x = self.score_dropout(x) 170 | x = torch.mm(x, self.embedding.weight.transpose(1,0)) 171 | pred = torch.sigmoid(x) 172 | return pred 173 | 174 | def DistMult(self, head, relation): 175 | head = self.bn0(head) 176 | head = self.ent_dropout(head) 177 | relation = self.rel_dropout(relation) 178 | s = head * relation 179 | s = self.bn2(s) 180 | s = self.score_dropout(s) 181 | ans = torch.mm(s, self.embedding.weight.transpose(1,0)) 182 | pred = torch.sigmoid(ans) 183 | return pred 184 | 185 | def SimplE(self, head, relation): 186 | head = self.bn0(head) 187 | head = self.ent_dropout(head) 188 | relation = self.rel_dropout(relation) 189 | s = head * relation 190 | s_head, s_tail = torch.chunk(s, 2, dim=1) 191 | s = torch.cat([s_tail, s_head], dim=1) 192 | s = self.bn2(s) 193 | s = self.score_dropout(s) 194 | s = torch.mm(s, self.embedding.weight.transpose(1,0)) 195 | s = 0.5 * s 196 | pred = torch.sigmoid(s) 197 | return pred 198 | 199 | 200 | 201 | def ComplEx(self, head, relation): 202 | head = torch.stack(list(torch.chunk(head, 2, dim=1)), dim=1) 203 | if self.do_batch_norm: 204 | head = self.bn0(head) 205 | 206 | head = self.ent_dropout(head) 207 | relation = self.rel_dropout(relation) 208 | head = head.permute(1, 0, 2) 209 | re_head = head[0] 210 | im_head = head[1] 211 | 212 | re_relation, im_relation = torch.chunk(relation, 2, dim=1) 213 | re_tail, im_tail = torch.chunk(self.embedding.weight, 2, dim =1) 214 | 215 | re_score = re_head * re_relation - im_head * im_relation 216 | im_score = re_head * im_relation + im_head * re_relation 217 | 218 | score = torch.stack([re_score, im_score], dim=1) 219 | if self.do_batch_norm: 220 | score = self.bn2(score) 221 | 222 | score = self.score_dropout(score) 223 | score = score.permute(1, 0, 2) 224 | 225 | re_score = score[0] 226 | im_score = score[1] 227 | score = torch.mm(re_score, re_tail.transpose(1,0)) + torch.mm(im_score, im_tail.transpose(1,0)) 228 | # pred = torch.sigmoid(score) 229 | pred = score 230 | return pred 231 | 232 | 233 | 234 | def getQuestionEmbedding(self, question_tokenized, attention_mask): 235 | if self.que_embedding_model == "SentenceTransformer": 236 | with torch.no_grad(): 237 | model_output = self.que_embedding_model(question_tokenized, attention_mask) 238 | # model_output = model(**encoded_input) 239 | 240 | question_embedding = mean_pooling(model_output, attention_mask) 241 | return question_embedding[0] 242 | else: 243 | last_hidden_states = self.que_embedding_model( 244 | question_tokenized, 245 | attention_mask=attention_mask).last_hidden_state 246 | states = last_hidden_states.transpose(1,0) 247 | cls_embedding = states[0] 248 | question_embedding = cls_embedding 249 | question_embedding = torch.mean(last_hidden_states, dim=1) 250 | return question_embedding 251 | 252 | def forward(self, question_tokenized, attention_mask, p_head, p_tail): 253 | question_embedding = self.getQuestionEmbedding(question_tokenized, attention_mask) 254 | rel_embedding = self.applyNonLinear(question_embedding) 255 | p_head = self.embedding(p_head) 256 | 257 | pred = self.getScores(p_head, rel_embedding) 258 | actual = p_tail 259 | if self.label_smoothing: 260 | actual = ((1.0-self.label_smoothing)*actual) + (1.0/actual.size(1)) 261 | loss = self.loss(pred, actual) 262 | if not self.freeze: 263 | if self.l3_reg: 264 | norm = torch.norm(self.embedding.weight, p=3, dim=-1) 265 | loss = loss + self.l3_reg * torch.sum(norm) 266 | return loss 267 | 268 | 269 | def get_score_ranked(self, head, question_tokenized, attention_mask): 270 | question_embedding = self.getQuestionEmbedding(question_tokenized.unsqueeze(0), attention_mask.unsqueeze(0)) 271 | rel_embedding = self.applyNonLinear(question_embedding) 272 | head = self.embedding(head).unsqueeze(0) 273 | scores = self.getScores(head, rel_embedding) 274 | # top2 = torch.topk(scores, k=2, largest=True, sorted=True) 275 | # return top2 276 | return scores 277 | 278 | 279 | 280 | 281 | 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![SWH](https://archive.softwareheritage.org/badge/origin/https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA/)](https://archive.softwareheritage.org/browse/origin/?origin_url=https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA) [![SWH](https://archive.softwareheritage.org/badge/swh:1:dir:c95bc4fec7023c258c7190975279b5baf6ef6725/)](https://archive.softwareheritage.org/swh:1:dir:c95bc4fec7023c258c7190975279b5baf6ef6725;origin=https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA;visit=swh:1:snp:d08d258bc04ace7627e00bf0f3b12c499297e84d;anchor=swh:1:rev:9af249590ec26d122bd82eb2dc10a0c3545e7c1c) 2 | 3 | # EmbedKGQA: Reproduction and Extended Study 4 | - This is the code for the [MLRC2020 challenge](https://paperswithcode.com/rc2020) w.r.t. the [ACL 2020](https://acl2020.org/) paper [Improving Multi-hop Question Answering over Knowledge Graphs using Knowledge Base Embeddings](https://malllabiisc.github.io/publications/papers/final_embedkgqa.pdf)[1] 5 | - The code is build upon [1]:[5d8fdbd4](https://github.com/malllabiisc/EmbedKGQA/tree/5d8fdbd4be77fdcb2e67a0dc8a7115844606175a) 6 | - Minor modifications have been made to [5d8fdbd4](https://github.com/malllabiisc/EmbedKGQA/tree/5d8fdbd4be77fdcb2e67a0dc8a7115844606175a) in order to perform the ablation study. In case of any query relating to the original code[1], please contact [Apoorv](https://apoorvumang.github.io/). 7 | # Additional Experiments 8 | - Knowledge Graph Embedding model 9 | - [TuckER](https://arxiv.org/abs/1901.09590) 10 | - Tested on {MetaQA_full, MetaQA_half} datasets 11 | - Question embedding models 12 | - [ALBERT](https://arxiv.org/abs/1909.11942) 13 | - [XLNet](https://arxiv.org/abs/1906.08237) 14 | - [Longformer](https://arxiv.org/abs/2004.05150) 15 | - [SentenceBERT](https://arxiv.org/abs/1908.10084) (SentenceTransformer) 16 | - Tested on {fbwq_full, fbwq_half} datasets 17 | 18 | # Requirements 19 | - Python >= 3.7.5, pip 20 | - zip, unzip 21 | - Docker (Recommended) 22 | - Pytorch version [1.3.0a0+24ae9b5](https://github.com/pytorch/pytorch/tree/24ae9b504094937fbc7c24012fbe5c601e024bcd). For more info, visit [here](https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel_19-10.html). 23 | 24 | # Helpful pointers 25 | - Docker Image: [Cuda-Python[2]](https://hub.docker.com/r/qts8n/cuda-python/) can be used. Use the `runtime` tag. 26 | - ```bash 27 | docker run -itd --rm --runtime=nvidia -v /raid/kgdnn/:/raid/kgdnn/ --name embedkgqa__4567 -e NVIDIA_VISIBLE_DEVICES=4,5,6,7 -p 7777:7777 qts8n/cuda-python:runtime 28 | ``` 29 | - Alternatively, Docker Image: [Embed_KGQA[3]](https://hub.docker.com/r/jishnup/embed_kgqa) can be used as well. It's build upon [2] and contains all the packages for conducting the experiments. 30 | - Use `env` tag for image without models. 31 | - Use `env-models` tag for image with models. 32 | - ```bash 33 | docker run -itd --rm --runtime=nvidia -v /raid/kgdnn/:/raid/kgdnn/ --name embedkgqa__4567 -e NVIDIA_VISIBLE_DEVICES=4,5,6,7 -p 7777:7777 jishnup/embed_kgqa:env 34 | ``` 35 | - All the required packages and models (from the extended study with better performance) are readily available in [3]. 36 | - Model location within the docker container: `/raid/mlrc2020models/` 37 | - `/raid/mlrc2020models/embeddings/` contain the KG embedding models. 38 | - `/raid/mlrc2020models/qa_models/` contain the QA models. 39 | - The experiments have been done using [2]. The requirements.txt packages' version have been set accordingly. This may vary w.r.t. [1]. 40 | - `KGQA/LSTM` and `KGQA/RoBERTa` directory nomenclature hasn't been changed to avoid unnecessary confusion w.r.t. the original codebase[1]. 41 | 42 | - `fbwq_full` and `fbwq_full_new` are the same but independent existence is required because 43 | - Pretrained `ComplEx` model uses `fbwq_full_new` as the dataset name 44 | - Trained `SimplE` model uses `fbwq_full` as the dataset name 45 | - No `fbwq_full_new` dataset was found in the data shared by the author[1], so went ahead with this setting. 46 | 47 | - Also, pretrained qa_models were absent in the data shared. The reproduction results are based on training scheme used by us. 48 | 49 | - For training QA datasets, use ```batch_size >= 2```. 50 | 51 | # Get started 52 | ```bash 53 | # Clone the repo 54 | git clone https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA && cd "$_" 55 | 56 | # Set a new env variable called EMBED_KGQA_DIR with MLRC2020-EmbedKGQA/ directory's absolute path as value 57 | # If using bash shell, run 58 | echo 'export EMBED_KGQA_DIR=`pwd`' >> ~/.bash_profile && source ~/.bash_profile 59 | 60 | # Change script permissions 61 | chmod -R 700 scripts/ 62 | 63 | # Initial setup 64 | ./scripts/initial_setup.sh 65 | 66 | # Download and unzip, data and pretrained_models from the original EmbedKGQA paper 67 | ./scripts/download_artifacts.sh 68 | 69 | # Install LibKGE 70 | ./scripts/install_libkge.sh 71 | ``` 72 | 73 | # Train KG Embeddings 74 | - [Steps](https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA/tree/main/train_embeddings#steps-to-train-knowledge-graph-embedding-models) to train KG embeddings. 75 | 76 | # Train QA Datasets 77 | Hyperparameters in the following commands are set w.r.t. [[1]](https://github.com/malllabiisc/EmbedKGQA#metaqa). 78 | ### MetaQA 79 | ```bash 80 | # Method: 1 81 | cd $EMBED_KGQA_DIR/KGQA/LSTM; 82 | python main.py --mode train \ 83 | --nb_epochs 100 \ 84 | --relation_dim 200 \ 85 | --hidden_dim 256 \ 86 | --gpu 0 \ #GPU-ID 87 | --freeze 0 \ 88 | --batch_size 64 \ 89 | --validate_every 4 \ 90 | --hops <1/2/3> \ #n-hops 91 | --lr 0.0005 \ 92 | --entdrop 0.1 \ 93 | --reldrop 0.2 \ 94 | --scoredrop 0.2 \ 95 | --decay 1.0 \ 96 | --model \ #KGE models 97 | --patience 10 \ 98 | --ls 0.0 \ 99 | --use_cuda True \ #Enable CUDA 100 | --kg_type 101 | 102 | 103 | # Method: 2 104 | # Modify the hyperparameters in the script file w.r.t. your usecase 105 | $EMBED_KGQA_DIR/scripts/train_metaQA.sh \ 106 | \ 107 | \ 108 | <1/2/3> \ 109 | \ 110 | \ 111 | 112 | ``` 113 | 114 | ### WebQuestionsSP 115 | ```bash 116 | # Method: 1 117 | cd $EMBED_KGQA_DIR/KGQA/RoBERTa; 118 | python main.py --mode train \ 119 | --relation_dim 200 \ 120 | --que_embedding_model RoBERTa \ 121 | --do_batch_norm 0 \ 122 | --gpu 0 \ 123 | --freeze 1 \ 124 | --batch_size 16 \ 125 | --validate_every 10 \ 126 | --hops webqsp_half \ 127 | --lr 0.00002 \ 128 | --entdrop 0.0 129 | --reldrop 0.0 \ 130 | --scoredrop 0.0 \ 131 | --decay 1.0 \ 132 | --model ComplEx \ 133 | --patience 20 \ 134 | --ls 0.0 \ 135 | --l3_reg 0.001 \ 136 | --nb_epochs 200 \ 137 | --outfile delete 138 | 139 | # Method: 2 140 | # Modify the hyperparameters in the script file w.r.t. your usecase 141 | $EMBED_KGQA_DIR/scripts/train_webqsp.sh \ 142 | \ 143 | \ 144 | \ 145 | \ 146 | \ 147 | 148 | ``` 149 | 150 | # Test QA Datasets 151 | Set the mode parameter as `test` (keep the other hyperparameters same as used in training) 152 | 153 | # Helpful links 154 | - [Details](https://github.com/malllabiisc/EmbedKGQA#instructions) about data and pretrained weights. 155 | - [Details](https://github.com/malllabiisc/EmbedKGQA#dataset-creation) about dataset creation. 156 | - [Presentation](https://slideslive.com/38929421/improving-multihop-question-answering-over-knowledge-graphs-using-knowledge-base-embeddings) for [1] by [Apoorv](https://apoorvumang.github.io/). 157 | 158 | 159 | ### Citation: 160 | Please cite the following if you incorporate our work. 161 | 162 | ```bibtex 163 | @article{P:2021, 164 | author = {P, Jishnu Jaykumar and Sardana, Ashish}, 165 | title = {{[Re] Improving Multi-hop Question Answering over Knowledge Graphs using Knowledge Base Embeddings}}, 166 | journal = {ReScience C}, 167 | year = {2021}, 168 | month = may, 169 | volume = {7}, 170 | number = {2}, 171 | pages = {{#15}}, 172 | doi = {10.5281/zenodo.4834942}, 173 | url = {https://zenodo.org/record/4834942/files/article.pdf}, 174 | code_url = {https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA}, 175 | code_doi = {}, 176 | code_swh = {swh:1:dir:c95bc4fec7023c258c7190975279b5baf6ef6725}, 177 | data_url = {}, 178 | data_doi = {}, 179 | review_url = {https://openreview.net/forum?id=VFAwCMdWY7}, 180 | type = {Replication}, 181 | language = {Python}, 182 | domain = {ML Reproducibility Challenge 2020}, 183 | keywords = {knowledge graph, embeddings, multi-hop, question-answering, deep learning} 184 | } 185 | ``` 186 | 187 | Following 3 options are available for any clarification, comments or suggestions 188 | - Join the [discussion forum](https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA/discussions/). 189 | - Create an [issue](https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA/issues). 190 | - Contact [Jishnu](https://jishnujayakumar.github.io/) or [Ashish](mailto:asardana@nvidia.com). 191 | -------------------------------------------------------------------------------- /config/simple-train-webqsp-full.yaml: -------------------------------------------------------------------------------- 1 | job.type: train 2 | job.device: 'cuda' 3 | dataset.name: fbwq_full 4 | model: simple 5 | 6 | train: 7 | max_epochs: 100 8 | num_workers: 20 9 | 10 | optimizer.default: 11 | type: Adagrad 12 | args: 13 | lr: 0.1 14 | weight_decay: 0.4e-7 15 | batch_size: 512 16 | subbatch_auto_tune: True 17 | 18 | valid: 19 | every: 1 20 | metric: mean_reciprocal_rank_filtered 21 | -------------------------------------------------------------------------------- /config/simple-train-webqsp-half.yaml: -------------------------------------------------------------------------------- 1 | job.type: train 2 | job.device: 'cuda' 3 | dataset.name: fbwq_half 4 | model: simple 5 | 6 | train: 7 | max_epochs: 100 8 | num_workers: 20 9 | 10 | optimizer.default: 11 | type: Adagrad 12 | args: 13 | lr: 0.1 14 | weight_decay: 0.4e-7 15 | batch_size: 512 16 | subbatch_auto_tune: True 17 | 18 | valid: 19 | every: 1 20 | metric: mean_reciprocal_rank_filtered -------------------------------------------------------------------------------- /model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishnujayakumar/MLRC2020-EmbedKGQA/606edf6f9e1c2a19e15010bd9f8c69c4a35d9b04/model.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | networkx==2.5 2 | tqdm==4.55.1 3 | gdown==3.12.2 4 | prettytable==2.0.0 5 | transformers==4.1.1 6 | sentencepiece==0.1.94 7 | torch==1.7.1 -------------------------------------------------------------------------------- /scripts/download_artifacts.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Google frive folder: https://drive.google.com/drive/folders/1RlqGBMo45lTmWz9MUPTq-0KcjSd3ujxc 4 | # gdown requires anyone with the link id; right click on each file and get it 5 | gdown --id 1uWaavrpKKllVSQ73TTuLWPc4aqVvrkpx && unzip data.zip 6 | gdown --id 1Ly_3RR1CsYDafdvdfTG35NPIG-FLH-tz && unzip pretrained_models.zip -------------------------------------------------------------------------------- /scripts/initial_setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Install required packages 4 | pip install -r requirements.txt 5 | 6 | # Create required directories 7 | mkdir -p $EMBED_KGQA_DIR/checkpoints/ $EMBED_KGQA_DIR/KGQA/RoBERTa/results/ 8 | 9 | echo "Initial setup complete." -------------------------------------------------------------------------------- /scripts/install_libkge.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Retrieve and install LibKGE in development mode 4 | cd train_embeddings/ 5 | git clone https://github.com/uma-pi1/kge.git && cd kge 6 | pip install -e . 7 | 8 | cp $EMBED_KGQA_DIR/scripts/preprocess_webqsp_dataset.sh data 9 | cp -R $EMBED_KGQA_DIR/data/fbwq_* data 10 | 11 | # To train WebQSP dataset using pretrained ComplEx kge model, fbwq_full_new is required 12 | cp -R data/fbwq_full/ data/fbwq_full_new/ 13 | 14 | echo "LibKGE setup complete." 15 | -------------------------------------------------------------------------------- /scripts/preprocess_webqsp_dataset.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | BASEDIR=`$EMBED_KGQA_DIR/data` 4 | 5 | for webqsp_dataset in {'fbwq_half', 'fbwq_full'} 6 | do 7 | if [ ! -d "$BASEDIR/$webqsp_dataset" ]; then 8 | echo "\"$webqsp_dataset\" dataset not found. Kindly download it by following steps mentioned in getting-started section [README]." 9 | else 10 | echo "\"$webqsp_dataset\" is present." 11 | 12 | if [ ! -f "$BASEDIR/$webqsp_dataset/dataset.yaml" ]; then 13 | python preprocess/preprocess_default.py data/$webqsp_dataset/ 14 | else 15 | echo "\"$webqsp_dataset\" already prepared." 16 | fi 17 | done -------------------------------------------------------------------------------- /scripts/train_metaQA.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | kg_embedding_model=$1 4 | kg_type=$2 5 | n_hops=$3 6 | batch_size=$4 7 | gpu_id=$5 8 | relation_dim=$6 9 | 10 | cd $EMBED_KGQA_DIR/KGQA/LSTM; 11 | python main.py --mode train 12 | --nb_epochs 100 13 | --relation_dim $relation_dim 14 | --hidden_dim 256 15 | --gpu $gpu_id #GPU-ID 16 | --freeze 0 17 | --batch_size $batch_size 18 | --validate_every 4 19 | --hops $n_hops #n-hops 20 | --lr 0.0005 21 | --entdrop 0.1 22 | --reldrop 0.2 23 | --scoredrop 0.2 24 | --decay 1.0 25 | --model $kg_embedding_model #KGE models 26 | --patience 10 27 | --ls 0.0 28 | --use_cuda True #Enable CUDA 29 | --kg_type $kg_type 30 | 31 | 32 | #Usage: $EMBED_KGQA_DIR/scripts/train_metaQA.sh <1/2/3> -------------------------------------------------------------------------------- /scripts/train_webqsp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | kg_embedding_model=$1 4 | que_embedding_model=$2 5 | kg_type=$3 6 | batch_size=$4 7 | gpu_id=$5 8 | relation_dim=$6 9 | cd $EMBED_KGQA_DIR/$que_embedding_model 10 | python main.py --mode train --relation_dim $relation_dim --que_embedding_model $que_embedding_model --do_batch_norm 0 \ 11 | --gpu $gpu_id --freeze 1 --batch_size $batch_size --validate_every 1 --hops webqsp_$kg_type --lr 0.00002 --entdrop 0.0 --reldrop 0.0 --scoredrop 0.0 \ 12 | --decay 1.0 --model $kg_embedding_model --patience 10 --ls 0.0 --l3_reg 0.001 --nb_epochs 200 --outfile webqsp_$kg_type_$que_embedding_model 13 | 14 | # Usage: $EMBED_KGQA_DIR/scripts/train_webqsp.sh -------------------------------------------------------------------------------- /train_embeddings/README.md: -------------------------------------------------------------------------------- 1 | # Steps to train Knowledge Graph Embedding Models 2 | 3 | ### **NOTE:** 4 | - First, make sure to complete all the steps mentioned in [getting-started](https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA#get-started) section. 5 | - Make sure to be in **MLRC2020-EmbedKGQA/train_embeddings** directory. 6 | - ```bash 7 | cd $EMBED_KGQA_DIR/train_embeddings/ 8 | ``` 9 | - Please tune the hyperparameters according to your need. If needed, add more parameters from [here](https://github.com/jishnujayakumar/MLRC2020-EmbedKGQA/blob/main/train_embeddings/main.py). 10 | - Tests have been performed on the following models(``) 11 | - ComplEx: Pretrained-model has been taken from [EmbedKGQA](https://github.com/malllabiisc/EmbedKGQA#metaqa)[1]. 12 | - TuckER: Training has been performed for `MetaQA` KG dataset. 13 | - SimplE: Training has been performed for `WebQSP` KG dataset. 14 | - (Tested due to non-availability of Vanilla TuckER model in `LibKGE`: [2b693e3](https://github.com/uma-pi1/kge/tree/2b693e31c4c06c71336f1c553727419fe01d4aa6)). 15 | - Results are not good based on the default LibKGE settings. Hence, not included in the summary report. Feel free to change the parameters in the config and test it out yourself. 16 | 17 | - Other supported types include: 18 | - DistMult 19 | - RESCAL 20 | 21 | ### Train MetaQA KG 22 | 23 | ```bash 24 | python main.py --model TuckER \ 25 | --cuda True \ # CUDA enabled 26 | --outfile \ 27 | --valid_steps 1 \ 28 | --dataset \ #for kg_type:{half, full} use dataset:{MetaQA_half, MetaQA} 29 | --num_iterations 5 \ 30 | --batch_size 256 \ 31 | --l3_reg .00001 32 | ``` 33 | - **Output path**: `$EMBED_KGQA_DIR/kg_embeddings/MetaQA/....` 34 | 35 | - After training the respective MetaQA KG dataset, place the output to predefined path to train the QA dataset 36 | - ```bash 37 | # For MetaQA_half dataset 38 | # dataset-name-1=MetaQA_half, dataset-name-2=MetaQA_half 39 | 40 | # For MetaQA dataset 41 | # dataset-name-1=MetaQA_full, dataset-name-2=MetaQA 42 | 43 | # Predefined path to store the necessary KGE training output files 44 | # to be used for training QA dataset 45 | destination_path="EMBED_KGQA_DIR/pretrained_models/embeddings/_/" 46 | 47 | # Make the required directory 48 | mkdir -p $destination_path 49 | 50 | # Copy to predefined location 51 | cp -R $EMBED_KGQA_DIR/kg_embeddings///* $destination_path 52 | ``` 53 | ### Train WebQSP KG 54 | 55 | ```bash 56 | #for kg_type:{half, full} use config_suffix:{half, full} 57 | kge start $EMBED_KGQA_DIR/config/simple-train-webqsp-.yaml \ 58 | --job.device cuda: 59 | ``` 60 | - **Output path**: `$EMBED_KGQA_DIR/train_embeddings/kge/local/experiments/....` 61 | 62 | - After training the respective WebQSP KG dataset, place the output to predefined path to train the QA dataset 63 | - ```bash 64 | # NOTE: For dataset-name:{fbwq_half, fbwq_full}, kg-type:{half, full} 65 | 66 | # Predefined path to store the necessary KGE training output files 67 | # to be used for training QA dataset 68 | destination_path="$EMBED_KGQA_DIR/pretrained_models/embeddings/_/" 69 | 70 | # Make the required directory 71 | mkdir -p $destination_path 72 | 73 | # Find the best checkpoint and copy to predefined path for training QA dataset 74 | 75 | # NOTE: Don't remove '*' prior to 76 | 77 | find \ 78 | $EMBED_KGQA_DIR/train_embeddings/kge/local/experiments/** \ 79 | -type f -name 'checkpoint_best.pt' -print0 | xargs -0 -r cp -t $destination_path 80 | 81 | # Copy entity_ids.del to predefined path for training QA dataset 82 | cp $EMBED_KGQA_DIR/data//entity_ids.del $destination_path 83 | ``` 84 | 85 | - This scheme is used as suggested by [1]'s author. View [here](https://github.com/malllabiisc/EmbedKGQA#webquestionssp). 86 | - Feel free to try out different parameters mentioned in config/*.yaml as per your need. 87 | - See [LibKGE](https://github.com/uma-pi1/kge) for more details regarding the `kge` tool. 88 | 89 | -------------------------------------------------------------------------------- /train_embeddings/load_data.py: -------------------------------------------------------------------------------- 1 | class Data: 2 | 3 | def __init__(self, data_dir="data/FB15k-237/", reverse=False): 4 | self.train_data = self.load_data(data_dir, "train", reverse=reverse) 5 | self.valid_data = self.load_data(data_dir, "valid", reverse=reverse) 6 | self.test_data = self.load_data(data_dir, "test", reverse=reverse) 7 | self.data = self.train_data + self.valid_data + self.test_data 8 | self.entities = self.get_entities(self.data) 9 | self.train_relations = self.get_relations(self.train_data) 10 | self.valid_relations = self.get_relations(self.valid_data) 11 | self.test_relations = self.get_relations(self.test_data) 12 | self.relations = self.train_relations + [i for i in self.valid_relations \ 13 | if i not in self.train_relations] + [i for i in self.test_relations \ 14 | if i not in self.train_relations] 15 | 16 | def load_data(self, data_dir, data_type="train", reverse=False): 17 | with open("%s%s.txt" % (data_dir, data_type), "r") as f: 18 | data = f.read().strip().split("\n") 19 | data = [i.split('\t') for i in data] 20 | if reverse: 21 | data += [[i[2], i[1]+"_reverse", i[0]] for i in data] 22 | return data 23 | 24 | def get_relations(self, data): 25 | relations = sorted(list(set([d[1] for d in data]))) 26 | return relations 27 | 28 | def get_entities(self, data): 29 | entities = sorted(list(set([d[0] for d in data]+[d[2] for d in data]))) 30 | return entities 31 | -------------------------------------------------------------------------------- /train_embeddings/main.py: -------------------------------------------------------------------------------- 1 | from load_data import Data 2 | import numpy as np 3 | import torch 4 | import time 5 | from collections import defaultdict 6 | from model import * 7 | from torch.optim.lr_scheduler import ExponentialLR 8 | import argparse 9 | from tqdm import tqdm 10 | import os 11 | from prettytable import PrettyTable 12 | 13 | 14 | class Experiment: 15 | 16 | def __init__(self, learning_rate=0.0005, ent_vec_dim=200, rel_vec_dim=200, 17 | num_iterations=500, batch_size=128, decay_rate=0., cuda=False, 18 | input_dropout=0.3, hidden_dropout1=0.4, hidden_dropout2=0.5, 19 | label_smoothing=0., outfile='tucker.model', valid_steps=1, loss_type='BCE', do_batch_norm=1, 20 | dataset='', model='Rotat3', l3_reg = 0.0, load_from = ''): 21 | self.dataset = dataset 22 | self.learning_rate = learning_rate 23 | self.ent_vec_dim = ent_vec_dim 24 | self.rel_vec_dim = rel_vec_dim 25 | self.num_iterations = num_iterations 26 | self.batch_size = batch_size 27 | self.decay_rate = decay_rate 28 | self.label_smoothing = label_smoothing 29 | self.cuda = cuda 30 | self.outfile = outfile 31 | self.valid_steps = valid_steps 32 | self.model = model 33 | self.l3_reg = l3_reg 34 | self.loss_type = loss_type 35 | self.load_from = load_from 36 | if do_batch_norm == 1: 37 | do_batch_norm = True 38 | else: 39 | do_batch_norm = False 40 | self.kwargs = {"input_dropout": input_dropout, "hidden_dropout1": hidden_dropout1, 41 | "hidden_dropout2": hidden_dropout2, "model": model, "loss_type": loss_type, 42 | "do_batch_norm": do_batch_norm, "l3_reg": l3_reg} 43 | 44 | def get_data_idxs(self, data): 45 | 46 | ''' 47 | Returns triples in their idx form, 48 | e.g.: (head_entity,relation,tail_entity) gets converted to (1,1,2) 49 | ''' 50 | 51 | data_idxs = [(self.entity_idxs[data[i][0]], self.relation_idxs[data[i][1]], \ 52 | self.entity_idxs[data[i][2]]) for i in range(len(data))] 53 | return data_idxs 54 | 55 | def get_er_vocab(self, data): 56 | 57 | """ 58 | data =[[1,2,3],[1,2,3], [1,4,3]] 59 | der_vocab : efaultdict(, {(1, 2): [3, 3, 3], (1, 4): [3]}) 60 | 61 | returns er_vocab: (h,r):[t] 62 | """ 63 | 64 | er_vocab = defaultdict(list) 65 | for triple in data: 66 | er_vocab[(triple[0], triple[1])].append(triple[2]) 67 | return er_vocab 68 | 69 | 70 | def get_batch(self, er_vocab, er_vocab_pairs, idx): 71 | 72 | ''' 73 | Returns 74 | 1. batch: er_vocab_pairs(size:batch_size) 75 | 2. targets: batch_size*num_entities tensor with target label for each er_vocab pair 76 | ''' 77 | 78 | batch = er_vocab_pairs[idx:idx+self.batch_size] 79 | targets = torch.zeros([len(batch), len(d.entities)], dtype=torch.float32) 80 | if self.cuda: 81 | targets = targets.cuda() 82 | for idx, pair in enumerate(batch): 83 | targets[idx, er_vocab[pair]] = 1. 84 | return np.array(batch), targets 85 | 86 | def evaluate(self, model, data): 87 | model.eval() 88 | hits = [] 89 | ranks = [] 90 | for i in range(10): 91 | hits.append([]) 92 | 93 | test_data_idxs = self.get_data_idxs(data) 94 | er_vocab = self.get_er_vocab(self.get_data_idxs(d.data)) 95 | 96 | print("Number of data points: %d" % len(test_data_idxs)) 97 | for i in tqdm(range(0, len(test_data_idxs), self.batch_size)): 98 | data_batch, _ = self.get_batch(er_vocab, test_data_idxs, i) 99 | e1_idx = torch.tensor(data_batch[:,0]) 100 | r_idx = torch.tensor(data_batch[:,1]) 101 | e2_idx = torch.tensor(data_batch[:,2]) 102 | if self.cuda: 103 | e1_idx = e1_idx.cuda() 104 | r_idx = r_idx.cuda() 105 | e2_idx = e2_idx.cuda() 106 | predictions = model.forward(e1_idx, r_idx) 107 | 108 | # following lines commented means RAW evaluation (not filtered) 109 | for j in range(data_batch.shape[0]): 110 | filt = er_vocab[(data_batch[j][0], data_batch[j][1])] 111 | target_value = predictions[j,e2_idx[j]].item() 112 | predictions[j, filt] = 0.0 113 | predictions[j, e2_idx[j]] = target_value 114 | 115 | sort_values, sort_idxs = torch.sort(predictions, dim=1, descending=True) 116 | sort_idxs = sort_idxs.cpu().numpy() 117 | for j in range(data_batch.shape[0]): 118 | rank = np.where(sort_idxs[j]==e2_idx[j].item())[0][0] 119 | ranks.append(rank+1) 120 | 121 | for hits_level in range(10): 122 | if rank <= hits_level: 123 | hits[hits_level].append(1.0) 124 | else: 125 | hits[hits_level].append(0.0) 126 | 127 | hitat10 = np.mean(hits[9]) 128 | hitat3 = np.mean(hits[2]) 129 | hitat1 = np.mean(hits[0]) 130 | meanrank = np.mean(ranks) 131 | mrr = np.mean(1./np.array(ranks)) 132 | 133 | pretty_tbl = PrettyTable() 134 | pretty_tbl.field_names = ["Metric", "Result"] 135 | pretty_tbl.add_row(['Hits@10', hitat10]) 136 | pretty_tbl.add_row(['Hits@3', hitat3]) 137 | pretty_tbl.add_row(['Hits@1', hitat1]) 138 | pretty_tbl.add_row(['MeanRank', meanrank]) 139 | pretty_tbl.add_row(['MeanReciprocalRank', mrr]) 140 | print(pretty_tbl) 141 | 142 | return [mrr, meanrank, hitat10, hitat3, hitat1] 143 | 144 | def write_embedding_files(self, model): 145 | model.eval() 146 | model_folder = f"../kg_embeddings/{self.model}/{self.dataset}" 147 | data_folder = "../data/%s/" % self.dataset 148 | embedding_type = self.model 149 | if(not os.path.exists(model_folder)): 150 | os.makedirs(model_folder) 151 | R_numpy = model.R.weight.data.cpu().numpy() 152 | E_numpy = model.E.weight.data.cpu().numpy() 153 | bn_list = [] 154 | for bn in [model.bn0, model.bn1, model.bn2]: 155 | bn_weight = bn.weight.data.cpu().numpy() 156 | bn_bias = bn.bias.data.cpu().numpy() 157 | bn_running_mean = bn.running_mean.data.cpu().numpy() 158 | bn_running_var = bn.running_var.data.cpu().numpy() 159 | bn_numpy = {} 160 | bn_numpy['weight'] = bn_weight 161 | bn_numpy['bias'] = bn_bias 162 | bn_numpy['running_mean'] = bn_running_mean 163 | bn_numpy['running_var'] = bn_running_var 164 | bn_list.append(bn_numpy) 165 | 166 | if embedding_type == 'TuckER': 167 | W_numpy = model.W.detach().cpu().numpy() 168 | 169 | np.save(model_folder +'/E.npy', E_numpy) 170 | np.save(model_folder +'/R.npy', R_numpy) 171 | for i, bn in enumerate(bn_list): 172 | np.save(model_folder + '/bn' + str(i) + '.npy', bn) 173 | 174 | if embedding_type == 'TuckER': 175 | np.save(model_folder +'/W.npy', W_numpy) 176 | 177 | f = open(data_folder + '/entities.dict', 'r') 178 | f2 = open(model_folder + '/entities.dict', 'w') 179 | ents = {} 180 | idx2ent = {} 181 | for line in f: 182 | line = line.rstrip().split('\t') 183 | name = line[0] 184 | id = int(line[1]) 185 | ents[name] = id 186 | idx2ent[id] = name 187 | f2.write(str(id) + '\t' + name + '\n') 188 | f.close() 189 | f2.close() 190 | f = open(data_folder + '/relations.dict', 'r') 191 | f2 = open(model_folder + '/relations.dict', 'w') 192 | rels = {} 193 | idx2rel = {} 194 | for line in f: 195 | line = line.strip().split('\t') 196 | name = line[0] 197 | id = int(line[1]) 198 | rels[name] = id 199 | idx2rel[id] = name 200 | f2.write(str(id) + '\t' + name + '\n') 201 | f.close() 202 | f2.close() 203 | 204 | 205 | def train_and_eval(self, d): 206 | torch.set_num_threads(2) 207 | best_valid = [0, 0, 0, 0, 0] 208 | best_test = [0, 0, 0, 0, 0] 209 | self.entity_idxs = {d.entities[i]:i for i in range(len(d.entities))} 210 | self.relation_idxs = {d.relations[i]:i for i in range(len(d.relations))} 211 | f = open('../data/' + self.dataset +'/entities.dict', 'w') 212 | for key, value in self.entity_idxs.items(): 213 | f.write(key + '\t' + str(value) +'\n') 214 | f.close() 215 | f = open('../data/' + self.dataset + '/relations.dict', 'w') 216 | for key, value in self.relation_idxs.items(): 217 | f.write(key + '\t' + str(value) +'\n') 218 | f.close() 219 | train_data_idxs = self.get_data_idxs(d.train_data) 220 | 221 | pretty_tbl = PrettyTable() 222 | pretty_tbl.field_names = ["ARTIFACT", "SAMPLES"] 223 | pretty_tbl.add_row(['#TrainingSamples', len(train_data_idxs)]) 224 | pretty_tbl.add_row(['#Entities', len(self.entity_idxs)]) 225 | pretty_tbl.add_row(['#Relations', len(self.relation_idxs)]) 226 | print(pretty_tbl) 227 | 228 | model = KGE(d, self.ent_vec_dim, self.rel_vec_dim, **self.kwargs) 229 | model.init() 230 | if self.load_from != '': 231 | fname = self.load_from 232 | checkpoint = torch.load(fname) 233 | model.load_state_dict(checkpoint) 234 | if self.cuda: 235 | model.cuda() 236 | opt = torch.optim.Adam(model.parameters(), lr=self.learning_rate) 237 | if self.decay_rate: 238 | scheduler = ExponentialLR(opt, self.decay_rate) 239 | 240 | er_vocab = self.get_er_vocab(train_data_idxs) 241 | er_vocab_pairs = list(er_vocab.keys()) #list(er_vocab.keys()) 242 | 243 | print("Starting training...") 244 | 245 | for it in range(1, self.num_iterations+1): 246 | print(f"Iteration: {it}/{self.num_iterations}") 247 | start_train = time.time() 248 | model.train() 249 | losses = [] 250 | np.random.shuffle(er_vocab_pairs) 251 | for j in tqdm(range(0, len(er_vocab_pairs), self.batch_size)): 252 | data_batch, targets = self.get_batch(er_vocab, er_vocab_pairs, j) 253 | opt.zero_grad() 254 | e1_idx = torch.tensor(data_batch[:,0]) 255 | r_idx = torch.tensor(data_batch[:,1]) 256 | if self.cuda: 257 | e1_idx = e1_idx.cuda() 258 | r_idx = r_idx.cuda() 259 | predictions = model.forward(e1_idx, r_idx) 260 | if self.label_smoothing: 261 | targets = ((1.0-self.label_smoothing)*targets) + (1.0/targets.size(1)) 262 | loss = model.loss(predictions, targets) 263 | loss.backward() 264 | opt.step() 265 | losses.append(loss.item()) 266 | if self.decay_rate: 267 | scheduler.step() 268 | if it%100 == 0: 269 | print('Epoch', it, ' Epoch time', time.time()-start_train, ' Loss:', np.mean(losses)) 270 | model.eval() 271 | 272 | with torch.no_grad(): 273 | if it % self.valid_steps == 0: 274 | start_test = time.time() 275 | print("Validation:") 276 | valid = self.evaluate(model, d.valid_data) 277 | print("Test:") 278 | test = self.evaluate(model, d.test_data) 279 | valid_mrr = valid[0] 280 | test_mrr = test[0] 281 | if valid_mrr >= best_valid[0]: 282 | best_valid = valid 283 | best_test = test 284 | print('Validation MRR increased.') 285 | print('Saving model...') 286 | self.write_embedding_files(model) 287 | print('Model saved!') 288 | 289 | pretty_tbl = PrettyTable() 290 | pretty_tbl.field_names = ["ARTIFACT", "VALUE"] 291 | pretty_tbl.add_row(['Best valid', best_valid]) 292 | pretty_tbl.add_row(['Best test', best_test]) 293 | pretty_tbl.add_row(['Dataset', self.dataset]) 294 | pretty_tbl.add_row(['Model', self.model]) 295 | print(pretty_tbl) 296 | 297 | print(f'Training-time: {round(time.time()-start_test,2)}') 298 | 299 | pretty_tbl = PrettyTable() 300 | pretty_tbl.field_names = ["Parameter", "Value"] 301 | pretty_tbl.add_row(['Learning rate', self.learning_rate]) 302 | pretty_tbl.add_row(['Decay', self.decay_rate]) 303 | pretty_tbl.add_row(['Dim', self.ent_vec_dim]) 304 | pretty_tbl.add_row(['Input drop', self.kwargs["input_dropout"]]) 305 | pretty_tbl.add_row(['Hidden drop 2', self.kwargs["hidden_dropout2"]]) 306 | pretty_tbl.add_row(['Label Smoothing', self.label_smoothing]) 307 | pretty_tbl.add_row(['Batch size', self.batch_size]) 308 | pretty_tbl.add_row(['Loss type', self.loss_type]) 309 | pretty_tbl.add_row(['L3 reg', self.l3_reg]) 310 | print(pretty_tbl) 311 | 312 | if __name__ == '__main__': 313 | parser = argparse.ArgumentParser() 314 | parser.add_argument("--dataset", type=str, default="FB15k-237", nargs="?", 315 | help="Which dataset to use: FB15k, FB15k-237, WN18 or WN18RR.") 316 | parser.add_argument("--num_iterations", type=int, default=500, nargs="?", 317 | help="Number of iterations.") 318 | parser.add_argument("--batch_size", type=int, default=128, nargs="?", 319 | help="Batch size.") 320 | parser.add_argument("--lr", type=float, default=0.0005, nargs="?", 321 | help="Learning rate.") 322 | parser.add_argument("--model", type=str, default='Rotat3', nargs="?", 323 | help="Model.") 324 | parser.add_argument("--dr", type=float, default=1.0, nargs="?", 325 | help="Decay rate.") 326 | parser.add_argument("--edim", type=int, default=200, nargs="?", 327 | help="Entity embedding dimensionality.") 328 | parser.add_argument("--rdim", type=int, default=200, nargs="?", 329 | help="Relation embedding dimensionality.") 330 | parser.add_argument("--cuda", type=bool, default=True, nargs="?", 331 | help="Whether to use cuda (GPU) or not (CPU).") 332 | parser.add_argument("--input_dropout", type=float, default=0.3, nargs="?", 333 | help="Input layer dropout.") 334 | parser.add_argument("--hidden_dropout1", type=float, default=0.4, nargs="?", 335 | help="Dropout after the first hidden layer.") 336 | parser.add_argument("--hidden_dropout2", type=float, default=0.5, nargs="?", 337 | help="Dropout after the second hidden layer.") 338 | parser.add_argument("--label_smoothing", type=float, default=0.1, nargs="?", 339 | help="Amount of label smoothing.") 340 | parser.add_argument("--outfile", type=str, default='tucker.model', nargs="?", 341 | help="File to save") 342 | parser.add_argument("--valid_steps", type=int, default=1, nargs="?", 343 | help="Epochs before u validate") 344 | parser.add_argument("--loss_type", type=str, default='BCE', nargs="?", 345 | help="Loss type") 346 | parser.add_argument("--do_batch_norm", type=int, default=1, nargs="?", 347 | help="Do batch norm or not (0, 1)") 348 | parser.add_argument("--l3_reg", type=float, default=0.0, nargs="?", 349 | help="l3 reg hyperparameter") 350 | parser.add_argument("--load_from", type=str, default='', nargs="?", 351 | help="load from state dict") 352 | 353 | args = parser.parse_args() 354 | dataset = args.dataset 355 | data_dir = f"../data/{dataset}/" 356 | torch.backends.cudnn.deterministic = True 357 | seed = 20 358 | np.random.seed(seed) 359 | torch.manual_seed(seed) 360 | if torch.cuda.is_available: 361 | torch.cuda.manual_seed_all(seed) 362 | 363 | experiment = Experiment(num_iterations=args.num_iterations, batch_size=args.batch_size, learning_rate=args.lr, 364 | decay_rate=args.dr, ent_vec_dim=args.edim, rel_vec_dim=args.rdim, cuda=args.cuda, 365 | input_dropout=args.input_dropout, hidden_dropout1=args.hidden_dropout1, 366 | hidden_dropout2=args.hidden_dropout2, label_smoothing=args.label_smoothing, outfile=args.outfile, 367 | valid_steps=args.valid_steps, loss_type=args.loss_type, do_batch_norm=args.do_batch_norm, 368 | dataset=args.dataset, model=args.model, l3_reg=args.l3_reg, load_from=args.load_from) 369 | 370 | d=Data(data_dir=data_dir, reverse=True) 371 | 372 | experiment.train_and_eval(d) 373 | 374 | 375 | -------------------------------------------------------------------------------- /train_embeddings/model.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torch.nn.init import xavier_normal_ 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | class KGE(torch.nn.Module): 8 | def __init__(self, d, ent_vec_dim, rel_vec_dim, **kwargs): 9 | super(KGE, self).__init__() 10 | 11 | self.model = kwargs["model"] 12 | multiplier = 3 13 | self.loss_type = kwargs['loss_type'] 14 | 15 | if self.loss_type == 'BCE': 16 | # self.loss = torch.nn.BCELoss() 17 | self.loss = self.bce_loss 18 | self.bce_loss_loss = torch.nn.BCELoss() 19 | elif self.loss_type == 'CE': 20 | self.loss = self.ce_loss 21 | else: 22 | print('Incorrect loss specified:', self.loss_type) 23 | exit(0) 24 | if self.model == 'DistMult': 25 | multiplier = 1 26 | self.score_func = self.DistMult 27 | elif self.model == 'SimplE': 28 | multiplier = 2 29 | self.score_func = self.SimplE 30 | elif self.model == 'ComplEx': 31 | multiplier = 2 32 | self.score_func = self.ComplEx 33 | elif self.model == 'RESCAL': 34 | self.score_func = self.RESCAL 35 | multiplier = 1 36 | elif self.model == 'TuckER': 37 | self.score_func = self.TuckER 38 | multiplier = 1 39 | self.W = torch.nn.Parameter(torch.tensor(np.random.uniform(-1, 1, (rel_vec_dim, ent_vec_dim, ent_vec_dim)), 40 | dtype=torch.float, device="cuda", requires_grad=True)) 41 | else: 42 | print('Incorrect model specified:', self.model) 43 | exit(0) 44 | self.E = torch.nn.Embedding(len(d.entities), ent_vec_dim * multiplier, padding_idx=0) 45 | 46 | if self.model == 'RESCAL': 47 | self.R = torch.nn.Embedding(len(d.relations), ent_vec_dim * ent_vec_dim, padding_idx=0) 48 | elif self.model == 'TuckER': 49 | self.R = torch.nn.Embedding(len(d.relations), rel_vec_dim, padding_idx=0) 50 | else: 51 | self.R = torch.nn.Embedding(len(d.relations), ent_vec_dim * multiplier, padding_idx=0) 52 | 53 | self.entity_dim = ent_vec_dim * multiplier 54 | self.do_batch_norm = True 55 | if kwargs["do_batch_norm"] == False: 56 | print('Not doing batch norm') 57 | self.do_batch_norm = False 58 | self.input_dropout = torch.nn.Dropout(kwargs["input_dropout"]) 59 | self.hidden_dropout1 = torch.nn.Dropout(kwargs["hidden_dropout1"]) 60 | self.hidden_dropout2 = torch.nn.Dropout(kwargs["hidden_dropout2"]) 61 | self.l3_reg = kwargs["l3_reg"] 62 | 63 | if self.model in ['DistMult', 'RESCAL', 'SimplE', 'TuckER']: 64 | self.bn0 = torch.nn.BatchNorm1d(ent_vec_dim * multiplier) 65 | self.bn1 = torch.nn.BatchNorm1d(ent_vec_dim * multiplier) 66 | self.bn2 = torch.nn.BatchNorm1d(ent_vec_dim * multiplier) 67 | else: 68 | self.bn0 = torch.nn.BatchNorm1d(multiplier) 69 | self.bn1 = torch.nn.BatchNorm1d(multiplier) 70 | self.bn2 = torch.nn.BatchNorm1d(multiplier) 71 | 72 | self.logsoftmax = torch.nn.LogSoftmax(dim=-1) 73 | print('Model is', self.model) 74 | 75 | def freeze_entity_embeddings(self): 76 | self.E.weight.requires_grad = False 77 | print('Entity embeddings are frozen') 78 | 79 | def ce_loss(self, pred, true): 80 | pred = F.log_softmax(pred, dim=-1) 81 | true = true/true.size(-1) 82 | loss = -torch.sum(pred * true) 83 | return loss 84 | 85 | def bce_loss(self, pred, true): 86 | loss = self.bce_loss_loss(pred, true) 87 | #l3 regularization 88 | if self.l3_reg: 89 | norm = torch.norm(self.E.weight.data, p=3, dim=-1) 90 | loss += self.l3_reg * torch.sum(norm) 91 | return loss 92 | 93 | def init(self): 94 | xavier_normal_(self.E.weight.data) 95 | if self.model == 'Rotat3': 96 | nn.init.uniform_(self.R.weight.data, a=-1.0, b=1.0) 97 | else: 98 | xavier_normal_(self.R.weight.data) 99 | 100 | def RESCAL(self, head, relation): 101 | if self.do_batch_norm: 102 | head = self.bn0(head) 103 | head = self.input_dropout(head) 104 | head = head.view(-1, 1, self.entity_dim) 105 | relation = relation.view(-1, self.entity_dim, self.entity_dim) 106 | relation = self.hidden_dropout1(relation) 107 | x = torch.bmm(head, relation) 108 | x = x.view(-1, self.entity_dim) 109 | if self.do_batch_norm: 110 | x = self.bn2(x) 111 | x = self.hidden_dropout2(x) 112 | s = torch.mm(x, self.E.weight.transpose(1,0)) 113 | return s 114 | 115 | def TuckER(self, head, relation): 116 | if self.do_batch_norm: 117 | head = self.bn0(head) 118 | ent_embedding_size = head.size(1) 119 | head = self.input_dropout(head) 120 | head = head.view(-1, 1, ent_embedding_size) 121 | 122 | W_mat = torch.mm(relation, self.W.view(relation.size(1), -1)) 123 | W_mat = W_mat.view(-1, ent_embedding_size, ent_embedding_size) 124 | W_mat = self.hidden_dropout1(W_mat) 125 | 126 | s = torch.bmm(head, W_mat) 127 | s = s.view(-1, ent_embedding_size) 128 | s = self.bn2(s) 129 | s = self.hidden_dropout2(s) 130 | s = torch.mm(s, self.E.weight.transpose(1,0)) 131 | return s 132 | 133 | def DistMult(self, head, relation): 134 | if self.do_batch_norm: 135 | head = self.bn0(head) 136 | head = self.input_dropout(head) 137 | relation = self.hidden_dropout1(relation) 138 | s = head * relation 139 | if self.do_batch_norm: 140 | s = self.bn2(s) 141 | s = self.hidden_dropout2(s) 142 | s = torch.mm(s, self.E.weight.transpose(1,0)) 143 | return s 144 | 145 | 146 | def SimplE(self, head, relation): 147 | if self.do_batch_norm: 148 | head = self.bn0(head) 149 | head = self.input_dropout(head) 150 | relation = self.hidden_dropout1(relation) 151 | s = head * relation 152 | s_head, s_tail = torch.chunk(s, 2, dim=1) 153 | s = torch.cat([s_tail, s_head], dim=1) 154 | if self.do_batch_norm: 155 | s = self.bn2(s) 156 | s = self.hidden_dropout2(s) 157 | s = torch.mm(s, self.E.weight.transpose(1,0)) 158 | s = 0.5 * s 159 | return s 160 | 161 | def ComplEx(self, head, relation): 162 | head = torch.stack(list(torch.chunk(head, 2, dim=1)), dim=1) 163 | if self.do_batch_norm: 164 | head = self.bn0(head) 165 | head = self.input_dropout(head) 166 | head = head.permute(1, 0, 2) 167 | re_head = head[0] 168 | im_head = head[1] 169 | 170 | relation = self.hidden_dropout1(relation) 171 | re_relation, im_relation = torch.chunk(relation, 2, dim=1) 172 | re_tail, im_tail = torch.chunk(self.E.weight, 2, dim =1) 173 | 174 | re_score = re_head * re_relation - im_head * im_relation 175 | im_score = re_head * im_relation + im_head * re_relation 176 | 177 | score = torch.stack([re_score, im_score], dim=1) 178 | if self.do_batch_norm: 179 | score = self.bn2(score) 180 | score = self.hidden_dropout2(score) 181 | score = score.permute(1, 0, 2) 182 | re_score = score[0] 183 | im_score = score[1] 184 | score = torch.mm(re_score, re_tail.transpose(1,0)) + torch.mm(im_score, im_tail.transpose(1,0)) 185 | return score 186 | 187 | 188 | def forward(self, e1_idx, r_idx): 189 | e1 = self.E(e1_idx) 190 | h = e1 191 | r = self.R(r_idx) 192 | ans = self.score_func(h, r) 193 | pred = torch.sigmoid(ans) 194 | return pred 195 | --------------------------------------------------------------------------------