MCPcopy Create free account
hub / github.com/clab/dynet / BuildLMGraph

Method BuildLMGraph

examples/batching/rnnlm-batch.py:28–69  ·  view source on GitHub ↗
(self, sents)

Source from the content-addressed store, hash-verified

26
27 # Build the language model graph
28 def BuildLMGraph(self, sents):
29 dy.renew_cg()
30 # initialize the RNN
31 init_state = self.builder.initial_state()
32 # parameters -> expressions
33 R = dy.parameter(self.R)
34 bias = dy.parameter(self.bias)
35
36 S = vocab.w2i["<s>"]
37 # get the cids and masks for each step
38 tot_chars = 0
39 cids = []
40 masks = []
41
42 for i in range(len(sents[0])):
43 cids.append([(vocab.w2i[sent[i]] if len(sent) > i else S) for sent in sents])
44 mask = [(1 if len(sent)>i else 0) for sent in sents]
45 masks.append(mask)
46 tot_chars += sum(mask)
47
48 # start the rnn with "<s>"
49 init_ids = cids[0]
50 s = init_state.add_input(dy.lookup_batch(self.lookup, init_ids))
51
52 losses = []
53
54 # feed char vectors into the RNN and predict the next char
55 for cid, mask in zip(cids[1:], masks[1:]):
56 score = dy.affine_transform([bias, R, s.output()])
57 loss = dy.pickneglogsoftmax_batch(score, cid)
58 # mask the loss if at least one sentence is shorter
59 if mask[-1] != 1:
60 mask_expr = dy.inputVector(mask)
61 mask_expr = dy.reshape(mask_expr, (1,), len(sents))
62 loss = loss * mask_expr
63
64 losses.append(loss)
65 # update the state of the RNN
66 cemb = dy.lookup_batch(self.lookup, cid)
67 s = s.add_input(cemb)
68
69 return dy.sum_batches(dy.esum(losses)), tot_chars
70
71
72 def sample(self, first=1, nchars=0, stop=-1):

Callers 1

rnnlm-batch.pyFile · 0.45

Calls 5

sumFunction · 0.85
initial_stateMethod · 0.80
appendMethod · 0.80
add_inputMethod · 0.45
outputMethod · 0.45

Tested by

no test coverage detected