分类
综合技术 长期更新的内容

Linux系统下安装TensorFlow的GPU版本

(在苹果系统下,如果文章中的图片不能正常显示,请升级Safari浏览器到最新版本,或者使用Chrome、Firefox浏览器打开。)

本文已在2021年11月更新到最新方法,确保本文教程的有效性。

前言:
曾经(2017年)安装TensorFlow的GPU版本真的不是一件容易的事,好难(因为能用的教程很少,有些连最基本的一些必需的步骤都没写到,那样子的话能安装到位才是奇迹),但是现在不会了,因为本文出现了,本文是为数不多的可用教程

在经历各种踩坑后,我终于总结出来一个走的通的安装tensorflow-gpu的方法,并且亲自动手实践,在Linux(Ubuntu) + Python3安装且运行成功。

Python2.7下安装过程跟本文内容大同小异,可参考NVIDIA官方教程:
http://www.nvidia.com/object/gpu-accelerated-applications-tensorflow-installation.html

现在(2020年之后)不要使用Python2,因为其已经被官方停止维护。

如果已经安装过旧版CUDA,需要重新安装新版CUDA,请先参考这篇文章:

linux卸载旧版CUDA并安装新版CUDA

准备:

  • 一块计算性能大于等于3.0的NVIDIA的显卡
    (不知道自己的NVIDIA GPU的计算性能的可以在这里查到: https://developer.nvidia.com/cuda-gpus )
    推荐使用Tesla、Quadro系列或GTX/RTX 1080、2070以上系列显卡做深度学习(至少要保证有8GB显存空间,推荐使用具有11-16GB或者以上显存空间的显卡),消费级游戏显卡(1060、1660等)还是趁早放弃吧,让老板给你们氪金买个好点的显卡。
  • 装有Linux系统的电脑
    (本文以Ubuntu 18.04 LTS 64位系统为例展开,其他的也是大同小异)
    建议的系统为Ubuntu 18.04、20.04、16.04(已停止主流支持),以及CentOS 7、8系列,而且必须是64位的。
  • Python 3.6 – 3.9
    (请使用Python3版本,而不是2.7版)

关闭图形界面,使用纯命令行:

如果你使用的是带图形界面的桌面版Ubuntu系统,那么首先需要关闭图形界面:

$ sudo systemctl stop lightdm

当全部操作结束后,再开启图形界面:

$ sudo systemctl start lightdm

开始:

安装NVIDIA Driver (可以跳过,并直接使用CUDA安装包自动安装)

首先检查你的NVIDIA VGA card model,检查你的显卡型号

$ sudo lshw -numeric -C display

我的电脑上可以看到其中的nvidia显卡有这样一条信息

product: GP100GL [Tesla P100 PCIe 12GB] [10DE:15F7]

根据刚才显示的信息内容,到官网上选择合适的选项,检查你的显卡所适合的驱动版本:

http://www.nvidia.com/Download/index.aspx

我的电脑上的显卡所适合的版本是460.73.01。

同样,你还可以在终端上输入命令来看所需的版本:

$ ubuntu-drivers devices

我的电脑上出现有nividia-460字样,跟在官网上查的一样。所以我们可以在终端上使用apt来安装它,安装前建议先update一下源,或者更换一个速度快的源。

在Ubuntu系列系统中,我们只需要使用下面一行命令,即可一键自动地正确安装Nvidia显卡驱动,不需要使用任何其他的手动安装方式,简单高效便捷。

$ sudo apt install nvidia-460

其中,nvidia-460这个需要根据自己显卡的型号所支持的驱动版本来修改后面的数字。

如果您比较喜欢折腾或者想自己动手练习一步一步安装的话,可以考虑从官网上下载驱动来安装,但是AI柠檬不建议您这样做,因为您的时间是宝贵的,不要将有限的时间和精力投入到繁琐的装显卡驱动的操作中。

装完之后,你可以在dashboard上搜索nvidia,看到有 NVIDIA X Server Settings的东西,那么驱动就安装成功了,如果没有,那就重启一次电脑看看。

安装Cuda:

TensorFlow从最初的版本到现在,也已经有很多种版本了,很多以前的一些资料都不适用了。不同的TensorFlow的版本,所需要的CUDA和cuDNN的最低版本要求也不一样,2021年08月10日最新整理相关信息如下:

TensorFlow版本 Python版本 CUDA版本 cuDNN版本
tensorflow_gpu-2.5.0~2.6.0 3.6-3.9 11.2 8.1
tensorflow_gpu-2.4.0 3.5 ~ 3.8 11.0 8.0
tensorflow_gpu-2.2.0 ~ 2.3.0 3.5 ~ 3.8 10.1 7.6
tensorflow_gpu-2.1.0 2.7、3.5-3.7 10.1 7.6
tensorflow_gpu 1.15.x 2.7、3.5-3.7 10.0 7.6
tensorflow_gpu-1.13.0 ~ 2.0.0

(不包含1.15.x)

2.7、3.3-3.7 10.0 7.4
tensorflow_gpu-1.5.0 ~ 1.12.0 2.7、3.3-3.6 9 7
tensorflow_gpu-1.3.0 ~ 1.4.0 2.7、3.3-3.6 8 6
tensorflow_gpu-1.0.0 ~ 1.2.0 2.7、3.3-3.6 8 5.1

当前,所有版本均需要GCC的版本为4.8(从源码编译安装的话)。

信息来源:

https://www.tensorflow.org/install/source

而CUDA需要根据自己计算机中显卡支持的驱动的版本来下载,如果电脑的显卡最高只能支持到Cuda 10,或者最低必须11.0以上,那么tf也就最高只能使用2.3版本和最低要求必须2.4以上了。一般来说,在服务器上Tesla计算卡支持所有CUDA版本,可以支持所有TF版本。我在服务器上安装了11.2版本的Cuda,其他的Cuda版本可以借鉴以下内容,就是注意一下版本号的不同即可。

首先是去官网下载 cuda toolkit download ,确认好需要的CUDA版本,比如11.2,如果不是当前最新版本的话,那么就要到 Archive of Previous CUDA Releases 先前发布版本页面找到需要的版本来下载,然后请确认你电脑对应的选项,操作系统版本,架构平台,和发行版本号,下载文件一定要选择runfile。如果选错了会导致安装失败,切记。

https://developer.nvidia.com/cuda-downloads

下载完成之后,执行

$ sudo bash cuda_11.2.0_460.27.04_linux.run

就进入安装了,开始的一大堆文字都是End User License Agreement,输入accept表示接受协议

┌──────────────────────────────────────────────────────────────────────────────┐
│  End User License Agreement                                                  │
│  --------------------------                                                  │
│                                                                              │
│  The CUDA Toolkit End User License Agreement applies to the                  │
│  NVIDIA CUDA Toolkit, the NVIDIA CUDA Samples, the NVIDIA                    │
│  Display Driver, NVIDIA Nsight tools (Visual Studio Edition),                │
│  and the associated documentation on CUDA APIs, programming                  │
│  model and development tools. If you do not agree with the                   │
│  terms and conditions of the license agreement, then do not                  │
│  download or use the software.                                               │
│                                                                              │
│  Last updated: Nov 2, 2020.                                                  │
│                                                                              │
│                                                                              │
│  Preface                                                                     │
│  -------                                                                     │
│                                                                              │
│  The Software License Agreement in Chapter 1 and the Supplement              │
│  in Chapter 2 contain license terms and conditions that govern               │
│  the use of NVIDIA software. By accepting this agreement, you                │
│──────────────────────────────────────────────────────────────────────────────│
│ Do you accept the above EULA? (accept/decline/quit):                         │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

接下来就是安装的交互界面,根据提示一步一步进行就好。

┌──────────────────────────────────────────────────────────────────────────────┐
│ CUDA Installer                                                               │
│ - [X] Driver                                                                 │
│      [X] 460.27.04                                                           │
│ + [X] CUDA Toolkit 11.2                                                      │
│   [X] CUDA Samples 11.2                                                      │
│   [X] CUDA Demo Suite 11.2                                                   │
│   [X] CUDA Documentation 11.2                                                │
│   Options                                                                    │
│   Install                                                                    │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│ Up/Down: Move | Left/Right: Expand | 'Enter': Select | 'A': Advanced options │
└──────────────────────────────────────────────────────────────────────────────┘

安装中Driver里面那个460.27.04的驱动,如果刚才没安装驱动,就保持现状选择安装,否则就移动光标并按空格键以选择不安装,因为之前已经安装驱动了。如果不知道该如何做,那么保持不变,不要动。最后,将光标移动到Install选项,并按下回车键,等待片刻。安装完成后显示:

===========
= Summary =
===========

Driver:   Installed
Toolkit:  Installed in /usr/local/cuda-11.2/
Samples:  Installed in /home/gpu01/, but missing recommended libraries

Please make sure that
 -   PATH includes /usr/local/cuda-11.2/bin
 -   LD_LIBRARY_PATH includes /usr/local/cuda-11.2/lib64, or, add /usr/local/cuda-11.2/lib64 to /etc/ld.so.conf and run ldconfig as root

To uninstall the CUDA Toolkit, run cuda-uninstaller in /usr/local/cuda-11.2/bin
To uninstall the NVIDIA Driver, run nvidia-uninstall
Logfile is /var/log/cuda-installer.log

旧版本CUDA(8.0 / 9.0)等版本的交互显示如下(用新版本的话请忽略),供参考:

Using more to view the EULA.

End User License Agreement

--------------------------

Preface

-------

The following contains specific license terms and conditions

for four separate NVIDIA products. By accepting this

agreement, you agree to comply with all the terms and

conditions applicable to the specific product(s) included

herein.


NVIDIA CUDA Toolkit


Description

 

The NVIDIA CUDA Toolkit provides command-line and graphical

tools for building, debugging and optimizing the performance

of applications accelerated by NVIDIA GPUs, runtime and math

libraries, and documentation including programming guides,

user manuals, and API references. The NVIDIA CUDA Toolkit

License Agreement is available in Chapter 1.

 

Default Install Location of CUDA Toolkit

 

Windows platform:

 

Do you accept the previously read EULA?

accept/decline/quit: accept

 

Install NVIDIA Accelerated Graphics Driver for Linux-x86_64 410.48?

(y)es/(n)o/(q)uit: n

 

Install the CUDA 9.0 Toolkit?

(y)es/(n)o/(q)uit: y

 

Enter Toolkit Location

 [ default is /usr/local/cuda-9.0 ]: 

 

Do you want to install a symbolic link at /usr/local/cuda?

(y)es/(n)o/(q)uit: y

 

Install the CUDA 9.0 Samples?

(y)es/(n)o/(q)uit: y



Enter CUDA Samples Location

 [ default is /home/kinny ]:

Installing the CUDA Toolkit in /usr/local/cuda-9.0 ...

Missing recommended library: libXmu.so

Installing the CUDA Samples in /home/kinny ...

Copying samples to /home/kinny/NVIDIA_CUDA-9.0_Samples now...

Finished copying samples.

===========

= Summary =

===========

Driver:   Not Selected

Toolkit:  Installed in /usr/local/cuda-9.0

Samples:  Installed in /home/kinny, but missing recommended libraries

Please make sure that

 -   PATH includes /usr/local/cuda-9.0/bin

 -   LD_LIBRARY_PATH includes /usr/local/cuda-9.0/lib64, or, add /usr/local/cuda-9.0/lib64 to /etc/ld.so.conf and run ldconfig as root

To uninstall the CUDA Toolkit, run the uninstall script in /usr/local/cuda-9.0/bin

Please see CUDA_Installation_Guide_Linux.pdf in /usr/local/cuda-9.0/doc/pdf for detailed information on setting up CUDA.

***WARNING: Incomplete installation! This installation did not install the CUDA Driver. A driver of version at least 361.00 is required for CUDA 9.0 functionality to work.

To install the driver using this installer, run the following command, replacing <CudaInstaller> with the name of this run file:

    sudo <CudaInstaller>.run -silent -driver

Logfile is /tmp/cuda_install_17494.log

 配置Cuda环境变量:

在 ~/.bashrc 的最后添加

export PATH=/usr/local/cuda-11.2/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-11.2/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
export CUDA_HOME=/usr/local/cuda

其中,

前 2 个(PATH, LD_LIBRARY_PATH) 是 CUDA 官网安装文档中建议的变量。

第 3 个(CUDA_HOME)是 tensorflow-GPU 版本要求的变量。

配置完环境变量之后,一定要重载.bashrc文件更新一下环境,否则不能立即生效。也可以通过重启电脑使得环境变量生效。

$ source ~/.bashrc

网上很多其他的相关教程都遗漏了这一步,对于新手来说,这是致命的灾难,往往会出现,明明按照教程配置的,却根本无法使用GPU的情况。

检查显卡驱动安装结果

$ nvidia-smi
Wed Nov  3 16:37:23 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.27.04    Driver Version: 460.27.04    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla P100-PCIE...  Off  | 00000000:06:00.0 Off |                    0 |
| N/A   28C    P0    29W / 250W |      0MiB / 12198MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

 安装深度学习库cuDNN

上文提到过,不同版本的TensorFlow需要的cuDNN版本也不一样,如果我安装tf2.5,那么就是需要CUDA 11.2 + cuDNN 8.1。而当前各个情况下不同版本的配置要求详见上文刚才所述内容。

首先到官网下载cuDNN ( https://developer.nvidia.com/cudnn ),需要注册为开发者才能下载,而且直接下载可能速度非常慢,如果已有别人下载好的,应该是可以直接拿过来用,不过前提是版本是你需要的。

文件名为:cudnn-11.2-linux-x64-v8.1.0.77.tgz

如果文件文件拓展名是.solitairetheme8等后缀的话(一些旧版本cudnn包,新版本应该不会有,这里只是做个示例)需要先用mv命令改名再解压,否则可以直接指定下面第2行:

$ mv cudnn-11.2-linux-x64-v8.1.0.77.solitairetheme8 cudnn-11.2-linux-x64-v8.1.0.77.tgz
$ tar zxf cudnn-11.2-linux-x64-v8.1.0.77.tgz

然后将库和头文件copy到cuda目录(一定是你自己安装的目录如/usr/local/cuda-11.2),不过正确安装的话,ubuntu一般就会有软链接/usr/local/cuda -> /usr/local/cuda-11.2/

$ sudo cp cuda/include/cudnn.h /usr/local/cuda/include

$ sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64

接下来就是修改文件访问权限:

$ sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*

 最后一步:安装TensorFlow的GPU版本

在我博客的前一篇文章中,我写了如何安装支持GPU版本的TensorFlow,详见:

在多平台上安装TensorFlow的方法

这里我再重复一下

终端命令行输入

$ sudo pip3 install tensorflow-gpu==2.5.2

可根据自己的需要将2.5改为其他版本。等待一会儿,就安装好了。然后可以使用我刚才提到的那篇文章中的测试代码验证是否安装成功,以及GPU是否可用。

以下这段代码仅针对tf 1.x可用,tf2.x 不适用。

$ python3
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
Hello, TensorFlow!
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> print(sess.run(a + b))
42
>>>

以下这段代码适用于tf2.x:

$ python
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> hello.numpy()
b'Hello, TensorFlow!'
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> c = a + b
>>> c.numpy()
42
>>> 

对于GPU版本,可以使用下面的代码来测试TF是否可以使用GPU来加速计算,如果输出False,那就是不能使用,否则是可以使用,会输出GPU信息。以下这段代码所有版本tensorflow均可用。

>>> tf.test.is_gpu_available()
WARNING:tensorflow:From <stdin>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
2021-11-03 17:24:05.891745: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-11-03 17:24:05.894300: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1
2021-11-03 17:24:06.450754: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1733] Found device 0 with properties:
pciBusID: 0000:06:00.0 name: Tesla P100-PCIE-12GB computeCapability: 6.0
coreClock: 1.3285GHz coreCount: 56 deviceMemorySize: 11.91GiB deviceMemoryBandwidth: 511.41GiB/s
2021-11-03 17:24:06.450814: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
2021-11-03 17:24:06.454440: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublas.so.11
2021-11-03 17:24:06.454500: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublasLt.so.11
2021-11-03 17:24:06.455616: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcufft.so.10
2021-11-03 17:24:06.455885: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcurand.so.10
2021-11-03 17:24:06.459100: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcusolver.so.11
2021-11-03 17:24:06.459875: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcusparse.so.11
2021-11-03 17:24:06.460034: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudnn.so.8
2021-11-03 17:24:06.461785: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1871] Adding visible gpu devices: 0
2021-11-03 17:24:06.461830: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
2021-11-03 17:24:07.120614: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1258] Device interconnect StreamExecutor with strength 1 edge matrix:
2021-11-03 17:24:07.120661: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1264] 0
2021-11-03 17:24:07.120674: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1277] 0: N
2021-11-03 17:24:07.123297: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1418] Created TensorFlow device (/device:GPU:0 with 11321 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-12GB, pci bus id: 0000:06:00.0, compute capability: 6.0)
True

