卷积算法获取失败。这可能是因为cuDNN初始化失败。

81
在Tensorflow/Keras中运行https://github.com/pierluigiferrari/ssd_keras的代码时,请使用estimator:ssd300_evaluation。我收到了这个错误信息。
“无法获取卷积算法。这可能是因为cuDNN初始化失败,因此请尝试查看是否在上面打印了警告日志消息。”
这与未解决的问题非常相似:Google Colab Error : Failed to get convolution algorithm.This is probably because cuDNN failed to initialize 我遇到的问题如下: python: 3.6.4。
Tensorflow版本:1.12.0。
Keras版本:2.2.4。
CUDA: V10.0。
cuDNN: V7.4.1.5。
NVIDIA GeForce GTX 1080。
我还运行了:
import tensorflow as tf
with tf.device('/gpu:0'):
      a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
      b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
      c = tf.matmul(a, b)
with tf.Session() as sess:
print (sess.run(c))

没有错误或问题。

最简单的例子是:

 from keras import backend as K
 from keras.models import load_model
 from keras.optimizers import Adam
 from scipy.misc import imread
 import numpy as np
 from matplotlib import pyplot as plt

 from models.keras_ssd300 import ssd_300
 from keras_loss_function.keras_ssd_loss import SSDLoss
 from keras_layers.keras_layer_AnchorBoxes import AnchorBoxes
 from keras_layers.keras_layer_DecodeDetections import DecodeDetections
 from keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast
 from keras_layers.keras_layer_L2Normalization import L2Normalization
 from data_generator.object_detection_2d_data_generator import DataGenerator
 from eval_utils.average_precision_evaluator import Evaluator
 import tensorflow as tf
 %matplotlib inline
 import keras
 keras.__version__



 # Set a few configuration parameters.
 img_height = 300
 img_width = 300
 n_classes = 20
 model_mode = 'inference'


 K.clear_session() # Clear previous models from memory.

 model = ssd_300(image_size=(img_height, img_width, 3),
            n_classes=n_classes,
            mode=model_mode,
            l2_regularization=0.0005,
            scales=[0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05], # The scales 
 for MS COCO [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05]
            aspect_ratios_per_layer=[[1.0, 2.0, 0.5],
                                     [1.0, 2.0, 0.5, 3.0, 1.0/3.0],
                                     [1.0, 2.0, 0.5, 3.0, 1.0/3.0],
                                     [1.0, 2.0, 0.5, 3.0, 1.0/3.0],
                                     [1.0, 2.0, 0.5],
                                     [1.0, 2.0, 0.5]],
            two_boxes_for_ar1=True,
            steps=[8, 16, 32, 64, 100, 300],
            offsets=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
            clip_boxes=False,
            variances=[0.1, 0.1, 0.2, 0.2],
            normalize_coords=True,
            subtract_mean=[123, 117, 104],
            swap_channels=[2, 1, 0],
            confidence_thresh=0.01,
            iou_threshold=0.45,
            top_k=200,
            nms_max_output_size=400)

 # 2: Load the trained weights into the model.

 # TODO: Set the path of the trained weights.
 weights_path = 'C:/Users/USAgData/TF SSD 
 Keras/weights/VGG_VOC0712Plus_SSD_300x300_iter_240000.h5'

 model.load_weights(weights_path, by_name=True)

 # 3: Compile the model so that Keras won't complain the next time you load it.

 adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)

 ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)

 model.compile(optimizer=adam, loss=ssd_loss.compute_loss)


dataset = DataGenerator()

# TODO: Set the paths to the dataset here.
dir= "C:/Users/USAgData/TF SSD Keras/VOC/VOCtest_06-Nov-2007/VOCdevkit/VOC2007/"
Pascal_VOC_dataset_images_dir = dir+ 'JPEGImages'
Pascal_VOC_dataset_annotations_dir = dir + 'Annotations/'
Pascal_VOC_dataset_image_set_filename = dir+'ImageSets/Main/test.txt'

