-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrnnlm.py
306 lines (254 loc) · 12.3 KB
/
rnnlm.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import dynet
import random
import util
import os
import pickle
import math
import numpy
from scipy.misc import logsumexp
###########################################################################
class SaveableModel(object):
name = "template"
def __init__(self, model, args):
self.model = model
self.args = args
self.add_params()
def add_params(self):
pass
def sample(self, sent_args={}, nchars=100):
pass
def save(self, path):
if not os.path.exists(path): os.makedirs(path)
self.model.save(path + "/params")
with open(path+"/args", "w") as f: pickle.dump(self.args, f)
@staticmethod
def load(model, path, load_model_params=True):
if not os.path.exists(path): raise Exception("Model "+path+" does not exist")
with open(path+"/args", "r") as f: args = pickle.load(f)
lm = get_model(args.mode)(model, args)
if load_model_params: lm.model.load(path+"/params")
return lm
class SaveableRNNLM(SaveableModel):
name = "rnnlm_template"
def __init__(self, model, vocab, args):
self.model = model
self.vocab = vocab
self.args = args
self.add_params()
def save(self, path):
if not os.path.exists(path): os.makedirs(path)
self.vocab.save(path+"/vocab")
self.model.save(path + "/params")
with open(path+"/args", "w") as f: pickle.dump(self.args, f)
@staticmethod
def load(model, path, load_model_params=True):
if not os.path.exists(path): raise Exception("Model "+path+" does not exist")
vocab = util.Vocab.load(path+"/vocab")
with open(path+"/args", "r") as f: args = pickle.load(f)
lm = get_model(args.arch)(model, vocab, args)
if load_model_params: lm.model.load(path+"/params")
return lm
class SaveableS2S(SaveableModel):
name = "s2s_template"
def __init__(self, model, src_vocab, tgt_vocab, args):
self.model = model
self.src_vocab = src_vocab
self.tgt_vocab = tgt_vocab
self.args = args
self.add_params()
def save(self, path):
if not os.path.exists(path): os.makedirs(path)
self.src_vocab.save(path+"/src_vocab")
self.tgt_vocab.save(path+"/tgt_vocab")
self.model.save(path + "/params")
with open(path+"/args", "w") as f: pickle.dump(self.args, f)
@staticmethod
def load(model, path, load_model_params=True):
if not os.path.exists(path): raise Exception("Model "+path+" does not exist")
src_vocab = util.Vocab.load(path+"/src_vocab")
tgt_vocab = util.Vocab.load(path+"/tgt_vocab")
with open(path+"/args", "r") as f: args = pickle.load(f)
lm = get_model(args.disc_arch)(model, src_vocab, tgt_vocab, args)
if load_model_params: lm.model.load(path+"/params")
return lm
def get_model(name):
for c in util.itersubclasses(SaveableModel):
if c.name == name: return c
raise Exception("no language model found with name: " + name)
##########################################################################
class BaselineGenRNNLM(SaveableRNNLM):
name = "baseline"
def add_params(self):
if self.args.rnn == "lstm": rnn = dynet.LSTMBuilder
elif self.args.rnn == "gru": rnn = dynet.GRUBuilder
else: rnn = dynet.SimpleRNNBuilder
# GENERATIVE MODEL PARAMETERS
self.gen_lookup = self.model.add_lookup_parameters((self.vocab.size, self.args.gen_input_dim))
self.gen_rnn = rnn(self.args.gen_layers, self.args.gen_input_dim, self.args.gen_hidden_dim, self.model)
self.gen_R = self.model.add_parameters((self.vocab.size, self.args.gen_hidden_dim))
self.gen_bias = self.model.add_parameters((self.vocab.size,))
# print self.vocab.size, self.args.hidden_dim, self.args.input_dim
def BuildLMGraph(self, sent, sent_args=None):
if "skip_renew" not in sent_args: dynet.renew_cg()
APPLY_DROPOUT = self.args.dropout is not None and ("test" not in sent_args or sent_args["test"] != True)
if APPLY_DROPOUT: self.gen_rnn.set_dropout(self.args.dropout)
else: self.gen_rnn.disable_dropout()
# GENERATIVE MODEL
init_state = self.gen_rnn.initial_state()
R = dynet.parameter(self.gen_R)
bias = dynet.parameter(self.gen_bias)
errs = [] # will hold expressions
state = init_state
for (cw,nw) in zip(sent,sent[1:]):
x_t = self.gen_lookup[cw]
state = state.add_input(x_t)
y_t = state.output()
if APPLY_DROPOUT: y_t = dynet.dropout(y_t, self.args.dropout)
r_t = bias + (R * y_t)
err = dynet.pickneglogsoftmax(r_t, int(nw))
errs.append(err)
gen_err = dynet.esum(errs)
return gen_err
def BuildLMGraph_batch(self, batch, sent_args=None):
if "skip_renew" not in sent_args: dynet.renew_cg()
APPLY_DROPOUT = self.args.dropout is not None and ("test" not in sent_args or sent_args["test"] != True)
if APPLY_DROPOUT: self.gen_rnn.set_dropout(self.args.dropout)
else: self.gen_rnn.disable_dropout()
init_state = self.gen_rnn.initial_state()
#MASK SENTENCES
isents = [] # Dimension: maxSentLength * minibatch_size
# List of lists to store whether an input is
# present(1)/absent(0) for an example at a time step
masks = [] # Dimension: maxSentLength * minibatch_size
#No of words processed in this batch
maxSentLength = max([len(sent) for sent in batch])
for sent in batch:
isents.append([self.vocab[word].i for word in sent] + [self.vocab[self.vocab.END_TOK].i for _ in range(maxSentLength-len(sent))])
masks.append( [1 for _ in sent] + [0 for _ in range(maxSentLength-len(sent))])
isents = map(list, zip(*isents)) # transposes
masks = map(list, zip(*masks))
# print isents
# print masks
R = dynet.parameter(self.gen_R)
bias = dynet.parameter(self.gen_bias)
errs = [] # will hold expressions
state = init_state
for (mask, curr_words, next_words) in zip(masks[1:], isents, isents[1:]):
x_t = dynet.lookup_batch(self.gen_lookup, curr_words)
state = state.add_input(x_t)
y_t = state.output()
if APPLY_DROPOUT: y_t = dynet.dropout(y_t, self.args.dropout)
r_t = bias + (R * y_t)
err = dynet.pickneglogsoftmax_batch(r_t, next_words)
## mask the loss if at least one sentence is shorter. (sents sorted reverse-length, so it must be bottom)
if mask[-1] == 0:
mask_expr = dynet.inputVector(mask)
mask_expr = dynet.reshape(mask_expr, (1,), len(mask))
err = err * mask_expr
errs.append(err)
nerr = dynet.esum(errs)
return nerr
def sample(self, sent_args={}, max_toks=100):
if "skip_renew" not in sent_args: dynet.renew_cg()
APPLY_DROPOUT = self.args.dropout is not None and ("test" not in sent_args or sent_args["test"] != True)
if APPLY_DROPOUT: self.gen_rnn.set_dropout(self.args.dropout)
else: self.gen_rnn.disable_dropout()
# GENERATIVE MODEL
init_state = self.gen_rnn.initial_state()
R = dynet.parameter(self.gen_R)
bias = dynet.parameter(self.gen_bias)
errs = [] # will hold expressions
toks = []
state = init_state
cw = self.vocab[self.vocab.START_TOK].i
while len(toks) < max_toks:
x_t = self.gen_lookup[cw]
state = state.add_input(x_t)
y_t = state.output()
if APPLY_DROPOUT: y_t = dynet.dropout(y_t, self.args.dropout)
r_t = bias + (R * y_t)
nw = util.weightedChoice(r_t.vec_value(), range(self.vocab.size), apply_softmax=True)
toks.append(nw)
if "get_err" in sent_args:
err = dynet.pickneglogsoftmax(r_t, int(nw))
errs.append(err)
if nw == self.vocab[self.vocab.END_TOK].i: break
cw = nw
if "get_err" in sent_args:
gen_err = dynet.esum(errs)
return gen_err
else:
return toks
# Here's an example of how to implement another model to test.
# This model implements the reused word embeddings from https://arxiv.org/pdf/1611.01462v1.pdf
class ReuseEmbeddingsRNNLM(SaveableRNNLM):
name = "reuse_emb"
def add_params(self):
if self.args.rnn == "lstm": rnn = dynet.LSTMBuilder
elif self.args.rnn == "gru": rnn = dynet.GRUBuilder
else: rnn = dynet.SimpleRNNBuilder
# GENERATIVE MODEL PARAMETERS
self.gen_lookup = self.model.add_lookup_parameters((self.vocab.size, self.args.gen_input_dim))
self.gen_rnn = rnn(self.args.gen_layers, self.args.gen_input_dim, self.args.gen_hidden_dim, self.model)
self.gen_R = self.model.add_parameters((self.args.gen_input_dim, self.args.gen_hidden_dim))
self.gen_bias = self.model.add_parameters((self.args.gen_input_dim,))
def BuildLMGraph(self, sent, sent_args=None):
if "skip_renew" not in sent_args: dynet.renew_cg()
APPLY_DROPOUT = self.args.dropout is not None and ("test" not in sent_args or sent_args["test"] != True)
if APPLY_DROPOUT: self.gen_rnn.set_dropout(self.args.dropout)
else: self.gen_rnn.disable_dropout()
# GENERATIVE MODEL
init_state = self.gen_rnn.initial_state()
R = dynet.parameter(self.gen_R)
bias = dynet.parameter(self.gen_bias)
vocab_basis = dynet.transpose(dynet.concatenate_cols([self.gen_lookup[i] for i in range(self.vocab.size)]))
errs = [] # will hold expressions
state = init_state
for (cw,nw) in zip(sent,sent[1:]):
x_t = self.gen_lookup[cw]
state = state.add_input(x_t)
y_t = state.output()
if APPLY_DROPOUT: y_t = dynet.dropout(y_t, self.args.dropout)
r_t = vocab_basis * (bias + (R * y_t))
err = dynet.pickneglogsoftmax(r_t, int(nw))
errs.append(err)
gen_err = dynet.esum(errs)
return gen_err
def BuildLMGraph_batch(self, batch, sent_args=None):
if "skip_renew" not in sent_args: dynet.renew_cg()
APPLY_DROPOUT = self.args.dropout is not None and ("test" not in sent_args or sent_args["test"] != True)
if APPLY_DROPOUT: self.gen_rnn.set_dropout(self.args.dropout)
else: self.gen_rnn.disable_dropout()
init_state = self.gen_rnn.initial_state()
#MASK SENTENCES
isents = [] # Dimension: maxSentLength * minibatch_size
# List of lists to store whether an input is
# present(1)/absent(0) for an example at a time step
masks = [] # Dimension: maxSentLength * minibatch_size
#No of words processed in this batch
maxSentLength = max([len(sent) for sent in batch])
for sent in batch:
isents.append([self.vocab[word].i for word in sent] + [self.vocab[self.vocab.END_TOK].i for _ in range(maxSentLength-len(sent))])
masks.append( [1 for _ in sent] + [0 for _ in range(maxSentLength-len(sent))])
isents = map(list, zip(*isents)) # transposes
masks = map(list, zip(*masks))
R = dynet.parameter(self.gen_R)
bias = dynet.parameter(self.gen_bias)
vocab_basis = dynet.transpose(dynet.concatenate_cols([self.gen_lookup[i] for i in range(self.vocab.size)]))
errs = [] # will hold expressions
state = init_state
for (mask, curr_words, next_words) in zip(masks[1:], isents, isents[1:]):
x_t = dynet.lookup_batch(self.gen_lookup, curr_words)
state = state.add_input(x_t)
y_t = state.output()
if APPLY_DROPOUT: y_t = dynet.dropout(y_t, self.args.dropout)
r_t = vocab_basis * (bias + (R * y_t))
err = dynet.pickneglogsoftmax_batch(r_t, next_words)
## mask the loss if at least one sentence is shorter. (sents sorted reverse-length, so it must be bottom)
if mask[-1] == 0:
mask_expr = dynet.inputVector(mask)
mask_expr = dynet.reshape(mask_expr, (1,), len(mask))
err = err * mask_expr
errs.append(err)
nerr = dynet.esum(errs)
return nerr