至此,如果你看到了跟我一样的输出的话,那么恭喜你,tensorflow-gpu可以正常使用GPU来计算了。

如果你是使用的图形界面的系统的话,不要忘记再开启图形界面哦。

后记:

博主曾在给工作站配置的时候,import tensorflow之后遇到过一个这样的报错:

ImportError: libcudnn.6: cannot open shared object file:
  No such file or directory

详见 StackOverflow 42013316

这是因为我安装的1.4版的TF,却装了7.0版本的cuDNN,而不是tensorflow默认寻找的6.0版本,这时只需要使用 ” ln “命令创建一个名为“libcudnn.6”的软连接指向“libcudnn.7.0*”即可,然后,tensorflow即可正常使用了。但是博主建议还是直接安装6.0,否则基于tensorflow的一些其他框架比如keras可能无法正常使用tf来训练。

版权声明
本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。
本文地址: https://blog.ailemon.net/2017/06/06/install-tensorflow-gpu-on-ubuntu-linux/
All articles are under Attribution-NonCommercial-ShareAlike 4.0

关注“AI柠檬博客”微信公众号,及时获取你最需要的干货。


AI柠檬博主正在阿里云上出售域名 “y403.com”,感兴趣就快去看看吧

“Linux系统下安装TensorFlow的GPU版本”上的1条回复

发表回复

您的电子邮箱地址不会被公开。

如果您是第一次在本站发布评论,内容将在博主审核后显示,请耐心等待