def RNN(X, weights, biases):
X = tf.reshape(X, [-1, n_inputs])
X_in = tf.matmul(X, weights['in']) + biases['in']
X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=0.0, state_is_tuple=True)
init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32)
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=init_state, time_major=False)
outputs = tf.unpack(tf.transpose(outputs, [1, 0, 2])) # states is the last outputs
results = tf.matmul(outputs[-1], weights['out']) + biases['out']
del outputs,final_state,lstm_cell,init_state,X,X_in
return results
def while_loop(s,e,step):
while s+batch_size<ran:
batch_id=file_id[s:e]
batch_col=label_matrix[s:e]
batch_label = csc_matrix((data, (batch_row, batch_col)), shape=(batch_size, n_classes))
batch_label = batch_label.toarray()
batch_xs1=tf.nn.embedding_lookup(embedding_matrix,batch_id)
batch_xs=sess.run(batch_xs1)
del batch_xs1
sess.run([train_op], feed_dict={x: batch_xs,
y: batch_label})
print(step,':',sess.run(accuracy, feed_dict={x: batch_xs,y: batch_label}),sess.run(cost,feed_dict={x: batch_xs,y: batch_label}))
if step!=0 and step % 20 == 0:
save_path = saver.save(sess, './model/lstm_classification.ckpt',write_meta_graph=False)
print('Save to path', save_path)
step += 1
s+=batch_size
e+=batch_size
del batch_label,batch_xs,batch_id,batch_col
print(hp.heap())
print(hp.heap().more)
This is my code.It keeps going this mistake 'ResourceExhaustedError:OOM when allocating tensor with shape' I used guppy.Then got this.result of guppy
Why the variable of tensorflow take so much space.
The problem was caused by this line in the training loop:
Calling the
tf.nn.embedding_lookup()function adds nodes to the TensorFlow graph, and—because these are never garbage collected—doing so in a loop causes a memory leak.The actual cause of the memory leak is probably the
embedding_matrixNumPy array in the argument totf.nn.embedding_lookup(). TensorFlow tries to be helpful and convert all NumPy arrays in the arguments to a function intotf.constant()nodes in the TensorFlow graph. However, in a loop, this will end up with multiple separate copies of theembedding_matrixcopied into TensorFlow and then onto scarce GPU memory.The simplest solution is to move the
tf.nn.embedding_lookup()call outside the training loop. For example: