Triton + TRT-LLM으로 Phi-3 모델 배포하기
Triton + TRT-LLM으로 Phi-3 모델 배포하기 (Deploying Phi-3 with Triton and TRT-LLM)
이 가이드는 Phi-3를 TRT-LLM으로 빌드하고 트리톤 인퍼런스 서버로 배포하는 단계를 담아요. 또 GenAI-Perf를 사용해 처리량과 지연 시간 측면에서 모델 성능을 벤치마킹하는 방법도 보여줍니다.
이 가이드는 A100 80GB SXM4와 H100 80GB PCIe에서 테스트됐고, TRT-LLM v0.11과 Triton Inference Server 24.07에서 Phi-3-mini-128k-instruct와 Phi-3-mini-4k-instruct로 동작이 확인됐어요(전체 목록은 Support Matrix 참고).
- TRT-LLM 엔진 빌드·테스트
- 트리톤 인퍼런스 서버로 배포
- GenAI-Perf로 벤치마킹
- 참조 구성
TRT-LLM 엔진 빌드·테스트
참고: https://nvidia.github.io/TensorRT-LLM/installation/linux.html
Docker 컨테이너 가져와 실행 (선택)
# Pre-install the environment using the NVIDIA Container Toolkit to avoid manual environment configuration
docker run --rm --ipc=host --runtime=nvidia --gpus '"device=0"' --entrypoint /bin/bash -it nvidia/cuda:12.4.1-devel-ubuntu22.04
TensorRT-LLM 설치
# Install dependencies, TensorRT-LLM requires Python 3.10
apt-get update && apt-get -y install python3.10 python3-pip openmpi-bin libopenmpi-dev git git-lfs
# Install TensorRT-LLM (v0.11.0)
pip3 install tensorrt_llm==0.11.0 --extra-index-url https://pypi.nvidia.com
# Check installation
python3 -c "import tensorrt_llm"
Phi-3 변환 스크립트가 있는 TRT-LLM repo 클론
git clone -b v0.11.0 https://github.com/NVIDIA/TensorRT-LLM.git
cd TensorRT-LLM/examples/phi/
# only need to install requirements.txt if you want to test the summarize.py example
# if so, modify requirements.txt such that tensorrt_llm==0.11.0
# pip install -r requirements.txt
TRT-LLM 엔진 빌드
Phi-3-mini-4k-instruct 다운로드
git lfs install
git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
HF Transformers → TensorRT-LLM 형식 가중치 변환
python3 ./convert_checkpoint.py \
--model_dir ./Phi-3-mini-4k-instruct \
--output_dir ./phi-checkpoint \
--dtype float16
TensorRT 엔진 빌드
# Build a float16 engine using a single GPU and HF weights.
# Enable several TensorRT-LLM plugins to increase runtime performance. It also helps with build time.
# --tp_size and --pp_size are the model shard size
trtllm-build \
--checkpoint_dir ./phi-checkpoint \
--output_dir ./phi-engine \
--gemm_plugin float16 \
--max_batch_size 8 \
--max_input_len 1024 \
--max_seq_len 2048 \
--tp_size 1 \
--pp_size 1
모델 실행
python3 ../run.py --engine_dir ./phi-engine \
--max_output_len 500 \
--tokenizer_dir ./Phi-3-mini-4k-instruct \
--input_text "How do I count to nine in French?"
Phi 모델로 요약 테스트
TensorRT-LLM Phi 모델로 cnn_dailymail 데이터셋의 기사를 요약하는 테스트를 할 수 있어요. 각 요약에 대해 스크립트는 ROUGE 점수를 계산하고 ROUGE-1 점수로 구현을 검증합니다. 같은 요약을 HF Phi 모델로도 수행할 수 있어요.
# Run the summarization task using a TensorRT-LLM model and a single GPU.
python3 ../summarize.py --engine_dir ./phi-engine \
--hf_model_dir ./Phi-3-mini-4k-instruct \
--batch_size 1 \
--test_trt_llm \
--test_hf \
--data_type fp16 \
--check_accuracy \
--tensorrt_llm_rouge1_threshold=20
트리톤 인퍼런스 서버로 배포
Docker 컨테이너에서 호스트로 엔진 파일 복사
# In another terminal instance, before exiting the current container
docker cp <container_id>:<path_in_container> <path_on_host>
# For example
docker cp 452ee1c1d8a1:/TensorRT-LLM/examples/phi/phi-engine /home/user/phi-engine
컴파일 모델을 TRT-LLM 백엔드 스켈레톤 저장소에 복사
# After exiting the TensorRT-LLM Docker container
git clone https://github.com/triton-inference-server/tensorrtllm_backend.git
cd tensorrtllm_backend
cp ../phi-engine/* all_models/inflight_batcher_llm/tensorrt_llm/1/
모델 저장소의 구성 파일 수정
다음 구성 파일들을 갱신해야 해요.
ensemble/config.pbtxtpostprocessing/config.pbtxtpreprocessing/config.pbtxttensorrt_llm/config.pbxttensorrt_llm/1/config.json
ensemble/config.pbtxt 갱신
python3 tools/fill_template.py --in_place \
all_models/inflight_batcher_llm/ensemble/config.pbtxt \
triton_max_batch_size:128
preprocessing/config.pbtxt 갱신
python3 tools/fill_template.py --in_place \
all_models/inflight_batcher_llm/postprocessing/config.pbtxt \
tokenizer_type:auto,\
tokenizer_dir:../Phi-3-mini-4k-instruct,\
triton_max_batch_size:128,\
postprocessing_instance_count:2
postprocessing/config.pbtxt 갱신
python3 tools/fill_template.py --in_place \
all_models/inflight_batcher_llm/preprocessing/config.pbtxt \
tokenizer_type:auto,\
tokenizer_dir:../Phi-3-mini-4k-instruct,\
triton_max_batch_size:128,\
preprocessing_instance_count:2
tensorrt_llm/config.pbxt 갱신
python3 tools/fill_template.py --in_place \
all_models/inflight_batcher_llm/tensorrt_llm/config.pbtxt \
decoupled_mode:true,\
engine_dir:/all_models/inflight_batcher_llm/tensorrt_llm/1,\
max_tokens_in_paged_kv_cache:,\
batch_scheduler_policy:guaranteed_completion,\
kv_cache_free_gpu_mem_fraction:0.2,\
max_num_sequences:4,\
triton_backend:tensorrtllm,\
triton_max_batch_size:128,\
max_queue_delay_microseconds:10,\
max_beam_width:1,\
batching_strategy:inflight_fused_batching,\
engine_dir:/opt/all_models/inflight_batcher_llm/tensorrt_llm/1,\
max_tokens_in_paged_kv_cache:1,\
batch_scheduler_policy:guaranteed_completion,\
kv_cache_free_gpu_mem_fraction:0.2
# manually access tensort_llm/config.pbtxt and change the CPU instances to > 1
# unfortunately this was hard-coded and cannot be update with the above script
# instance_group [
# {
# count: 2
# kind : KIND_CPU
# }
# ]
Paged KV Cache의 Max Tokens
이 항목은 Phi-3-mini-128k-instruct에만 필요하며, Phi-3-mini-4k-instruct에서는 수정할 필요가 없어요. 128k 컨텍스트를 수용하려면 tensorrt_llm/config.pbxt에서 다음을 제거해 max tokens가 KV cache manager에 의해 결정되게 합니다. 제거하기 싫다면 maxTokensInPagedKvCache를 충분히 크게(예: 4096) 설정해 최소 1개 시퀀스를 완료 처리할 수 있게 해요 (즉 beam_width * tokensPerBlock * maxBlocksPerSeq보다 커야 함).
parameters: {
key: "max_tokens_in_paged_kv_cache"
value: {
string_value: "4096"
}
}
tensorrt_llm/1/config.json 갱신
엔진 config(tensorrtllm_backend/all_models/inflight_batcher_llm/tensorrt_llm/1/config.json)의 plugin_config 아래에 다음을 추가합니다.
"Use_context_fmha_for_generation": false
# for example:
"plugin_config": {
"dtype": "float16",
"bert_attention_plugin": "auto",
"streamingllm": false,
"Use_context_fmha_for_generation": false
위는 선호하는 에디터로 수동으로 해야 해요. 완료 후 작업 디렉토리가 ~/tensorrtllm_backend인지 확인하세요.
tensorrt_llm_bls 삭제
# Recommended to remove the BLS directory if not needed
rm -rf all_models/inflight_batcher_llm/tensorrt_llm_bls/
모델 저장소 다운로드
# for tokenizer
git lfs install
git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
Triton Inference Server 실행 (trtllm-python3-py3)
docker run -it --rm --gpus all --network host --shm-size=1g \
-v $(pwd)/all_models:/opt/all_models \
-v $(pwd)/scripts:/opt/scripts \
-v $(pwd)/Phi-3-mini-4k-instruct:/opt/Phi-3-mini-4k-instruct \
nvcr.io/nvidia/tritonserver:26.08-trtllm-python-py3
# Launch Server
python3 ../scripts/launch_triton_server.py --model_repo ../all_models/inflight_batcher_llm --world_size 1
요청 보내기
curl -X POST localhost:8000/v2/models/ensemble/generate -d \
'{
"text_input": "A farmer with a wolf, a goat, and a cabbage must cross a river by boat. The boat can carry only the farmer and a single item. If left unattended together, the wolf would eat the goat, or the goat would eat the cabbage. How can they cross the river without anything being eaten?",
"parameters": {
"max_tokens": 256,
"bad_words":[""],
"stop_words":[""]
}
}' | jq
GenAI-Perf로 벤치마킹
Triton Inference Server 실행 (py3-sdk)
export RELEASE="26.08"
docker run -it --net=host --gpus '"device=0"' nvcr.io/nvidia/tritonserver:${RELEASE}-py3-sdk
Phi-3 토크나이저 다운로드
Hugging Face에 로그인(User Access Tokens)해 Phi-3 토크나이저를 받아요. 이 단계는 필수는 아니지만 프롬프트·응답의 토큰 메트릭 해석에 도움이 됩니다. 건너뛴다면 18단계 GenAI-Perf 스크립트에서 --tokenizer 플래그를 제거하면 됩니다.
git lfs install
git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
pip install huggingface_hub
huggingface-cli login --token hf_***
GenAI-Perf 실행
export INPUT_SEQUENCE_LENGTH=128
export OUTPUT_SEQUENCE_LENGTH=128
export CONCURRENCY=25
genai-perf \
-m ensemble \
--service-kind triton \
--backend tensorrtllm \
--random-seed 123 \
--synthetic-input-tokens-mean $INPUT_SEQUENCE_LENGTH \
--synthetic-input-tokens-stddev 0 \
--streaming \
--output-tokens-mean $OUTPUT_SEQUENCE_LENGTH \
--output-tokens-stddev 0 \
--output-tokens-mean-deterministic \
--concurrency $CONCURRENCY \
--tokenizer microsoft/Phi-3-mini-4k-instruct \
--measurement-interval 4000 \
--url localhost:8001
GenAI-Perf로 성능 벤치마킹하는 더 자세한 내용은 여기에서 볼 수 있어요.
참조 구성
/tensorrtllm_backend/all_models/inflight_batcher_llm 안의 모든 config 파일은 각자의 이름으로 config.pbtxt에 담겨 있어요. ensemble/config.pbtxt는 preprocessing → tensorrt_llm → postprocessing으로 이어지는 앙상블 스케줄링을 정의하고, preprocessing/postprocessing은 python 백엔드로 tokenizer를 사용하며, tensorrt_llm은 inflight_fused_batching 전략과 decoupled 모델 트랜잭션 폴리시를 설정해요. 핵심 파라미터:
ensemble/config.pbtxt—name: "ensemble",platform: "ensemble",max_batch_size: 128. 입력text_input(TYPE_STRING, dims [1])을 받아text_output을 반환. ensemble_scheduling에서 preprocessing → tensorrt_llm → postprocessing을 input_map/output_map으로 연결.preprocessing/config.pbtxt—backend: "python",max_batch_size: 128,parameters에tokenizer_dir: "../Phi-3-mini-4k-instruct", instance_groupcount: 4, kind: KIND_CPU. QUERY(문자열)를 입력받아 INPUT_ID·REQUEST_INPUT_LEN 등을 출력.postprocessing/config.pbtxt—backend: "python",max_batch_size: 128,tokenizer_dir: "../Phi-3-mini-4k-instruct", instance_groupcount: 4, kind: KIND_CPU. TOKENS_BATCH·SEQUENCE_LENGTH를 받아 OUTPUT(문자열)·로그확률 등을 출력.tensorrt_llm/config.pbtxt—backend: "tensorrtllm",max_batch_size: 128,model_transaction_policy { decoupled: true },dynamic_batching { preferred_batch_size: [128], max_queue_delay_microseconds: 10 }. 다양한 입력(ragged batch 지원)과 출력을 정의하고, parameters로gpt_model_type: "inflight_fused_batching",gpt_model_path: "/opt/all_models/inflight_batcher_llm/tensorrt_llm/1",batch_scheduler_policy: "guaranteed_completion",kv_cache_free_gpu_mem_fraction: "0.2",executor_worker_path: "/opt/tritonserver/backends/tensorrtllm/trtllmExecutorWorker"등을 설정.
[!참고] 각 config.pbtxt 파일의 전체 소스(라이선스 헤더 포함)는 원문 페이지와 tensorrtllm_backend 저장소에서 확인할 수 있어요. 위는 배포에 필요한 핵심 값만 요약한 것입니다.
더 알아보기 (Learn more)
- GenAI-Perf — 생성형 AI 벤치마킹
- TRT-LLM 백엔드 — TensorRT-LLM 모델 서빙
- Triton Quickstart — 도커 기반 기초 배포