开始使用

使用 Ultralytics YOLO26 的 Triton Inference Server

Triton 推理服务器(原名 TensorRT 推理服务器)是 NVIDIA 开发的开源软件解决方案。它提供针对 NVIDIA GPU 优化的云端推理解决方案。Triton 简化了生产环境中的大规模模型服务。将 Ultralytics YOLO26 与 Triton 推理服务器集成后,你可以部署可扩展、高性能的深度学习推理工作负载。本指南介绍如何设置并测试这项集成。



观看: NVIDIA Triton Inference Server 入门

什么是 Triton Inference Server?#

Triton Inference Server 专为在生产环境中部署各种 AI 模型而设计。它支持多种深度学习和机器学习框架,包括 PyTorch、TensorFlow、ONNX、OpenVINO、TensorRT 等。它的主要用途包括:

  • 通过单个服务器实例提供多个模型服务
  • 无需重启服务器即可动态加载和卸载模型
  • 集成推理:结合使用多个模型以取得结果
  • 模型版本管理,用于 A/B 测试和滚动更新

Triton Inference Server 的主要优势#

将 Triton 推理服务器与 Ultralytics YOLO26 搭配使用有以下几个优势:

  • 自动批处理:在处理之前将多个 AI 请求合并,提高吞吐量和 GPU 利用率
  • Kubernetes 集成:云原生设计可与 Kubernetes 配合,用于管理和扩展 AI 应用
  • 硬件专项优化:充分利用 NVIDIA GPU,实现最高性能
  • 框架灵活性:支持多种 AI 框架,包括 PyTorch、TensorFlow、ONNX、OpenVINO 和 TensorRT
  • 开源且可定制:可根据具体需求进行修改,灵活适用于各种 AI 应用

前置条件#

继续操作前,请确保满足以下先决条件:

  • 你的计算机上已安装 Docker(>= 28.2.0,使用 NVIDIA Container Toolkit >= 1.18 以通过 CDI 访问 GPU)或 Podman
  • 安装 ultralytics:
    pip install ultralytics
  • 安装 tritonclient:
    pip install tritonclient[all]

设置 Triton Inference Server#

运行以下完整设置代码块,将 Ultralytics YOLO26 导出为 ONNX、构建 Triton 模型仓库并启动 Triton 推理服务器:

注意

在脚本中使用 runtime 开关选择容器引擎:

  • 设置 runtime = "docker" 以使用 Docker
  • 设置 runtime = "podman" 以使用 Podman
import contextlib
import subprocess
import time
from pathlib import Path

from tritonclient.http import InferenceServerClient

from ultralytics import YOLO

runtime = "docker"  # set to "podman" to use Podman

# 1) Exporting YOLO26 to ONNX Format

# Load a model
model = YOLO("yolo26n.pt")  # load an official model

# Retrieve metadata during export. Metadata needs to be added to config.pbtxt. See next section.
metadata = []

def export_cb(exporter):
    metadata.append(exporter.metadata)

model.add_callback("on_export_end", export_cb)

# Export the model
onnx_file = model.export(format="onnx", dynamic=True)

# 2) Setting Up Triton Model Repository

# Define paths
model_name = "yolo"
triton_repo_path = Path("tmp") / "triton_repo"
triton_model_path = triton_repo_path / model_name

# Create directories
(triton_model_path / "1").mkdir(parents=True, exist_ok=True)

# Move ONNX model to Triton Model path
Path(onnx_file).rename(triton_model_path / "1" / "model.onnx")

# Create config file
(triton_model_path / "config.pbtxt").touch()

data = """
# Add metadata
parameters {
  key: "metadata"
  value {
    string_value: "%s"
  }
}

# Enable TensorRT acceleration (requires a GPU and TensorRT-enabled Triton; remove this block for CPU-only serving)
# The first run will be slow due to TensorRT engine conversion
optimization {
  execution_accelerators {
    gpu_execution_accelerator {
      name: "tensorrt"
      parameters {
        key: "precision_mode"
        value: "FP16"
      }
      parameters {
        key: "max_workspace_size_bytes"
        value: "3221225472"
      }
      parameters {
        key: "trt_engine_cache_enable"
        value: "1"
      }
      parameters {
        key: "trt_engine_cache_path"
        value: "/models/yolo/1"
      }
    }
  }
}
""" % metadata[0]  # noqa

with open(triton_model_path / "config.pbtxt", "w") as f:
    f.write(data)

# 3) Running Triton Inference Server

# Define image https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver
tag = "nvcr.io/nvidia/tritonserver:26.02-py3"  # 16.17 GB (Compressed Size)

subprocess.call(f"{runtime} pull {tag}", shell=True)

# CDI GPU request works identically on Docker and Podman
gpu_flags = "--device nvidia.com/gpu=all"

container_name = "triton_server"

# Note: The :z flag on the volume mount is necessary for systems with SELinux (like Fedora/RHEL)
subprocess.call(
    f"{runtime} run -d --rm --name {container_name} {gpu_flags} -v {triton_repo_path.absolute()}:/models:z -p 8000:8000 {tag} tritonserver --model-repository=/models",
    shell=True,
)

# Wait for the Triton server to start
triton_client = InferenceServerClient(url="127.0.0.1:8000", verbose=False, ssl=False)

# Wait until model is ready
for _ in range(10):
    with contextlib.suppress(Exception):
        assert triton_client.is_model_ready(model_name)
        break
    time.sleep(1)

运行推理#

使用 Triton Server 模型运行推理:

from ultralytics import YOLO

# 加载 Triton Server 模型
model = YOLO("http://127.0.0.1:8000/yolo", task="detect")

