Docker打包深度学习项目

时间:2022-10-15 09:54:14

1、docker的安装使用,及打包深度学习环境【很详细】
2、Docker打包深度学习项目(解决:Opencv依赖库、共享内存)
3、Docker 镜像构建之 Dockerfile
4、Docker深度学习环境安装、部署、打包
5、使用conda pack进行环境迁移(步骤很详细)

1、 Docker安装

不同平台的Docker安装方式可以参考官方文档(Docker Install) ,我这里就用Ubuntu系统作为例子。

1、Install Docker Engine on Ubuntu

# Docker
#在首次在新的主机上安装Docker Engine之前,需要设置Docker存储库。之后,您可以从存储库中安装和更新Docker。
#1、更新apt包索引并安装包,以允许apt通过HTTPS使用存储库:
$ sudo apt-get update
$ sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
#2. 添加Docker的官方GPG密钥:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
#添加docker官方gpg密钥,这里改成中科大镜像的
curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg


#3、使用以下命令设置存储库:
$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"  
 
 #设置稳定版本库,也换成中科大的
 echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/ \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Docker engine,安装docker,默认是安装最新版
#1. 更新apt包索引,安装最新版本的Docker Engine、containd和Docker Compose,或者执行下一步安装具体版本:
$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io

 sudo apt-get update
 sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
在完成安装后,执行下面命令,以确保安装成功:
sudo docker run hello-world

执行后看到打印出来正常的提示信息则表示安装成功。

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete 
Digest: sha256:10d7d58d5ebd2a652f4d93fdd86da8f265f5318c6a73cc5b6a9798ff6d2b2e67
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
7. 卸载
sudo apt-get purge docker-ce docker-ce-cli containerd.io docker-compose-plugin

sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd

输入指令: docker version或者docker -v
然后启动,输入指令:systemctl start docker
输入指令:systemctl status docker 查看状态
设置开机自启动
输入指令:systemctl enable docker

2、安装NVIDIA Docker。

详细安装步骤见NVIDIA Docker Installation Guide. 安装完记得重启Docker,并用nvidia/cuda:11.0-base这个默认容器测试一下是否安装成功。

1、Setting up Docker

在更新包清单后安装nvidia-docker2包(和依赖项):

curl https://get.docker.com | sh \
  && sudo systemctl --now enable docker
sudo apt-get update
sudo apt-get install -y nvidia-docker2

2、重启docker

sudo systemctl restart docker
sudo docker run --rm --gpus all nvidia/cuda:11.0.3-base-ubuntu20.04 nvidia-smi
# Restart the Docker daemon to complete the installation after setting the default runtime:
sudo systemctl restart docker

sudo docker run --rm --gpus all nvidia/cuda:11.0-base nvidia-smi
# 出现显卡信息界面即为安装成功
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.51.06    Driver Version: 450.51.06    CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| 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 T4            On   | 00000000:00:1E.0 Off |                    0 |
| N/A   34C    P8     9W /  70W |      0MiB / 15109MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+
#查看目前有的镜像
$: docker images
REPOSITORY        TAG                            IMAGE ID       CREATED          SIZE
chicken           v1                             1108516f1e34   40 minutes ago   41.5GB
pytorch/pytorch   1.10.0-cuda11.3-cudnn8-devel   46961cbf2ac7   13 days ago      14.4GB
nvidia/cuda       11.0-base                      2ec708416bb8   14 months ago    122MB
pytorch/pytorch   0.4-cuda9-cudnn7-devel         63994d8624a2   3 years ago      4.71GB

2、打包镜像Docker Build Image

1、整理代码

将需要打包的模型代码整理到同一个目录下。举例来说,目录应该包含模型代码、数据文件夹、输出文件夹:

Model:
      Code
      Val Data
      Output Data

Docker打包深度学习项目

如果用的是python语言的,可以准备一个requirement.txt,列出需要安装的包。后面就可以一步安装到位。

# 到代码目录下新建requirement.txt文件
touch requirment.txt

我的只需要再安装一个opencv包,所以我的requirment文件只要加上:

opencv-python==3.4.2.17

大家看自己需要什么额外的包直接写上名称和对应版本就可以了。用pip生成的requirement文件包含太多重复无用的包,建议还是自己简单写几个。
例如:
Docker打包深度学习项目

2、创建Dockfile

同样,新建一个Dockfile文件,每一步的详细说明可以查看Dockerfile说明 、Dockerfile reference

# Use an official PyTorch runtime as a parent image
FROM pytorch/pytorch

# Set the working directory
WORKDIR /docker_sample

# Copy the current directory contents into the container
COPY . /docker_sample

# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt

# Run when the container launches
CMD ["python", "deploy_models.py"]

3、Dockerbuild

1、打包Docker镜像

