如何构建一台机器学习服务器
Version:V1.0
Author:NeoNexus
Date:2024.03.26
服务器设计要求:高性能、满足同时多人开发的需求、架构清晰、后期方便维护。因此写下此文档。
基于 最先进的架构、最先进硬件。
监修中敬告
本文处于Preview阶段,不对文章内容负任何责任,如有意见探讨欢迎留言。
联系方式——绿泡泡:NeoNexusX
系统信息
系统安装
系统安装这里就不再赘述,推荐使用ventory作为PE盘,来安装系统,这样方便快捷,可同时包含多个镜像,无需重复制作,需要注意的是在安装系统的时候需要手动进行分区,我们可以看一下我的分区结果:
在安装系统之后请先确认系统版本等内容和预想一致:
使用命令:
uname -m && cat /etc/*release
结果:
x86_64 DISTRIB_ID=Ubuntu DISTRIB_RELEASE=22.04 DISTRIB_CODENAME=jammy DISTRIB_DESCRIPTION="Ubuntu 22.04.3 LTS" PRETTY_NAME="Ubuntu 22.04.3 LTS" NAME="Ubuntu" VERSION_ID="22.04" VERSION="22.04.3 LTS (Jammy Jellyfish)" VERSION_CODENAME=jammy ID=ubuntu ID_LIKE=debian HOME_URL="https://www.ubuntu.com/" SUPPORT_URL="https://help.ubuntu.com/" BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" UBUNTU_CODENAME=jammy
GCC版本:
gcc --version
bionet@Bionet:/usr/local/cuda-12.4$ gcc --version gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Copyright (C) 2021 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
由于后边要配置cuda信息,这里就直接先把需求放上来,各位要看符不符合要求:
下图由CUDA官方文档发布:1. Introduction — Installation Guide for Linux 12.4 documentation (nvidia.com)
硬件配置:
硬件安装指南
由于服务器上存在几个残缺的pcie插槽,什么叫残缺的呢?如下图:
不适合安装显卡,所以通过转接版来安装PCIE下的NVME协议M.2接口固态硬盘,其优点是稳定,速度快。
相比普通的SATA顺序读写快上5倍~10倍,测试效果如下:

CPU
bionet@Bionet:~$ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz CPU family: 6 Model: 79 Thread(s) per core: 2 Core(s) per socket: 8 Socket(s): 2 Stepping: 1 CPU max MHz: 3000.0000 CPU min MHz: 1200.0000 BogoMIPS: 4199.71 NUMA: NUMA node(s): 2 NUMA node0 CPU(s): 0-7,16-23 NUMA node1 CPU(s): 8-15,24-31
GPU
bionet@Bionet:~$ nvidia-smi Sat Mar 23 19:30:36 2024 +---------------------------------------------------------------------------------------+ | NVIDIA-SMI 535.161.07 Driver Version: 535.161.07 CUDA Version: 12.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 NVIDIA GeForce RTX 2080 Ti Off | 00000000:04:00.0 Off | N/A | | 0% 27C P8 16W / 300W | 1MiB / 11264MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 1 NVIDIA GeForce RTX 4090 Off | 00000000:09:00.0 Off | Off | | 0% 29C P8 20W / 450W | 1MiB / 24564MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 2 NVIDIA GeForce RTX 2080 Ti Off | 00000000:86:00.0 Off | N/A | | 0% 28C P8 13W / 300W | 1MiB / 11264MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 3 NVIDIA GeForce RTX 3090 Off | 00000000:8A:00.0 Off | N/A | | 0% 23C P8 7W / 370W | 1MiB / 24576MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ +---------------------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=======================================================================================| | No running processes found | +---------------------------------------------------------------------------------------+
简单查询:
bionet@Bionet:~$ nvidia-smi --query-gpu=index,name,uuid,serial --format=csv index, name, uuid, serial 0, NVIDIA GeForce RTX 2080 Ti, GPU-2fdf7ca3-be62-5646-3d62-2e2db057e8b2, [N/A] 1, NVIDIA GeForce RTX 4090, GPU-3d19dd88-2507-8278-5045-9f68011b7ce0, [N/A] 2, NVIDIA GeForce RTX 2080 Ti, GPU-6384bfe4-3e8a-18a2-2132-fc5e686d1404, [N/A] 3, NVIDIA GeForce RTX 3090, GPU-d91f3e9a-e7d0-4f91-2798-1d8b05587fb6, [N/A]
验证显卡速率正常:
nvidia-smi -i 0 -q
指定GPUID来实现,0为0号设备,再输出信息中找到:
16x带宽为正常
硬盘分区结果
以太网和IP设置
使用命令查看目前已安装的,能检测到对应的驱动的网卡信息:
bionet@Bionet:~$ lspci | grep -i 'eth'
结果如下:
81:00.0 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01) 81:00.1 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01) #双千兆网口
基础内容配置
Jetbrain IDE & VSCode安装
Jetbrain系IDE针对在校大学生都是免费的,该如何申请JetBrian系的IDE呢?
详见此文,申请后就拥有了一个免费的JetBrain全家桶账号,非常方便,可以使用他们家的全部IDE,关于IDE的使用和优化,可以参考我的专栏:Jetbrain入门指南 - 文章分类 - NeoNexus - 博客园 (cnblogs.com)
为了方便管理和使用IDE这里使用Toolbox来操作IDE:
首先下载ToolBox:
下载之后是一个.tar.gz的压缩包,我们使用命令解压即可:
tar -zxvf 文件名.tar.gz
其中,-z 表示使用 gzip 解压缩,-x 表示解压缩,-v 表示显示详细信息,-f 表示指定文件名。
(base) bionet@Bionet:~/Downloads$ tar -zxvf ./jetbrains-toolbox-2.2.3.20090.tar.gz
如下图所示解压之后效果如下:
jetbrains-toolbox-2.2.3.20090/ jetbrains-toolbox-2.2.3.20090/jetbrains-toolbox (base) bionet@Bionet:~/Downloads$ ls Anaconda3-2024.02-1-Linux-x86_64.sh jetbrains-toolbox-2.2.3.20090 cudnn-local-repo-ubuntu2204-9.0.0_1.0-1_amd64.deb jetbrains-toolbox-2.2.3.20090.tar.gz
将解压过后的文件夹的内容迁移到我们规定的目录,命令执行如下:
base) bionet@Bionet:~/Downloads$ sudo mv jetbrains-toolbox-2.2.3.20090 jetbrain-toolbox-2.2.3 [sudo] password for bionet: (base) bionet@Bionet:~/Downloads$ ls Anaconda3-2024.02-1-Linux-x86_64.sh jetbrains-toolbox-2.2.3.20090.tar.gz cudnn-local-repo-ubuntu2204-9.0.0_1.0-1_amd64.deb jetbrain-toolbox-2.2.3 (base) bionet@Bionet:~/Downloads$ sudo mv ./jetbrain-toolbox-2.2.3 /home/jetbrain-toolbox-2.2.3 (base) bionet@Bionet:~/Downloads$ cd /home/ (base) bionet@Bionet:/home$ ls anaconda3 bionet jetbrain-toolbox-2.2.3 lost+found Neo
同时将其添加到启动项中:
添加即可:

用户登录之后toolbox就可以启动:
登录过程稍微有点慢,慢慢等就行。
当然选择之后登陆即可下载对应的IDE:

效果如下:
需要注意的是我们需要修改安装路径到指定位置:
我们在管理用户的Home下创建一个文件夹来专门存放IDE,这样每个用户就不需要重复下载IDE了,同时需要有一个环境变量的路径来存放安装的IDE的运行脚本:
向全局变量中导入一个PATH:
(base) bionet@Bionet:~/Desktop$ sudo vim /etc/profile
打开后在最下面添加一个PATH:
export PATH="/home/SoftWares/JetBrains/Scripts:$PATH"
注意这里的路径要放在有权限的地方,大家都有权限可以使用才可以。
工具安装位置也要放置到大家都能使用的位置,如下图所示(隔了一个命令)。
让环境变量生效:
source /etc/profile
这时候你会发现shell scripts location还是会报错,不过没关系,我们只需要将此用户重新登出再登入即可:
Jetbrains shell scripts有什么用?
让我们先安装一个IDE在讨论这个问题:
打开一个IDE设置:
我们拉到最下面:
随便写个缩写名字,比如:

打开命令行直接执行PCP,可以发现直接运行了~
需要注意的是JetbrainToolBox只能让一个用户来使用!每个用户如果要使用ToolBox的话需要单独安装,这里只给root用户安装,是为了方便管理。
Matlab安装与配置
MATLAB学校购买了正版,这里需要按照学校的安装步骤来走:
我们直接跳转到下载的步骤:
登录之后下载,在之后是一个安装包:
注意要解决安装路径的问题我们可以把他放在我们建立好的SoftWare目录之下:
参照官方教程安装:下载并安装 MATLAB - MATLAB & Simulink - MathWorks 中国
注意这一步只需要执行这个既可:

一路安装下去即可:
勾选全部内容:
注意下一页需要将脚本映射到合理位置,这里映射到了如下路径,就不放图了:
/home/SoftWares/MATLAB/MATLABScripts
在对应安装目录下运行一下:

效果如下:

R Studio Server安装
R使用过Docker来部署的:
R-studio server版本的镜像都在这里:rocker/rstudio Tags | Docker Hub
我们直接创建一个容器:
docker run -d -p 8787:8787 -p 8788:22 -v /home/SoftWares/R_Share:/home/rstudio/R_Share -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime --name R_422 rocker/rstudio:4.2.2
-v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime 为时间同步命令
-v /home/SoftWares/R_Share:/home/rstudio/R_Share 将对应的文件挂载到系统上某个盘
--name R_422 名字命名为R422
rocker/rstudio:4.2.2拉去这个版本的镜像
-p 8787:8787 -p 8788:22端口映射命令 主机的8788映射到22端口
进入容器里面:
docker exec -it R_422 /bin/bash
R_422是容器的名字。可根据需要切换
我们安装一些必要的内容,来保证容器的运行:
首先设置密码:
passwd root
设置完毕之后需要安装ssh,来方便管理,使用命令:
sudo apt update sudo apt-get install -y vim openssh-server sudo apt upgrade
配置容器内的SSH:
echo "PermitRootLogin yes">>/etc/ssh/sshd_config echo "export VISIBLE=now" >>/etc/profile
echo "PermitRootLogin yes">>/etc/ssh/sshd_config添加一段信息到sshd_config中。
echo "export VISIBLE=now" >> /etc/profile:向 /etc/profile 文件中添加一行 export VISIBLE=now,这个设置使得 SSH 会话可以在登录时创建 utmp 记录,使得用户能够在 w 或 who 命令中看到 SSH 登录的用户信息。
然后运行重启:
service ssh restart
这时候你如果打开另一个宿主机命令行运行以下命令可以看到:
Neo@Bionet:~/Desktop$ docker port pytorch 22 0.0.0.0:10003 [::]:10003
这时候我们打开一个远程的命令行来来连接一下容器:

输入后正常登录即可。
为什么要添加用户呢因为RStudio默认不允许root用户登录,我们需要添加一些用户进来,这里可以使用我的脚本,来批量添加用户,我们直接运行即可:
sudo ./createuser4R.sh
默认密码为名字+123即 名字123.
登录之后可以看到:

VSCode安装与配置
首先下载VsCode安装包,在官网这里:Visual Studio Code - Code Editing. Redefined
然后使用命令:
(base) bionet@Bionet:~/Desktop$ sudo dpkg -i code_1.87.2-1709912201_amd64.deb
进行安装,效果如下:

报错了不要慌,实际上是传输过来的时候安装包损坏了,也就是无法通过校验。

安装完成之后就可以在目录中看到了:

将软件快捷方式(desktop)送到用户桌面
到这里还没结束呢,安装完成之后我们还需要再把快捷方式丢去每个用户的目录,这里提示一下,每个创建的用户都需要在这个目录下有对应的文件才能看到应用程序,或者直接将软件丢去此目录也可以这里展示其中一个比较通用的方式:
一般桌面的软件的快捷方式都在此文件夹下:
/usr/share/applications/
用户安装的软件目录在:
~/.local/share/applications/
我们需要将安装软件的用户的目录下的图标迁移到此目录下,使用如下命令:
sudo cp -r ~/.local/share/applications/. /usr/share/applications/
r如果无法执行,需要切换到对应的用户,这里安装的用户就是bonet所以可以使用bionet的,如果还不行的话只能使用root来实现,输入以下命令之后安装:
sudo -i
这样后来的用户都可以看到安装的软件了。
内网磁盘映射
虽然目前已经实现了文件的传输,直接复制粘贴就可以,但是对于一些稍微大一点的文件,还是不靠谱,所以通过另一个服务将服务器上的磁盘映射过来:
使用SAMBA服务
安装SAMBA:
sudo apt-get install samba samba-common-bin
配置SAMBA:
sudo gedit /etc/samba/smb.conf
在最下面加入一行:
# 共享文件夹显示的名称 [Storge] # 说明信息 comment = Bionet No1 WorkStation Storage # 可以访问的用户 valid users = Neo,root,Bionet # 共享文件的路径 path = /home/SAMBA/Storge/ # 可被其他人看到资源名称(非内容) browseable = yes # 可写 writable = yes # 新建文件的权限为 664 create mask = 0664 # 新建目录的权限为 775 directory mask = 0775
运行以下命令来测试:
bionet@Bionet:~$ testparm
结果如下:
Load smb config files from /etc/samba/smb.conf Loaded services file OK. Weak crypto is allowed Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions # Global parameters [global] log file = /var/log/samba/log.%m logging = file map to guest = Bad User max log size = 1000 obey pam restrictions = Yes pam password change = Yes panic action = /usr/share/samba/panic-action %d passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* . passwd program = /usr/bin/passwd %u server role = standalone server server string = %h server (Samba, Ubuntu) unix password sync = Yes usershare allow guests = Yes idmap config * : backend = tdb [printers] browseable = No comment = All Printers create mask = 0700 path = /var/spool/samba printable = Yes [print$] comment = Printer Drivers path = /var/lib/samba/printers [Storge] comment = Bionet No1 WorkStation Storage create mask = 0664 directory mask = 0775 path = /home/SAMBA/Storge/ read only = No valid users = Neo root Bionet
添加SMB用户(必须是已经创建了的linux用户):
bionet@Bionet:~$ sudo smbpasswd -a Neo New SMB password: Retype new SMB password: Added user Neo.
这里由于学校网络分割,这一部分暂且搁置
安装Git
使用命令:
sudo apt install git
版本:
bionet@Bionet:~$ git --version git version 2.34.1
git本身需要设置用户名等内容,这里建议先设置一个全局的通用的用户名和账号,个人用户有需求再用个人的key来进行代码同步,这里就简单说一下,详细内容敬请百度。
git config --global user.name "Your Name" git config --global user.email "youremail@yourdomain.com"
配置完成以后验证一下:
bionet@Bionet:/usr/local/cuda-12.4$ git config --global user.name "Bionet" bionet@Bionet:/usr/local/cuda-12.4$ git config --global user.email "Bionet@xmu.edu.cn" bionet@Bionet:/usr/local/cuda-12.4$ git config --list user.name=Bionet user.email=Bionet@xmu.edu.cn
注册一个Github账号(实验室已经有账号了,详询老大):
生成密钥:
bionet@Bionet:/usr/local/cuda-12.4$ ssh-keygen -t ed25519 -C "BioNet@xmu.edu.cn" Generating public/private ed25519 key pair. Enter file in which to save the key (/home/bionet/.ssh/id_ed25519): Created directory '/home/bionet/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/bionet/.ssh/id_ed25519 Your public key has been saved in /home/bionet/.ssh/id_ed25519.pub
然后添加到咱们的账户中即可,如果重装的话,此处就要把原来的删除掉,在生成一个新的来作为验证。
没有添加密钥,验证失败结果如下:
bionet@Bionet:/usr/local/cuda-12.4$ ssh -T git@github.com git@github.com: Permission denied (publickey).
等待添加密钥即可
(base) bionet@Bionet:~/Desktop$ ssh -T git@github.com Hi NeoNexusX! You've successfully authenticated, but GitHub does not provide shell access.
用户与用户组管理
管理用户及用户组的权限是十分重要的,合理的权限分配能大大的减少后期维护成本。这里简单介绍一下linux文件权限的内容,并由此来介绍一下如何配用户组的权限。
Linux系统一般将文件可存/取访问的身份分为3个类别:owner、group、others,且3种身份各有read、write、execute等权限。在多用户(可以不同时)计算机系统的管理中,权限是指某个特定的用户具有特定的系统资源使用权力,像是文件夹、特定系统指令的使用。
-
读权限:
对于文件夹来说,读权限影响用户是否能够列出目录结构
对于文件来说,读权限影响用户是否可以查看文件内容 -
写权限:
对文件夹来说,写权限影响用户是否可以在文件夹下“创建/删除/复制到/移动到”文档
对于文件来说,写权限影响用户是否可以编辑文件内容 -
执行权限:
一般都是对于文件来说,特别脚本文件
上述说了身份也分为很多种,下面是详细介绍:
- Owner身份:文件所有者,默认为文档的创建者
- Group身份:与文件所有者同组的用户
- Others身份:其他人,相对于所有者所在组
- Root用户:超级用户,管理着普通用户,具有所有权限
查看文件权限
使用命令如下可以查看当前文件下的文件的权限:

权限区一共有10个字母,每个的内容意思是:

上图中权限为:-rwxr-xr-x 意思是 文件(-)、在bionet用户下有全部权限(rwx)、在所属用户组下有除了写的全部权限(r-x)、其他用户有除了写的全部权限(r-x)。
查看当前用户
使用命令:
Neo@Bionet:/home/jetbrain-toolbox-2.2.3$ getent passwd
上述内容表达为:用户名:密码(x):用户ID:组ID:描述信息(无用):HOME目录:执行终端(默认bash)
查看当前用户组:
getent group
在我们划分的时候需要将所有core组成员公用的地方加上权限,效果如下:
红框的三个文件夹都是公用的所以要加上权限
sudo chown -R :core /path/to/folder
sudo chmod -R 770 /path/to/folder
Docker部署
Docker也是虚拟化环境的神器,前面说的conda虽然可以提供python的虚拟环境并方便地切换,但是有的时候我们的开发环境并不只是用到python,比如有的native库需要对应gcc版本的编译环境,或者进行交叉编译时哟啊安装很多工具链等等。如果这些操作都在服务器本地上进行,那时间久了就会让服务器的文件系统非常杂乱,而且还会遇到各种软件版本冲突问题。
简单理解Docker为一个轻量化的虚拟机即可,但是其并不是虚拟机,虚拟机需要提供操作系统等,Docker只需要提供程序运行所需要的环境,对与常规开发流程来说一般是:
这里主要考虑服务器环境搭建和运行
docker官方教程:Install Docker Engine on Ubuntu | Docker Docs
首先设置docker的apt仓库信息:
# Add Docker's official GPG key: sudo apt-get update sudo apt-get install ca-certificates curl sudo install -m 0755 -d /etc/apt/keyrings sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc sudo chmod a+r /etc/apt/keyrings/docker.asc # Add the repository to Apt sources: echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update
命令一条一条复制,比较安全。
安装docker:
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

运行测试的镜像:
sudo docker run hello-world

运行版本信息查看一下:

为了方便后边Docker设置:我们先来创建一个用户组,因为对于后面使用docker来说,其守护进程使用的是Unix socket,并不是TCP socket,Docker的守护进程通常只能运行在root权限用户下,因此我们只能创建一个docker用户组来专门赋予权限,我们先看看是否有docker用户组,已经被创建好了,因为在某些发行版的linux下,安装完成docker后会自行创建:
使用命令:
getent group

果然有!所以我们就需要把当前的需要使用docker的用户加入到这个用户组里面去,这样运行的时候就不需要sudo权限了。
sudo usermod -aG docker $USER
-aG:这是 usermod 命令的选项之一,其中:
-a表示“追加”,它告诉usermod命令将用户添加到指定的组,而不是覆盖原有的组成员资格。-G表示“组”,它指定要操作的组。
登出后重新登录这个账户,并输入以下内容:
newgrp docker
重新再来验证一下,目前是否能使用了

设置开机自启动:
Neo@Bionet:~/Desktop$ sudo systemctl enable docker.service sudo systemctl enable containerd.service [sudo] password for Neo: Synchronizing state of docker.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable docker
如果需要关闭请使用:
sudo systemctl disable docker.service sudo systemctl disable containerd.service
到此完成docker的基本部署,接下来安装Nvida的docker,这部分在深度学习配置最后。
深度学习配置相关
安装NVIDIA驱动,由于新的版Ubuntu可以在管理器中直接安装,这里就不再赘述,只需要点击即可,新的显卡使用较新的驱动是最好的了:

安装Python和Pip
使用命令
sudo apt install python3 sudo apt install python3-pip
安装完成之后,替换python的pip源
bionet@Bionet:~$ cd ~ bionet@Bionet:~$ mkdir .pip bionet@Bionet:~$ sudo gedit ~/.pip/pip.conf
其中gedit是ubuntu自带的图形化文本编辑器,如果你喜欢vim那么可以替换成:
bionet@Bionet:~$ sudo vim ~/.pip/pip.conf
将以下内容填入:
[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple/ [install] trusted-host = pypi.tuna.tsinghua.edu.cn
测试一下:
bionet@Bionet:~$ python3 Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> quit();
安装CUDA Toolkit
这里选择最新的CUDA Toolkit12.4,在网页上按我的选择如下:

复制对应的命令后下载下来:
bionet@Bionet:~$ wget https://developer.download.nvidia.com/compute/cuda/12.4.0/local_installers/cuda_12.4.0_550.54.14_linux.run Saving to: ‘cuda_12.4.0_550.54.14_linux.run’ cuda_12.4.0_550.54.14_linux.run 100%[==============================================================================================>] 4.15G 89.4MB/s in 57s 2024-03-23 20:26:43 (73.9 MB/s) - ‘cuda_12.4.0_550.54.14_linux.run’ saved [4454353277/4454353277] bionet@Bionet:~$ ls cuda_12.4.0_550.54.14_linux.run Desktop Documents Downloads matlab Music Pictures Public snap Templates thinclient_drives Videos
使用命令执行:
sudo sh cuda_12.4.0_550.54.14_linux.run
注意进入选择模式之后,不要选择驱动,我们已经打了新驱动了,无需在安装一次:
至于这里选择不选择新驱动要看这个图:
如果你不满足对应的驱动条件我建议可以打上新驱动。
根据提示我们需要套件的内容添加到环境变量里面:
bionet@Bionet:~$ sudo gedit ~/.bashrc
环境变量如下:
export CUDA_HOME=/usr/local/cuda-12.4 export LD_LIBRARY_PATH=${CUDA_HOME}/lib64 export PATH=${CUDA_HOME}/bin:${PATH}
使其生效:
bionet@Bionet:~$ source ~/.bashrc
使用命令测试:
bionet@Bionet:~$ nvcc -V nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2024 NVIDIA Corporation Built on Tue_Feb_27_16:19:38_PST_2024 Cuda compilation tools, release 12.4, V12.4.99 Build cuda_12.4.r12.4/compiler.33961263_0
到这一步并不代表成功了,要成功运行cuda才说明环境没有问题:
自从11.7之后cuda不再单独提供测试样例,我们可以从github上克隆下来,直接编译后运行即可:
cd /usr/local/cuda-12.4/ git clone https://github.com/NVIDIA/cuda-samples.git cd /cuda-samples/Samples/1_Utilities/deviceQuery make ./deviceQuery
结果如下:
bionet@Bionet:/usr/local/cuda-12.4/cuda-samples/Samples/1_Utilities/deviceQuery$ ./deviceQuery ./deviceQuery Starting... CUDA Device Query (Runtime API) version (CUDART static linking) Detected 4 CUDA Capable device(s) Device 0: "NVIDIA GeForce RTX 4090" CUDA Driver Version / Runtime Version 12.2 / 12.4 CUDA Capability Major/Minor version number: 8.9 Total amount of global memory: 24217 MBytes (25393692672 bytes) (128) Multiprocessors, (128) CUDA Cores/MP: 16384 CUDA Cores GPU Max Clock rate: 2580 MHz (2.58 GHz) Memory Clock rate: 10501 Mhz Memory Bus Width: 384-bit L2 Cache Size: 75497472 bytes Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384) Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 49152 bytes Total shared memory per multiprocessor: 102400 bytes Total number of registers available per block: 65536 Warp size: 32 Maximum number of threads per multiprocessor: 1536 Maximum number of threads per block: 1024 Max dimension size of a thread block (x,y,z): (1024, 1024, 64) Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535) Maximum memory pitch: 2147483647 bytes Texture alignment: 512 bytes Concurrent copy and kernel execution: Yes with 2 copy engine(s) Run time limit on kernels: No Integrated GPU sharing Host Memory: No Support host page-locked memory mapping: Yes Alignment requirement for Surfaces: Yes Device has ECC support: Disabled Device supports Unified Addressing (UVA): Yes Device supports Managed Memory: Yes Device supports Compute Preemption: Yes Supports Cooperative Kernel Launch: Yes Supports MultiDevice Co-op Kernel Launch: Yes Device PCI Domain ID / Bus ID / location ID: 0 / 9 / 0 Compute Mode: < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) > Device 1: "NVIDIA GeForce RTX 3090" CUDA Driver Version / Runtime Version 12.2 / 12.4 CUDA Capability Major/Minor version number: 8.6 Total amount of global memory: 24260 MBytes (25438126080 bytes) (082) Multiprocessors, (128) CUDA Cores/MP: 10496 CUDA Cores GPU Max Clock rate: 1755 MHz (1.75 GHz) Memory Clock rate: 9751 Mhz Memory Bus Width: 384-bit L2 Cache Size: 6291456 bytes Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384) Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 49152 bytes Total shared memory per multiprocessor: 102400 bytes Total number of registers available per block: 65536 Warp size: 32 Maximum number of threads per multiprocessor: 1536 Maximum number of threads per block: 1024 Max dimension size of a thread block (x,y,z): (1024, 1024, 64) Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535) Maximum memory pitch: 2147483647 bytes Texture alignment: 512 bytes Concurrent copy and kernel execution: Yes with 2 copy engine(s) Run time limit on kernels: No Integrated GPU sharing Host Memory: No Support host page-locked memory mapping: Yes Alignment requirement for Surfaces: Yes Device has ECC support: Disabled Device supports Unified Addressing (UVA): Yes Device supports Managed Memory: Yes Device supports Compute Preemption: Yes Supports Cooperative Kernel Launch: Yes Supports MultiDevice Co-op Kernel Launch: Yes Device PCI Domain ID / Bus ID / location ID: 0 / 138 / 0 Compute Mode: < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) > Device 2: "NVIDIA GeForce RTX 2080 Ti" CUDA Driver Version / Runtime Version 12.2 / 12.4 CUDA Capability Major/Minor version number: 7.5 Total amount of global memory: 11012 MBytes (11546394624 bytes) (068) Multiprocessors, (064) CUDA Cores/MP: 4352 CUDA Cores GPU Max Clock rate: 1650 MHz (1.65 GHz) Memory Clock rate: 7000 Mhz Memory Bus Width: 352-bit L2 Cache Size: 5767168 bytes Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384) Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 49152 bytes Total shared memory per multiprocessor: 65536 bytes Total number of registers available per block: 65536 Warp size: 32 Maximum number of threads per multiprocessor: 1024 Maximum number of threads per block: 1024 Max dimension size of a thread block (x,y,z): (1024, 1024, 64) Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535) Maximum memory pitch: 2147483647 bytes Texture alignment: 512 bytes Concurrent copy and kernel execution: Yes with 3 copy engine(s) Run time limit on kernels: No Integrated GPU sharing Host Memory: No Support host page-locked memory mapping: Yes Alignment requirement for Surfaces: Yes Device has ECC support: Disabled Device supports Unified Addressing (UVA): Yes Device supports Managed Memory: Yes Device supports Compute Preemption: Yes Supports Cooperative Kernel Launch: Yes Supports MultiDevice Co-op Kernel Launch: Yes Device PCI Domain ID / Bus ID / location ID: 0 / 4 / 0 Compute Mode: < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) > Device 3: "NVIDIA GeForce RTX 2080 Ti" CUDA Driver Version / Runtime Version 12.2 / 12.4 CUDA Capability Major/Minor version number: 7.5 Total amount of global memory: 11012 MBytes (11546394624 bytes) (068) Multiprocessors, (064) CUDA Cores/MP: 4352 CUDA Cores GPU Max Clock rate: 1650 MHz (1.65 GHz) Memory Clock rate: 7000 Mhz Memory Bus Width: 352-bit L2 Cache Size: 5767168 bytes Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384) Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 49152 bytes Total shared memory per multiprocessor: 65536 bytes Total number of registers available per block: 65536 Warp size: 32 Maximum number of threads per multiprocessor: 1024 Maximum number of threads per block: 1024 Max dimension size of a thread block (x,y,z): (1024, 1024, 64) Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535) Maximum memory pitch: 2147483647 bytes Texture alignment: 512 bytes Concurrent copy and kernel execution: Yes with 3 copy engine(s) Run time limit on kernels: No Integrated GPU sharing Host Memory: No Support host page-locked memory mapping: Yes Alignment requirement for Surfaces: Yes Device has ECC support: Disabled Device supports Unified Addressing (UVA): Yes Device supports Managed Memory: Yes Device supports Compute Preemption: Yes Supports Cooperative Kernel Launch: Yes Supports MultiDevice Co-op Kernel Launch: Yes Device PCI Domain ID / Bus ID / location ID: 0 / 134 / 0 Compute Mode: < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) > > Peer access from NVIDIA GeForce RTX 4090 (GPU0) -> NVIDIA GeForce RTX 3090 (GPU1) : No > Peer access from NVIDIA GeForce RTX 4090 (GPU0) -> NVIDIA GeForce RTX 2080 Ti (GPU2) : No > Peer access from NVIDIA GeForce RTX 4090 (GPU0) -> NVIDIA GeForce RTX 2080 Ti (GPU3) : No > Peer access from NVIDIA GeForce RTX 3090 (GPU1) -> NVIDIA GeForce RTX 4090 (GPU0) : No > Peer access from NVIDIA GeForce RTX 3090 (GPU1) -> NVIDIA GeForce RTX 2080 Ti (GPU2) : No > Peer access from NVIDIA GeForce RTX 3090 (GPU1) -> NVIDIA GeForce RTX 2080 Ti (GPU3) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU2) -> NVIDIA GeForce RTX 4090 (GPU0) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU2) -> NVIDIA GeForce RTX 3090 (GPU1) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU2) -> NVIDIA GeForce RTX 2080 Ti (GPU3) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU3) -> NVIDIA GeForce RTX 4090 (GPU0) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU3) -> NVIDIA GeForce RTX 3090 (GPU1) : No > Peer access from NVIDIA GeForce RTX 2080 Ti (GPU3) -> NVIDIA GeForce RTX 2080 Ti (GPU2) : No deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 12.2, CUDA Runtime Version = 12.4, NumDevs = 4 Result = PAS
可以看到4090的ECC没有开启不过问题不大,这个以后再处理。
同样可以再跑一个BandwidthTest,编译后结果如下
bionet@Bionet:/usr/local/cuda-12.4/cuda-samples/Samples/1_Utilities/bandwidthTest$ ./bandwidthTest [CUDA Bandwidth Test] - Starting... Running on... Device 0: NVIDIA GeForce RTX 4090 Quick Mode Host to Device Bandwidth, 1 Device(s) PINNED Memory Transfers Transfer Size (Bytes) Bandwidth(GB/s) 32000000 11.9 Device to Host Bandwidth, 1 Device(s) PINNED Memory Transfers Transfer Size (Bytes) Bandwidth(GB/s) 32000000 13.2 Device to Device Bandwidth, 1 Device(s) PINNED Memory Transfers Transfer Size (Bytes) Bandwidth(GB/s) 32000000 3627.5 Result = PASS NOTE: The CUDA Samples are not meant for performance measurements. Results may vary when GPU Boost is enabled.
安装cuDNN
cuDNN是nvidia专门用来加速深度学习的一些库,需要注意的是安装的时候要和你的cuda版本对应
这里是网页下载途径,但是网有墙,很烂,推荐使用这个页面下载,选择对应的命令即可,我这里是cuda12所以要用cuda12的内容:
注意这个和网上的不太一样,这里使用的是系统原生的包管理器来进行安装,详见:Installing cuDNN on Linux — NVIDIA cuDNN 9.0.0 documentation。
安装Anaconda环境
从清华镜像站下载:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
bionet@Bionet:~/Downloads$ chmod +x Anaconda3-2024.02-1-Linux-x86_64.sh bionet@Bionet:~/Downloads$ sudo ./Anaconda3-2024.02-1-Linux-x86_64.sh
注意这里我修改到了home目录下,home很大,我就喜欢整整齐齐的
安装完成之后再输入一个yes,最后会给你显示目前安装的内容:
你安装完成以后发现不行啊没有conda的环境变量,其实并不是,他只是把环境变量写到了root的shell里面,这就很尴尬了。
所以我们需要手动baroot里面的内容复制过来:
这里下边打个样:
# >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/home/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" else if [ -f "/home/anaconda3/etc/profile.d/conda.sh" ]; then . "/home/anaconda3/etc/profile.d/conda.sh" else export PATH="/home/anaconda3/bin:$PATH" fi fi unset __conda_setup # <<< conda initialize <<<
不同的系统需要的路径也不一样,这里需要注意下。
使用的命令如下:
bionet@Bionet:~/Desktop$ sudo vim ~/.bashrc bionet@Bionet:~/Desktop$ source ~/.bashrc
可以看到使用后的结果:

你以为到这里就结束了吗?当然不可能对于我一个目录洁癖的人来说,肯定不止于此,我们要设置其包的路径,来保证整洁。
在开始之前先完成换源:
(base) bionet@Bionet:~$ sudo vim ~/.condarc
替换成如下内容:
channels: - defaults show_channel_urls: true default_channels: - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2 custom_channels: conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud pytorch-lts: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud deepmodeling: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/

我们检查一下当前路径结果:
(base) bionet@Bionet:~$ conda info active environment : base active env location : /home/anaconda3 shell level : 1 user config file : /home/bionet/.condarc populated config files : /home/bionet/.condarc conda version : 24.1.2 conda-build version : 24.1.2 python version : 3.11.7.final.0 solver : libmamba (default) virtual packages : __archspec=1=broadwell __conda=24.1.2=0 __cuda=12.2=0 __glibc=2.35=0 __linux=6.5.0=0 __unix=0=0 base environment : /home/anaconda3 (read only) conda av data dir : /home/anaconda3/etc/conda conda av metadata url : None channel URLs : https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/linux-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/noarch https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r/linux-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r/noarch https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2/linux-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2/noarch package cache : /home/anaconda3/pkgs /home/bionet/.conda/pkgs envs directories : /home/bionet/.conda/envs /home/anaconda3/envs
发现目录正好不用改都在/home下,注意这里的路径是/home不是用户的home。
Pytorch安装
终于到了这一步了,我们在conda上创建一个新环境:
conda create --name test python=3.10 conda activate test
在pytorch官网中找到合适的版本:PyTorch

复制命令下载:
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
随便写一个脚本,然后运行一下看看:
sudo vim test.py
脚本内容如下:
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.backends.cudnn as cudnn from torchvision import datasets, transforms class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.log_softmax(x, dim=1) def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % 10 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) def main(): cudnn.benchmark = True torch.manual_seed(1) device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") print("Using device: {}".format(device)) kwargs = {'num_workers': 1, 'pin_memory': True} train_loader = torch.utils.data.DataLoader( datasets.MNIST('./data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=64, shuffle=True, **kwargs) model = Net().to(device) optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) for epoch in range(1, 11): train(model, device, train_loader, optimizer, epoch) if __name__ == '__main__': main()
运行后没有报错的话就因该是这样的:
test) bionet@Bionet:~$ python test.py Using device: cuda Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/MNIST/raw/train-images-idx3-ubyte.gz 100.0% Extracting ./data/MNIST/raw/train-images-idx3-ubyte.gz to ./data/MNIST/raw 100.0% Extracting ./data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ./data/MNIST/raw Train Epoch: 1 [0/60000 (0%)] Loss: 2.327492 Train Epoch: 1 [640/60000 (1%)] Loss: 2.328194 Train Epoch: 1 [1280/60000 (2%)] Loss: 2.278235 Train Epoch: 1 [1920/60000 (3%)] Loss: 2.281009 省略一部分 Train Epoch: 10 [56320/60000 (94%)] Loss: 0.196389 Train Epoch: 10 [56960/60000 (95%)] Loss: 0.387766 Train Epoch: 10 [57600/60000 (96%)] Loss: 0.109143 Train Epoch: 10 [58240/60000 (97%)] Loss: 0.077670 Train Epoch: 10 [58880/60000 (98%)] Loss: 0.182428 Train Epoch: 10 [59520/60000 (99%)] Loss: 0.392815
注意这里的device一定要是cuda。别急,这是裸机部分,但我们真正需要的是Docker!
NVIDIA Container Toolkit
英伟达虚拟化环境技术分类:
nvidia docker, nvidia docker2, nvidia container toolkits三者的区别-CSDN博客
不扯没用的,我们直接上最新的nvidia-container-toolkits
NVIDIA Container Toolkit 的目的是为了能够创造一个合适的环境来运行显卡的程序。同时有一定的自由度,可以切换CUDA版本等操作,最重要的是实现在不同机器上、不同硬件上无需提前配置相同环境就可以直接运行。
官方教程:NVIDIA/nvidia-container-toolkit: Build and run containers leveraging NVIDIA GPUs (github.com)
Installing the NVIDIA Container Toolkit — NVIDIA Container Toolkit 1.14.5 documentation

NVIDIA 容器工具包允许用nvidai户构建和运行 GPU 加速容器。该工具包包括一个容器运行时库和实用程序,用于自动配置容器以利用 NVIDIA GPU。产品文档(包括体系结构概述、平台支持以及安装和使用指南)可以在文档存储库中找到。
需要注意的是,这里的使用的docker无需安装Nvidia Toolkit,但是需要在宿主机上安装Nvidia的驱动来支撑运行,
首先需要配置仓库信息:
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg && curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
这里把命令行拉的长一点看的清楚一点:

使用如下命令:
sudo apt-get update

开始安装:
sudo apt-get install -y nvidia-container-toolkit
安装完成之后开始配置部分:
使用nvidia-ctk命令修改docker在宿主机上的配置文件,来让Docker能使用 NVIDIA Container Runtime:
sudo nvidia-ctk runtime configure --runtime=docker

运行docker部署测试
先跑一个简单一点的测试:
使用命令创建一个Ubuntu的镜像,并输出容器内GPU的信息
Neo@Bionet:~/Desktop$ docker run --rm --runtime=nvidia --gpus all ubuntu nvidia-smi
结果如下:
Neo@Bionet:~/Desktop$ docker run --rm --runtime=nvidia --gpus all ubuntu nvidia-smi Mon Mar 25 09:15:30 2024 +---------------------------------------------------------------------------------------+ | NVIDIA-SMI 535.161.07 Driver Version: 535.161.07 CUDA Version: 12.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 NVIDIA GeForce RTX 2080 Ti Off | 00000000:04:00.0 Off | N/A | | 0% 28C P8 17W / 300W | 1MiB / 11264MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 1 NVIDIA GeForce RTX 4090 Off | 00000000:09:00.0 Off | Off | | 0% 31C P8 34W / 450W | 1MiB / 24564MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 2 NVIDIA GeForce RTX 2080 Ti Off | 00000000:86:00.0 Off | N/A | | 0% 28C P8 12W / 300W | 1MiB / 11264MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ | 3 NVIDIA GeForce RTX 3090 Off | 00000000:8A:00.0 Off | N/A | | 0% 27C P8 20W / 370W | 1MiB / 24576MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ +---------------------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=======================================================================================| | No running processes found | +---------------------------------------------------------------------------------------+
接着测试代码任务,使用命令安装一个镜像,然后配置环境之后打包成新的镜像保存下来供大家使用:
执行以下命令之前需要使用,命令:
newgrp docker
来刷新一下用户组信息,当然前提是你的账户已经被添加到用户组了,否则需要联系管理员处理。
docker run -it -p 10003:22 -p 10004:10002 --name pytorch -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime -v /home/Neo/WorkSpace/_Share:/home/workspace/_share --gpus all nvidia/cuda:12.2.2-cudnn8-runtime-ubuntu22.04
-v /etc/timezone:/etc/timezone 和 -v /etc/localtime:/etc/localtime:这两个选项用于将宿主机的 /etc/timezone 和 /etc/localtime 文件挂载到容器内对应的位置,以确保容器内的时间设置与宿主机一致。
-v /home/Neo/WorkSpace/_Share:/home/workspace/_share:这个选项将宿主机上的 /home/Neo/WorkSpace/_Share 目录挂载到容器内的 /home/workspace/_share 目录,以实现宿主机和容器之间的共享文件。
每个标签都具有以下格式:
11.4.0-base-ubuntu20.04docker
- 11.4.0 – CUDA version.
- base – Image flavor. Image的变种类型,常见有base runtime等,有不同功能。
- ubuntu20.04 – Operating system version.
目前有什么Tags,请参考:
这里需要注意的是:cuda tollkit的版本要和驱动的版本匹配:
详见:1. CUDA 12.4 Release Notes — Release Notes 12.4 documentation (nvidia.com)
同时需要把对应的端口映射出来,SSH端口是22,从容器中映射出来,映射到主机的10001端口。同时保留一个10002端口以备不时之需。
此时就进入了docker之中,可以愉快的运行了~
我们把裸机的例子拿来再跑一遍看看有什么效果~
root@54990fb612d5:/# nvidia-smi
你如果仔细看这张图就看到了docker的真正优点:在于CUDA版本的切换!这里的cuda版本成功切换到12.3版本~
当然你在容器里面随便操作也不会太影响其他人,这是最棒的优点。
此处应使用dockerfile来配置,后续更新,先手动。
接下来安装一些必要的工具来方便后边的开发:
apt update apt-get install sudo sudo apt-get install -y vim git curl unzip net-tools openssh-server
修改源:
sudo vim /etc/apt/sources.list
将以下内容填入:
适用 22.04:
deb https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse # deb https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse # deb-src https://mirrors.aliyun.com/ubuntu/ jammy-proposed main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ jammy-backports main restricted universe multiverse
适用 20.04:
deb https://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse # deb https://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse # deb-src https://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse deb https://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse deb-src https://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
记得再次升级:
sudo apt update sudo apt upgrade
当然别忘记设置密码:
root@49906fdf69a6:/# passwd root New password: Retype new password: passwd: password updated successfully
配置容器内的SSH:
echo "PermitRootLogin yes">>/etc/ssh/sshd_config echo "export VISIBLE=now" >>/etc/profile
echo "PermitRootLogin yes">>/etc/ssh/sshd_config添加一段信息到sshd_config中。
echo "export VISIBLE=now" >> /etc/profile:向 /etc/profile 文件中添加一行 export VISIBLE=now,这个设置使得 SSH 会话可以在登录时创建 utmp 记录,使得用户能够在 w 或 who 命令中看到 SSH 登录的用户信息。
然后运行重启:
service ssh restart
这时候你如果打开另一个宿主机命令行运行以下命令可以看到:
Neo@Bionet:~/Desktop$ docker port pytorch 22 0.0.0.0:10003 [::]:10003
这时候我们打开一个远程的命令行来来连接一下容器:
ssh root@10.26.58.61 -p 10003
这时候我们就成功进入啦,到这里已经完成一个镜像的50%了,我们还需要安装python环境,这里选择miniconda来作为虚拟Python环境运行,或者你觉得麻烦,直接用pip也可以,这里不赘述pip方案,这里选择conda 方案。
额外注意如果你出现以下报错:
PS C:UsersNeoNexusDesktop> ssh root@10.26.58.61 -p 10003 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the ED25519 key sent by the remote host is SHA256:8jZY1c5+1VHkr9H0HoLXl6dV6c/oGj1i6HlsPsUCjPA. Please contact your system administrator. Add correct host key in C:\Users\NeoNexus/.ssh/known_hosts to get rid of this message. Offending ECDSA key in C:\Users\NeoNexus/.ssh/known_hosts:9 Host key for [10.26.58.61]:10003 has changed and you have requested strict checking.
同样的问题在vscode中报错如下:

请按照下图删除对应内容即可

再来安装miniconda:
首先去官网下载好miniconda的安装包,地址如下:
Miniconda — Anaconda documentation

这里就安装在默认的位置,这样好安排一点,就不做路径修改了。
root@6ee3c0747be2:/# echo "PermitRootLogin yes">>/etc/ssh/sshd_config root@6ee3c0747be2:/# echo "export VISIBLE=now" >>/etc/profile root@6ee3c0747be2:/# service ssh restart * Restarting OpenBSD Secure Shell server sshd [ OK ] root@6ee3c0747be2:/# cd /home/workspace/_share/ root@6ee3c0747be2:/home/workspace/_share# chmod +x Miniconda3-latest-Linux-x86_64.sh root@6ee3c0747be2:/home/workspace/_share# sudo ./Miniconda3-latest-Linux-x86_64.sh



安装完成之后我们可以使用了,这时候需要推出一下容器的命令行然后再进入:
root@49906fdf69a6:/home/workspace/_share# exit exit Neo@Bionet:~/Desktop$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 49906fdf69a6 nvidia/cuda:12.3.2-runtime-ubuntu22.04 "/opt/nvidia/nvidia_…" 12 hours ago Up 12 hours 0.0.0.0:10003->22/tcp, :::10003->22/tcp, 0.0.0.0:10004->10002/tcp, :::10004->10002/tcp pytorch Neo@Bionet:~/Desktop$ docker exec -it pytorch /bin/bash #这时候就会看到conda的启动,我们直接安装pytorch来运行一下上边的测试代码,不同的是我们这次使用vscode来远程连接docker。 (base) root@49906fdf69a6:/# (base) root@49906fdf69a6:/#
vscode通过SSH连接之后我们创建一个test文件夹在这里,同时把测试代码复制过来:
将推荐的插件安装一下:
选择方才的conda来使用:

选择完成之后会自动帮你创建一个新的虚拟环境:

我们来打开terminal来安装一下pytorh环境:

使用命令如下:
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
在其下载的同时我们来看一下性能的消耗:
点击右上角直接执行,运行结果如下:
你仔细看会看到这里实际上运行的设备是cpu!这是不对的,因为cuda版本驱动版本不匹配导致的,修改后(就是上边的命令已经修改好了,你正常安装应该是我下边的结果):

我们将镜像打包一下方便以后用:
命令格式:
docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
docker commit -a Neo -m "first commit" pytorch pytorch221_cuda122
打包完成之后使用docker images查看:
打包成镜像以后,要保存成tar方便传输:
docker save [OPTIONS] IMAGE [IMAGE...]
示例:
docker save -o pytorch221_cuda122 pytorch
选配:rootless来操作docker daemon
根据提示restart一下docker:
systemctl --user restart docker
Neo@Bionet:~/Desktop$ systemctl --user restart docker Failed to restart docker.service: Unit docker.service not found.
实际上只是添加了几个参数:
这里暂停,因为服务器权限不开放,所以暂停这样使用。
参考文章
Ubuntu - 测试硬盘读写速度 - Citrusliu - 博客园 (cnblogs.com)
Ubuntu 20.04安装XRDP远程桌面服务及xfce轻量桌面 – 技术什锦派 (weizhiyong.com)
Ubuntu 20.04 安装xfce4桌面、Xrdp远程桌面 - 掘金 (juejin.cn)
如何在 Ubuntu 20.04 安装 Xrdp 服务器 | myfreax
How To Transfer Files Over Remote Desktop (All You Need To Know) (helpwire.app)
[debian 关闭gnome-掘金 (juejin.cn)](https://juejin.cn/s/debian 关闭gnome)
【保姆级教程】个人深度学习工作站配置指南 - 知乎 (zhihu.com)
linux之用户和权限管理(干货) - 知乎 (zhihu.com)
Linux——用户和权限、用户组管理、权限管理_用户权限跟组权限的关系linux-CSDN博客
/etc/profile、/etc/bashrc、/.bash_profile、/.bashrc 文件的作用 - 倥偬时光 - 博客园 (cnblogs.com)
1. Introduction — Installation Guide for Linux 12.4 documentation (nvidia.com)
CUDA Toolkit 12.4 Downloads | NVIDIA Developer
【Linux】CUDA Toolkit和cuDNN版本对应关系(更新至2022年6月,附官网永久更新链接)_cuda12.0对应cudnn-CSDN博客
linux添加环境变量 - ilovetesting - 博客园 (cnblogs.com)
Anaconda下载与安装详解 - 上善若泪 - 博客园 (cnblogs.com)
How to SSH into Docker containers | CircleCI
ssh连接docker容器;docker容器设置root密码_docker容器root用户密码-CSDN博客
使用Docker容器配置ssh服务,远程直接进入容器_ssh连接docker容器 群晖-CSDN博客
如何通过 SSH 连接到 Docker 容器 |CircleCI的
Install Docker Engine on Ubuntu | Docker Docs
Linux post-installation steps for Docker Engine | Docker Docs
Install Docker Engine on Ubuntu | Docker Docs
Run the Docker daemon as a non-root user (Rootless mode) | Docker Docs