Triton Server Python 后端优化

接上文 不使用 Docker 构建 Triton 服务器并在 Google Colab 平台上部署 HuggingFace 模型

MultiGPU && Multi Instance

Config

追加

bash 复制代码
·
·
·
instance_group [
  {
    count: 4
    kind: KIND_GPU
    gpus: [ 0, 1 ]
  }
]

Python Backend

Triton 会根据配置信息启动四个实例,model_instance_device_id 可以获取到 Triton 给每个实例自动分配的 GPU,模型加载到GPU时使用 .to(f"cuda:{gpu}"时指定 GPU 的 id 即可。

python 复制代码
import numpy as np
import triton_python_backend_utils as pb_utils
from transformers import ViTImageProcessor, ViTModel
from diffusers import DiffusionPipeline
import torch
import time
import os
import shutil
import json
import numpy as np

class TritonPythonModel:
    def initialize(self, args):
        gpu = json.loads(args["model_instance_device_id"])
        self.model = DiffusionPipeline.from_pretrained(
            "playgroundai/playground-v2.5-1024px-aesthetic",
            torch_dtype=torch.float16,
            variant="fp16"
        ).to(f"cuda:{gpu}")
·
·
·

Dynamic Batch

开启此配置 Triton 会将一段时间间隔内的请求组成一个batch交给模型批处理

Config

bash 复制代码
·
·
·
dynamic_batching {
    max_queue_delay_microseconds: 100
}

Python Backend

此时需要对后端代码进行改造,之前的代码每次只能处理一个请求,GPU仅仅占用30G,对于80G的 GPU 来说实在是浪费资源。SDXL 依次是可以处理多个 Prompt 生成多个图片的,只要不把现存撑爆就行。现在我们要在最大 Batch 的限制内处理多个请求,假设客户端每个请求只包含一个 Prompt。

我们获取到一个请求后不直接输入到模型,而是都添加到 Prompts 列表里,然后统一生成图片,然后把生成的图片和请求一一对应上,最后响应给客户端就OK了。

python 复制代码
·
·
·
    def execute(self, requests):
        responses = []
        prompts = []
        for request in requests:
            inp = pb_utils.get_input_tensor_by_name(request, "prompt")
            for i in inp.as_numpy():
                prompts.append(i[0].decode())
        images = self.model(prompt=prompts, num_inference_steps=50, guidance_scale=3).images
        pixel_values = []
        for image in images:
            pixel_values.append(np.asarray(image))
            inference_response = pb_utils.InferenceResponse(
                output_tensors=[
                    pb_utils.Tensor(
                        "generated_image",
                        np.array(pixel_values),
                    )
                ]
            )
            responses.append(inference_response)
        return responses

ONNX_RUNTIME(失败)

转换 playgroundai/playground-v2.5-1024px-aesthetic pipeline 为 onnx 格式

bash 复制代码
pip3 install diffusers>=0.27.0 transformers accelerate safetensors optimum["onnxruntime"]
optimum-cli export onnx --model playgroundai/playground-v2.5-1024px-aesthetic --task stable-diffusion-xl playground-v2.5_onnx/

分享已经转换好的文件:

测试一下

python 复制代码
from optimum.onnxruntime import ORTStableDiffusionXLPipeline

model_id = "playground-v2.5_onnx"
pipeline = ORTStableDiffusionXLPipeline.from_pretrained(model_id)
prompt = "sailing ship in storm by Leonardo da Vinci"
image = pipeline(prompt).images[0]
# pipeline.save_pretrained("playground-v2.5-onnx/")

成功加载,发现使用的是 CPU 推理,参考Accelerated inference on NVIDIA GPUs发现默认是用CPU,需要卸载 optimum["onnxruntime"] 安装 optimum[onnxruntime-gpu]。

python 复制代码
pipeline = ORTStableDiffusionXLPipeline.from_pretrained(model_id, provider="CUDAExecutionProvider", device=f"cuda:{gpu}")

FAQ

CPU 推理正常,GPU推理报错,类似这种错误:

  1. E:onnxruntime:Default, provider_bridge_ort.cc:1480 TryGetProviderInfo_CUDA\] /onnxruntime_src/onnxruntime/core/session/provider_bridge_ort.cc:1193 onnxruntime::Provider\& onnxruntime::ProviderLibrary::Get() \[ONNXRuntimeError\] : 1 : FAIL : Failed to load library libonnxruntime_providers_cuda.so with error: libcublasLt.so.12: cannot open shared object file: No such file or directory 解决方法: 安装CUDNN,[官方手册](https://docs.nvidia.com/deeplearning/cudnn/installation/linux.html)

apt install libcudnn8=8.9.2.26-1+cuda12.1 -y
apt install libcudnn8-dev=8.9.2.26-1+cuda12.1 -y
apt install libcudnn8-samples=8.9.2.26-1+cuda12.1 -y

复制代码
2. 2024-04-08 15:21:39.497586288 \[E:onnxruntime:, sequential_executor.cc:514 ExecuteKernel\] Non-zero status code returned while running Add node. Name:'/down_blocks.1/attentions.0/Add' Status Message: /down_blocks.1/attentions.0/Add: left operand cannot broadcast on dim 3 LeftShape: {2,64,4096,10}, RightShape: {2,640,64,64}  
   ![在这里插入图片描述](https://file.jishuzhan.net/article/1777457375091888129/10a2040eaf2be676d6a7430330fd5906.webp)  
   解决方法:  
   未解决,参考 [Issue](https://github.com/pytorch/pytorch/issues/101502)

### TENSORRT_RUNTIME

Doing...
相关推荐
胡攀峰3 小时前
第12章 微调生成模型
人工智能·大模型·llm·sft·强化学习·rlhf·指令微调
RUNTIME10 小时前
大模型微调实操记录
llm
数据智能老司机10 小时前
构建具备自主性的人工智能系统——探索协调者、工作者和委托者方法
深度学习·llm·aigc
数据智能老司机11 小时前
构建具备自主性的人工智能系统——使代理能够使用工具和进行规划
深度学习·llm·aigc
量子位14 小时前
智能车速度刷新:仅 10 个月,首个纯端侧大模型上车量产!
人工智能·llm
技术你大飞哥16 小时前
【突破数据孤岛】MCP协议进化史:从 STDIO 到全双工流式 —— AI 应用开发效率提升 90% 的秘密武器
llm·ai编程·mcp
Goboy17 小时前
零基础搞定 Trae 智能体配置 + MySQL MCP 集成!手把手教学
llm·ai编程·trae
漫谈网络1 天前
Ollama API 应用指南
ai·llm·aigc·api·ollama
数据智能老司机1 天前
使用 FastAPI 构建生成式 AI 服务——与生成模型的实时通信
llm·openai·fastapi