-
Notifications
You must be signed in to change notification settings - Fork 3
/
train_embedding.py
142 lines (117 loc) · 5.37 KB
/
train_embedding.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
# Code from https://github.com/pfnet-research/hyperbolic_wrapped_distribution/blob/master/lib/models/embedding.py
import copy
import wandb
import torch
import argparse
import importlib
import numpy as np
from math import ceil
from torch.optim import Adagrad
from torch.nn import functional as F
from torch.utils.data import DataLoader
from tasks.WordNet import Dataset, evaluation
class LRScheduler():
def __init__(self, optimizer, lr, c, n_burnin_steps):
self.optimizer = optimizer
self.lr = lr
self.n_burnin_steps = n_burnin_steps
self.c = c
self.n_steps = 0
def step_and_update_lr(self):
self._update_learning_rate()
self.optimizer.step()
def zero_grad(self):
self.optimizer.zero_grad()
def _update_learning_rate(self):
self.n_steps += 1
if self.n_steps <= self.n_burnin_steps:
lr = self.lr / self.c
else:
lr = self.lr
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('--data_dir', type=str, default='data/')
parser.add_argument('--data_type', type=str, default='noun')
parser.add_argument('--n_negatives', type=int, default=1)
parser.add_argument('--latent_dim', type=int)
parser.add_argument('--batch_size', type=int, default=50000)
parser.add_argument('--lr', type=float, default=0.6)
parser.add_argument('--n_epochs', type=int, default=10000)
parser.add_argument('--dist', type=str, choices=['EuclideanNormal', 'IsotropicHWN', 'DiagonalHWN', 'RoWN', 'FullHWN'])
parser.add_argument('--initial_sigma', type=float, default=0.01)
parser.add_argument('--bound', type=float, default=37)
parser.add_argument('--train_samples', type=int, default=1)
parser.add_argument('--test_samples', type=int, default=100)
parser.add_argument('--eval_interval', type=int, default=1000)
parser.add_argument('--seed', type=int, default=1234)
parser.add_argument('--c', type=float, default=40)
parser.add_argument('--burnin_epochs', type=int, default=100)
parser.add_argument('--device', type=str, default='cuda:0')
args = parser.parse_args()
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
torch.set_default_tensor_type(torch.DoubleTensor)
dataset = Dataset(args)
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=1)
dist_module = importlib.import_module(f'distributions.{args.dist}')
model = getattr(dist_module, 'EmbeddingLayer')(args, dataset.n_words).to(args.device)
dist_fn = getattr(dist_module, 'Distribution')
optimizer = Adagrad(model.parameters(), lr=args.lr)
n_batches = int(ceil(len(dataset) / args.batch_size))
n_burnin_steps = args.burnin_epochs * n_batches
lr_scheduler = LRScheduler(optimizer, args.lr, args.c, n_burnin_steps)
best_model = copy.deepcopy(model)
best_score = None
wandb.init(project='RoWN')
wandb.run.name = 'wordnet'
wandb.config.update(args)
for epoch in range(1, args.n_epochs + 1):
total_loss, total_kl_target, total_kl_negative = 0., 0., 0.
total_diff = 0.
n_batches = 0
model.train()
for x in loader:
for param in model.parameters():
param.grad = None
x = x.cuda()
mean, covar = model(x)
dist_anchor = dist_fn(mean[:, 0, :], covar[:, 0, :])
dist_target = dist_fn(mean[:, 1, :], covar[:, 1, :])
dist_negative = dist_fn(mean[:, 2, :], covar[:, 2, :])
z = dist_anchor.rsample(args.train_samples)
log_prob_anchor = dist_anchor.log_prob(z)
log_prob_target = dist_target.log_prob(z)
log_prob_negative = dist_negative.log_prob(z)
kl_target = (log_prob_anchor - log_prob_target).mean(dim=0)
kl_negative = (log_prob_anchor - log_prob_negative).mean(dim=0)
loss = F.relu(args.bound + kl_target - kl_negative).mean()
loss.backward()
lr_scheduler.step_and_update_lr()
total_loss += loss.item() * kl_target.size(0)
total_kl_target += kl_target.sum().item()
total_kl_negative += kl_negative.sum().item()
total_diff += (kl_target - kl_negative).sum().item()
n_batches += kl_target.size(0)
if best_score is None or best_score > total_loss:
best_score = total_loss
best_model = copy.deepcopy(model)
print(f"Epoch {epoch:8d} | Total loss: {total_loss / n_batches:.3f} | KL Target: {total_kl_target / n_batches:.3f} | KL Negative: {total_kl_negative / n_batches:.3f}")
wandb.log({
'epoch': epoch,
'train_loss': total_loss / n_batches,
'train_kl_target': total_kl_target / n_batches,
'train_kl_negative': total_kl_negative / n_batches
})
if epoch % args.eval_interval == 0 or epoch == args.n_epochs:
best_model.eval()
rank, ap = evaluation(args, best_model, dataset, dist_fn)
print(f"===========> Mean rank: {rank} | MAP: {ap}")
wandb.log({
'epoch': epoch,
'rank': rank,
'map': ap
})