前言
在PyTorch 环境下生成模型 .pt 格式,放到指定目录下,再转换为 .mar 格式,利用模型预测
1、本地生成 .pt 模型
#scripted mode
from torchvision import models
import torch
model = models.resnet18(pretrained=True)
sm = torch.jit.script(model)
sm.save("/Users/hb/serve/model-archiver/resnet-18.pt")
2、转换为 .mar 格式
# model-archiver
pip install .
torch-model-archiver -f --model-name resnet-18 \
--version 1.0 \
--serialized-file resnet-18.pt \
--handler image_classifier \
--export-path model-store/
可能会执行报错,把 \ 全部删了就能运行成功
torch-model-archiver -f --model-name resnet-18 --version 1.0 --serialized-file resnet-18.pt --handler image_classifier --export-path model-store/
3、 docker 启动 torchserve
docker run --rm -it -p 8080:8080 -p 8081:8081 --name mar -v $(pwd)/model-store:/home/model-server/model-store -v $(pwd)/examples:/home/model-server/examples pytorch/torchserve:latest
4、注册模型
curl --location --request POST 'http://localhost:8081/models' \
--header 'Content-Type: application/json' \
--data-raw '{
"url": "resnet-18.mar",
"batch_size": 64,
"initial_workers": 1
}'
代码可能会报错,格式不对
https://code.bizseer.com/puruokun/torch-serving/-/tree/master/
从这里修改的代码,可以用;复制到其他地方,再次复制使用就会出现问题。
5、预测
-
下载图片
curl -O https://s3.amazonaws.com/model-server/inputs/kitten.jpg -
预测
curl 'http://127.0.0.1:8080/predictions/resnet-18' -T kitten.jpg
6、删除没有注册并且没用的模型(可选)
curl --location --request DELETE ‘http://localhost:8081/models/shape_cnn’ \