当前位置: 首页 > 工具软件 > WasmEdge > 使用案例 >

使用wasmedge release版本+wasi-nn搭建pytorch运行镜像

姚雅珺
2023-12-01
docker pull dslim/slim

一、背景

因为公司内网无法使用wasmedge源码在docker容器中进行编译(酸那些可以编译的),所以使用官方发布的稳定版本进行环境搭建。

二、准备

1、wasmedge官网上下载wasmedge  release版本当前稳定版本,目前是0.11.2以及wasi-nn  plugin

2、可以通过私服拉取外部image的docker

三、步骤

1、构建初始容器

      1)拉取wasmedge编译docker镜像

docker pull wasmedge/wasmedge # Pulls the latest - wasmedge/wasmedge:latest

      2)拉取docker-slim

docker pull dslim/slim

     3)下载pytorch(libtorch-cxx11-abi-shared-with-deps-1.8.2+cpu.zip),存放到/zipdir目录(没有自己创建,这是一个自定义目录),使用unzip -p   libtorch-cxx11-abi-shared-with-deps-1.8.2+cpu.zip 解压。

     4)将使用git下载Second State  提供的WasmEdge-WASINN-examples项目,将项目中的pytorch-mobilenet-image目录复制到/zipdir目录中

      5)将wasmedge release版本解压到  /zipdir目录,将wasi-nn解压到/zipdir目录

tar  -zxvf  WasmEdge-0.11.2-ubuntu20.04_x86_64.tar.gz
tar  -zxvf  WasmEdge-plugin-wasi_nn-pytorch-0.11.2-ubuntu20.04_x86_64.tar.gz

   6)参考wasmedge官网进行部署

Build on Linux - WasmEdge Runtime

三点:1、wasmedge安装到/usr/local目录下,wasi-nn安装到/usr/local/lib/wasmedge中,可以写脚本执行如:source   install.sh或者 . install.sh  可以带上export命令一起执行:)

          2、docker是用-v挂载上/zipdir

          3、记得添加LD_LIBRARY_PATH和Torch_PATH哦。

   7)执行wasmedge官网  4.5.2 Pytorch | WasmEdge Developer Guides

pytorch运行命令行:

wasmedge --dir .:. wasmedge-wasinn-example-mobilenet-image.wasm mobilenet.pt input.jpg

将会得到如下结果:

Read torchscript binaries, size in bytes: 14376924
Loaded graph into wasi-nn with ID: 0
Created wasi-nn execution context with ID: 0
Read input tensor, size in bytes: 602112
Executed graph inference
   1.) [954](20.6681)banana
   2.) [940](12.1483)spaghetti squash
   3.) [951](11.5748)lemon
   4.) [950](10.4899)orange
   5.) [953](9.4834)pineapple, ananas

到此完成构建成功了初始容器。

2、使用Dockerfile创建新镜像,将环境变量增加到里面

Dockerfile内容如下:

FROM   wasmedge/<your-image-name>

ENV  LD_LIBRARY_PATH   <your-local-libtorch-path>/lib

ENV  Torch_PATH  <your-local-libtorch-path>

CMD wasmedge

在dockerfile所在目录使用下面命令行创建docker容器:

docker build -t wasmedge/pytorchapp -f Dockerfile ./

3、使用docker-slim进行docker镜像瘦身:

docker run -it --rm -v /var/run/docker.sock:/var/run/docker.sock dslim/slim build --http-probe=false --include-path=<you-want-path> wasmedge/pytorchapp

4、瘦身成功后,会生成一个带.slim的镜像,使用该镜像创建新容器运行wasmedge的pytorch例子运行

docker run -it --rm -v  $PWD:/app wasmedge/pytorhapp:latest wasmedge --dir .:. /app/wasmedge-wainn-example-mobilenet-image.wasm /app/mobilenet.pt /app/input.jpg

随后输出

Read torchscript binaries, size in bytes: 14376924
Loaded graph into wasi-nn with ID: 0
Created wasi-nn execution context with ID: 0
Read input tensor, size in bytes: 602112
Executed graph inference
   1.) [954](20.6681)banana
   2.) [940](12.1483)spaghetti squash
   3.) [951](11.5748)lemon
   4.) [950](10.4899)orange
   5.) [953](9.4834)pineapple, ananas

说明我们成功了!!!

使用docker  images查看成果:

大小瘦身:原来2.86G  -> 现在1.04G(可以再优化)

虚拟环境细化分离:做到了wasm虚拟机和docker容器分离,即wasm虚拟机和torch环境的分离。

 类似资料: