使用tensorflow-gpu 訓練keras無法啟用cudnn的問題

Paul Tang
4 min readJan 15, 2020

--

說真的,雖然現在 Nvidia 以及 cuda 在 Linux 的安裝門檻大大降低了,但是每次安裝完系統都會有一種「啊~終於完成了」的感覺,而這個時候就是要拿最簡單的 mnist_cnn.py 來測試一番~

當然,這邊的前提是至少你能看到 nvcc 的版本以及 nvidia-smi 的 output,nvcc 代表 cuda,而 nvidia-smi 代表 nvidia driver。

但是如果近期你使用 tensorflow 為底層的 keras (不是新一代的tf.keras),執行 python mnist_cnn.py 的話,你很有可能(可能是一定)會遇到一個無法啟用 cudnn 的問題

錯誤訊息如下:

2020-01-16 00:25:55.881381: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR2020-01-16 00:25:55.901231: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR2020-01-16 00:25:55.901300: W tensorflow/core/common_runtime/base_collective_executor.cc:216] BaseCollectiveExecutor::StartAbort Unknown: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.

但是我們明明已經安裝 cudnn 了,也把 lib64 path 確實設定在 LD_LIBRARY_PATH 裡面,應該沒問題啊?

對,你沒問題,有問題的是 tensorflow ….

筆者搜尋了一下,發現了有一串 github 討論串在討論這件事情

簡單整理一下,如果你遇到這樣的問題,記得在訓練程式碼最前面加上這一段程式碼 ( for tensorflow 1.xx)

# for tf 1.xx
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.InteractiveSession(config=config)

如果是使用 tf 2.xx 的朋友呢?

很抱歉,tensorflow 沒有 ConfigProto 了,不過好險他只是放在其他的地方

# for tf 2.xx 
import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.InteractiveSession(config=config)

可能會有人覺得這樣加上 session 很奇怪,所以筆者拿 tensorflow 1.15.0 加上 keras.backend.get_session() 取得 keras 預設的 tf session,和我們剛剛加上的 session 做一個比較

print("the tf session we add", session)the tf session we add <tensorflow.python.client.session.InteractiveSession object at 0x7f96a09ce208>print("the keras session we use", keras.backend.get_session())the keras session we use <tensorflow.python.client.session.InteractiveSession object at 0x7f96a09ce208>

由此可見,他們是一樣的 session。

本篇心得分享就到這邊囉!!

--

--

Paul Tang
Paul Tang

Written by Paul Tang

初來乍到,剛到東京的菜鳥後端工程師,希望有一天能成為獨當一面的Full Stack Hacker

No responses yet