容器服务 ACK 大模型推理最佳实践系列一:TensorRT-LLM

本文涉及的产品
对象存储 OSS,标准 - 本地冗余存储 20GB 3个月
对象存储 OSS,内容安全 1000 次 1年
对象存储 OSS,恶意文件检测 1000次 1年
简介: 在 ACK 中使用 KServe 部署 Triton+TensorRT-LLM

【阅读原文】戳:容器服务 ACK 大模型推理最佳实践系列一:TensorRT-LLM


在ACK中使用KServe部署Triton+TensorRT-LLM。本教程以Llama-2-7b-hf模型为例,演示如何在ACK中使用KServe部署Triton框架。Triton采用TensorRT-LLM后端。

 

 

背景介绍

 

1. KServe

 

KServe[1]是一个开源的云原生模型服务平台,旨在简化在Kubernetes上部署和运行机器学习模型的过程,支持多种机器学习框架、具备弹性扩容能力。KServe通过定义简单的YAML文件,提供声明式的API来部署模型,使得配置和管理模型服务变得更加容易。

 

更多关于KServe框架的信息,请参见KServe社区文档[2]

 

2. Triton(Triton Inference Server)

 

Triton Inference Server[3]是一个NVIDIA开源的推理服务框架,用于帮助用户快速搭建AI推理应用。Triton支持多种不同的机器学习框架作为它的运行时后端,包括TensorRT,TensorFlow,PyTorch,ONNX,vLLM等。Triton面向实时推理、批量推理以及音视频流式推理场景进行了许多优化,以在推理时获得更好的性能。

 

更多关于Triton推理服务框架的信息,请参考Triton Inference Server Github代码库[4]

 

3. TensorRT-LLM

 

TensorRT-LLM[5]是NVIDIA开源的LLM模型优化引擎。该框架用于定义LLM模型并将模型构建为TensorRT Engine,以提升在NVIDIA GPU上的推理效率。TensorRT-LLM还可以与Triton框架结合,作为Triton推理框架的一种后端tensorrtllm_backend[6]。TensorRT-LLM构建的模型可以在单个或多个GPU上运行,支持Tensor Parallelism及Pipeline Parallelism。

 

更多关于TensorRT-LLM的信息,请参考TensorRT-LLM Github代码库[7]

 

 

 

前提条件

 

 

已创建包含GPU的Kubernetes集群。具体操作,请参见创建包含GPU的Kubernetes集群[8]

 

GPU节点显存需要>=24GB。

 

已安装KServe。具体操作,请参见安装ack-kserve组件[9]

 

 

 

1. 准备模型数据及模型编译脚本

 

 

1.1. 从HuggingFace/ModelScope上下载Llama-2-7b-hf模型

 

其他TensorRT-LLM框架支持的模型请参考文档TensorRT-LLM支持矩阵[10]

 

1.2. 准备模型编译脚本

 

新建trtllm-llama-2-7b.sh文件,文件内容如下:

#!/bin/sh
set -e
# 脚本适用于 nvcr.io/nvidia/tritonserver:24.04-trtllm-python-py3 镜像
MODEL_MOUNT_PATH=/mnt/models
OUTPUT_DIR=/root/trt-llm
TRT_BACKEND_DIR=/root/tensorrtllm_backend
# clone tensorrtllm_backend
echo "clone tensorrtllm_backend..."
if [ -d "$TRT_BACKEND_DIR" ]; then
    echo "directory $TRT_BACKEND_DIR exists, skip clone tensorrtllm_backend"
else
  cd /root
  git clone -b v0.9.0 https://github.com/triton-inference-server/tensorrtllm_backend.git
  cd $TRT_BACKEND_DIR
  git submodule update --init --recursive
  git lfs install
  git lfs pull
fi
# covert checkpoint
if [ -d "$OUTPUT_DIR/llama-2-7b-ckpt" ]; then
    echo "directory $OUTPUT_DIR/llama-2-7b-ckpt exists, skip convert checkpoint"