# 在服务器上运行推理
results = model("path/to/image.jpg")

清理容器:

import subprocess

runtime = "docker"  # set to "podman" to use Podman
container_name = "triton_server"  # Kill the named container
subprocess.call(f"{runtime} kill {container_name}", shell=True)

TensorRT 优化(可选)#

如果需要更高的性能,可以在 Triton 推理服务器中使用 TensorRT。TensorRT 是专为 NVIDIA GPU 打造的高性能深度学习优化器,可以显著提升推理速度。

在 Triton 中使用 TensorRT 的主要优势包括:

  • 据 NVIDIA 称,推理速度最高可比仅使用 CPU 的平台快 36 倍
  • 针对硬件进行优化,最大限度地利用 GPU
  • 支持 INT8、FP16 等低精度格式,同时保持精度
  • 通过层融合降低计算开销

上面的 config.pbtxt 已为 ONNX 模型启用 Triton 的 TensorRT 加速器。如果要直接通过 Ultralytics 使用 TensorRT,请将 Ultralytics YOLO26 模型导出为 TensorRT 格式:

from ultralytics import YOLO

# 加载 YOLO26 模型
model = YOLO("yolo26n.pt")

# 将模型导出为 TensorRT 格式
model.export(format="engine")  # 创建 'yolo26n.engine'

有关 TensorRT 优化的更多信息,请参阅 TensorRT 集成指南。

现在,你可以在 Triton Inference Server上部署并运行 Ultralytics YOLO26 模型,实现可扩展的高性能推理。如果你更倾向于托管服务,Ultralytics Platform 可提供专用部署端点。

常见问题#

  • 使用 Ultralytics YOLO26 和 NVIDIA Triton Inference Server 进行设置包含几个关键步骤:

    1. 将 YOLO26 导出为 ONNX 格式:

      from ultralytics import YOLO
      
      # 加载模型
      model = YOLO("yolo26n.pt")  # 加载官方模型
      
      # 将模型导出为 ONNX 格式
      onnx_file = model.export(format="onnx", dynamic=True)
    2. 设置 Triton 模型仓库:

      from pathlib import Path
      
      # 定义路径
      model_name = "yolo"
      triton_repo_path = Path("tmp") / "triton_repo"
      triton_model_path = triton_repo_path / model_name
      
      # 创建目录
      (triton_model_path / "1").mkdir(parents=True, exist_ok=True)
      Path(onnx_file).rename(triton_model_path / "1" / "model.onnx")
      (triton_model_path / "config.pbtxt").touch()
    3. 运行 Triton Server:

      import contextlib
      import subprocess
      import time
      
      from tritonclient.http import InferenceServerClient
      
      # Define image https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver
      tag = "nvcr.io/nvidia/tritonserver:26.02-py3"
      
      runtime = "docker"  # set to "podman" to use Podman
      subprocess.call(f"{runtime} pull {tag}", shell=True)
      
      # CDI GPU request works identically on Docker and Podman
      gpu_flags = "--device nvidia.com/gpu=all"
      
      container_name = "triton_server"
      subprocess.call(
          f"{runtime} run -d --rm --name {container_name} {gpu_flags} -v {triton_repo_path.absolute()}:/models:z -p 8000:8000 {tag} tritonserver --model-repository=/models",
          shell=True,
      )
      
      triton_client = InferenceServerClient(url="127.0.0.1:8000", verbose=False, ssl=False)
      
      for _ in range(10):
          with contextlib.suppress(Exception):
              assert triton_client.is_model_ready(model_name)
              break
          time.sleep(1)

    这套配置可以帮助你在 Triton 推理服务器上高效、大规模地部署 Ultralytics YOLO26 模型,实现高性能 AI 模型推理。

  • 将 Ultralytics YOLO26 与 NVIDIA Triton 推理服务器集成有以下几个优势:

    • 可扩展的 AI 推理:Triton 支持通过单个服务器实例提供多个模型服务,还支持动态加载和卸载模型,因此能够灵活扩展以满足各种 AI 工作负载的需求。
    • 高性能:Triton Inference Server 针对 NVIDIA GPU 进行了优化,可确保高速推理,非常适合目标检测等实时应用。
    • 集成与模型版本管理:Triton 的集成模式可组合多个模型以改善结果;模型版本管理则支持 A/B 测试和滚动更新。
    • 自动批处理:Triton 会自动合并多个推理请求,显著提高吞吐量。
    • 简化部署:Ultralytics 会像加载本地模型一样加载 Triton 端点,因此你无需重写推理代码即可采用 Triton。
  • 在 NVIDIA Triton 推理服务器上部署 Ultralytics YOLO26 模型之前,使用 ONNX(开放神经网络交换)格式有以下几个主要优势:

    • 互操作性:ONNX 格式支持在不同深度学习框架(如 PyTorch、TensorFlow)之间迁移,确保更广泛的兼容性。
    • 优化:包括 Triton 在内的许多部署环境都针对 ONNX 进行了优化,因此能够实现更快的推理和更好的性能。
    • 易于部署:ONNX 在各种框架和平台中都得到广泛支持,可简化不同操作系统和硬件配置下的部署流程。
    • 框架独立性:模型转换为 ONNX 后,就不再受原始框架限制,因此更易于移植。
    • 标准化:ONNX 提供标准化表示,有助于解决不同 AI 框架之间的兼容性问题。

    要导出模型,请使用:

    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    onnx_file = model.export(format="onnx", dynamic=True)

    你可以按照 ONNX 集成指南中的步骤完成此流程。

  • 可以,你可以在 NVIDIA Triton 推理服务器上使用 Ultralytics YOLO26 模型进行推理。将模型设置到 Triton 模型仓库并启动服务器后,你可以按如下方式加载模型并运行推理:

    from ultralytics import YOLO
    
    # 加载 Triton Server 模型
    model = YOLO("http://127.0.0.1:8000/yolo", task="detect")
    
    # 在服务器上运行推理
    results = model("path/to/image.jpg")

    这种方法让你能够在使用熟悉的 Ultralytics YOLO 接口的同时,利用 Triton 的优化功能。

  • 与 TensorFlow 和 PyTorch 模型相比,Ultralytics YOLO26 在部署方面具有多项独特优势:

    • 实时性能:Ultralytics YOLO26 针对实时目标检测任务进行了优化,兼具高准确率和高速度,因此非常适合需要实时视频分析的应用。
    • 易于使用:Ultralytics YOLO26 可与 Triton 推理服务器配合使用,并支持多种导出格式(ONNX、TensorRT),因此能够灵活适应各种部署场景。
    • 高级功能:通过 Triton 提供服务可实现动态模型加载、模型版本管理和集成推理,这些功能对于可扩展且可靠的 AI 部署至关重要。
    • 简化的 API:Ultralytics API 为不同部署目标提供一致的接口,降低了学习门槛并缩短开发时间。
    • 边缘端优化:Ultralytics YOLO26 模型在设计时考虑了边缘部署,即使在资源受限的设备上也能提供出色性能。

    如需了解更多详情,请比较模型导出指南中的部署选项。

