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

Linux系统下安装TensorFlow的GPU版本

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

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

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

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

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

准备:

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

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

如果你使用的是带图形界面的桌面版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的最低版本要求也不一样,2023年05月03日最新整理相关信息如下(已移除低版本的环境依赖列表,如有需要请查看下方信息来源链接原文内容):

TensorFlow版本Python版本CUDA版本cuDNN版本
tensorflow_gpu-2.12.03.8-3.1111.88.6
tensorflow_gpu-2.8.0~2.11.03.7-3.1011.28.1
tensorflow_gpu-2.7.03.7-3.911.28.1
tensorflow_gpu-2.5.0~2.6.03.6-3.911.28.1
tensorflow_gpu-2.4.03.5 ~ 3.811.08.0
tensorflow_gpu-2.2.0 ~ 2.3.03.5 ~ 3.810.17.6
tensorflow_gpu-2.1.02.7、3.5-3.710.17.6
tensorflow_gpu 1.15.x2.7、3.5-3.710.07.6
tensorflow_gpu-1.13.0 ~ 2.0.0 (不包含1.15.x)2.7、3.3-3.710.07.4

信息来源:

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

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

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

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

下载完成之后,执行

$ sudo sh cuda_11.8.0_520.61.05_linux.run

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

┌──────────────────────────────────────────────────────────────────────────────┐
│  End User License Agreement                                                  │
│  --------------------------                                                  │
│                                                                              │
│  NVIDIA Software License Agreement and CUDA Supplement to                    │
│  Software License Agreement. Last updated: October 8, 2021                   │
│                                                                              │
│  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: October 8, 2021.                                              │
│                                                                              │
│                                                                              │
│  Preface                                                                     │
│  -------                                                                     │
│                                                                              │
│──────────────────────────────────────────────────────────────────────────────│
│ Do you accept the above EULA? (accept/decline/quit):                         │
│ accept                                                                       │
└──────────────────────────────────────────────────────────────────────────────┘

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

┌──────────────────────────────────────────────────────────────────────────────┐
│ CUDA Installer                                                               │
│ - [X] Driver                                                                 │
│      [X] 520.61.05                                                           │
│ + [X] CUDA Toolkit 11.8                                                      │
│   [X] CUDA Demo Suite 11.8                                                   │
│   [X] CUDA Documentation 11.8                                                │
│ - [ ] Kernel Objects                                                         │
│      [ ] nvidia-fs                                                           │
│   Options                                                                    │
│   Install                                                                    │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│                                                                              │
│ Up/Down: Move | Left/Right: Expand | 'Enter': Select | 'A': Advanced options │
└──────────────────────────────────────────────────────────────────────────────┘

安装中Driver里面那个520.61.05的驱动,如果刚才没安装驱动,就保持现状选择安装,否则就移动光标并按空格键以选择不安装,因为之前已经安装驱动了。如果不知道该如何做,那么保持不变,不要动。最后,将光标移动到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环境变量:

在 ~/.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,详见:

这里我再重复一下

终端命令行输入

$ sudo pip3 install tensorflow-gpu==2.5.2

$ sudo pip3 install tensorflow==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柠檬博客”微信公众号,及时获取你最需要的干货。


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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

18 + 12 =

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