else
  echo "covert checkpoint..."
  python3 $TRT_BACKEND_DIR/tensorrt_llm/examples/llama/convert_checkpoint.py \
  --model_dir $MODEL_MOUNT_PATH/Llama-2-7b-hf \
  --output_dir $OUTPUT_DIR/llama-2-7b-ckpt \
  --dtype float16
fi
# build trtllm engine
if [ -d "$OUTPUT_DIR/llama-2-7b-engine" ]; then
    echo "directory $OUTPUT_DIR/llama-2-7b-engine exists, skip convert checkpoint"
else
  echo "build trtllm engine..."
  trtllm-build --checkpoint_dir $OUTPUT_DIR/llama-2-7b-ckpt \
               --remove_input_padding enable \
               --gpt_attention_plugin float16 \
               --context_fmha enable \
               --gemm_plugin float16 \
               --output_dir $OUTPUT_DIR/llama-2-7b-engine \
               --paged_kv_cache enable \
               --max_batch_size 8
fi
# config model
echo "config model..."
cd $TRT_BACKEND_DIR
cp all_models/inflight_batcher_llm/ llama_ifb -r
export HF_LLAMA_MODEL=$MODEL_MOUNT_PATH/Llama-2-7b-hf
export ENGINE_PATH=$OUTPUT_DIR/llama-2-7b-engine
python3 tools/fill_template.py -i llama_ifb/preprocessing/config.pbtxt tokenizer_dir:${HF_LLAMA_MODEL},triton_max_batch_size:8,preprocessing_instance_count:1
python3 tools/fill_template.py -i llama_ifb/postprocessing/config.pbtxt tokenizer_dir:${HF_LLAMA_MODEL},triton_max_batch_size:8,postprocessing_instance_count:1
python3 tools/fill_template.py -i llama_ifb/tensorrt_llm_bls/config.pbtxt triton_max_batch_size:8,decoupled_mode:False,bls_instance_count:1,accumulate_tokens:False
python3 tools/fill_template.py -i llama_ifb/ensemble/config.pbtxt triton_max_batch_size:8
python3 tools/fill_template.py -i llama_ifb/tensorrt_llm/config.pbtxt triton_backend:tensorrtllm,triton_max_batch_size:8,decoupled_mode:False,max_beam_width:1,engine_dir:${ENGINE_PATH},max_tokens_in_paged_kv_cache:1280,max_attention_window_size:1280,kv_cache_free_gpu_mem_fraction:0.5,exclude_input_in_output:True,enable_kv_cache_reuse:False,batching_strategy:inflight_fused_batching,max_queue_delay_microseconds:0
# run server
echo "run server..."
pip install SentencePiece
tritonserver --model-repository=$TRT_BACKEND_DIR/llama_ifb --http-port=8080 --grpc-port=9000 --metrics-port=8002 --disable-auto-complete-config --backend-config=python,shm-region-prefix-name=prefix0_

 

1.3. 上传OSS,并在集群内创建PV/PVC

 

# 创建目录
ossutil mkdir oss://<your-bucket-name>/Llama-2-7b-hf
# 上传模型文件
ossutil cp -r ./Llama-2-7b-hf oss://<your-bucket-name>/Llama-2-7b-hf
# 上传脚本文件
chmod +x trtllm-llama-2-7b.sh
ossutil cp -r ./trtllm-llama-2-7b.sh oss://<your-bucket-name>/trtllm-llama-2-7b.sh

 

预期oss中文件路径如下:

 

tree -L 1
.
├── Llama-2-7b-hf
└── trtllm-llama-2-7b.sh

 

1.4. 创建PV,PVC

 

替换文件中${your-accesskey-id}、${your-accesskey-secert}、${your-bucket-name}、${your-bucket-endpoint} 变量。

 

kubectl apply -f- << EOF
apiVersion: v1
kind: Secret
metadata:
  name: oss-secret
stringData:
  akId: ${your-accesskey-id} # 用于访问oss的AK
  akSecret: ${your-accesskey-secert} # 用于访问oss的SK
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: llm-model
  labels:
    alicloud-pvname: llm-model
