transformers serve 성능 최적화 — 처리량과 메모리 다루기

transformers serve 성능 최적화 — 처리량과 메모리 다루기

transformers serve는 처리량을 높이고 메모리 사용을 줄이기 위한 여러 최적화를 갖추고 있어요. 필요에 따라 조합해서 쓸 수 있습니다.

출처: https://huggingface.co/docs/transformers/en/serve-cli/serving_optims

연속 배칭 (Continuous batching)

연속 배칭은 요청을 동적으로 그룹화해 인터리브해서 GPU forward pass를 공유해요. 새 요청은 다른 요청이 prefill을 진행하는 동안 배치에 합류하고, 완료된 요청은 디코딩 후 빠져나옵니다. GPU 활용률과 처리량이 올라가면서도 지연 시간은 해치지 않아요. --continuous-batching으로 켭니다.

transformers serve \
  --continuous-batching \
  --attn-implementation "sdpa"

양자화

양자화는 가중치를 낮은 정밀도로 매핑해 메모리 사용을 줄이는데, Transformers의 모든 양자화 방식과 호환돼요. 사전 양자화 모델은 별도 변경 없이 성능과 정확도의 균형이 가장 좋아서 권장합니다. Hub에서 사전 양자화 모델을 model 인자로 넘기면 됩니다.

curl http://localhost:8000/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen3-8B-GGUF",
    "stream": true,
    "input": "Tell me a three sentence bedtime story about a unicorn."
  }'

사전 양자화 가중치가 없는 새 체크포인트라면 --quantization으로 런타임 양자화를 할 수 있어요. bitsandbytes의 4비트·8비트 양자화를 지원합니다.

transformers serve \
  --quantization bnb-4bit

어텐션 백엔드와 컴파일

최적화된 어텐션 백엔드는 메모리 효율을 높이고 추론을 빠르게 해요. Apple Silicon(MPS)에서는 kernels 패키지로 Metal flash attention이 기본 선택되는데, SDPA보다 1.66배 빠르다고 해요. 반대가 필요하면 --attn-implementation sdpa로 빠져나갈 수 있습니다.

pip install kernels
transformers serve --attn-implementation sdpa

torch.compile로 디코드 루프를 트레이스·컴파일해 추론을 빠르게 할 수도 있어요. 단, 연속 배칭과는 호환되지 않습니다.

transformers serve \
  --compile

데이터 타입

"bfloat16"이나 "float16" 데이터 타입은 메모리를 아끼고 처리량을 올립니다.

transformers serve \
  --continuous-batching \
  --dtype "bfloat16"

더 알아보기