评论56

提出问题、分享结果,或帮助其他人。

  1. Tariq-droidGitHub

    I followed the steps and I am encountering this error: AttributeError: 'AutoBackend' object has no attribute 'task'

    can someone help? I have upgraded to the latest version

    1
    1. Glenn JocherUltralytics

      @Tariq-droid it seems like there might be an issue with the model setup. Please ensure that the model is correctly loaded and that the Triton server is running with the appropriate configuration. Double-check the model export and repository setup steps. If the problem persists, consider reviewing the Triton Inference Server documentation for further troubleshooting.

  2. Sachi9soniGitHub

    i am following the same approach and able to complete inference with above code, i did one extra step i also converted onnx model into TensorRT using ( nvcr.io/nvidia/tensorrt:22.11-py3 ) this TRT container and i ran inference with (nvcr.io/nvidia/tritonserver 22.11-py3 ) and i ran the infernce succesfully on any size of input image:

    however i want to run inference with different model size (i.e. 1024 or 800 or 1088), as i want model to be more accuratly work with certain size of images so i exported the onnx model with different size (1024) onnx_file = model.export(format='onnx', dynamic=True,imgsz=1024) converted mode to tesorRT engine using the same conatiner (22.11-py3) trtexec --onnx=yolov8l.onnx --saveEngine=model.plan

    the config.pbxt file i am using are also working fine model loaded succesfully showing status ready but at the time of inference its showing this error:: tritonclient.utils.InferenceServerException: [400] [request id: <id_unknown>] unexpected shape for input 'images' for model 'yolov8l'. Expected [1,3,1024,1024], got [1,3,640,640]

    @glenn-jocher

    1
    1. Glenn JocherUltralytics

      Hey there! It looks like you've done a great job running inference with different input sizes and converting the ONNX model to TensorRT. 👍

      For the error you're encountering, it seems like the Triton server is expecting an input size of [1,3,1024,1024] but is receiving [1,3,640,640] instead. This mismatch is likely due to the model configuration on the server still being set for the original size.

      To resolve this, you'll need to update the config.pbtxt file for your model in the Triton server to match the new input size that you've used during the export (imgsz=1024). Make sure the input section of your config.pbtxt reflects the new dimensions:

      input [
        {
          name: "images"
          data_type: TYPE_FP32
          format: FORMAT_NCHW
          dims: [3, 1024, 1024]
        }
      ]

      After updating the configuration, reload the model on the Triton server to apply the changes. If the server is set to watch the model repository, it should pick up the changes automatically. Otherwise, you may need to manually reload the model or restart the server.

      Give that a try and see if it resolves the issue! If you need more assistance, feel free to reach out. 😊

    2. Sachi9soniGitHub

      Hello, thanks for replying As I said .config.pbxt is ok for me .I have already mentioned the same .into config.pbxt For that I have used inspect model yolov8l.onnx

      https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://www.delltechnologies.com/asset/en-us/products/servers/industry-market/developing-and-deploying-vision-ai-with-dell-and-nvidia-metropolis.pdf&ved=2ahUKEwjU34X9xLCEAxW-ja8BHX_3AwAQFnoECB4QAQ&usg=AOvVaw2AsdCYUzyocT0opY0Rr8gD

      Following this pdf for reference .here in appendix they have given the way to inspect the model .after that I put the same configuration into config.pbxt.. I have problem only with different size of export . My cutomize models are also facing same problem for different sizes party from 640.. 640 is working fine

    3. Sachi9soniGitHub

      Apart from 640 , different export sizes are facing the same problem

      Min reproducible: Convert any model with different size model.export(onnx,imgsz=1024, dynamic = True)

      Use tensorRT container I am using the same tag as in this blog(23.09-py-3) Convert into .plan file using command trtexec --onnx= yolov8l.onnx --saveEngine = model.plan After this conversion we get summary of model too in which we also get input and output shape .( I put the same shape into config.pbxt) Setup the directory Update the config.pbxt according to model Start triton server

      Status is ready

      Send request to client for inference Run the inference using above code.

    4. Paula DerrengerUltralytics

      Hello! It seems like you've followed the steps correctly but are facing an issue with the input size during inference. Since you've already ensured that the config.pbtxt is set up with the correct input size and the model is loaded successfully, the problem might be with the client inference request.

      Make sure that when you send the inference request, the input data is also reshaped to the expected size [1,3,1024,1024]. If you're sending an image of size [1,3,640,640], it will not match the model's expected input shape and will result in the error you're seeing.

      Here's a quick check you can do:

      import numpy as np
      from tritonclient.utils import triton_to_np_dtype
      from tritonclient.http import InferenceServerClient, InferInput
      
      # Assuming 'input_name' is the name of your model's input tensor
      input_name = 'images'
      input_shape = (1, 3, 1024, 1024)
      input_dtype = 'FP32'
      
      # Create a dummy input data with the expected shape
      input_data = np.random.rand(*input_shape).astype(triton_to_np_dtype(input_dtype))
      
      # Initialize the Triton client
      client = InferenceServerClient(url='localhost:8000')
      
      # Create the InferInput object and set the data
      infer_input = InferInput(input_name, input_shape, input_dtype)
      infer_input.set_data_from_numpy(input_data)
      
      # Send inference request
      response = client.infer(model_name='yolov8l', inputs=[infer_input])

      Make sure to replace 'images' and 'yolov8l' with the actual input name and model name used in your Triton server setup.

      If you're still facing issues, double-check the client code to ensure the input data being sent for inference matches the model's expected input shape. If everything seems correct and the problem persists, it might be helpful to share the client code snippet that sends the inference request for further assistance. 😊

    5. Sachi9soniGitHub(已编辑)

      import contextlib import tritonclient.http as httpclient #pip install if needed from ultralytics import YOLO import subprocess import time import cv2 from tritonclient.http import InferenceServerClient import os import numpy as np from tritonclient.utils import triton_to_np_dtype from tritonclient.http import InferenceServerClient, InferInput,InferResult

      Assuming 'input_name' is the name of your model's input tensor

      input_name = 'images' input_shape = (1, 3, 1088, 1088) input_dtype = 'FP32'

      image=cv2.imread("1.jpg") input_data=cv2.resize(image,(1088,1088),interpolation = cv2.INTER_LINEAR) input_data=input_data.reshape(1,3,1088,1088).astype(triton_to_np_dtype(input_dtype))

      Initialize the Triton client

      client = InferenceServerClient(url='localhost:8000')

      Create the InferInput object and set the data

      infer_input = InferInput(input_name, input_shape, input_dtype) infer_input.set_data_from_numpy(input_data)

      Send inference request

      response = client.infer(model_name='v8_p2x_2_1080_50', inputs=[infer_input])

      i am able to run this succesfully by doig this but what to do with response object? now how to use YOLO

    6. Paula DerrengerUltralytics

      Hey there! Great job on successfully running inference with Triton Inference Server! 🎉 To work with the response object from your Triton client, you'll want to extract the inference results, which typically include the detected objects' bounding boxes, classes, and confidence scores.

      Here's a quick example of how you might process the response object:

      # Extract the output from the response
      output_data = response.as_numpy('<output_layer_name>')  # Replace with your actual output layer name
      
      # Now, output_data contains the results of the inference
      # You can process these results as needed, for example:
      for detection in output_data:
          x, y, w, h = detection[:4]  # Bounding box coordinates
          conf = detection[4]  # Confidence score
          class_id = detection[5]  # Class ID
          # ... Now you can use these values as needed

      Make sure to replace '<output_layer_name>' with the actual name of the output layer from your YOLO model.

      If you need further assistance or have more questions, feel free to reach out. Happy coding! 😊

    7. Sachi9soniGitHub

      hey thanks for your response , i was following this code for drwaing and visualizing the result which is availble on ultralytics:::::::: model = YOLO(f'http://localhost:8000/v8_p2x_2_1080_50', task='detect') results=model(input_image)

      Visualize the results on the frame

      annotated_frame = results[0].plot()

      Display the annotated frame

      cv2.imshow("YOLOv8 Inference", annotated_frame)

      which seems quiet simple to work with... but now i am getting tensor so should i have to write a cutomize python script to extracting the result?

    8. Glenn JocherUltralytics

      @Sachi9soni hey, thanks for reaching out! 😊 You're on the right track with the Triton Inference Server. If you've got the response tensor from Triton and you're looking to visualize the results similar to how it's done with Ultralytics directly, you're correct that you'll need to process the tensor.

      The response from Triton will give you raw output, which you'll need to decode to get the bounding boxes, classes, and scores. Here's a simplified way to do it:

      # Assuming 'output_data' is the raw tensor you got from Triton
      output_data = response.as_numpy('<output_layer_name>')  # Replace with your actual output layer name
      
      # Decode the detections (you'll need to implement the decoding based on your model's output format)
      detections = decode_output(output_data)  # This is a placeholder function
      
      # Now you can visualize the detections on your image
      for detection in detections:
          x1, y1, x2, y2, conf, class_id = detection
          cv2.rectangle(input_image, (x1, y1), (x2, y2), (255, 0, 0), 2)  # Draw rectangle
          cv2.putText(input_image, f'{class_id} {conf:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)  # Put class label
      
      # Show the annotated image
      cv2.imshow('YOLOv8 Inference', input_image)
      cv2.waitKey(0)
      cv2.destroyAllWindows()

      Remember to replace '<output_layer_name>' with the name of the output layer from your model and implement the decode_output function according to how your model formats its output.

      Hope this helps! If you need more detailed guidance, the Ultralytics docs and community are always here to help. Happy coding! 🚀

    9. Sachi9soniGitHub(已编辑)

      hey thanks for your responsee , i was trying for interepret the results i was getting (1,5,98260) size tensor . and also getting negative values and so many zero values after printing out the tensor values. i am thinking it like this : image size =1088x1088 is there 1088/32=34 x34 grids and each grids have 85 values? so 34x34x85=98260 and there are 5 boxes for each grid?? am i right? this is the output 5*98260 https://drive.google.com/file/d/1YmRey1AHUNr3lBQDYVjHJQpGu_cLqELi/view?usp=drive_link

    10. Glenn JocherUltralytics(已编辑)

      @Sachi9soni hey there! You're on the right track with your understanding of the output tensor. The tensor shape (1, 5, 98260) is the raw output of an anchor-free YOLOv8/YOLO11-style detector: batch 1, 4 box values plus 1 class score per candidate (a single-class model), and 98260 candidate predictions across all scales. There are no anchor boxes or 85-value layout.

      However, the negative and zero values you're seeing are likely due to raw model outputs that need to be processed through a detection post-processing step. This step typically involves applying a sigmoid function to certain outputs to get probabilities, decoding the bounding boxes, and applying Non-Maximum Suppression (NMS) to remove duplicates and keep only the most confident detections.

      The output you're seeing is not directly interpretable as detections; it's an intermediate representation that needs to be decoded. The YOLO class in Ultralytics handles this for you when you use it for inference, as in the code snippet you provided.

      If you're working with raw output tensors from Triton, you'll need to implement similar post-processing to interpret the results. If you'd like to stick with the simplicity of the Ultralytics interface, you can continue using the YOLO class as you've been doing, and it will take care of the post-processing for you.

      Hope this helps clear things up! If you have any more questions, feel free to ask. 😊👍

  3. eshine996GitHub

    How to do the pre-processing and post-processing of the images when converting the model to onnx? I hope to use Triton client to directly obtain inference results.

  4. nsaadatiGitHub

    Hello,

    I followed the standard steps to deploy a YOLO model using Triton Inference Server on a local machine. However, I noticed that inference without Triton is consistently faster. I’m looking to understand why this might be the case.

    Below is the code I used, along with system information and sample outputs from both local and Triton-based inference runs.

    '''from ultralytics import YOLO from pathlib import Path

    Local inference

    print("Processing video without Triton...") model = YOLO("yolo11n.pt") for _ in range(4): results = model("bus.jpg")

    Export to ONNX

    onnx_file = model.export(format="onnx", dynamic=True)

    Triton repo setup

    triton_repo_path = Path("tmp/triton_repo") triton_model_path = triton_repo_path / "yolo" / "1" triton_model_path.mkdir(parents=True, exist_ok=True) Path(onnx_file).rename(triton_model_path / "model.onnx")

    Triton config

    with open(triton_repo_path / "yolo" / "config.pbtxt", "w") as f: f.write("...") # contains standard TRT config with FP16

    Start Triton Server

    subprocess.call(f"docker run -d --rm --gpus 0 -v {triton_repo_path}:/models -p 8200:8000 <triton_image_tag> tritonserver --model-repository=/models", shell=True)

    Triton inference

    model = YOLO("http://localhost:8200/yolo", task="detect") print("Processing video Triton...") for _ in range(4): results = model("bus.jpg")'''

    System Info:

    GPU: NVIDIA RTX A3000 Laptop GPU

    CUDA: 12.2

    Driver: 538.78

    Python: 3.10.16

    Torch: 2.7.0+cu126

    Inference Output:

    Without Triton:

    css Copy Edit Processing video without Triton... 640x480 4 persons, 1 bus, 49.5ms 640x480 4 persons, 1 bus, 6.8ms 640x480 4 persons, 1 bus, 6.8ms 640x480 4 persons, 1 bus, 7.4ms With Triton:

    css Copy Edit Processing video Triton... 640x480 4 persons, 1 bus, 54.9ms 640x480 4 persons, 1 bus, 46.7ms 640x480 4 persons, 1 bus, 43.9ms 640x480 4 persons, 1 bus, 32.0ms As shown above, inference through Triton is noticeably slower. I expected Triton to offer better or at least similar performance, especially with TensorRT and FP16 optimizations.

    Could you please help explain why this might be happening, and if there are any recommendations for optimizing Triton inference performance?

    Best regards, Nastaran

    1. kuanyshbakytulyGitHub

      you need to optimize triton client using cuda shared memory due to constant requests to triton server. You can test request time.

      2
    2. Glenn JocherUltralytics

      @nsaadati the performance difference you're observing is expected behavior when comparing local inference to Triton server deployment. The additional latency comes from network communication overhead, even when running locally. Each inference request goes through HTTP/gRPC protocols, adding round-trip time.

      To optimize Triton performance, consider enabling dynamic batching in your config.pbtxt to process multiple requests together, and as @kuanyshbakytuly mentioned, using CUDA shared memory to reduce data transfer overhead between client and server. You can also try enabling the TensorRT execution accelerator directly in Triton's config rather than pre-converting to engine format.

      For single-image inference scenarios, local inference will typically be faster due to eliminating network overhead. Triton's benefits become apparent with concurrent requests, batching, and scaled deployments.

      1
    3. hpx502766238GitHub

      you need to optimize triton client using cuda shared memory due to constant requests to triton server. You can test request time.

      I need to optimize the Triton client using CUDA shared memory to reduce the overhead of constant requests to the Triton server. My question is: How can I enable CUDA shared memory via the Ultralytics API? Currently, Ultralytics only exposes a simple model.predict method. Although I have implemented custom preprocessing and postprocessing logic with shared memory acquisition, this approach is overly complex compared to the convenience of the standard Ultralytics API. Is there a more streamlined way to achieve this?

    4. Glenn JocherUltralytics

      At the moment, no—the high-level YOLO(...).predict() Triton path does not expose CUDA shared memory, and the current Triton backend sends im.cpu().numpy() to Triton via TritonRemoteModel, so if you need CUDA SHM/zero-copy-style client optimization you’ll need to use tritonclient directly rather than the Ultralytics wrapper; if you’d like, please open a feature request in Ultralytics Discussions so the team can track demand for adding this support.

  5. OBEsensiaGitHub

    Hello all,

    @glenn-jocher and @vladk-ml maybe a solution can be to consider OBB as a 4 points polygons and use some mask IoU function? It maybe not has efficient as the box IoU but doesn't it worth a try ?

    Best regards.

    1. Glenn JocherUltralytics

      @kuanyshbakytuly Thank you for the detailed analysis and benchmarks. The accuracy difference between direct model inference and Triton deployment is concerning. This could be due to several factors:

      1. Check if preprocessing/scaling is identical between direct inference and Triton - even small differences can impact results significantly
      2. Verify your TensorRT conversion parameters - try explicitly setting precision constraints (FP32/FP16)
      3. Examine your confidence threshold settings in both implementations
      4. Investigate if dynamic batching is causing any issues with tensor shapes

      For the most reliable conversion path, I recommend using:

      model = YOLO("best.pt")
      onnx_file = model.export(format="onnx", dynamic=True, simplify=True)

      Then convert to TensorRT within Triton using the GPU execution accelerator in your config.pbtxt rather than pre-converting to .plan files.

      @OBEsensia Your suggestion for handling OBB as 4-point polygons is interesting. Using mask IoU could indeed be a viable alternative for OBB post-processing in Triton deployments. This approach would allow for standard NMS implementations while still capturing the orientation information. The computational overhead might be worth the integration simplicity, especially when working with format constraints. If you or others implement this approach, we'd be interested in hearing about your results.

    2. kuanyshbakytulyGitHub

      @kuanyshbakytuly Thank you for the detailed analysis and benchmarks. The accuracy difference between direct model inference and Triton deployment is concerning. This could be due to several factors:

      1. Check if preprocessing/scaling is identical between direct inference and Triton - even small differences can impact results significantly
      2. Verify your TensorRT conversion parameters - try explicitly setting precision constraints (FP32/FP16)
      3. Examine your confidence threshold settings in both implementations
      4. Investigate if dynamic batching is causing any issues with tensor shapes

      For the most reliable conversion path, I recommend using:

      model = YOLO("best.pt")
      onnx_file = model.export(format="onnx", dynamic=True, simplify=True)

      Then convert to TensorRT within Triton using the GPU execution accelerator in your config.pbtxt rather than pre-converting to .plan files.

      @OBEsensia Your suggestion for handling OBB as 4-point polygons is interesting. Using mask IoU could indeed be a viable alternative for OBB post-processing in Triton deployments. This approach would allow for standard NMS implementations while still capturing the orientation information. The computational overhead might be worth the integration simplicity, especially when working with format constraints. If you or others implement this approach, we'd be interested in hearing about your results.

      Thank you, problem was on preprocessing. I rechecked and fixed.

  6. kuanyshbakytulyGitHub(已编辑)

    Summary: When deploying YOLOv8 models on Triton Inference Server (TIS), detection accuracy and confidence scores drop significantly compared to running the same models directly with ONNXRuntime or TensorRT.

    First, I tried to deploy by using this guide. I tested the inference performance for different model formats:

    s = time.time()
    for i in range(20):
        inference()
    print(time.time() - s)

    Results:

    Format	         Inference Time (20 runs)
    Triton (.plan)	     2.48 s
    YOLOv8 .engine.      0.56 s
    YOLOv8 .onnx	     1.29 s
    YOLOv8 .pt	     0.65 s

    So, I guess the problem due to low metrics (latency, so on) in Triton Server. Finally, I decided to deploying by handle in order to optimise client.py using cuda shared memory.

    Deployment Setup

    1. Export to ONNX:
    yolo export model=Models/best.pt format=onnx simplify=True opset=19 imgsz=640 batch=20 dynamic=True
    1. Convert ONNX to TensorRT (.plan) via polygraphy:
    polygraphy convert Models/model_det_fp32/best.onnx -o Models/model_det_fp32/model.plan \
      --trt-min-shapes images:[1,3,640,640] \
      --trt-opt-shapes images:[10,3,640,640] \
      --trt-max-shapes images:[20,3,640,640]
    1. Triton Server Config (tensorrt_plan):
    name: "model_det"
    platform: "tensorrt_plan"
    max_batch_size: 20
    
    input {
      name: "images"
      data_type: TYPE_FP32
      dims: [3, 640, 640]
    }
    
    output {
      name: "output0"
      data_type: TYPE_FP32
      dims: [5, 8400]
    }
    
    dynamic_batching {
      preferred_batch_size: [1, 2, 4, 8, 16, 20]
      max_queue_delay_microseconds: 500
    }
    
    instance_group {
      kind: KIND_GPU
      count: 1
    }
    1. Alternative Export via Ultralytics for comparing inference results:
    model = YOLO('Models/best.pt')
    model.export(format='engine', dynamic=True, batch=20, imgsz=640)

    ⚠️ Problem Comparing outputs from:

    model.engine (Ultralytics default TensorRT export)

    model.plan (via Triton)

    → The .plan version deployed on Triton loses confidence and detection count. Inference of model.engine detects true 17 detections (all conf in range(0.5, 0.96), while model.plan (via Triton) detects only 3 detections with max conf=0.6

    🧪 Experiment 2: ONNX Deployment on Triton Export Command:

    yolo export model=Models/model_det_test/best.pt format=onnx opset=19 dynamic=True
    name: "model_det"
    platform: "onnxruntime_onnx"
    max_batch_size: 0
    
    input {
      name: "images"
      data_type: TYPE_FP32
      format: FORMAT_NCHW
      dims: [3, -1, -1] 
    }
    
    output {
      name: "output0"
      data_type: TYPE_FP32
      dims: [5, -1] 
    }
    
    instance_group {
      kind: KIND_GPU
      count: 1
    }

    Comparison ONNXRuntime:

    preprocessed_imgs = preprocess(frame)
    sess = ort.InferenceSession("model.onnx")
    outputs = sess.run(["output"], {"input": preprocessed_imgs})

    Triton:

    client = InferenceServerClient(url='localhost:8000')
    infer_input, scales = preprocess(frame)
    response = client.infer(model_name='model_det', inputs=[infer_input])
    outputs = response.as_numpy('output')

    Result: ONNXRuntime returns 17 detections (as expected). Triton with .onnx returns only 3 detections, all with low confidence (conf=0.4, iou=0.4). Also, I tested convergence of the inferences (Onnxruntime vs Onnx on Triton). They are differing, I forgot saving values.

    diff = np.abs(onnxruntime_outputs - onnx_triton_outputs)

    ❗Expected Behavior Triton Server inference should match the accuracy and output quality of direct inference using ONNXRuntime or TensorRT.

    💬 Question Has anyone experienced similar issues when: Converting YOLOv8 models to .plan using TensorRT for Triton deployment? Observed loss of confidence scores and detection count? Any help or pointers on how to preserve accuracy when deploying YOLOv8 on Triton would be much appreciated!

    Versions: ultralytics 8.3.105 tensorrt 10.9.0.34 tensorrt-cu12 10.9.0.34 tensorrt_cu12_bindings 10.9.0.34 tensorrt_cu12_libs 10.9.0.34 onnx 1.17.0 onnxruntime 1.21.0 onnxruntime-gpu 1.21.0 torch 2.8.0.dev20250408+cu128 torchaudio 2.6.0.dev20250408+cu128 torchvision 0.22.0.dev20250408+cu128 triton 3.2.0 tritonclient 2.56.0

    Docker images: nvcr.io/nvidia/tritonserver 25.03-py3
    nvcr.io/nvidia/tensorrt 25.03-py3

    nvidia-smi Mon Apr 14 22:07:42 2025
    +-----------------------------------------------------------------------------------------+ | NVIDIA-SMI 570.124.06 Driver Version: 570.124.06 CUDA Version: 12.8 | |-----------------------------------------+------------------------+----------------------+ | GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |=========================================+========================+======================| | 0 NVIDIA RTX A4000 Off | 00000000:00:05.0 Off | Off | | 41% 34C P8 15W / 140W | 2415MiB / 16376MiB | 0% Default | | | | N/A | +-----------------------------------------+------------------------+----------------------+

    +-----------------------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=========================================================================================| | 0 N/A N/A 42398 C ...ect_conveyer/.venv/bin/python 188MiB | | 0 N/A N/A 61556 C tritonserver 2212MiB | +-----------------------------------------------------------------------------------------+

    nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2025 NVIDIA Corporation Built on Fri_Feb_21_20:23:50_PST_2025 Cuda compilation tools, release 12.8, V12.8.93 Build cuda_12.8.r12.8/compiler.35583870_0

  7. vladk-mlGitHub

    Hello, I am currently developing an inference solution dependent on a YOLO OBB model for deployment as a docker container, and I have some questions with regards to the recommended development approach.

    I am using currently Triton container 25.01, with specific Nvidia pre-built container form " xx.yy-pyt-python-py3 " This container gives support for PyTorch(pytorch_libtorch) and Python backend for model inferencing and pre and post processing model ensembles.

    https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver

    This was very suitable at the start due the need for python processes both in pre and post-inferencing, but actually integrating the OBB torchscript model into the Triton ensemble has been very painful, apparently the problem lies within the torchscript model itself with regards to how YOLO handles it's dynamic operations versus the static computation graph in TorchScript.

    I have been pursuing solutions and workarounds to the problem but have been met with only failure, and have begun considering alternatives. The error is at opt/pytorch/pytorch/aten/src/ATen/native/xnnpack/Convolution.cpp:188.

    Error Message: xnnpack::convolution not available! Reason: The provided (weight, bias, padding, stride, dilation, groups, transposed, output_min, output_max) parameters are either invalid individually or their combination is not supported by XNNPACK

    Despite XNNPACK and other optimizations being disabled at model load.

    My question(s) are this.

    1. This page only mentions ONNX for integration into Triton, is this the only official supported format by Ultralytics in terms of Triton integration? Or just the only documented one? If so, is this due to Triton's preference for scripted vs traced Torchscript model conversions in multi-GPU, and the preferred method for YOLO export being traced?

    2. If ONNX is the only supported format, is it known if ONNX OBB models converted from the standard yolo.pt models are compatible with Triton?

    3. There is an experimental feature with Triton where Pytorch models above 2.0 can be run with the python runtime, has this feature been looked at by Ultralytics in terms of support with OBB model support?

    Thanks, -Vlad K.

    1. Glenn JocherUltralytics

      @vladk-ml thank you for your detailed questions about Triton deployment with YOLO OBB models. Here's a concise response:

      1. ONNX is the officially documented format for Triton integration due to its broad compatibility and optimization benefits, but TorchScript exports are also supported. The Triton guide focuses on ONNX as it avoids graph staticity issues common in traced models. For TorchScript troubleshooting, see our TorchScript export documentation.

      2. YOLO OBB models exported to ONNX should work with Triton when using the dynamic export flag (dynamic=True). We recommend validating your ONNX export with the YOLO OBB model format documentation.

      3. Python backend support for PyTorch models in Triton hasn’t been formally tested by Ultralytics, but community contributions are welcome. For immediate needs, ONNX remains the recommended path.

      For further Triton configuration help, refer to NVIDIA’s Triton OBB deployment examples.

      1
    2. vladk-mlGitHub

      Thank you for the reply!

      I switched over to the recommended ONNX deployment, but have hit another snag, class mapping and NMS have been very difficult to implement in the post-processing stage of the model ensemble, since now the model is ONNX rather than Pytorch, the postprocessing must be done outside of the model, but this has been more difficult than expected. Either too many detections resulting in memory overload, no usable detections due to degenerate coordinates from output tensor channels [11], or all properly drawn bounding boxes don't actually have any objects within them. So I have a question:

      Do YOLO11 OBB models with multiple classes pre-trained on DOTA dataset have issues when exported to ONNX with nms and optimization disabled for Triton integration? If I have multiple classes of objects to detect with OBB or segmentation in the future, with Triton being the main development path for deployment, would it be best to have 1 model for each class?

      Thanks, -Vlad K.

    3. Glenn JocherUltralytics

      @vladk-ml Thanks for the update on your progress with ONNX deployment. The challenges you're facing with post-processing OBB models in Triton are not uncommon. Here are some insights to help:

      For post-processing OBB models in ONNX format, you'll need to implement custom NMS specific to oriented boxes, which differs from standard NMS. The output tensor from OBB models contains additional rotation parameters that require special handling.

      Regarding your specific questions:

      1. YOLO11 OBB models with multiple classes should work when exported to ONNX, but post-processing is more complex. The raw output needs careful decoding to extract the oriented bounding box parameters correctly.

      2. Using one model per class is generally not recommended - it increases deployment complexity and resource usage. Instead, focus on proper post-processing implementation for multi-class models.

      For a workable solution, consider:

      • Implement OBB-specific NMS in your Python backend (see our OBB task documentation for reference)
      • Ensure correct tensor parsing: OBB outputs include rotation parameters that standard NMS doesn't handle
      • Start with smaller confidence thresholds and gradually tune parameters

      You might also want to examine the ONNX model structure using tools like Netron to better understand the output format. If you continue to face issues, sharing a minimal reproducible example would help us provide more specific guidance.

  8. OBEsensiaGitHub

    Hello Ultralytics Community,

    I was facing an issue with the triton server integration when the model hasn't square input shape (for example 320640 for HW). It seems that the model object stucks to 640640 size even if the triton configuration is set to 320640. The real issue is that even if I resize the image to 320640 the pre_process reverts this change back to 640640... So running the inference with

    results = model(image)

    isn't enough and

    results = model(image, imgsz=[320,640])

    should be used instead. I just put the workaround here in any case someone else can save 5 minutes but...

    Do you think it would be great if the model (and actually the pre_process stage can use the model input configuration as a default?

    1. Glenn JocherUltralytics

      @OBEsensia thank you for sharing your experience! You're correct that when using non-square input shapes with Triton, explicitly specifying imgsz in the predict call is currently required. While the model configuration in Triton does set the server-side parameters, the client-side inference call needs to match those dimensions. We'll consider your suggestion for auto-inferring input shape from Triton config as a potential enhancement. For now, your workaround is the recommended approach. For more details on input shape management, see our Triton configuration guide: https://docs.ultralytics.com/guides/triton-inference-server

  9. faheem-khaskheliGitHub

    hello, i am trying to use .engine (tensorrt) format when using triton inference server but i get error, because triton does not recognize the backend needed for .engine file.

    1. faheem-khaskheliGitHub

      does .onnx give same speed as .engine file? also i have read the documentation of triton it does say that it support tensorrt, by doing some research i found it uses model.plan file. but i donot know how to make it. also i have tried .pt file it say constant.pkl file not found. in config.pbtxt i changes the backend: pytorch or backend: tensorrt. still cannot find any working solution.

    2. Glenn JocherUltralytics

      For Triton Inference Server, please export your YOLOv8 model to ONNX format, as Triton supports ONNX natively. The .engine format is not directly supported by Triton. Ensure your config.pbtxt is correctly set up for ONNX. For more details, refer to the Triton documentation.

    3. faheem-khaskheliGitHub

      https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/index.html

      if you look at the heading major features, first one say it support multiple DL frameworks, also github link clearly mention tensorrr, pytorch, tensorflow and all other popular frameworks.

      https://github.com/triton-inference-server/backend#where-can-i-find-all-the-backends-that-are-available-for-triton.

      also here is support matrix of OS and DL frameworks for triton. https://github.com/triton-inference-server/backend/blob/main/docs/backend_platform_support_matrix.md.

      i want to find out which format work better with triton specially on GPU.

    4. Glenn JocherUltralytics

      For optimal performance with Triton Inference Server, exporting your YOLOv8 model to ONNX format is recommended. While Triton supports TensorRT, it requires a .plan file, which can be generated using TensorRT tools outside of Triton. ONNX generally provides good performance and compatibility across various frameworks. If you encounter issues with .pt files, ensure your configuration aligns with Triton's supported backends. For further details, please consult the Triton documentation.