# 服务器优化

`transformers serve` 包含多项优化，以提升吞吐量并降低内存占用。

## 连续批处理

[连续批处理](../continuous_batching)会动态地对请求进行分组和交错，以在 GPU 上共享前向传播。当其他请求进入预填充阶段时，新请求会加入批次。请求在解码完成后退出批次。这在不牺牲延迟的情况下提高了 GPU 利用率和吞吐量。

添加 `--continuous-batching` 以启用该功能。

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

## 量化

[量化](../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 backend](../attention_interface) 能够提升内存效率并加快推理速度。

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

### Apple Silicon（Metal 快速注意力机制）

在 MPS 上使用 `--continuous-batching` 时，请安装 [kernels](https://github.com/huggingface/kernels) 以切换到 [kernels-community/metal-flash-sdpa](https://huggingface.co/kernels-community/metal-flash-sdpa)。在 `generate_batch`（gsm8k、Qwen2.5-0.5B-Instruct、fp16）下，其运行速度比 SDPA 快 1.66 倍，并且在贪心解码下逐 token 结果一致。

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

在没有连续批处理的情况下，模型会保持其默认的注意力机制（SDPA）。传入 `--attn-implementation` 以尝试其他实现，例如 `kernels-community/metal-flash-sdpa`。

## 编译

[torch.compile](../perf_torch_compile) 会对解码循环进行追踪和编译，以加快推理速度。

> [!NOTE]
> Compile 与连续批处理不兼容。

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

## 数据类型

`"bfloat16"` 或 `"float16"` [数据类型](../models#model-data-type)可以节省内存并提高吞吐量。

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

