翼度科技»论坛 编程开发 python 查看内容

Pytorch基础教程之torchserve模型部署解析

9

主题

9

帖子

27

积分

新手上路

Rank: 1

积分
27
note


    1. torch-model-archiver
    复制代码
    打包模型;利用
    1. torchserve
    复制代码
    加载前面打包的模型,并以grpc和http等接口往外提供推理服务

    • 自定义
      1. handler
      复制代码
      类时initialize()、preprocess()、postprocess()和handle()这四个方法都是可选的

  • 启动模型的api服务、
    1. curl
    复制代码
    命令发送http post请求,请求模型服务API;流程和TensorFlow serving流程大同小异
    1. torchserve
    复制代码
    是基于
    1. netty
    复制代码
    网络框架实现的,底层使用
    1. EpollServerSocketChannel
    复制代码
    服务进行网络通信,通过
    1. epoll
    复制代码
    多路复用技术实现高并发网络连接处理。

一、torchserve和archiver模块



  • 模型部署需要用到两个模块
  • torchserve用来模型部署
  • torch-model-archiver打包模型
  1. pip:
  2.     - torch-workflow-archiver
  3.     - torch-model-archiver
  4.     - torchserve
复制代码
二、Speech2Text Wav2Vec2模型部署


2.1 准备模型和自定义handler


  • Wav2Vec2语音转文本的模型。这里我们为了简化流程从huggingface下载对应的模型,进行本地化利用torchserve部署
    1. hander
    复制代码
    将原始data进行转为模型输入所需的格式;nlp中很多任务可以直接用torchtext的
    1. text_classifier
    复制代码

  1. # 1. 导入huggingface模型
  2. from transformers import AutoModelForCTC, AutoProcessor
  3. import os
  4. modelname = "facebook/wav2vec2-base-960h"
  5. model = AutoModelForCTC.from_pretrained(modelname)
  6. processor = AutoProcessor.from_pretrained(modelname)
  7. modelpath = "model"
  8. os.makedirs(modelpath, exist_ok=True)
  9. model.save_pretrained(modelpath)
  10. processor.save_pretrained(modelpath)
  11. # 2. 自定义handler
  12. import torch
  13. import torchaudio
  14. from transformers import AutoProcessor, AutoModelForCTC
  15. import io
  16. class Wav2VecHandler(object):
  17.     def __init__(self):
  18.         self._context = None
  19.         self.initialized = False
  20.         self.model = None
  21.         self.processor = None
  22.         self.device = None
  23.         # Sampling rate for Wav2Vec model must be 16k
  24.         self.expected_sampling_rate = 16_000
  25.     def initialize(self, context):
  26.         """Initialize properties and load model"""
  27.         self._context = context
  28.         self.initialized = True
  29.         properties = context.system_properties
  30.         # See https://pytorch.org/serve/custom_service.html#handling-model-execution-on-multiple-gpus
  31.         self.device = torch.device("cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu")
  32.         model_dir = properties.get("model_dir")
  33.         self.processor = AutoProcessor.from_pretrained(model_dir)
  34.         self.model = AutoModelForCTC.from_pretrained(model_dir)
  35.     def handle(self, data, context):
  36.         """Transform input to tensor, resample, run model and return transcribed text."""
  37.         input = data[0].get("data")
  38.         if input is None:
  39.             input = data[0].get("body")
  40.         # torchaudio.load accepts file like object, here `input` is bytes
  41.         model_input, sample_rate = torchaudio.load(io.BytesIO(input), format="WAV")
  42.         # Ensure sampling rate is the same as the trained model
  43.         if sample_rate != self.expected_sampling_rate:
  44.             model_input = torchaudio.functional.resample(model_input, sample_rate, self.expected_sampling_rate)
  45.         model_input = self.processor(model_input, sampling_rate = self.expected_sampling_rate, return_tensors="pt").input_values[0]
  46.         logits = self.model(model_input)[0]
  47.         pred_ids = torch.argmax(logits, axis=-1)[0]
  48.         output = self.processor.decode(pred_ids)
  49.         return [output]
复制代码
在自定义 Handler 中,需要实现以下方法:

  • initialize: 用于初始化模型,加载权重等操作。
  • preprocess: 用于将原始输入数据转换为 PyTorch 张量。
  • inference: 用于执行模型推理。
  • postprocess: 用于将模型输出转换为 API 输出格式。

