| 65 | |
| 66 | |
| 67 | class Model(ModelDesc): |
| 68 | def inputs(self): |
| 69 | return [tf.TensorSpec((None, param.seq_len), tf.int32, 'input'), |
| 70 | tf.TensorSpec((None, param.seq_len), tf.int32, 'nextinput')] |
| 71 | |
| 72 | def build_graph(self, input, nextinput): |
| 73 | cell = rnn.MultiRNNCell([rnn.LSTMBlockCell(num_units=param.rnn_size) |
| 74 | for _ in range(param.num_rnn_layer)]) |
| 75 | |
| 76 | def get_v(n): |
| 77 | ret = tf.get_variable(n + '_unused', [param.batch_size, param.rnn_size], |
| 78 | trainable=False, |
| 79 | initializer=tf.constant_initializer()) |
| 80 | ret = tf.placeholder_with_default(ret, shape=[None, param.rnn_size], name=n) |
| 81 | return ret |
| 82 | initial = (rnn.LSTMStateTuple(get_v('c0'), get_v('h0')), |
| 83 | rnn.LSTMStateTuple(get_v('c1'), get_v('h1'))) |
| 84 | |
| 85 | embeddingW = tf.get_variable('embedding', [param.vocab_size, param.rnn_size]) |
| 86 | input_feature = tf.nn.embedding_lookup(embeddingW, input) # B x seqlen x rnnsize |
| 87 | |
| 88 | input_list = tf.unstack(input_feature, axis=1) # seqlen x (Bxrnnsize) |
| 89 | |
| 90 | outputs, last_state = rnn.static_rnn(cell, input_list, initial, scope='rnnlm') |
| 91 | last_state = tf.identity(last_state, 'last_state') |
| 92 | |
| 93 | # seqlen x (Bxrnnsize) |
| 94 | output = tf.reshape(tf.concat(outputs, 1), [-1, param.rnn_size]) # (Bxseqlen) x rnnsize |
| 95 | logits = FullyConnected('fc', output, param.vocab_size, activation=tf.identity) |
| 96 | tf.nn.softmax(logits / param.softmax_temprature, name='prob') |
| 97 | |
| 98 | xent_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( |
| 99 | logits=logits, labels=tf.reshape(nextinput, [-1])) |
| 100 | cost = tf.reduce_mean(xent_loss, name='cost') |
| 101 | summary.add_param_summary(('.*/W', ['histogram'])) # monitor histogram of all W |
| 102 | summary.add_moving_summary(cost) |
| 103 | return cost |
| 104 | |
| 105 | def optimizer(self): |
| 106 | lr = tf.get_variable('learning_rate', initializer=2e-3, trainable=False) |
| 107 | opt = tf.train.AdamOptimizer(lr) |
| 108 | return optimizer.apply_grad_processors(opt, [GlobalNormClip(5)]) |
| 109 | |
| 110 | |
| 111 | def get_config(): |
no outgoing calls
no test coverage detected