# The XML parser needs to now what object class names to look for and in which order to map them to integers.
classes = ['background',
           'aeroplane', 'bicycle', 'bird', 'boat',
           'bottle', 'bus', 'car', 'cat',
           'chair', 'cow', 'diningtable', 'dog',
           'horse', 'motorbike', 'person', 'pottedplant',
           'sheep', 'sofa', 'train', 'tvmonitor']

dataset.parse_xml(images_dirs=[Pascal_VOC_dataset_images_dir],
                  image_set_filenames=[Pascal_VOC_dataset_image_set_filename],
                  annotations_dirs=[Pascal_VOC_dataset_annotations_dir],
                  classes=classes,
                  include_classes='all',
                  exclude_truncated=False,
                  exclude_difficult=False,
                  ret=False)



evaluator = Evaluator(model=model,
                      n_classes=n_classes,
                      data_generator=dataset,
                      model_mode=model_mode)



results = evaluator(img_height=img_height,
                    img_width=img_width,
                    batch_size=8,
                    data_generator_mode='resize',
                    round_confidences=False,
                    matching_iou_threshold=0.5,
                    border_pixels='include',
                    sorting_algorithm='quicksort',
                    average_precision_mode='sample',
                    num_recall_points=11,
                    ignore_neutral_boxes=True,
                    return_precisions=True,
                    return_recalls=True,
                    return_average_precisions=True,
                    verbose=True)

如果使用Conda环境,在我的情况下,问题是通过安装tensorflow-gpu而不是CUDAtoolkit或cuDNN解决的,因为它们已经被tensorflow-gpu安装(请参见此答案)。但请注意,新的conda tensorflow-gpu版本可能不会安装CUDAtoolkit或cuDNN -> 解决方法是安装较低版本的tensorflow-gpu,然后使用pip升级它(请参见此答案)。 - Javier TG
30个回答

112

我曾经遇到过这个错误信息,原因有三种,解决方法也各不相同:

1. 缓存问题

我通常通过关闭Python进程,删除~/.nv目录(在Linux上,使用rm -rf ~/.nv命令),然后重新启动Python进程来解决此错误。我不确定为什么这样做有效。可能与第二种选项有关:

2. 内存不足

如果你的图形卡内存不足,也会出现此错误。对于nvidia GPU,可以使用nvidia-smi检查显卡内存使用情况。这将给出一个读数,显示GPU RAM使用量(如果接近极限,则类似于6025MiB / 6086MiB),以及正在使用GPU RAM的进程列表。

如果你已经用完了RAM,那么你需要重新启动进程(这应该会释放RAM),然后采取更少内存的方法。几个选项是:

  • 减少批处理大小
  • 使用更简单的模型
  • 使用更少的数据
  • 限制TensorFlow GPU内存分数:例如,以下内容将确保TensorFlow使用<= 90%的RAM:
import keras
import tensorflow as tf

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9  # 0.6 sometimes works better for folks
keras.backend.tensorflow_backend.set_session(tf.Session(config=config))

如果不与上述项目一起使用,这可能会减慢您的模型评估速度,因为大型数据集将必须被交换并适应您分配的小内存。

第二个选项是让TensorFlow从最低限度的内存开始使用,然后根据需要分配更多内存(记录在这里):

os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'

3. 您的CUDA版本、TensorFlow版本、NVIDIA驱动程序等不兼容。

如果您以前从未运行过类似的模型,且您没有VRAM不足的问题并且您的缓存已清除,我建议您回到安装CUDA + TensorFlow的最佳指南进行设置 - 我根据以下网址中的说明获得了最大的成功率:https://www.tensorflow.org/install/gpu而不是NVIDIA / CUDA网站上的指导。 Lambda Stack 也是一个不错的选择。


