深度学习系列70:模型部署torchserve

1. 流程说明

ts文件夹下,

从launcher.py进入,执行jar文件。

入口为model_server.py的start()函数。内容包含:

  1. 读取args,创建pid文件

  2. 找到java,启动model-server.jar程序,同时读取log-config文件,TEMP文件夹地址,TS_CONFIG_FILE文件

  3. 根据cpu核数、gpu个数,启动多进程。每个进程有一个socket_name和socket_type,执行model_service_worker.py,创建TorchModelServiceWorker类,并执行run_server方法。run_server不断执行handle_connection方法,handle_connection不断执行predict(cmd为I时)或者load_model(cmd为L时)任务。

  4. load_model可以返回service对象,而service可以执行predict函数。如果handler中间包含冒号,则用后面的function作为_entry_point,否则默认用handle函数作为_entry_point。

  5. service的定义如下。其中manifest是一个字典,记录在MAR包里面的MAR_INF/MANIFEST.json中,包含modelName,serializedFile,handler,modelVersion等信息。这些信息也是modelArchiver打包模型时需要的内容。

    class Service(object):
    """
    Wrapper for custom entry_point
    """

    复制代码
     def __init__(
         self,
         model_name,
         model_dir,
         manifest,
         entry_point,
         gpu,
         batch_size,
         limit_max_image_pixels=True,
         metrics_cache=None,
     ):
  6. 接下来看一下predict函数。首先是调用retrieve_data_for_inference方法获取input_batch,其格式为{parameter["name"]: parameter["value"]}。然后是调用ret = self._entry_point(input_batch, self.context),这里的_entry_point就是我们自己定义的handler.handle方法。默认的handle方法执行三步:

    data_preprocess = self.preprocess(data)
    output = self.inference(data_preprocess)
    output = self.postprocess(output)

2. 运行

  1. 首先安装java,然后pip install torchserve torch-model-archiver

  2. 接着将模型和参数打包:torch-model-archiver --model-name test --version 1.0 --serialized-file test.torchscript.pt --handler handler_test.py --export-path model_store

  3. 启动服务torchserve --start --ncs --model-store model_store --models test.mar --disable-token-auth --ts-config config.properties

  4. 停止服务torchserve --stop

  5. 调用:

    res = requests.post("http://127.0.0.1:8080/predictions/test",files = {"data":data})

相关推荐
xsd2024111839 分钟前
船舶AI边缘计算终端技术实现方案:识别、跟踪、后端与云同步的技术点介绍
人工智能
syso_稻草人1 小时前
qwen-image-2.1 文生图:动物七段结构提示词生成10张萌宠写真(含完整提示词与参数)
人工智能·stable diffusion·comfyui·qwen-image2.1
stormzhangV1 小时前
Google 官方这个开源项目推荐给大家
人工智能·agent·ai编程
小宋10212 小时前
手机 Agent 读屏别默认整屏上交:按视图节点授权、敏感面遮蔽与采集预算,用泄漏率和任务成功率验收
人工智能·智能手机
@陈小鱼2 小时前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
always20222 小时前
AI运行时 · 06 - Kata 与 K8s 集成:RuntimeClass / CSI kata-directvolume / 性能开销与调优
人工智能·容器·kubernetes
谙弆悕博士3 小时前
动态自适应多智能体架构的 LangGraph 实现:从元调度器到可运行原型
人工智能·python·神经网络·机器学习·架构·多智能体·智能体
Rocky Ding*3 小时前
【三年面试五年模拟】2026-09-23 恒生电子AI Agent应用开发岗面试全解析
人工智能·深度学习·机器学习·面试·职场和发展·aigc·ai-native
火山引擎开发者社区4 小时前
员工问一句「我的年假还剩几天」,AI 怎么把事办成?
人工智能
牧羊人.3334 小时前
Dinky 实时计算平台 零基础Docke
人工智能