-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathtree.py
273 lines (234 loc) · 8.56 KB
/
tree.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# -*- coding: utf-8 -*-
# wandb login 7cd7ade39e2d850ec1cf4e914d9a148586a20900
from torch_struct import TreeCRF, SelfCritical
import torchtext.data as data
from torch_struct.data import ListOpsDataset, TokenBucket
from torch_struct.networks import TreeLSTM, SpanLSTM
import torch
import torch.nn as nn
import wandb
config = {
"method": "reinforce",
"baseline": "mean",
"opt": "adadelta",
"lr_struct": 0.1,
"lr_params": 1,
"train_model": True,
"var_norm": False,
"entropy": 0.001,
"v": 3,
"RL_K": 5,
"H": 100,
"train_len": 100,
"div_ent": 1,
}
NAME = "yoyo3"
wandb.init(project="pytorch-struct", config=config)
def clip(p):
torch.nn.utils.clip_grad_norm_(parameters=p, max_norm=0.5, norm_type=float("inf"))
def expand_spans(spans, words, K, V):
batch, N = words.shape
spans[:, torch.arange(N), torch.arange(N)] = 0
new_spans = torch.zeros(K, batch, N, N, 1 + V).cuda()
new_spans[:, :, :, :, :1] = spans.view(K, batch, N, N, 1)
new_spans[:, :, torch.arange(N), torch.arange(N), :].fill_(0)
new_spans[:, :, torch.arange(N), torch.arange(N), 1:] = (
torch.nn.functional.one_hot(words, V).float().cuda().view(1, batch, N, V)
)
new_spans = new_spans.view(batch * K, N, N, 1 + V)
return new_spans
def valid_sup(valid_iter, model, tree_lstm, V):
total = 0
correct = 0
Dist = TreeCRF
for i, ex in enumerate(valid_iter):
words, lengths = ex.word
trees = ex.tree
label = ex.label
words = words.cuda()
def tree_reward(spans):
new_spans = expand_spans(spans, words, 1, V)
g, labels, indices, topo = TreeLSTM.spans_to_dgl(new_spans)
_, am = tree_lstm(g, labels, indices, topo, lengths).max(-1)
return (label == am).sum(), label.shape[0]
words = words.cuda()
phi = model(words, lengths)
dist = TreeCRF(phi, lengths)
argmax = dist.argmax
argmax_tree = dist.struct.from_parts(argmax.detach())[0]
score, tota = tree_reward(argmax_tree)
total += int(tota)
correct += score
if i == 25:
break
print(correct.item() / float(total), correct, total)
return correct.item() / float(total)
def run_train(train_iter, valid_iter, model, tree_lstm, V):
opt_struct = torch.optim.Adadelta(list(model.parameters()), lr=config["lr_struct"])
opt_params = torch.optim.Adadelta(
list(tree_lstm.parameters()), lr=config["lr_params"]
)
model.train()
tree_lstm.train()
losses = []
Dist = TreeCRF
step = 0
trees = None
for epoch in range(100):
print("Epoch", epoch)
for i, ex in enumerate(train_iter):
step += 1
words, lengths = ex.word
label = ex.label
batch = label.shape[0]
_, N = words.shape
words = words.cuda()
def tree_reward(spans, K):
new_spans = expand_spans(spans, words, K, V)
g, labels, indices, topo = TreeLSTM.spans_to_dgl(new_spans)
ret = tree_lstm(
g, labels, indices, topo, torch.cat([lengths for _ in range(K)])
)
ret = ret.view(K, batch, -1)
return -ret[:, torch.arange(batch), label].view(K, batch)
sc = SelfCritical(tree_reward)
phi = model(words, lengths)
dist = Dist(phi)
structs, rewards, score, max_score = sc.forward(dist, K=config["RL_K"])
if config["train_model"]:
opt_params.zero_grad()
score.mean().backward()
clip(tree_lstm.parameters())
opt_params.step()
opt_params.zero_grad()
if config["method"] == "reinforce":
opt_struct.zero_grad()
entropy = dist.entropy
r = dist.log_prob(structs)
obj = rewards.mul(r).mean(-1).mean(-1)
policy = (
obj - config["entropy"] * entropy.div(lengths.float().cuda()).mean()
)
policy.backward()
clip(model.parameters())
opt_struct.step()
losses.append(-max_score.mean().detach())
# DEBUG
if i % 50 == 9:
print(torch.tensor(losses).mean(), words.shape)
print("Round")
print("Entropy", entropy.mean().item())
print("Reward", rewards.mean().item())
if i % 1000 == 9:
valid_loss = valid_sup(valid_iter, model, tree_lstm, V)
fname = "/tmp/checkpoint.%s.%0d.%0d.%s" % (
NAME,
epoch,
i,
valid_loss,
)
torch.save((model, tree_lstm), fname)
wandb.save(fname)
trees = valid_show(valid_iter, model)
else:
print(valid_loss)
wandb.log(
{
"entropy": entropy.mean(),
"valid_loss": valid_loss,
"reward": rewards.mean(),
"step": step,
"tree": trees,
"reward_var": rewards.var(),
"loss": torch.tensor(losses).mean(),
}
)
losses = []
def valid_show(valid_iter, model):
table = wandb.Table(columns=["Sent", "Predicted Tree", "True Tree"])
Dist = TreeCRF
for i, ex in enumerate(valid_iter):
words, lengths = ex.word
label = ex.label
batch = label.shape[0]
words = words.cuda()
phi = model(words, lengths)
dist = Dist(phi)
argmax = dist.argmax
argmax_tree = dist.struct.from_parts(argmax.detach())[0].cpu()
for b in range(words.shape[0]):
out = [WORD.vocab.itos[w.item()] for w in words[b]]
sent = " ".join(out)
def show(tree):
output = ""
start = {}
end = {}
for i, j, _ in tree.nonzero():
i = i.item()
j = j.item()
start.setdefault(i, -1)
end.setdefault(j, -1)
start[i] += 1
end[j] += 1
for i, w in enumerate(out):
for _ in range(start.get(i, 0)):
output += "( "
output += w + " "
for _ in range(end.get(i, 0)):
output += ") "
return output
predict_text = show(ex.tree[b].cpu())
true_text = show(argmax_tree[b].cpu())
table.add_data(sent, predict_text, true_text)
break
return table
WORD = None
def main():
global WORD
WORD = data.Field(
include_lengths=True, batch_first=True, eos_token=None, init_token=None
)
LABEL = data.Field(sequential=False, batch_first=True)
TREE = data.RawField(postprocessing=ListOpsDataset.tree_field(WORD))
TREE.is_target = False
train = ListOpsDataset(
"data/train_d20s.tsv",
(("word", WORD), ("label", LABEL), ("tree", TREE)),
filter_pred=lambda x: 5 < len(x.word) < config["train_len"],
)
WORD.build_vocab(train)
LABEL.build_vocab(train)
valid = ListOpsDataset(
"data/test_d20s.tsv",
(("word", WORD), ("label", LABEL), ("tree", TREE)),
filter_pred=lambda x: 5 < len(x.word) < 150,
)
train_iter = TokenBucket(
train, batch_size=1500, device="cuda:0", key=lambda x: len(x.word)
)
train_iter.repeat = False
valid_iter = data.BucketIterator(
train, batch_size=50, train=False, sort=False, device="cuda:0"
)
NT = 1
T = len(WORD.vocab)
V = T
if True:
tree_lstm = TreeLSTM(
config["H"], len(WORD.vocab) + 100, len(LABEL.vocab)
).cuda()
for p in tree_lstm.parameters():
if p.dim() > 1:
torch.nn.init.xavier_uniform_(p)
model = SpanLSTM(NT, len(WORD.vocab), config["H"]).cuda()
for p in model.parameters():
if p.dim() > 1:
torch.nn.init.xavier_uniform_(p)
wandb.watch((model, tree_lstm))
print(wandb.config)
tree = run_train(train_iter, valid_iter, model, tree_lstm, V)
else:
print("loading")
model, tree_lstm = torch.load("cp.yoyo.model")
print(valid_sup(valid_iter, model, tree_lstm, V))
main()