使用TensorRT LLM构建和运行Qwen模型

简介: 本文档介绍如何在单GPU和单节点多GPU上使用TensorRT LLM构建和运行Qwen模型,涵盖模型转换、引擎构建、量化推理及LoRA微调等操作,并提供详细的代码示例与支持矩阵。

本文档展示了如何在单GPU和单节点多GPU上使用TensorRT LLM构建和运行Qwen[1]模型。


本文对应的代码位置位于:https://github.com/NVIDIA/TensorRT-LLM/tree/main/examples/models/core/qwen

    概述

    TensorRT LLM Qwen的实现可以在models/qwen[31]中找到。TensorRT LLM Qwen示例代码位于examples/models/core/qwen[32]中。主要文件如下:

    • convert_checkpoint.py[33] 用于构建运行Qwen模型所需的TensorRT[34]引擎。

    此外,在上级文件夹examples[35]中有两个用于推理和评估的共享文件:

    • run.py[36] 用于对输入文本运行推理;
    • summarize.py[37] 用于对cnn_dailymail[38]数据集中的文章进行摘要。

    支持矩阵

    Model Name FP16/BF16 FP8 nvfp4 WO AWQ GPTQ SQ TP PP EP Arch
    Qwen-1_8B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen-7B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen-14B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen-72B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen1.5-0.5B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen1.5-1.8B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen1.5-4B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen1.5-7B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen1.5-14B(-Chat) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen1.5-32B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen1.5-72B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen1.5-110B(-Chat) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen1.5-MoE-A2.7B(-Chat) Y - - Y - - - Y Y - Ampere+
    Qwen2-0.5B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen2-1.5B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen2-7B(-Instruct) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen2-57B-A14B(-Instruct) Y - - Y - - - Y Y - Ampere+
    Qwen2-72B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen2.5-0.5B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen2.5-3B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    Qwen2.5-1.5B(-Instruct) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen2.5-7B(-Instruct) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen2.5-32B(-Instruct) Y Y - Y Y Y Y Y Y - Ampere+
    Qwen2.5-72B(-Instruct) Y Y - Y Y* Y Y Y Y - Ampere+
    QwQ-32B Y Y - Y Y Y Y Y Y - Ampere+
    Qwen3-32B Y Y Y - - - - Y - Y Hopper+
    Qwen3-235B-A22B Y Y Y - - - - Y - Y Hopper+

    请注意,Y*标记表示该模型不支持所有AWQ + TP的组合。

    • • 模型名称:模型的名称,与HuggingFace上的名称相同
    • • WO:仅权重量化(int8 / int4)
    • • AWQ:激活感知权重量化(int4)
    • • GPTQ:生成式预训练Transformer量化(int4)
    • • SQ:平滑量化(int8)
    • • TP:张量并行
    • • PP:流水线并行

    目前Qwen1模型不支持动态NTK和logn注意力。因此,对于Qwen-7B和Qwen-14B模型,长序列输入的准确性无法保证。

    对于Qwen3模型,我们仅列出了密集架构和MoE架构中最大的模型,但其他尺寸的模型遵循类似的模式。

    使用方法

    TensorRT LLM Qwen示例代码位于examples/models/core/qwen[39]。它以HF权重作为输入,并构建相应的TensorRT引擎。TensorRT引擎的数量取决于用于运行推理的GPU数量。

    下载模型权重

    安装依赖包并设置git-lfs

    # 安装依赖
    pip install -r requirements.txt
    # 设置git-lfs
    git lfs install

    下载一个或多个您想要构建为TensorRT LLM引擎的Qwen模型。您可以从HuggingFace[40]中心下载:

    git clone https://huggingface.co/Qwen/Qwen-7B-Chat   ./tmp/Qwen/7B
    git clone https://huggingface.co/Qwen/Qwen-14B-Chat  ./tmp/Qwen/14B
    git clone https://huggingface.co/Qwen/Qwen-72B-Chat  ./tmp/Qwen/72B

    构建TensorRT引擎

    convert_checkpoint.py[41]脚本将HF权重转换为TensorRT LLM检查点。

    trtllm-build命令从TensorRT LLM检查点构建TensorRT LLM引擎。引擎文件的数量与用于运行推理的GPU数量相同。

    通常trtllm-build只需要单个GPU,但如果您已经在推理时拥有所有需要的GPU,您可以通过添加--workers参数来启用并行构建以加快引擎构建过程。请注意,目前workers功能仅支持单节点。

    以下是一些示例:

    # 从HF权重构建单GPU float16引擎。
    # 尝试使用--gemm_plugin来防止精度问题。
    # 使用单个GPU和FP16构建Qwen-7B-Chat模型。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_fp16 \
                                  --dtype float16
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_fp16 \
                --output_dir ./tmp/qwen/7B/trt_engines/fp16/1-gpu \
                --gemm_plugin float16
    # 使用单个GPU和BF16构建Qwen-7B-Chat模型。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_bf16 \
                                  --dtype bfloat16
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_bf16 \
                --output_dir ./tmp/qwen/7B/trt_engines/bf16/1-gpu \
                --gpt_attention_plugin bfloat16 \
                --gemm_plugin bfloat16
    # 使用单个GPU构建Qwen-7B-Chat模型并应用INT8仅权重量化。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_fp16_wq \
                                  --dtype float16 \
                                  --use_weight_only \
                                  --weight_only_precision int8
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_fp16_wq \
                --output_dir ./tmp/qwen/7B/trt_engines/weight_only/1-gpu/ \
                --gemm_plugin float16
    # 使用单个GPU构建Qwen-7B-Chat模型并应用INT4仅权重量化。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_fp16_wq \
                                  --dtype float16 \
                                  --use_weight_only \
                                  --weight_only_precision int4
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_fp16_wq \
                --output_dir ./tmp/qwen/7B/trt_engines/weight_only/1-gpu/ \
                --gemm_plugin float16
    # 使用2路张量并行构建Qwen-7B-Chat。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                --output_dir ./tllm_checkpoint_2gpu_tp2 \
                                --dtype float16 \
                                --tp_size 2
    trtllm-build --checkpoint_dir ./tllm_checkpoint_2gpu_tp2 \
                --output_dir ./tmp/qwen/7B/trt_engines/fp16/2-gpu/ \
                --gemm_plugin float16
    # 使用2路张量并行和2路流水线并行构建Qwen-7B-Chat。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                --output_dir ./tllm_checkpoint_4gpu_tp2_pp2 \
                                --dtype float16 \
                                --tp_size 2 \
                                --pp_size 2
    trtllm-build --checkpoint_dir ./tllm_checkpoint_4gpu_tp2_pp2 \
                --output_dir ./tmp/qwen/7B/trt_engines/fp16/4-gpu/ \
                --gemm_plugin float16
    # 使用2路张量并行构建Qwen-14B-Chat。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/14B/ \
                                --output_dir ./tllm_checkpoint_2gpu_tp2 \
                                --dtype float16 \
                                --tp_size 2
    trtllm-build --checkpoint_dir ./tllm_checkpoint_2gpu_tp2 \
                --output_dir ./tmp/qwen/14B/trt_engines/fp16/2-gpu/ \
                --gemm_plugin float16
    # 使用8路张量并行构建Qwen-72B-Chat。
    python convert_checkpoint.py --model_dir ./tmp/Qwen/72B/ \
                                --output_dir ./tllm_checkpoint_8gpu_tp8 \
                                --dtype float16 \
                                --tp_size 8
    trtllm-build --checkpoint_dir ./tllm_checkpoint_8gpu_tp8 \
                --output_dir ./tmp/qwen/72B/trt_engines/fp16/8-gpu/ \
                --gemm_plugin float16

    INT8 KV缓存

    可以启用INT8 KV缓存来减少内存占用。当批次大小变大时,它会带来更多的性能提升。

    对于INT8 KV缓存,convert_checkpoint.py[42]提供了一个--int8_kv_cache选项。设置--int8_kv_cache将校准模型,然后导出INT8 KV缓存推理所需的缩放因子。

    示例:

    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/   \
                                 --output_dir ./tllm_checkpoint_1gpu_fp16_int8kv
                                 --dtype float16  \
                                 --int8_kv_cache
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_sq \
                 --output_dir ./engine_outputs \
                 --gemm_plugin float16

    convert_checkpoint.py[43]添加了支持INT8 KV缓存的新选项。

    SmoothQuant

    SmoothQuant支持Qwen模型。与直接将HF权重处理并加载到TensorRT LLM的FP16构建不同,SmoothQuant需要加载预处理过的INT8权重,然后再构建引擎。

    示例:

    python3 convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ --output_dir ./tllm_checkpoint_1gpu_sq --dtype float16 --smoothquant 0.5
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_sq \
                 --output_dir ./engine_outputs \
                 --gemm_plugin float16

    convert_checkpoint.py[44]添加了支持SmoothQuant模型INT8推理的新选项。

    --smoothquant是INT8推理的起点。默认情况下,它将以_per-tensor_模式运行模型。

    然后,您可以添加--per-token--per-channel的任意组合来获得相应的行为。

    构建调用的示例:

    # 以_per_token_ + _per_channel_模式为SmoothQuant构建模型
    python3 convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_sq \
                                  --dtype float16 \
                                  --smoothquant 0.5 \
                                  --per_token \
                                  --per_channel
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_sq \
                 --output_dir ./engine_outputs \
                 --gemm_plugin float16

    FP8 Post-Training Quantization

    下面的示例使用NVIDIA Modelopt(算法模型优化)工具包进行模型量化过程。

    首先确保Modelopt工具包已安装(请参阅examples/quantization/README.md[45]

    # 将模型量化为FP8并导出trtllm检查点
    python ../../../quantization/quantize.py --model_dir ./tmp/Qwen/7B/ \
                                       --dtype float16 \
                                       --qformat fp8 \
                                       --kv_cache_dtype fp8 \
                                       --output_dir ./tllm_checkpoint_1gpu_fp8 \
                                       --calib_size 512
    # 从trtllm检查点构建trtllm引擎
    # 通过设置`--use_fp8_context_fmha enable`启用fp8上下文fmha以获得进一步加速
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_fp8 \
                 --output_dir ./engine_outputs \
                 --gemm_plugin float16 \

    INT4-GPTQ

    您可以在此处找到Qwen-7B-Chat的官方GPTQ量化INT4权重:Qwen-7B-Chat-Int4[46]

    构建INT4 GPTQ量化Qwen模型引擎的示例:

    python3 convert_checkpoint.py --model_dir ./tmp/Qwen-7B-Chat-Int4 \
                                  --output_dir ./tllm_checkpoint_1gpu_gptq \
                                  --dtype float16 \
                                  --use_weight_only \
                                  --weight_only_precision int4_gptq \
                                  --per_group
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_gptq \
                    --output_dir ./tmp/Qwen/7B/trt_engines/int4_GPTQ/1-gpu/ \
                    --gemm_plugin float16

    INT4-AWQ

    要运行AWQ Qwen示例,需要执行以下步骤:

    1. 1. 权重量化 NVIDIA Modelopt工具包用于AWQ权重量化。请参阅examples/quantization/README.md[47]获取Modelopt安装说明。
    # 将Qwen-7B-Chat检查点量化为INT4 AWQ格式
    python ../../../quantization/quantize.py --model_dir ./tmp/Qwen/7B/ \
                                       --dtype float16 \
                                       --qformat int4_awq \
                                       --awq_block_size 128 \
                                       --output_dir ./quantized_int4-awq \
                                       --calib_size 32
    1. 还支持通过以下转换脚本使用AutoAWQ[48]生成的HF检查点:
    # 将AutoAWQ HF检查点转换为TRT-LLM检查点
    python convert_checkpoint.py --model_dir ./tmp/Qwen2-7B-Instruct-AWQ \
                                 --output_dir ./quantized_int4-awq
    1. 2. 构建TRT-LLM引擎:
    trtllm-build --checkpoint_dir ./quantized_int4-awq \
                 --output_dir ./tmp/qwen/7B/trt_engines/int4_AWQ/1-gpu/ \
                 --gemm_plugin float16

    运行

    使用trtllm-build生成的引擎运行TensorRT LLM Qwen模型

    # 使用fp16推理
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen/7B/ \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/fp16/1-gpu/
    # 使用bf16推理
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen/7B/ \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/bf16/1-gpu
    # 使用int8仅权重量化推理
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen/7B/ \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/int8_weight_only/1-gpu/
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    你好,请问你叫什么?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "你好,我是来自阿里云的大规模语言模型,我叫通义千问。<|im_end|>
    <|im_start|>
    <|im_start|>
    "
    # 使用int4仅权重量化推理
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen/7B/ \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/int4_weight_only/1-gpu/
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    你好,请问你叫什么?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "我叫通义千问,是由阿里云开发的预训练语言模型。<|im_end|>
    "
    # 使用INT4 GPTQ量化
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen-7B-Chat-Int4 \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/int4_GPTQ/1-gpu/
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    你好,请问你叫什么?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "你好,我是通义千问,由阿里云开发。<|im_end|>
    "
    # 使用INT4 AWQ量化
    python3 ../../../run.py --input_text "你好,请问你叫什么?" \
                      --max_output_len=50 \
                      --tokenizer_dir ./tmp/Qwen/7B/ \
                      --engine_dir=./tmp/Qwen/7B/trt_engines/int4_AWQ/1-gpu/
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    你好,请问你叫什么?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "你好,我是通义千问,由阿里云开发。<|im_end|>
    "
    # 使用8-GPU运行72B模型
    mpirun -n 8 --allow-run-as-root \
        python ../../../run.py --input_text "What is your name?" \
                         --max_output_len=50 \
                         --tokenizer_dir ./tmp/Qwen/72B/ \
                         --engine_dir=./tmp/Qwen/72B/trt_engines/fp16/8-gpu/
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    What is your name?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "I am QianWen, a large language model created by Alibaba Cloud."

    使用LoRA运行模型

    从HF下载lora模型:

    git clone https://huggingface.co/Jungwonchang/Ko-QWEN-7B-Chat-LoRA ./tmp/Ko-QWEN-7B-Chat-LoRA

    构建引擎,设置--lora_plugin--lora_dir。如果lora有独立的lm_head和embedding,它们将替换基础模型的lm_head和embedding。

    python convert_checkpoint.py --model_dir ./tmp/Qwen/7B/ \
                                  --output_dir ./tllm_checkpoint_1gpu_fp16 \
                                  --dtype float16
    trtllm-build --checkpoint_dir ./tllm_checkpoint_1gpu_fp16 \
                --output_dir ./tmp/qwen/7B_lora/trt_engines/fp16/1-gpu \
                --gemm_plugin auto \
                --lora_plugin auto \
                --lora_dir ./tmp/Ko-QWEN-7B-Chat-LoRA

    运行推理:

    python ../../../run.py --engine_dir ./tmp/qwen/7B_lora/trt_engines/fp16/1-gpu \
                  --max_output_len 50 \
                  --tokenizer_dir ./tmp/Qwen/7B/ \
                  --input_text "안녕하세요, 혹시 이름이 뭐에요?" \
                  --lora_task_uids 0 \
                  --use_py_session
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    안녕하세요, 혹시 이름이 뭐에요?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "안녕하세요! 저는 인공지능 어시스턴트로, 여러분의 질문에 답하고 도움을 드리기 위해 여기 있습니다. 제가 무엇을 도와드릴까요?<|im_end|>
    <|im_start|>0
    <|im_start|><|im_end|>
    <|im_start|>"

    想要跳过LoRA模块的用户可以使用--lora_task_uids -1传递uid -1。
    在这种情况下,模型将不会运行LoRA模块,结果会有所不同。

    python ../../../run.py --engine_dir ./tmp/qwen/7B_lora/trt_engines/fp16/1-gpu \
                  --max_output_len 50 \
                  --tokenizer_dir ./tmp/Qwen/7B/ \
                  --input_text "안녕하세요, 혹시 이름이 뭐에요?" \
                  --lora_task_uids -1 \
                  --use_py_session
    Input [Text 0]: "<|im_start|>system
    You are a helpful assistant.<|im_end|>
    <|im_start|>user
    안녕하세요, 혹시 이름이 뭐에요?<|im_end|>
    <|im_start|>assistant
    "
    Output [Text 0 Beam 0]: "안녕하세요! 저는 "QianWen"입니다.<|im_end|>
    "

    使用Qwen模型进行摘要

    # 使用FP16运行Qwen 7B模型进行摘要。
    python ../../../summarize.py --test_trt_llm \
                           --hf_model_dir ./tmp/Qwen/7B/ \
                           --data_type fp16 \
                           --engine_dir ./tmp/Qwen/7B/trt_engines/fp16/1-gpu/ \
                           --max_input_length 2048 \
                           --output_len 2048
    # 使用BF16运行Qwen 7B模型进行摘要。
    python ../../../summarize.py --test_trt_llm \
                           --hf_model_dir ./tmp/Qwen/7B/ \
                           --data_type fp16 \
                           --engine_dir ./tmp/Qwen/7B/trt_engines/bf16/1-gpu/ \
                           --max_input_length 2048 \
                           --output_len 2048
    # 使用量化为INT8的Qwen 7B模型进行摘要。
    python ../../../summarize.py --test_trt_llm \
                           --hf_model_dir  ./tmp/Qwen/7B/ \
                           --data_type fp16 \
                           --engine_dir ./tmp/Qwen/7B/trt_engines/int8_weight_only/1-gpu/ \
                           --max_input_length 2048 \
                           --output_len 2048
    # 使用量化为INT4的Qwen 7B模型进行摘要。
    python ../../../summarize.py --test_trt_llm \
                           --hf_model_dir  ./tmp/Qwen/7B/ \
                           --data_type fp16 \
                           --engine_dir ./tmp/Qwen/7B/trt_engines/int4_weight_only/1-gpu/ \
                           --max_input_length 2048 \
                           --output_len 2048
    # 使用两个GPU以FP16运行Qwen 7B模型进行摘要。
    mpirun -n 2 --allow-run-as-root \
        python ../../../summarize.py --test_trt_llm \
                               --hf_model_dir  ./tmp/Qwen/7B/ \
                               --data_type fp16 \
                               --engine_dir ./tmp/Qwen/7B/trt_engines/fp16/2-gpu/ \
                               --max_input_length 2048 \
                               --output_len 2048
    # 使用两个GPU以FP16运行Qwen 14B模型进行摘要。
    mpirun -n 2 --allow-run-as-root \
        python ../../../summarize.py --test_trt_llm \
                               --hf_model_dir  ./tmp/Qwen/14B/ \
                               --data_type fp16 \
                               --engine_dir ./tmp/Qwen/14B/trt_engines/fp16/2-gpu/ \
                               --max_input_length 2048 \
                               --output_len 2048

    summarize.py的演示输出:

    python ../../../summarize.py --test_trt_llm \
                           --hf_model_dir ./tmp/Qwen/7B/ \
                           --data_type fp16 \
                           --engine_dir ./tmp/Qwen/7B/trt_engines/fp16/1-gpu/ \
                           --max_input_length 2048 \
                           --output_len 2048
    [11/09/2023-02:21:10] [TRT-LLM] [I] Load tokenizer takes: 0.4043385982513428 sec
    Downloading builder script: 100%|███████████████████████████████████████████| 9.27k/9.27k [00:00<00:00, 35.4MB/s]
    Downloading and preparing dataset cnn_dailymail/3.0.0 to /root/.cache/huggingface/datasets/ccdv___cnn_dailymail/3
    ......
    [11/09/2023-02:23:33] [TRT-LLM] [I]
     Highlights : ['James Best, who played the sheriff on "The Dukes of Hazzard," died Monday at 88 .\n"Hazzard" ran from 1979 to 1985 and was among the most popular shows on TV .']
    [11/09/2023-02:23:33] [TRT-LLM] [I]
     Summary : [['Actor James Best, known for his portrayal of bumbling sheriff Rosco P. Coltrane on TV\'s "The Dukes of Hazzard," has died at 88 after a brief illness. Best\'s career spanned decades in theater and Hollywood, but it was his role in "The Dukes of Hazzard" that made him a household name. The show ran for seven seasons from 1979 to 1985 and became a hit on TV, spawning TV movies, an animated series and video games. Best\'s portrayal of Rosco was beloved by fans for his childlike enthusiasm and goofy catchphrases. He is survived by friends and colleagues who paid tribute to him on social media.']]
    [11/09/2023-02:23:33] [TRT-LLM] [I] ---------------------------------------------------------
    load rouge ...
    Downloading builder script: 5.60kB [00:00, 18.9MB/s]
    load rouge done
    [11/09/2023-02:24:06] [TRT-LLM] [I] TensorRT LLM (total latency: 30.13867211341858 sec)
    [11/09/2023-02:24:06] [TRT-LLM] [I] TensorRT LLM beam 0 result
    [11/09/2023-02:24:06] [TRT-LLM] [I]   rouge1 : 26.35215119137573
    [11/09/2023-02:24:06] [TRT-LLM] [I]   rouge2 : 9.507814774384485
    [11/09/2023-02:24:06] [TRT-LLM] [I]   rougeL : 18.171982659482865
    [11/09/2023-02:24:06] [TRT-LLM] [I]   rougeLsum : 21.10413175647868

    Qwen3

    TensorRT LLM现在支持Qwen3,这是Qwen模型系列的最新版本。本指南将引导您完成使用NVIDIA TensorRT LLM框架与PyTorch后端运行Qwen3模型的示例。根据支持矩阵,TensorRT LLM为各种Qwen3模型变体提供全面支持,包括:

    • • Qwen3-0.6B
    • • Qwen3-1.7B
    • • Qwen3-4B
    • • Qwen3-8B
    • • Qwen3-14B
    • • Qwen3-32B
    • • Qwen3-30B-A3B
    • • Qwen3-235B-A22B

    如果需要,请参考此指南[49]了解如何从源代码构建TensorRT LLM并启动TRT-LLM Docker容器。

    Note

    本指南假设您将占位符值(例如<YOUR_MODEL_DIR>)替换为适当的路径。

    下载模型权重

    Qwen3模型权重可在Hugging Face[50]上获取。要下载权重,请执行以下命令(将<YOUR_MODEL_DIR>替换为您要存储权重的目标目录):

    git lfs install
    git clone https://huggingface.co/Qwen/Qwen3-30B-A3B <YOUR_MODEL_DIR>

    快速开始

    运行单次推理

    要快速运行Qwen3,请使用examples/llm-api/quickstart_advanced.py[51]

    python3 examples/llm-api/quickstart_advanced.py --model_dir Qwen3-30B-A3B/ --kv_cache_fraction 0.6

    评估

    1. 1. 在MMLU数据集上评估准确性:
    trtllm-eval --model=Qwen3-32B/ --tokenizer=Qwen3-32B/ --backend=pytorch mmlu --dataset_path=./datasets/mmlu/
    [05/01/2025-13:56:15] [TRT-LLM] [I] MMLU weighted average accuracy: 79.09 (14042)
    trtllm-eval --model=Qwen3-30B-A3B/ --tokenizer=Qwen3-30B-A3B/ --backend=pytorch mmlu --dataset_path=./datasets/mmlu/
    [05/05/2025-11:33:02] [TRT-LLM] [I] MMLU weighted average accuracy: 79.44 (14042)
    1. 2. 在GSM8K数据集上评估准确性:
    trtllm-eval --model=Qwen3-30B-A3B/ --tokenizer=Qwen3-30B-A3B/ --backend=pytorch gsm8k --dataset_path=./datasets/openai/gsm8k/
    [05/05/2025-12:05:40] [TRT-LLM] [I] lm-eval gsm8k results (scores normalized to range 0~100):
    | Tasks | Version | Filter           | n-shot | Metric      |     |   Value |     | Stderr |
    | ----- | ------: | ---------------- | -----: | ----------- | --- | ------: | --- | -----: |
    | gsm8k |       3 | flexible-extract |      5 | exact_match | ↑   | 84.3063 | ±   | 1.0019 |
    |       |         | strict-match     |      5 | exact_match | ↑   | 88.6277 | ±   | 0.8745 |

    模型量化

    要量化Qwen3模型以与PyTorch后端一起使用,我们将使用NVIDIA的Model Optimizer (ModelOpt)工具。请按照以下步骤操作:

    # 克隆TensorRT Model Optimizer (ModelOpt)
    git clone https://github.com/NVIDIA/TensorRT-Model-Optimizer.git
    pushd TensorRT-Model-Optimizer
    # 安装ModelOpt
    pip install -e .
    # 使用nvfp4量化Qwen3-235B-A22B模型
    # 默认情况下,检查点将存储在`TensorRT-Model-Optimizer/examples/llm_ptq/saved_models_Qwen3-235B-A22B_nvfp4_hf/`中。
    ./examples/llm_ptq/scripts/huggingface_example.sh --model Qwen3-235B-A22B/ --quant nvfp4 --export_fmt hf
    # 使用fp8_pc_pt量化Qwen3-32B模型
    # 默认情况下,检查点将存储在`TensorRT-Model-Optimizer/examples/llm_ptq/saved_models_Qwen3-32B_fp8_pc_pt_hf/`中。
    ./examples/llm_ptq/scripts/huggingface_example.sh --model Qwen3-32B/ --quant fp8_pc_pt --export_fmt hf
    popd

    基准测试

    要运行基准测试,我们建议使用trtllm-bench工具。请参考以下在B200上的脚本:

    #!/bin/bash
    folder_model=TensorRT-Model-Optimizer/examples/llm_ptq/saved_models_Qwen3-235B-A22B_nvfp4_hf/
    path_config=extra-llm-api-config.yml
    num_gpus=8
    ep_size=8
    max_input_len=1024
    max_batch_size=512
    # We want to limit the number of prefill requests to 1 with in-flight batching.
    max_num_tokens=$(( max_input_len + max_batch_size - 1 ))
    kv_cache_free_gpu_mem_fraction=0.9
    concurrency=128
    path_data=./aa_prompt_isl_1k_osl_2k_qwen3_10000samples.txt
    # Setup the extra configuration for llm-api
    echo -e "disable_overlap_scheduler: false
    print_iter_log: true
    cuda_graph_config:
      batch_sizes: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,32,64,128]
    enable_attention_dp: true " > ${path_config}
    # Run trtllm-bench with pytorch backend
    mpirun --allow-run-as-root --oversubscribe -n 1 \
    trtllm-bench --model ${folder_model} --model_path ${folder_model} throughput \
      --backend pytorch \
      --max_batch_size ${max_batch_size} \
      --max_num_tokens ${max_num_tokens} \
      --dataset ${path_data} \
      --tp ${num_gpus}\
      --ep ${ep_size} \
      --kv_cache_free_gpu_mem_fraction ${kv_cache_free_gpu_mem_fraction} \
      --extra_llm_api_options ${path_config} \
      --concurrency ${concurrency} \
      --num_requests $(( concurrency * 5 )) \
      --warmup 0 \
      --streaming

    We suggest benchmarking with a real dataset. It will prevent from having improperly distributed tokens in the MoE. Here, we use the aa_prompt_isl_1k_osl_2k_qwen3_10000samples.txt dataset. It has 10000 samples with an average input length of 1024 and an average output length of 2048. If you don't have a dataset (this or an other) and you want to run the benchmark, you can use the following command to generate a random dataset:

    folder_model=TensorRT-Model-Optimizer/examples/llm_ptq/saved_models_Qwen3-235B-A22B_nvfp4_hf/
    min_input_len=1024
    min_output_len=2048
    concurrency=128
    path_data=random_data.txt
    python3 benchmarks/cpp/prepare_dataset.py \
        --tokenizer=${folder_model} \
        --stdout token-norm-dist --num-requests=$(( concurrency * 5 )) \
        --input-mean=${min_input_len} --output-mean=${min_output_len} --input-stdev=0 --output-stdev=0 > ${path_data}

    服务

    trtllm-serve

    要使用trtllm-serve服务模型:

    cat >./extra-llm-api-config.yml <<EOF
    cuda_graph_config:
      enable_padding: true
      batch_sizes:
      - 1
      - 2
      - 4
      - 8
      - 16
      - 32
      - 64
      - 128
      - 256
      - 384
    print_iter_log: true
    enable_attention_dp: true
    EOF
    trtllm-serve \
      Qwen3-30B-A3B/ \
      --host localhost \
      --port 8000 \
      --max_batch_size 161 \
      --max_num_tokens 1160 \
      --tp_size 1 \
      --ep_size 1 \
      --pp_size 1 \
      --kv_cache_free_gpu_memory_fraction 0.8 \
      --extra_llm_api_options ./extra-llm-api-config.yml

    To query the server, you can start with a curl command:

    curl http://localhost:8000/v1/completions \
      -H "Content-Type: application/json" \
      -d '{
          "model": "Qwen3-30B-A3B/",
          "prompt": "Please describe what is Qwen.",
          "max_tokens": 12,
          "temperature": 0
      }'

    分布式服务

    要在分布式模式下服务模型,您应该使用trtllm-serve启动上下文和生成服务器。

    例如,您可以在端口8001上启动单个上下文服务器:

    export TRTLLM_USE_UCX_KVCACHE=1
    cat >./ctx-extra-llm-api-config.yml <<EOF
    print_iter_log: true
    enable_attention_dp: true
    EOF
    trtllm-serve \
      Qwen3-30B-A3B/ \
      --host localhost \
      --port 8001 \
      --max_batch_size 161 \
      --max_num_tokens 1160 \
      --tp_size 1 \
      --ep_size 1 \
      --pp_size 1 \
      --kv_cache_free_gpu_memory_fraction 0.8 \
      --extra_llm_api_options ./ctx-extra-llm-api-config.yml &> output_ctx &

    您可以在端口8002和8003上启动两个生成服务器:

    export TRTLLM_USE_UCX_KVCACHE=1
    cat >./gen-extra-llm-api-config.yml <<EOF
    cuda_graph_config:
      enable_padding: true
      batch_sizes:
        - 1
        - 2
        - 4
        - 8
        - 16
        - 32
        - 64
        - 128
        - 256
        - 384
    print_iter_log: true
    enable_attention_dp: true
    EOF
    for port in {8002..8003}; do \
    trtllm-serve \
      Qwen3-30B-A3B/ \
      --host localhost \
      --port ${port} \
      --max_batch_size 161 \
      --max_num_tokens 1160 \
      --tp_size 1 \
      --ep_size 1 \
      --pp_size 1 \
      --kv_cache_free_gpu_memory_fraction 0.8 \
      --extra_llm_api_options ./gen-extra-llm-api-config.yml \
      &> output_gen_${port} & \
    done

    Finally, you can launch the disaggregated server which will accept requests from the client and do
    the orchestration between the context and generation servers with:

    cat >./disagg-config.yml <<EOF
    hostname: localhost
    port: 8000
    backend: pytorch
    context_servers:
      num_instances: 1
      urls:
          - "localhost:8001"
    generation_servers:
      num_instances: 1
      urls:
          - "localhost:8002"
    EOF
    trtllm-serve disaggregated -c disagg-config.yaml

    To query the server, you can start with a curl command:

    curl http://localhost:8000/v1/completions \
      -H "Content-Type: application/json" \
      -d '{
          "model": "Qwen3-30B-A3B/",
          "prompt": "Please describe what is Qwen.",
          "max_tokens": 12,
          "temperature": 0
      }'

    Note that the optimal disaggregated serving configuration (i.e. tp/pp/ep mappings, number of ctx/gen instances, etc.) will depend
    on the request parameters, the number of concurrent requests and the GPU type. It is recommended to experiment to identify optimal
    settings for your specific use case.

    Eagle3

    Qwen3现在支持Eagle3(使用Eagle3的推测解码)。要在Qwen3上启用Eagle3,您需要在运行trtllm-benchtrtllm-serve时设置以下参数:

    • speculative_config.decoding_type: Eagle
      将解码类型设置为"Eagle"以启用Eagle3推测解码。
    • speculative_config.max_draft_len: 3
      设置每步生成的最大草稿token数量(此值可以根据需要调整)。
    • speculative_config.speculative_model_dir: <EAGLE3_DRAFT_MODEL_PATH>
      指定Eagle3草稿模型的路径(确保已准备好相应的草稿模型权重)。

    目前,启用Eagle3时有一些限制:

    1. 1. 不支持attention_dp。请禁用它或不设置相关标志(默认情况下它是禁用的)。
    2. 2. 如果您想使用enable_block_reuse,目标模型和草稿模型的kv缓存类型必须相同。由于草稿模型仅支持fp16/bf16,在使用fp8 kv缓存时需要禁用enable_block_reuse

    Eagle3的extra-llm-api-config.yml配置片段示例:

    echo "
    enable_attention_dp: false
    speculative_config:
        decoding_type: Eagle
        max_draft_len: 3
        speculative_model_dir: <EAGLE3_DRAFT_MODEL_PATH>
    kv_cache_config:
        enable_block_reuse: false
    " >> ${path_config}

    有关更多详细信息,请参考speculative-decoding.md[52]

    Dynamo

    NVIDIA Dynamo是一个高吞吐量低延迟推理框架,专为在多节点分布式环境中服务生成式AI和推理模型而设计。
    Dynamo支持TensorRT LLM作为其推理引擎之一。有关如何将TensorRT LLM与Dynamo一起使用的详细信息,请参考使用TensorRT-LLM的LLM部署示例[53]

    Qwen3-Next

    以下是运行Qwen3-Next模型的命令。

    mpirun -n 1 --allow-run-as-root --oversubscribe python3 examples/llm-api/quickstart_advanced.py --model_dir /Qwen3-Next-80B-A3B-Thinking --kv_cache_fraction 0.6 --disable_kv_cache_reuse --max_batch_size 1 --tp_size 4

    注意事项和故障排除

    • 模型目录:<YOUR_MODEL_DIR>更新为模型权重实际所在的路径。
    • GPU内存: 如果遇到内存不足错误,请调整--max_batch_size--max_num_tokens
    • 配置文件: 验证配置文件格式是否正确,以避免运行时问题。
    目录
    相关文章
    |
    2月前
    |
    数据采集 自然语言处理 供应链
    LLM安全新威胁:为什么几百个毒样本就能破坏整个模型
    数据投毒通过在训练数据中植入恶意样本,将后门永久嵌入大模型,仅需数百份毒样本即可触发数据泄露、越狱等行为,防御需结合溯源、聚类分析与自动化检测。
    216 2
    LLM安全新威胁:为什么几百个毒样本就能破坏整个模型
    |
    2月前
    |
    人工智能 搜索推荐 程序员
    当AI学会“跨界思考”:多模态模型如何重塑人工智能
    当AI学会“跨界思考”:多模态模型如何重塑人工智能
    265 120
    |
    2月前
    |
    机器学习/深度学习 缓存 监控
    139_剪枝优化:稀疏模型压缩 - 分析结构化剪枝的独特速度提升与LLM部署加速实践
    随着大语言模型(LLM)规模的不断增长,模型参数量已从最初的数亿扩展到数千亿甚至万亿级别。这种规模的模型在推理过程中面临着巨大的计算和内存挑战,即使在最先进的硬件上也难以高效部署。剪枝优化作为一种有效的模型压缩技术,通过移除冗余或不重要的参数,在保持模型性能的同时显著减少计算资源需求。
    |
    2月前
    |
    人工智能 API 开发工具
    构建AI智能体:一、初识AI大模型与API调用
    本文介绍大模型基础知识及API调用方法,涵盖阿里云百炼平台密钥申请、DashScope SDK使用、Python调用示例(如文本情感分析、图像文字识别),助力开发者快速上手大模型应用开发。
    1025 16
    构建AI智能体:一、初识AI大模型与API调用
    |
    3月前
    |
    人工智能 自然语言处理 IDE
    模型微调不再被代码难住!PAI和Qwen3-Coder加速AI开发新体验
    通义千问 AI 编程大模型 Qwen3-Coder 正式开源,阿里云人工智能平台 PAI 支持云上一键部署 Qwen3-Coder 模型,并可在交互式建模环境中使用 Qwen3-Coder 模型。
    682 109
    |
    3月前
    |
    分布式计算 测试技术 Spark
    科大讯飞开源星火化学大模型、文生音效模型
    近期,科大讯飞在魔搭社区(ModelScope)和Gitcode上开源两款模型:讯飞星火化学大模型Spark Chemistry-X1-13B、讯飞文生音频模型AudioFly,助力前沿化学技术研究,以及声音生成技术和应用的探索。
    271 2
    |
    3月前
    |
    人工智能 Java API
    AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
    本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
    1431 122
    AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
    |
    4月前
    |
    存储 人工智能 自然语言处理
    告别文字乱码!全新文生图模型Qwen-Image来咯
    通义千问团队开源了Qwen-Image,一个20B参数的MMDiT模型,具备卓越的文本渲染和图像编辑能力。支持复杂中英文文本生成与自动布局,适用于多场景图像生成与编辑任务,已在魔搭社区与Hugging Face开源。
    691 2
    |
    3月前
    |
    机器学习/深度学习 人工智能 自然语言处理
    AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型
    AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型
    572 13
    AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型