• 文档 >
  • 使用 Triton 服务 Torch-TensorRT 模型
快捷方式

使用 Triton 服务 Torch-TensorRT 模型

在关于机器学习基础设施的讨论中,优化和部署是相辅相成的。完成网络层面的优化以获得最大性能后,下一步就是部署模型。

然而,服务这个优化后的模型会带来一系列自身的考量和挑战,例如:构建支持并发模型执行的基础设施、通过 HTTP 或 gRPC 支持客户端等等。

Triton 推理服务器解决了上述问题及更多。让我们一步一步讨论使用 Torch-TensorRT 优化模型、将其部署到 Triton 推理服务器以及构建客户端来查询模型的过程。

步骤 1:使用 Torch-TensorRT 优化模型

大多数 Torch-TensorRT 用户都熟悉此步骤。为了演示目的,我们将使用 Torchhub 中的 ResNet50 模型。

我们将在 //examples/triton 目录下工作,该目录包含本教程中使用的脚本。

首先拉取 NGC PyTorch Docker 容器。您可能需要创建一个帐户并从此处获取 API 密钥。注册并使用您的密钥登录(注册后按照此处的说明操作)。

# YY.MM is the yy:mm for the publishing tag for NVIDIA's Pytorch
# container; eg. 24.08
# NOTE: Use the publishing tag for both the PyTorch container and the Triton Containers

docker run -it --gpus all -v ${PWD}:/scratch_space nvcr.io/nvidia/pytorch:YY.MM-py3
cd /scratch_space

使用该容器,我们可以将模型导出到 Triton 模型库中的正确目录。这个导出脚本使用 Torch-TensorRT 的 Dynamo 前端将 PyTorch 模型编译到 TensorRT。然后,我们使用 TorchScript 作为 Triton 支持的序列化格式保存模型。

import torch
import torch_tensorrt as torchtrt
import torchvision

import torch
import torch_tensorrt
torch.hub._validate_not_a_forked_repo=lambda a,b,c: True

# load model
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True).eval().to("cuda")

# Compile with Torch TensorRT;
trt_model = torch_tensorrt.compile(model,
    inputs= [torch_tensorrt.Input((1, 3, 224, 224))],
    enabled_precisions= {torch_tensorrt.dtype.f16}
)

ts_trt_model = torch.jit.trace(trt_model, torch.rand(1, 3, 224, 224).to("cuda"))

# Save the model
torch.jit.save(ts_trt_model, "/triton_example/model_repository/resnet50/1/model.pt")

您可以使用以下命令运行脚本(在 //examples/triton 目录下)

docker run --gpus all -it --rm -v ${PWD}:/triton_example nvcr.io/nvidia/pytorch:YY.MM-py3 python /triton_example/export.py

这将把 ResNet 模型的序列化 TorchScript 版本保存在模型库的正确目录中。

步骤 2:设置 Triton 推理服务器

如果您是 Triton 推理服务器的新手并想了解更多信息,我们强烈建议您查看我们的 Github 仓库

要使用 Triton,我们需要创建一个模型库。模型库,顾名思义,是推理服务器托管的模型仓库。虽然 Triton 可以服务来自多个仓库的模型,但在本例中,我们将讨论最简单的模型库形式。

这个仓库的结构应该看起来像这样

model_repository
|
+-- resnet50
    |
    +-- config.pbtxt
    +-- 1
        |
        +-- model.pt

Triton 需要两个文件来服务模型:模型本身和模型配置文件,通常以 config.pbtxt 格式提供。对于我们在步骤 1 中准备的模型,可以使用以下配置

name: "resnet50"
backend: "pytorch"
max_batch_size : 0
input [
  {
    name: "x"
    data_type: TYPE_FP32
    dims: [ 1, 3, 224, 224 ]
  }
]
output [
  {
    name: "output0"
    data_type: TYPE_FP32
    dims: [1, 1000]
  }
]

config.pbtxt 文件用于描述准确的模型配置,包含输入和输出层名称及形状、数据类型、调度和批处理细节等信息。如果您是 Triton 的新手,我们强烈建议您查阅我们的文档的这一部分以获取更多详细信息。

完成模型库设置后,我们可以使用下面的 docker 命令启动 Triton 服务器。请参考此页面获取容器的拉取标签。

# Make sure that the TensorRT version in the Triton container
# and TensorRT version in the environment used to optimize the model
# are the same. Roughly, like publishing tags should have the same TensorRT version

docker run --gpus all --rm -p 8000:8000 -p 8001:8001 -p 8002:8002 -v ${PWD}:/triton_example nvcr.io/nvidia/tritonserver:YY.MM-py3 tritonserver --model-repository=/triton_example/model_repository

这应该会启动一个 Triton 推理服务器。下一步,构建一个简单的 http 客户端来查询服务器。

步骤 3:构建 Triton 客户端来查询服务器

在继续之前,请确保手头有一个示例图像。如果您没有,请下载一个示例图像用于测试推理。在本节中,我们将介绍一个非常基础的客户端。有关更多丰富示例,请参考 Triton 客户端仓库

wget  -O img1.jpg "https://www.hakaimagazine.com/wp-content/uploads/header-gulf-birds.jpg"

然后我们需要安装构建 python 客户端的依赖项。这些依赖项会因客户端而异。有关 Triton 支持的所有语言的完整列表,请参考 Triton 的客户端仓库

pip install torchvision
pip install attrdict
pip install nvidia-pyindex
pip install tritonclient[all]

让我们开始构建客户端。首先,我们编写一个小型的预处理函数来调整查询图像的大小并进行归一化。

import numpy as np
from torchvision import transforms
from PIL import Image
import tritonclient.http as httpclient
from tritonclient.utils import triton_to_np_dtype

# preprocessing function
def rn50_preprocess(img_path="/triton_example/img1.jpg"):
  img = Image.open(img_path)
  preprocess = transforms.Compose(
      [
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ]
  )
  return preprocess(img).unsqueeze(0).numpy()

 transformed_img = rn50_preprocess()

构建客户端需要三个基本要点。首先,我们与 Triton 推理服务器建立连接。

# Setting up client
client = httpclient.InferenceServerClient(url="localhost:8000")

其次,我们指定模型的输入和输出层的名称。这可以在导出期间获得,并且应该已在您的 config.pbtxt 文件中指定。

inputs = httpclient.InferInput("x", transformed_img.shape, datatype="FP32")
inputs.set_data_from_numpy(transformed_img, binary_data=True)

outputs = httpclient.InferRequestedOutput("output0", binary_data=True, class_count=1000)

最后,我们向 Triton 推理服务器发送推理请求。

# Querying the server
results = client.infer(model_name="resnet50", inputs=[inputs], outputs=[outputs])
inference_output = results.as_numpy('output0')
print(inference_output[:5])

输出应该如下所示

[b'12.468750:90' b'11.523438:92' b'9.664062:14' b'8.429688:136'
 b'8.234375:11']

此处的输出格式为 <置信度得分>:<分类索引>。要了解如何将这些映射到标签名称以及更多信息,请参考 Triton 推理服务器的文档

您可以使用以下命令快速尝试此客户端

# Remember to use the same publishing tag for all steps (e.g. 24.08)

docker run -it --net=host -v ${PWD}:/triton_example nvcr.io/nvidia/tritonserver:YY.MM-py3-sdk bash -c "pip install torchvision && python /triton_example/client.py"

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题解答

查看资源