spec:
  capacity:
    storage: 30Gi 
  accessModes:
    - ReadOnlyMany
  persistentVolumeReclaimPolicy: Retain
  csi:
    driver: ossplugin.csi.alibabacloud.com
    volumeHandle: model-oss
    nodePublishSecretRef:
      name: oss-secret
      namespace: default
    volumeAttributes:
      bucket: ${your-bucket-name}
      url: ${your-bucket-endpoint} # e.g. oss-cn-hangzhou.aliyuncs.com
      otherOpts: "-o umask=022 -o max_stat_cache_size=0 -o allow_other"
      path: "/"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: llm-model
spec:
  accessModes:
    - ReadOnlyMany
  resources:
    requests:
      storage: 30Gi
  selector:
    matchLabels:
      alicloud-pvname: llm-model
EOF

 

 

 

2. 创建ClusterServerRuntime


kubectl apply -f- <<EOF
apiVersion: serving.kserve.io/v1alpha1
kind: ClusterServingRuntime
metadata:
  name: triton-trtllm
spec:
  annotations:
    prometheus.kserve.io/path: /metrics
    prometheus.kserve.io/port: "8002"
  containers:
  - args:
    - tritonserver
    - --model-store=/mnt/models
    - --grpc-port=9000
    - --http-port=8080
    - --allow-grpc=true
    - --allow-http=true
    image: nvcr.io/nvidia/tritonserver:24.04-trtllm-python-py3
    name: kserve-container
    resources:
      requests:
        cpu: "4"
        memory: 12Gi
  protocolVersions:
  - v2
  - grpc-v2
  supportedModelFormats:
  - name: triton
    version: "2"
<< EOF

 

 

 

3. 部署应用

 

 

3.1. 部署KServe应用

 

kubectl apply -f- << EOF
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: llama-2-7b
spec:
  predictor:
    model:
      modelFormat:
        name: triton
        version: "2"
      runtime: triton-trtllm
      storageUri: pvc://llm-model/
      name: kserve-container
      resources:
        limits:
          nvidia.com/gpu: "1"
        requests:
          cpu: "4"
          memory: 12Gi
          nvidia.com/gpu: "1"
      command:
      - sh
      - -c
      - /mnt/models/trtllm-llama-2-7b.sh
EOF

 

执行以下命令查看应用是否ready

 

kubectl get isvc llama-2-7b

 

预期输出:

 

NAME         URL                                     READY   PREV   LATEST   PREVROLLEDOUTREVISION   LATESTREADYREVISION   AGE
llama-2-7b   http://llama-2-7b-default.example.com   True                                                                  29m

 

3.2. 访问应用

 

3.2.1. 容器内访问

  •  
curl -X POST localhost:8080/v2/models/ensemble/generate -d '{"text_input": "What is machine learning?", "max_tokens": 20, "bad_words": "", "stop_words": "", "pad_id": 2, "end_id": 2}'

 

3.2.2. 集群内节点访问

 

NGINX_INGRESS_IP=`kubectl -n kube-system get svc nginx-ingress-lb -ojsonpath='{.spec.clusterIP}'`
# 如果不是部署在default命名空间下,需要修改下ns名称
SERVICE_HOSTNAME=$(kubectl get inferenceservice llama-2-7b -n default  -o jsonpath='{.status.url}' | cut -d "/" -f 3)
curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
http://$NGINX_INGRESS_IP:80/v2/models/ensemble/generate \
-d '{"text_input": "What is machine learning?", "max_tokens": 20, "bad_words": "", "stop_words": "", "pad_id": 2, "end_id": 2}'

 

3.2.3. 集群外访问

 

NGINX_INGRESS_IP=`kubectl -n kube-system get svc nginx-ingress-lb -ojsonpath='{.status.loadBalancer.ingress[0].ip}'`
# 如果不是部署在default命名空间下,需要修改下ns名称
SERVICE_HOSTNAME=$(kubectl get inferenceservice llama-2-7b -n default  -o jsonpath='{.status.url}' | cut -d "/" -f 3)
curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
http://$NGINX_INGRESS_IP:80/v2/models/ensemble/generate \
-d '{"text_input": "What is machine learning?", "max_tokens": 20, "bad_words": "", "stop_words": "", "pad_id": 2, "end_id": 2}'

 

