# 서버 최적화

`transformers serve`에는 처리량을 높이고 메모리 사용량을 줄이는 최적화가 포함되어 있습니다.

## 연속 배치

[Continuous batching](../continuous_batching)은 GPU에서 forward pass를 공유하도록 요청을 동적으로 그룹화하고 교차 처리합니다. 다른 요청이 prefill을 진행하는 동안 새로운 요청이 배치에 합류하고, 완료된 요청은 decoding 후 배치에서 제외됩니다. 이를 통해 지연 시간을 저해하지 않으면서 GPU 활용률과 처리량을 높일 수 있습니다.

`--continuous-batching`를 추가하여 활성화합니다.

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

## 양자화

[Quantization](../quantization/overview)은 가중치를 더 낮은 정밀도로 매핑하여 메모리 사용량을 줄입니다. `transformers serve`는 Transformers의 모든 양자화 방식과 호환됩니다. 사전 양자화 모델과 런타임 양자화를 지원합니다.

양자화 전 처리된 모델은 변경 사항이 필요하지 않습니다. 성능과 정확도 사이의 최적의 균형을 제공합니다. 적절한 양자화 라이브러리를 설치한 후, Hub의 양자화 전 처리된 모델을 `model` 인수로 전달합니다.

```sh
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](../quantization/bitsandbytes) 4비트 및 8비트 양자화만 지원됩니다.

```sh
transformers serve \
  --quantization bnb-4bit
```

## Attention 백엔드

최적화된 [attention backend](../attention_interface)는 메모리 효율성을 높이고 추론 속도를 향상시킵니다.

```sh
transformers serve \
  --continuous-batching \
  --attn-implementation "flash_attention_2"
```

### Apple Silicon (Metal flash attention)

MPS에서 `--continuous-batching`을 사용할 경우, [kernels](https://github.com/huggingface/kernels)를 설치하여 [kernels-community/metal-flash-sdpa](https://huggingface.co/kernels-community/metal-flash-sdpa)로 전환할 수 있습니다. `generate_batch`를 사용할 때 SDPA보다 1.66배 빠르며(gsm8k, Qwen2.5-0.5B-Instruct, fp16), greedy decoding 환경에서는 토큰 단위로 동일한 결과를 제공합니다.

```sh
pip install kernels
transformers serve --continuous-batching
```

연속 배치 처리가 없으면 모델은 기본 어텐션(SDPA)을 유지합니다. `kernels-community/metal-flash-sdpa`와 같은 다른 어텐션을 사용하려면 `--attn-implementation`을 전달하세요.

## 컴파일

[torch.compile](../perf_torch_compile)은 추론 속도를 높이기 위해 디코딩 루프를 추적하고 컴파일합니다.

> [!NOTE]
> Compile은 continuous batching과 호환되지 않습니다.

```sh
transformers serve \
  --compile
```

## 데이터 유형

`"bfloat16"` 또는 `"float16"` [데이터 유형](../models#model-data-type)은 메모리를 절약하고 처리량을 높입니다.

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