2.2 打包模型和启动模型api服务


  • 可以直接在linux环境的terminal进行如下相关操作(打包模型、启动模型的api服务、curl命令发送http post请求,请求模型服务API)
  • curl命令发送http post请求,请求模型服务API,如果遇到报错java.lang.NoSuchMethodError: java.nio.file.Files.readString(Ljava/nio/file/Path;)Ljava/lang/String;则应该是JRE没有安装或者需要升级:sudo apt install default-jre即可。
  • curl那坨后正常会返回I HAD THAT CURIOSITY BESIDE ME AT THIS MOMENT%,测试数据是一段简单的sample.wav语音文件
  • Waveform Audio File Format(WAVE,又或者是因为WAV后缀而被大众所知的),它采用RIFF(Resource Interchange File Format)文件格式结构。通常用来保存PCM格式的原始音频数据,所以通常被称为无损音频
  1. # 打包部署模型文件, 把model部署到torchserve
  2. torch-model-archiver --model-name Wav2Vec2 --version 1.0 --serialized-file model/pytorch_model.bin --handler ./handler.py --extra-files "model/config.json,model/special_tokens_map.json,model/tokenizer_config.json,model/vocab.json,model/preprocessor_config.json" -f
  3. mv Wav2Vec2.mar model_store
  4. # 启动model服务, 加载前面打包的model, 并以grpc和http接口向外提供推理服务
  5. torchserve --start --model-store model_store --models Wav2Vec2=Wav2Vec2.mar --ncs
  6. # Once the server is running, let's try it with:
  7. curl -X POST http://127.0.0.1:8080/predictions/Wav2Vec2 --data-binary '@./sample.wav' -H "Content-Type: audio/basic"
  8. # 暂停torchserve serving
  9. torchserve --stop
复制代码
2.3 相关参数记录

torch-model-archiver:用来打包模型

  • model-name: 设定部署的模型名称
  • version: 设定部署的模型版本
  • model-file: 定义模型结构的python文件
  • serialized-file: 设定训练模型保存的pth文件
  • export-path: 设定打包好的模型保存路径
  • extra-files: 设定额外的文件,如label跟id映射的定义文件等,用于一并打包到模型压缩包中
  • handler: 为一个处理器,用来指定模型推理预测前后的数据的处理问题;如 nlp模型中的文本分词和转换为id的步骤;以及分类问题中,模型预测结果映射为具体的label等数据处理功能
  1. torch-model-archiver:用来打包模型
  2. usage: torch-model-archiver [-h] --model-name MODEL_NAME
  3.                             [--serialized-file SERIALIZED_FILE]
  4.                             [--model-file MODEL_FILE] --handler HANDLER
  5.                             [--extra-files EXTRA_FILES]
  6.                             [--runtime {python,python2,python3}]
  7.                             [--export-path EXPORT_PATH]
  8.                             [--archive-format {tgz,no-archive,default}] [-f]
  9.                             -v VERSION [-r REQUIREMENTS_FILE]
复制代码
torchserve:该组件用来加载前面打包的模型,并以grpc和http等接口往外提供推理服务

  • start 和 stop: 即推理服务的启动和停止;
  • model-store: 打包模型存储的路径;
  • models: 设定模型名称和模型文件名,如:MODEL_NAME=MODEL_PATH2 格式;
  • no-config-snapshots: 即 --ncs,用来设置防止服务器存储配置快照文件;
Reference
[1] https://github.com/pytorch/serve
[2] Torch Model archiver for TorchServe
[3] https://github.com/pytorch/serve/tree/master/examples/speech2text_wav2vec2
[4] https://huggingface.co/docs/transformers/model_doc/wav2vec2
[5] https://github.com/pytorch/serve/tree/master/model-archiver
[6] pytorch 模型部署.nlper
[7] cURL - 学习/实践
[8] Serving PyTorch Models Using TorchServe(by using transformer model for example)
[9] 四种常见的 POST 提交数据方式
[10] TorchServe 详解:5 步将模型部署到生产环境
[11] PyTorch最新工具torchserve用于0.部署模型
到此这篇关于Pytorch基础教程之torchserve模型部署和推理的文章就介绍到这了,更多相关torchserve模型部署内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/python/292072sg8.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具