预期输出:

  •  
{"context_logits":0.0,"cum_log_probs":0.0,"generation_logits":0.0,"model_name":"ensemble","model_version":"1","output_log_probs":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],"sequence_end":false,"sequence_id":0,"sequence_start":false,"text_output":"\nMachine learning is a type of artificial intelligence (AI) that allows software applications to become more accurate"}

 

 

 

4. Q&A

 

 

Failed to pull image "nvcr.io/nvidia/tritonserver:24.04-trtllm-python-py3": failed to pull and unpack image "nvcr.io/nvidia/tritonserver:24.04-trtllm-python-py3": failed to copy: httpReadSeeker: failed open: failed to authorize: failed to fetch anonymous token: unexpected status from GET request to https://authn.nvidia.com/token?scope=repository%3Anvidia%2Ftritonserver%3Apull&service=registry: 401

 

报错原因:NVIDIA镜像仓库鉴权失败

 

解决方案:在本地机器上手动拉取nvcr.io/nvidia/tritonserver:24.04-trtllm-python-py3镜像并推送到自己的仓库中,然后修改ClusterServeRuntime中的镜像地址为自己的仓库地址。

 

 

 

5. Reference

 

 

https://github.com/triton-inference-server/tensorrtllm_backend/blob/main/docs/llama.md

 

https://github.com/NVIDIA/TensorRT-LLM/blob/main/examples/llama/README.md

 

相关链接:

 

[1] KServe

https://github.com/kserve/kserve

[2] KServe社区文档

https://kserve.github.io/website/latest/

[3] Triton Inference Server

https://github.com/triton-inference-server/server

[4] Triton Inference Server Github代码库

https://github.com/triton-inference-server/server

[5] TensorRT-LLM

https://github.com/NVIDIA/TensorRT-LLM

[6] tensorrtllm_backend

https://github.com/triton-inference-server/tensorrtllm_backend

[7] TensorRT-LLM Github代码库

https://github.com/triton-inference-server/server

[8] 创建包含GPU的Kubernetes集群

https://help.aliyun.com/zh/ack/ack-managed-and-ack-dedicated/user-guide/create-an-ack-managed-cluster-with-gpu-accelerated-nodes?spm=a2c4g.171073.0.0.4c78f95a00Mb5P

[9] 安装ack-kserve组件

https://help.aliyun.com/zh/ack/cloud-native-ai-suite/user-guide/installation-ack-kserve?spm=a2c4g.11186623.0.0.4b21769a06kLmR

[10] TensorRT-LLM支持矩阵

https://nvidia.github.io/TensorRT-LLM/reference/support-matrix.html



我们是阿里巴巴云计算和大数据技术幕后的核心技术输出者。

欢迎关注 “阿里云基础设施”同名微博知乎

获取关于我们的更多信息~

