-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrun.py
150 lines (126 loc) · 5.96 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import numpy as np
from torch_rgvae.GVAE import GVAE
from torch_rgvae.GCVAE import GCVAE
from torch_rgvae.GCVAE2 import GCVAE2
from lp_utils import *
from experiments.train_eval_vae import train_eval_vae
from experiments.link_prediction import link_prediction
from experiments.gen_people import eval_generation
from datetime import date
from ranger import Ranger
import pickle as pkl
import yaml, json, argparse, wandb, os, random
import torch
if __name__ == "__main__":
# Arg parsing
parser = argparse.ArgumentParser()
parser.add_argument('--configs', nargs=1,
help="YAML file with configurations",
dest="configs",
type=str,
default=['configs/config_file.yml'])
parser.add_argument("--dev",
dest="dev",
help="Run in develop mode",
nargs=1,
default=[1], type=int)
arguments = parser.parse_args()
with open(arguments.configs[0], 'r') as file:
args = yaml.full_load(file)
if arguments.dev[0] == 1:
develope = True
limit = 60
else:
develope = False
limit = -1
wandb.login(key='6d802b44b97d25931bacec09c5f1095e6c28fe36')
print('Dev mode: {}'.format(develope))
# Torch settings
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if device == 'cuda':
torch.cuda.set_device(0)
my_dtype = torch.float64
torch.set_default_dtype(my_dtype)
# model_name = 'VEmbed'
model_name = args['model_name']
dataset = args['dataset_name']
n = args['n'] # number of triples per matrix ( = matrix_n/2)
batch_size = 2**args['batch_size_exp2'] # Choose an apropiate batch size. cpu: 2**9
if dataset == 'wn18rr' and batch_size > 2**10: # Avoid out of memory errors on LISA
batch_size = 2**10
args['batch_size_exp2'] = 10
args['seed'] = seed = np.random.randint(1,21)
np.random.seed(seed=seed)
torch.manual_seed(seed)
if develope:
# wandb.init(project="dev-mode")
wandb.init(project="offline-dev", mode='offline')
else:
if 'project' in args:
wandb.init(project=args['project'], config=args)
else:
wandb.init(config=args)
# Get data
final = args['final'] if 'final' in args else False
(n2i, i2n), (r2i, i2r), train_set, test_set, all_triples = load_link_prediction_data(dataset, use_test_set=final)
n_e = len(n2i)
n_r = len(r2i)
args['n_e'] = n_e
args['n_r'] = n_r
truedict = truedicts(all_triples)
dataset_tools = [truedict, i2n, i2r]
# Obama triple: /m/02mjmr /people/person/place_of_birth /m/02hrh0_Michelangelo triple: /m/058w5 /people/deceased_person/place_of_death /m/06c62
args['obama_mangelo'] = torch.tensor([[n2i['/m/02mjmr'], r2i['/people/person/place_of_birth'], n2i['/m/02hrh0_']],
[n2i['/m/058w5'], r2i['/people/deceased_person/place_of_death'], n2i['/m/06c62']]], device=d())
todate = date.today().strftime("%Y%m%d")
exp_name = args['exp_name']
print('Experiment on the {}: {}'.format(todate, exp_name))
print(args)
result_dir = 'results/{}_{}'.format(exp_name, todate)
if not os.path.isdir(result_dir):
os.makedirs(result_dir)
# Initialize model and optimizer.
if model_name == 'GCVAE':
model = GCVAE(args, n_r, n_e, dataset,).to(device)
elif model_name == 'GCVAE2':
model = GCVAE2(args, n_r, n_e, dataset).to(device)
elif model_name == 'GVAE':
model = GVAE(args, n_r, n_e, dataset).to(device)
else:
raise ValueError('{} not defined!'.format(model_name))
optimizer = Ranger(model.parameters(),lr=args['lr'], k=args['k'] if 'k' in args else 9, betas=(.95,0.999), use_gc=True, gc_conv_only=False)
wandb.watch(model)
# Load model
if args['load_model']:
# model.load_state_dict(torch.load(model_path, map_location=torch.device(device))['model_state_dict'])
model.load_state_dict(torch.load(args['load_model_path'], map_location=torch.device(device))['model_state_dict'])
print('Saved model loaded.')
# Train model
if args['train']:
train_eval_vae(batch_size, args['epochs'], train_set[:limit], test_set[:limit], model, optimizer, dataset_tools, result_dir, final)
# Link prediction
if args['link_prediction']:
print('Start link prediction!')
testset_crop = int(len(test_set)/3) # Yes, only one third
testsub = torch.tensor(test_set, device=d())[random.sample(range(len(test_set)), k=testset_crop)] # TODO remove the testset croping
lp_results = link_prediction(model, testsub, truedict, batch_size)
lp_file_path = result_dir + '/lp_{}_{}.json'.format(exp_name, todate)
with open(lp_file_path, 'w') as outfile:
json.dump(lp_results, outfile)
wandb.save(lp_file_path)
print('Saved link prediction results!')
if 'eval_generation' in args:
if args['eval_generation']:
gen_list, new_triples = list(), list()
n_std = args['n_std'] if 'n_std' in args else 1
for ii in range(3):
gen_results, gen_triples = eval_generation(model, i2n, i2r, all_triples, n_eval=100000, n_std=n_std)
gen_list.append(gen_triples)
new_triples.append(gen_results[2])
print('The {} generated {:.3f}% possibly true triples, of which {:.3f}% already exist in the dataset.'.format(model_name, gen_results[0]*100, gen_results[1]*100))
wandb.log({'gen_true': gen_results[0], 'gen_new': gen_results[1], 'new_triples': gen_results[2], 'run': ii})
with open(result_dir +'/gen_people_list.pkl', 'wb') as f:
pkl.dump(gen_list, f)
with open(result_dir +'/gen_newpeople_list.pkl', 'wb') as f:
pkl.dump(new_triples , f)