14
由于我只是内存不足,所以我会给这个答案点赞。 - Carlos B
2
在我的情况下,问题出在不兼容的版本上。如果您仔细注意像=或>=这样的运算符,那么https://tensorflow.org/install/gpu中的说明是准确的。最初我认为“相等或更新”,但是对于TensorFlow 2.2(似乎需要像2.1一样处理),您需要确切地使用与CUDA 10.1兼容的>= CuDNN 7.6和CUDA 10.1(目前,只有7.6.5 - 并且有两个不同的版本适用于CUDA 10.2和10.1)。 - Heath
1
这对我来说也是一次记忆。感谢您提供深入的解释。 - natsuozawa
1
在我的情况下,这是内存不足的问题。而你针对 0.6 的代码对我很有效。谢谢。 - Nitesh
1
我一直在缺少内存。一个后台进程占用了我的GPU内存。使用htopnvidia-smi交叉检查进程ID。 - 24dinitrophenylhydrazine

47

我遇到了同样的问题,我通过以下方式解决:

os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
或者
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
   tf.config.experimental.set_memory_growth(physical_devices[0], True)

8
第一种解决方案像魔术一样解决了它。因此可能没有解决问题的根源。 - Inyoung Kim 김인영
1
这似乎是目前非常普遍的问题,我在GitHub和Medium上找到了类似的解决方案。对我也起作用,因此可能是当前TF或CuDNN版本的问题,而不是安装不正确的问题。具体来说,这是CNN层的问题,无论大小如何。其他操作/层都没问题。 - Denziloe
2
第一种解决方案对我也非常有效。 - ThisIsNotMe
1
谢谢!这个解决方案对我也起作用了。我只是使用了这里最受欢迎的答案的方法(除了重新安装),但它没有起作用。我想将所有在此线程中描述的措施制作成一个配方,这将是一个好主意。 - jottbe

15

我之前遇到了这个错误,通过卸载系统中的所有CUDA和cuDNN版本进行修复。然后我安装了CUDA Toolkit 9.0(没有任何补丁)和适用于CUDA 9.0的cuDNN v7.4.1


你也可以将 TensorFlow 版本降级。 - Vidit Varshney
3
我遇到了相同的错误,导致这个错误的原因是cudaa/cudnn的版本与你的tensorflow版本不匹配。有两种方法可以解决这个问题:要么你降低你的Tensorflow版本,使用以下命令:pip install --upgrade tensorflow-gpu==1.8.0或者你可以按照 https://www.tensorflow.org/install/gpu 上的步骤进行操作。提示:选择你的Ubuntu版本并按照步骤操作。 :-) - Vidit Varshney
对我来说,这是CUDA和cuDNN之间的不匹配。用相应版本替换cuDNN库解决了这个问题。 - Fang Zhang
2
这不是实际的解决方案,只是某种程度上对你起作用了。请查看 https://dev59.com/uVQJ5IYBdhLWcg3wg2JP#56511889 获取实际解决方案。 - Shrijit Basak
我该如何在Windows 10上下载CUDA Toolkit 9.0? - Wang Liang

7
我曾经在使用Tensorflow 2.4和Cuda 11.0以及CuDNN v8.0.4时遇到了同样的问题。我浪费了将近2到3天的时间来解决这个问题。问题只是驱动程序不匹配。我安装了Cuda 11.0更新1版,我认为这是更新1版,可能会有很好的效果,但这正是罪魁祸首。我卸载了Cuda 11.0更新1版,然后安装了没有更新的版本。
以下是适用于RTX 2060 6GB GPU的TensorFlow 2.4所需的驱动程序列表。 此处列出了所需的硬件和软件要求清单。
我还需要执行以下操作。
import tensorflow as tf
physical_devices = tf.config.list_physical_devices('GPU') 
tf.config.experimental.set_memory_growth(physical_devices[0], True)

为避免此错误

2020-12-23 21:54:14.971709: I tensorflow/stream_executor/stream.cc:1404] [stream=000001E69C1DA210,impl=000001E6A9F88E20] did not wait for [stream=000001E69C1DA180,impl=000001E6A9F88730]
2020-12-23 21:54:15.211338: F tensorflow/core/common_runtime/gpu/gpu_util.cc:340] CPU->GPU Memcpy failed
[I 21:54:16.071 NotebookApp] KernelRestarter: restarting kernel (1/5), keep random ports
kernel 8b907ea5-33f1-4b2a-96cc-4a7a4c885d74 restarted
kernel 8b907ea5-33f1-4b2a-96cc-4a7a4c885d74 restarted

