tensorflow icon indicating copy to clipboard operation
tensorflow copied to clipboard

Kernel Restarting The kernel appears to have died. It will restart automatically (Jupyter-Tensorflow)

Open dineshgit opened this issue 9 years ago • 42 comments

I am facing a huge problem where the jupyter kernel keeps dying. This is my first experience of kernel ending on Jupyter. I'm using Tensorflow to fit a CNN model (the total input datasize is only 9.8MB)

I did not have this issue in my previous run on the same code (however I did have errors where it said "dst tensor is not initialized". That was when I made the dataset really small to attempt to fit it. Could someone please kindly help ?

This is the code:

import tensorflow as tf import numpy as np

IMG_PX_SIZE = 50 HM_SLICES = 20

n_classes = 2

x = tf.placeholder('float') y = tf.placeholder('float')

keep_rate = 0.8 keep_prob = tf.placeholder(tf.float32)

def conv3d(x, W): return tf.nn.conv3d(x, W, strides=[1,1,1,1,1], padding='SAME')

def maxpool3d(x): return tf.nn.max_pool3d(x, ksize=[1,2,2,2,1], strides=[1,2,2,2,1], padding='SAME')

def convolutional_neural_network(x): weights = {'W_conv1':tf.Variable(tf.random_normal([3,3,3,1,32])), 'W_conv2':tf.Variable(tf.random_normal([3,3,3,32,64])), 'W_fc':tf.Variable(tf.random_normal([62720 ,1024])), 'out':tf.Variable(tf.random_normal([1024, n_classes]))}

biases = {'b_conv1':tf.Variable(tf.random_normal([32])),
           'b_conv2':tf.Variable(tf.random_normal([64])),
           'b_fc':tf.Variable(tf.random_normal([1024])),
           'out':tf.Variable(tf.random_normal([n_classes]))}

x = tf.reshape(x, shape=[-1, IMG_PX_SIZE, IMG_PX_SIZE, HM_SLICES, 1])

conv1 = tf.nn.relu(conv3d(x, weights['W_conv1']) + biases['b_conv1'])
conv1 = maxpool3d(conv1)

conv2 = tf.nn.relu(conv3d(conv1, weights['W_conv2']) + biases['b_conv2'])
conv2 = maxpool3d(conv2)

fc = tf.reshape(conv2,[-1, 62720  ])
fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+biases['b_fc'])
fc = tf.nn.dropout(fc, keep_rate)

output = tf.matmul(fc, weights['out']) + biases['out']

return output

def train_neural_network(x):

much_data = np.load('muchdata_sampled-50-50-20.npy')
train_data = much_data[:100]
validation_data = much_data[-100:]