sudo docker build -t docker_sample:latest .
其中-t参数指定镜像的名称为docker_sample和tag标签为latest,其中tag标签相当于版本号,最后的小点"."表示当前目录,因为当前目录下有Dockerfile文件。
# 保存文件
docker save -o output-filename image-name
sudo docker save -o docker_image.tar docker_sample:latest

2、运行Docker镜像

每个Docker镜像只被分配了几百M的共享内存,对于很多CNN模型是远远不够的,因此需要加上 --shm-size 8G 来增大Docker镜像的共享内存大小(Shared Memories Size)。我的任务8G就够用了。

docker run --shm-size 8G --gpus all -v -it --rm image-name

添加-v Path:/model/val 就可以将宿主机上的Path文件夹映射到Docker镜像里的val文件夹下,那么Docker镜像运行时就会从Path这个文件夹下取数据,记得Path一定要是绝对路径。Ubuntu中可以通过Ctrl+L得到文件的绝对路径。

对于我这个任务来说,我需要将新测试集和输出文件夹位置映射给Docker镜像,所以运行命令就是:

sudo docker run --shm-size 8G --gpus all -v PATH_TO_VAL:/model/val
-v PATH_TO_PUT:/model/output -it --rm image_name

测试成功就可以提交打包的镜像啦!

4、测试镜像

1、导入Docker镜像

sudo docker load -i docker_image.tar

2、运行Docker镜像

5、拉取基础镜像

Anaconda发行版被安装到/opt/conda文件夹中,并确保默认用户的路径中有conda命令。
You can download and run this image using the following commands:

docker pull continuumio/anaconda3
docker run -i -t continuumio/anaconda3 /bin/bash

6、实例:打包mmsegmentation深度学习环境

# 从conda开始构建
FROM continuumio/anaconda3:2020.07

# 作者
MAINTAINER xxxx

# 从cuda复制基础环境
COPY --from=nvidia/cuda:11.4.0-devel-ubuntu20.04 / /

# 复制代码
COPY xx_code /xx_code

# 复制conda环境
COPY env_name.tar.gz /opt/conda/envs/

# 解压创建conda环境
RUN mkdir /opt/conda/envs/env_name
RUN tar -zxf /opt/conda/envs/env_name.tar.gz -C /opt/conda/envs/env_name

# 设置全局shell环境,使用/bin/bash
SHELL ["/bin/bash","-c"]

# 安装mmcv的环境
WORkDIR /xx_code
RUN source activate env_name && pip install -r requirements.txt && pip install --no-cache-dir -e .

RUN echo "source activate env_name " >> ~/.bashrc

编译、构建镜像

docker build -t images_name:v1 .

运行深度学习镜像

docker run -idt --shm-size 4096m  --gpus all --name swin_seg xx:xx

# 参数一 
--shm-size  # 设置容器的共享内存大小,这里设置的4g

# 参数二
--gpus all # 开启gpu

导出镜像

docker save imagesID > /xxx.tar

导入镜像

docker load < xx.tar

7、Pyinstaller打包代码和虚拟环境exe与Dockfile封装

1、安装pyinstaller

pip install pyinstaller

2、打包可执行程序

Docker打包深度学习项目
生成一次之后路径下会生成XX.spec,修改后可以用spec生成。

options常用参数(按需求选择):
-D 与 -F 相反用法,生成一个文件目录包含可执行文件和相关动态链接库和资源文件等,对于打包结果较大的项目,选用-D生成目录相比-F的打包方式,执行速度更快,但包含更加多的文件

-F 表示在 dist 文件夹下只生成单个可执行文件(内部包含所有依赖),不加默认会在 dist 生成一大堆依赖文件+可执行文件。

-w 表示去掉控制台窗口,如果你的程序是有界面的,可以不写这个参数,

-c 表示去掉窗框,使用控制台,推荐使用,会打印各种信息和log到控制台,加上这个参数生成的spec中的console=True

-p 表示自己定义需要加载的类路径,项目中包含多个自建模块的时候需要加上 -p aaa.py -p bbb.py -p ccc.py

-i 表示可执行文件的图标,后面跟图标的路径,可以自定义exe文件的图标,我尝试了好多次没成功
  打包完毕后在 dist 文件夹下双击项目启动文件就可以执行了

3、执行.spec可执行程序

Docker打包深度学习项目

4、dist下面会生成可执行文件,将配置文件和参数存进来即可。

Docker打包深度学习项目

5、执行./exe即可。

Docker打包深度学习项目

6、拉去或者导入base镜像

7、 dockerfile:1.指定工作目录

8、 把打包好的推理文件夹考到docker里

9、Docker 调用的命令

Nvidia-docker run --rm -v /path:/path dockerimages:v1 /bin/bash -c “cat config.josn | ./main”

Docker打包深度学习项目

9、Docker commit -it 容器名 镜像名

10、Docker save -o 镜像名 tar包名