# 聊天基础

聊天模型是一种对话式模型，你可以向其发送消息并接收回复。2023 年中期之后发布的大多数语言模型都是聊天模型，通常也被称为“instruct”或“instruction-tuned”模型。不支持聊天的模型通常被称为“base”或“pretrained”模型。

更大、更新的模型通常能力更强，但在特定领域（如医疗、法律文本、非英语语言等）专门训练的模型往往能超越这些更大的模型。您可以尝试使用 [OpenLLM](https://hf.co/spaces/HuggingFaceH4/open_llm_leaderboard) 和 [LMSys Chatbot Arena](https://chat.lmsys.org/?leaderboard) 等排行榜，以帮助您找到最适合自身使用场景的模型。

本指南将向您展示如何快速从命令行在 Transformers 中加载聊天模型，如何构建和格式化对话，以及如何使用 [TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline) 进行聊天。

## chat CLI

在[安装 Transformers](./installation)之后，您可以直接从命令行与模型进行对话。以下命令会启动一个与模型的交互式会话，并在会话开始时列出一些基础命令。

> 对于以下命令，请确保 [`transformers serve` 正在运行](./serve-cli/serving)。

```bash
transformers chat Qwen/Qwen2.5-0.5B-Instruct
```

    

您可以使用任意 `generate` 标志启动 CLI，格式为 `arg_1=value_1 arg_2=value_2 ...`

```bash
transformers chat Qwen/Qwen2.5-0.5B-Instruct do_sample=False max_new_tokens=10
```

要查看完整的选项列表，请运行以下命令。

```bash
transformers chat -h
```

聊天功能基于 [AutoClass](./model_doc/auto) 实现，并使用了 [文本生成](./llm_tutorial) 和 [聊天](./chat_templating) 的工具。其底层使用 `transformers serve` CLI（[文档](./serve-cli/serving)）。

## TextGenerationPipeline

[TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline) 是一个具有“聊天模式”的高级文本生成类。当检测到对话模型且聊天提示词[格式正确](./llm_tutorial#prompt-format)时，聊天模式将被启用。

聊天模型接受一个消息列表（即聊天历史）作为输入。每条消息是一个包含 `role` 和 `content` 键的字典。要开始聊天，只需添加一条 `user` 消息。你还可以选择性地包含一条 `system` 消息，为模型提供关于如何表现的指令。

```py
chat = [
    {"role": "system", "content": "You are a helpful science assistant."},
    {"role": "user", "content": "Hey, can you explain gravity to me?"}
]
```

创建 [TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline) 并将 `chat` 传入。对于大型模型，设置 [device_map="auto"](./models#big-model-inference) 有助于更快地加载模型，并自动将其放置在最快的可用设备上。

```py
import torch
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="HuggingFaceTB/SmolLM2-1.7B-Instruct", dtype="auto", device_map="auto")
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
```

如果运行成功，您应该会看到模型的响应！如果您想继续对话，需要用模型的响应来更新聊天历史。您可以通过将文本追加到 `chat`（使用 `assistant` 角色）来实现，或者读取 `response[0]["generated_text"]`，其中包含完整的聊天历史，包括最新的响应。

获取模型的响应后，您可以通过在聊天历史记录中追加一条新的 `user` 消息来继续对话。

```py
chat = response[0]["generated_text"]
chat.append(
    {"role": "user", "content": "Woah! But can it be reconciled with quantum mechanics?"}
)
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
```

通过重复此过程，您可以继续对话，直到模型耗尽上下文窗口或您的内存用尽为止。

## 性能与内存使用

Transformers 默认以完整的 `float32` 精度加载模型，对于 8B 模型，这需要约 32GB 的内存！请使用 `torch_dtype="auto"` 参数，该参数通常对以 `bfloat16` 训练的模型使用 `bfloat16`，从而降低内存占用。

> [!TIP]
> 有关可用不同量化后端的更多信息，请参阅 [量化](./quantization/overview) 文档。

为了进一步降低内存占用，你可以使用 [bitsandbytes](https://hf.co/docs/bitsandbytes/index) 将模型量化为 8 位或 4 位。创建一个 [BitsAndBytesConfig](/docs/transformers/v5.23.0/zh/main_classes/quantization#transformers.BitsAndBytesConfig) 并设置所需的量化参数，然后将其传递给 pipelines 的 `model_kwargs` 参数。下面的示例将模型量化为 8 位。

```py
from transformers import pipeline, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config})
```

通常，模型规模与性能呈正相关。更大的模型不仅占用更多内存，速度也更慢，因为每生成一个 token，都必须从内存中读取每个激活参数。这是 LLM 文本生成的瓶颈，提升生成速度的主要方案是量化模型或使用内存带宽更高的硬件。单纯增加算力并不能带来显著改善。

您还可以尝试诸如[推测解码](./assisted_decoding#speculative-decoding)之类的技术，其中较小的模型生成候选 token，再由较大的模型进行验证。如果候选 token 正确，较大的模型可以一次生成多个 token。这能显著缓解带宽瓶颈并提升生成速度。

> [!TIP]
诸如 [Mixtral](./model_doc/mixtral)、[Qwen2MoE](./model_doc/qwen2_moe) 和 [GPT-OSS](./model_doc/gpt_oss) 等 Mixture-of-Expert (MoE) 模型拥有大量参数，但在生成每个 token 时仅“激活”其中的一小部分。因此，MoE 模型通常具有更低的内存带宽需求，并且可能比同等规模的常规 LLM 更快。然而，像投机解码（speculative decoding）这样的技术对 MoE 模型效果不佳，因为随着每个新推测 token 的生成，被激活的参数会越来越多。

