TGI로 Qwen 배포하기
TGI로 Qwen 배포하기
Hugging Face의 TGI(Text Generation Inference)는 텍스트 생성 작업을 위한 대규모 언어 모델(LLM) 배포·서빙을 위해 특별히 설계된 프로덕션 준비 프레임워크예요. 원활한 배포 경험을 제공하며 강력한 기능들을 갖추고 있어요.
출처: 문서
본문
⚠️ 주의: 이 페이지는 Qwen3 기준으로 업데이트 예정이에요.
Hugging Face의 TGI는 텍스트 생성 작업을 위한 LLM 배포·서빙을 위해 설계된 프로덕션 준비 프레임워크예요. 강력한 기능 집합으로 매끄러운 배포 경험을 제공합니다:
- Speculative Decoding: 생성 속도를 가속화해요.
- Tensor Parallelism: 여러 GPU에 걸친 효율적인 배포를 가능하게 해요.
- Token Streaming: 텍스트의 연속 생성을 허용해요.
- 다양한 디바이스 지원: AMD, Gaudi, AWS Inferentia와 매끄럽게 동작해요.
설치
TGI를 사용하는 가장 쉬운 방법은 TGI docker 이미지를 이용하는 거예요. 이 가이드에서는 docker로 TGI를 사용하는 방법을 보여드려요.
Conda로 로컬에서 실행하거나 로컬에서 직접 빌드하는 것도 가능해요. 자세한 내용은 설치 가이드와 CLI 도구를 참고하세요.
TGI로 Qwen2.5 배포하기
- Qwen2.5 모델 찾기: Qwen2.5 컬렉션에서 모델을 선택하세요.
- 배포 명령: 터미널에서 다음 명령을 실행하세요.
model은 선택한 Qwen2.5 모델 ID로,volume은 로컬 데이터 디렉터리 경로로 바꾸세요:
model=Qwen/Qwen2.5-7B-Instruct
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model
TGI API 사용하기
배포가 완료되면 모델은 매핑된 포트(8080)에서 사용할 수 있어요.
TGI에는 스트리밍 응답을 위한 편리한 API가 있어요:
curl http://localhost:8080/generate_stream -H 'Content-Type: application/json' \
-d '{"inputs":"Tell me something about large language models.","parameters":{"max_new_tokens":512}}'
OpenAI 스타일 API로도 사용할 수 있어요:
curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "",
"messages": [
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": "Tell me something about large language models."}
],
"temperature": 0.7,
"top_p": 0.8,
"repetition_penalty": 1.05,
"max_tokens": 512
}'
📝 참고: JSON의 model 필드는 TGI에서 사용되지 않으므로 아무 값이나 넣어도 돼요.
전체 API 참조는 TGI Swagger UI를 참고하세요.
Python API를 사용할 수도 있어요:
from openai import OpenAI
# initialize the client but point it to TGI
client = OpenAI(
base_url="http://localhost:8080/v1/", # replace with your endpoint url
api_key="", # this field is not used when running locally
)
chat_completion = client.chat.completions.create(
model="", # it is not used by TGI, you can put anything
messages=[
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": "Tell me something about large language models."},
],
stream=True,
temperature=0.7,
top_p=0.8,
max_tokens=512,
)
# iterate and print stream
for message in chat_completion:
print(message.choices[0].delta.content, end="")
성능을 위한 양자화
데이터 종속 양자화 (GPTQ 및 AWQ)
GPTQ와 AWQ 모델은 모두 데이터 종속적이에요. 공식 양자화 모델은 Qwen2.5 컬렉션에서 찾을 수 있고, 여러분만의 데이터셋으로 모델을 양자화해 여러분의 사용 사례에서 더 잘 동작하게 할 수도 있어요.
다음은 Qwen2.5-7B-Instruct-GPTQ-Int4로 TGI를 시작하는 명령이에요:
model=Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model --quantize gptq
모델이 AWQ로 양자화된 경우, 예를 들어 Qwen/Qwen2.5-7B-Instruct-AWQ라면 --quantize awq를 사용하세요.
데이터 무관 양자화
반면 EETQ는 데이터 종속적이지 않아 어떤 모델과도 함께 사용할 수 있어요. --quantize eetq 플래그와 함께 (양자화된 모델이 아닌) 원본 모델을 전달한다는 점을 참고하세요.
model=Qwen/Qwen2.5-7B-Instruct
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model --quantize eetq
다중 가속기 배포
--num-shard 플래그로 가속기 수를 지정하세요. 최적의 NCCL 성능을 위해 공유 메모리를 활성화하려면 --shm-size 1g도 함께 사용하세요:
model=Qwen/Qwen2.5-7B-Instruct
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model --num-shard 2
Speculative Decoding
Speculative decoding은 다음 토큰을 예측해 토큰당 시간을 줄여줘요. --speculative-decoding 플래그에 예측할 토큰 수를 값으로 설정하세요 (기본값: 0 = 예측 안 함):
model=Qwen/Qwen2.5-7B-Instruct
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model --speculate 2
Speculative decoding의 전반적인 성능은 작업 유형에 크게 의존해요. 코드나 반복이 많은 텍스트에 가장 잘 동작해요. Speculative decoding에 대한 더 많은 내용은 여기에서 확인할 수 있어요.
HF Inference Endpoints로 제로 코드 배포
손쉬운 배포를 위해 Hugging Face Inference Endpoints를 활용하세요:
- GUI 인터페이스: https://huggingface.co/inference-endpoints/dedicated
- 코딩 인터페이스: https://huggingface.co/blog/tgi-messages-api
배포되면 엔드포인트를 평소처럼 사용할 수 있어요.
일반적인 문제
Qwen2.5는 긴 컨텍스트 길이를 지원하기 때문에, 잠재적인 메모리 부족(OOM) 문제를 피하기 위해 --max-batch-prefill-tokens, --max-total-tokens, --max-input-tokens 값을 신중하게 선택하세요. OOM이 발생하면 시작 시 오류 메시지를 받게 돼요. 다음은 이 파라미터들을 수정하는 예시예요:
model=Qwen/Qwen2.5-7B-Instruct
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:2.0 --model-id $model --max-batch-prefill-tokens 4096 --max-total-tokens 4096 --max-input-tokens 2048