相关实践学习
深入解析Docker容器化技术
Docker是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。Docker是世界领先的软件容器平台。开发人员利用Docker可以消除协作编码时“在我的机器上可正常工作”的问题。运维人员利用Docker可以在隔离容器中并行运行和管理应用,获得更好的计算密度。企业利用Docker可以构建敏捷的软件交付管道,以更快的速度、更高的安全性和可靠的信誉为Linux和Windows Server应用发布新功能。 在本套课程中,我们将全面的讲解Docker技术栈,从环境安装到容器、镜像操作以及生产环境如何部署开发的微服务应用。本课程由黑马程序员提供。 &nbsp; &nbsp; 相关的阿里云产品:容器服务 ACK 容器服务 Kubernetes 版(简称 ACK)提供高性能可伸缩的容器应用管理能力,支持企业级容器化应用的全生命周期管理。整合阿里云虚拟化、存储、网络和安全能力,打造云端最佳容器化应用运行环境。 了解产品详情: https://www.aliyun.com/product/kubernetes
相关文章
|
29天前
|
负载均衡 测试技术 调度
大模型分布式推理:张量并行与流水线并行技术
本文深入探讨大语言模型分布式推理的核心技术——张量并行与流水线并行。通过分析单GPU内存限制下的模型部署挑战,详细解析张量并行的矩阵分片策略、流水线并行的阶段划分机制,以及二者的混合并行架构。文章包含完整的分布式推理框架实现、通信优化策略和性能调优指南,为千亿参数大模型的分布式部署提供全面解决方案。
438 4
|
1月前
|
机器学习/深度学习 缓存 监控
大模型推理优化技术:KV缓存机制详解
本文深入探讨了大语言模型推理过程中的关键技术——KV缓存(Key-Value Cache)机制。通过对Transformer自注意力机制的分析,阐述了KV缓存的工作原理、实现方式及其对推理性能的显著优化效果。文章包含具体的代码实现和性能对比数据,为开发者理解和应用这一关键技术提供实践指导。
749 8
|
3月前
|
并行计算 PyTorch 调度
大模型推理显存优化系列(4):eLLM-大模型推理中的弹性显存管理和优化
本文简要介绍eLLM相关技术挑战、总体设计和初步性能评估
|
3月前
|
负载均衡 并行计算 异构计算
大模型训练推理优化(5): FlexLink —— NVLink 带宽无损提升27%
本期我们将介绍蚂蚁集团ASystem团队在大模型通信优化上的新工作FlexLink,旨在通过动态聚合多路通信(NVLink,PCIe,RDMA),在H800等典型硬件上将典型通信算子如(AllReduce, All Gather)吞吐提升最高达27%,尤其适合大模型长序列推理(Prefill阶段),及训练等通信密集的带宽bound场景。方案对精度无影响。
|
1月前
|
机器学习/深度学习 缓存 自然语言处理
【万字长文】大模型训练推理和性能优化算法总结和实践
我们是阿里云公共云 AI 汽车行业大模型技术团队,致力于通过专业的全栈 AI 技术推动 AI 的落地应用。
1226 38
【万字长文】大模型训练推理和性能优化算法总结和实践
|
1月前
|
机器学习/深度学习 存储 并行计算
大模型推理加速技术:FlashAttention原理与实现
本文深入解析大语言模型推理加速的核心技术——FlashAttention。通过分析传统注意力机制的计算瓶颈,详细阐述FlashAttention的IO感知算法设计、前向反向传播实现,以及其在GPU内存层次结构中的优化策略。文章包含完整的CUDA实现示例、性能基准测试和实际部署指南,为开发者提供高效注意力计算的全套解决方案。
301 10
|
1月前
|
机器学习/深度学习 存储 缓存
大模型推理加速技术:PagedAttention原理与实现
本文深入解析大语言模型推理中的革命性技术——PagedAttention,该技术是vLLM推理引擎的核心创新。通过将操作系统中的虚拟内存分页概念引入注意力机制,PagedAttention有效解决了KV缓存的内存碎片问题,实现了近乎零浪费的KV缓存管理。文章详细阐述其原理、内存管理机制、实现细节,并提供完整的代码示例和性能分析。
221 1
|
2月前
|
机器学习/深度学习 算法 数据可视化
从零开始训练推理模型:GRPO+Unsloth改造Qwen实战指南
推理型大语言模型兴起,通过先思考再作答提升性能。本文介绍GRPO等强化学习算法,详解其原理并动手用Qwen2.5-3B训练推理模型,展示训练前后效果对比,揭示思维链生成的实现路径。
393 2
从零开始训练推理模型:GRPO+Unsloth改造Qwen实战指南
|
2月前
|
机器学习/深度学习 人工智能 JSON
微软rStar2-Agent:新的GRPO-RoC算法让14B模型在复杂推理时超越了前沿大模型
Microsoft Research最新推出的rStar2-Agent在AIME24数学基准测试中以80.6%的准确率超越超大规模模型DeepSeek-R1,展现“思考更聪明”而非“更长”的AI推理新方向。
155 8
微软rStar2-Agent:新的GRPO-RoC算法让14B模型在复杂推理时超越了前沿大模型

热门文章

最新文章

推荐镜像

更多