prediction = convolutional_neural_network(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 3
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0
        for data in train_data:
            X = data[0]
            Y = data[1]
            _, c = sess.run([optimizer, cost], feed_dict={x: X, y: Y})
            epoch_loss += c

        print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:',accuracy.eval({x:[i[0] for i in validation_data], y:[i[1] for i in validation_data]}))

train_neural_network(x)

(My System information)

Have I written custom code (as opposed to using a stock example script provided in TensorFlow):

  • Yes

OS Platform and Distribution:

  • OS = Windows 10

TensorFlow installed from (source or binary): *Installed from Source

TensorFlow version (use command below): *When I ran => python -c "import tensorflow as tf; print(tf.GIT_VERSION, tf.VERSION)" *I get only this result => b'unknown' 1.0.0

CUDA/cuDNN version: *cuda_8.0.61_win10 *cuDNN v5.1 (Jan 20, 2017), for CUDA 8.0

GPU model and memory: *GeForce GTX 1050 graphics card *RAM 32GB

dineshgit avatar May 11 '17 06:05 dineshgit

Don't use Jupyter notebook. Use a simple .py script. I know a known problem with notebook. It doesn't allow cuda to deallocate resources once the session is over which creates problems.

SrivastavaKshitij avatar May 11 '17 13:05 SrivastavaKshitij

Yes, I understand this point, but what perplexes me is that others with lesser CPU or GPU power is able to run this simple code without much issues. I tried this same code on Spyder instead of Jupyter and I get the error "ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[54080,1024]"

I'm starting to suspect that I must be missing a technique to get this working properly. I've been trying to decipher this for the past 7 hours - no success so far. A friend of mine with similar machine spec can get this to run without any issues, that too on Jupyter.

dineshgit avatar May 11 '17 15:05 dineshgit

It sounds like you are running out of memory. This question is better asked on StackOverflow since it is not a bug or feature request. There is also a larger community that reads questions there. Thanks!

girving avatar May 11 '17 20:05 girving

FWIW I was seeing this after getting an OOM and then reducing the batch size. The video card seems to hold on to memory after crashes sometimes. Restarting the machine fixed the problem for me.

rbwendt avatar Nov 11 '17 02:11 rbwendt

A good technique to try (I put this at the beginning of any script using tensorflow or keras). This prevents that resource exhausted error assuming you're batch size is within reason.

import tensorflow as tf

config = tf.ConfigProto() config.gpu_options.allow_growth = True Now when creating your session pass this config to it. sess = tf.Session(config=config)

juggernaut5k avatar Feb 01 '18 13:02 juggernaut5k

If you're running on a gpu, first thing I'd suggest doing is checking if the gpu drivers can be updated to a newer version. If so, this may solve the problem.

AmirAvnit avatar Aug 19 '18 11:08 AmirAvnit

This happened to me (with Keras) but I updated cuDNN (from 7.1 to 7.2), reinstalled tensorflow-gpu, and it worked! Whatever your case, a good starting point is always downloading the Jupyter Notebook to a .py script and running it. At least it will give you more the complete errors/warnings.

zhanwenchen avatar Aug 24 '18 16:08 zhanwenchen

just updating my packages using conda update anaconda fixed it for me.

NoreenMekky avatar Sep 15 '18 11:09 NoreenMekky

A good technique to try (I put this at the beginning of any script using tensorflow or keras). This prevents that resource exhausted error assuming you're batch size is within reason.

import tensorflow as tf

config = tf.ConfigProto() config.gpu_options.allow_growth = True Now when creating your session pass this config to it. sess = tf.Session(config=config)

worked for me

Tez01 avatar Dec 14 '18 19:12 Tez01

Don't use Jupyter notebook. Use a simple .py script. I know a known problem with notebook. It doesn't allow cuda to deallocate resources once the session is over which creates problems.

Thank you! This was driving me crazy for the longest time.

blakete avatar Jun 15 '19 21:06 blakete

Upgrading numpy works for me. pip install -U numpy

inspirepassion avatar Aug 11 '19 21:08 inspirepassion

This worked for me .. !pip install numpy --upgrade.

ram1209 avatar Sep 19 '19 01:09 ram1209

Quite unexpected that it was numpy caused this type of error: In jupyter notebook: Python Has Stopped Working In anaconda: KernelRestarter: restarting kernel (1/5), keep random ports

This worked for me:

Upgrading numpy works for me. pip install -U numpy

joeltorby avatar Sep 20 '19 08:09 joeltorby

Upgrading numpy works for me. pip install -U numpy

worked for me.

RuiWang1998 avatar Nov 02 '19 03:11 RuiWang1998

In case someone gets stuck (like me) and none of the above work, make sure you have a BLAS library. I installed libopenblas-dev, liblapack-dev through Synaptic (and all additional required changes), and got everything to work.

So I agree that the issue is -loosely speaking- numpy related :)

panosprotopapas avatar Nov 19 '19 10:11 panosprotopapas

uninstall tensorflow with pip uninstall tensorflow in consola and run again the jupyter.

patrick-code-dev avatar Jan 31 '20 22:01 patrick-code-dev

It worked for me - Follow the below steps - :) Download Python 3.6 - conda install python=3.6 Create a new conda environment- conda create --name newEnv To activate or deactive this environment use below commands - activate newEnv conda deactivate Activate your new Environment using activate newEnv If you want to use GPU - use this command - conda install -c anaconda keras-gpu for CPU use belwo command - conda install -c anaconda keras Now install other necessary libraries - Pandas - conda install -c anaconda pandas Sklearn - conda install -c anaconda scikit-learn I hope it helps! :) :)

DeeptiAgl avatar Feb 23 '20 18:02 DeeptiAgl

pip install --upgrade numpy worked for me thank you for your suggestions.

MuhammadNumanmn avatar Mar 15 '20 04:03 MuhammadNumanmn

I started a second Mac with exactly the same set-up, the same environment, which had nothing else then Anaconda and all its libraries and the code. Running it gave me the "Kernel Restarting The kernel appears to have died. It will restart automatically " msg immediately with the first "import Numpy as np" command. I reinstalled, updated, changed the order, renamed the Macs, rebooted 1000 times, tried for 5-6 hours all variations, it gave me always this msg ... I tried all here published ideas, no way. ... Have anybody an idea how to interrupt this videogame? Thanks

istvan1000 avatar Mar 27 '20 19:03 istvan1000

conda install nomkl worked on my computer (iMac, Tensorflow 2.0 which was installed with conda install -c anaconda tensorflow). However, it is really slow.

mehdirezaie avatar Mar 30 '20 16:03 mehdirezaie