以下是我遇到的一些错误样本

类型 1

UnpicklingError: invalid load key, 'H'.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-2-f049ceaad66a> in <module>

类型 2


InternalError: Blas GEMM launch failed : a.shape=(15, 768), b.shape=(768, 768), m=15, n=768, k=768 [Op:MatMul]

During handling of the above exception, another exception occurred:

类型 3

failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.534375: E tensorflow/stream_executor/cuda/cuda_blas.cc:226] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.534683: E tensorflow/stream_executor/cuda/cuda_blas.cc:226] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.534923: E tensorflow/stream_executor/cuda/cuda_blas.cc:226] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.539327: E tensorflow/stream_executor/cuda/cuda_dnn.cc:336] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.539523: E tensorflow/stream_executor/cuda/cuda_dnn.cc:336] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2020-12-23 21:31:04.539665: W tensorflow/core/framework/op_kernel.cc:1763] OP_REQUIRES failed at conv_ops_fused_impl.h:697 : 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.


6

Keras已经包含在TensorFlow 2.0及以上版本中。

  • 移除import keras语句,并
  • from keras.module.module import class语句替换为--> from tensorflow.keras.module.module import class
  • 可能您的GPU内存已满,因此请在GPU选项中使用allow growth = True。虽然该选项现已弃用,但是在导入后使用以下代码片段可能会解决您的问题。
import tensorflow as tf
from tensorflow.compat.v1.keras.backend import set_session
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True  # dynamically grow the memory used on the GPU
config.log_device_placement = True  # to log device placement (on which device the operation ran)
sess = tf.compat.v1.Session(config=config)
set_session(sess)

1
感谢您的完美答案!它对我帮助很大。 - Saurabh Chauhan

4

只需添加

from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession

config = ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)

添加 from tensorflow.compat.v1 import ConfigProto - toliveira

4

这是对 https://dev59.com/uVQJ5IYBdhLWcg3wg2JP#56511889 第2点的跟进。

2. 内存不足

我使用以下代码来限制GPU RAM的使用:

import tensorflow as tf

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1*X GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=(1024*4))])
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

以下代码示例来自:TensorFlow: 使用 GPU:限制 GPU 内存增长 将此代码放在您使用的任何 TF/Keras 代码之前。

注意:应用程序可能仍会使用比上面的数字稍多的 GPU RAM。

注意2:如果系统还运行其他应用程序(如 UI),这些程序也可以消耗一些 GPU RAM。(Xorg、Firefox 等有时组合起来最高可达 1GB 的 GPU RAM)


4
问题出在新版本的tensorflow 1.10.x及以上与cudnn 7.0.5和cuda 9.0不兼容。最简单的解决方法是将tensorflow降级至1.8.0版本。

pip install --upgrade tensorflow-gpu==1.8.0


3
我遇到了同样的问题,但是在代码开头添加这几行解决了我的问题:
physical_devices = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)

适用于TensorFlow V2。


在CentOS 7中,针对tensorflow-gpu 2.2、cuda 10.2和cudnn 7.4.2,我尝试了但不起作用,错误提示要我安装cudnn 7.6.4。 - Mona Jalal
@MonaJalal 你可以降级TensorFlow或升级你的CUDNN以进行兼容性检查,请参考此链接:https://www.tensorflow.org/install/source#gpu - Haziq Sheikh

3
我遇到了同样的错误,出错的原因是cudaa/cudnn版本与您的tensorflow版本不匹配,有两种方法可以解决这个问题:
  1. 降级你的Tensorflow版本:pip install --upgrade tensorflow-gpu==1.8.0

  2. 或者按照这里的步骤操作。

    提示:请选择您的Ubuntu版本并按照步骤进行操作。:-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接