# 聊天模板实用工具

有关 TRL 附带的聊天模板概览以及训练补丁背后的原理，请参阅 [聊天模板](chat_templates)。

## clone_chat_template[[trl.clone_chat_template]]

#### trl.clone_chat_template[[trl.clone_chat_template]]

```python
trl.clone_chat_template(model: PreTrainedModel, tokenizer: PreTrainedTokenizerBase, source_tokenizer_path: str, resize_to_multiple_of: int | None = 64)
```

[源代码](https://github.com/huggingface/trl/blob/v1.18.0/trl/chat_template_utils.py#L54)

**参数：**

model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel))：要更新的模型。

tokenizer ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.23.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase))：要更新的 Tokenizer。

source_tokenizer_path (`str`) : 要克隆的预训练分词器的路径或标识符。

resize_to_multiple_of (`int` 或 `None`，*可选*，默认为 `64`)：嵌入层将被调整至新的词汇表大小。如果此值不为 `None`，则会将新的词汇表大小向上取整为该值的最近倍数。

**返回：** model ([PreTrainedModel](https://huggingface.co/docs/transformers/v5.23.0/en/main_classes/model#transformers.PreTrainedModel))

已更新模型，调整了 token 嵌入的大小并配置了 EOS token。tokenizer ([PreTrainedTokenizerBase](https://huggingface.co/docs/transformers/v5.23.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase))：已更新 tokenizer，应用了聊天模板和特殊 token。added_tokens (`list[int]`)：从源 tokenizer 添加到当前 tokenizer 的 token 列表。

将聊天模板从源分词器克隆到目标分词器，并相应地更新模型。

此函数：
- 将聊天模板从源分词器复制到目标分词器。
- 将源分词器中的任何新标记添加到目标分词器中。
- 在分词器和模型之间设置并同步 EOS 标记。
- 将模型的 token 嵌入层大小调整为与新词汇表大小相匹配，可选择将其向上取整为指定值的倍数。在这种情况下，会向分词器添加虚拟 token，以确保词汇表大小与嵌入维度一致。

示例：
```python
>>> from transformers import AutoModelForCausalLM, AutoTokenizer
>>> from trl import clone_chat_template

>>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
>>> model, tokenizer, added_tokens = clone_chat_template(model, tokenizer, "Qwen/Qwen3-0.6B")
```

## is_chat_template_prefix_preserving[[trl.chat_template_utils.is_chat_template_prefix_preserving]]

#### trl.chat_template_utils.is_chat_template_prefix_preserving[[trl.chat_template_utils.is_chat_template_prefix_preserving]]

```python
trl.chat_template_utils.is_chat_template_prefix_preserving(processing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | transformers.processing_utils.ProcessorMixin)
```

[源代码](https://github.com/huggingface/trl/blob/v1.18.0/trl/chat_template_utils.py#L1038)

**参数：**

processing_class (`PreTrainedTokenizerBase` 或 `ProcessorMixin`)：要检查的分词器或处理器实例。

**返回：** `bool`

如果聊天模板保留前缀，则为`True`，否则为`False`。

检查应用聊天模板时是否保留了前缀。

前缀保留型聊天模板会以前缀一致的方式渲染较早的消息，无论后续消息是什么。这一特性是 `_get_tool_suffix_ids` 所必需的，该函数通过比较添加工具消息前后的分词结果，来提取工具响应的格式标记。

## get_training_chat_template[[trl.get_training_chat_template]]

#### trl.get_training_chat_template[[trl.get_training_chat_template]]

```python
trl.get_training_chat_template(processing_class: transformers.tokenization_utils_base.PreTrainedTokenizerBase | transformers.processing_utils.ProcessorMixin | None = None, tokenizer: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = None, require_prefix_preservation: bool = True)
```

[源代码](https://github.com/huggingface/trl/blob/v1.18.0/trl/chat_template_utils.py#L1281)

**参数：**

processing_class (`PreTrainedTokenizerBase` 或 `ProcessorMixin`)：要检查的分词器或处理器实例。

require_prefix_preservation (`bool`，*可选*，默认为 `True`)：如果模板没有存储的训练模板，是否也必须保持前缀不变才能原样返回。仅针对助手的损失只需要标记，因此 `SFTTrainer` 将其设置为 `False`。

**返回：** `str` 或 `None`

与训练兼容的聊天模板，如果无需修补则为 `None`。

如有需要，获取一个与训练兼容的聊天模板。

返回一个经过修补的聊天模板，该模板保留前缀，并包含用于仅对助手部分进行损失掩码的 `{%% generation %%}` / `{%% endgeneration %%}` 标记。如果模板中已存储了训练模板，则始终会应用此修补，即使该模板本身已包含标记。如果其他模板已满足要求，则返回 `None`。支持的模板列表见 [训练模板](chat_templates#training-templates)。

示例：

```python
>>> from trl.chat_template_utils import get_training_chat_template
>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
>>> messages1 = [
...     {"role": "user", "content": "What is 2 * 3?"},
...     {
...         "role": "assistant",
...         "content": "",
...         "tool_calls": [{"type": "function", "function": {"name": "multiply", "arguments": {"a": 2, "b": 3}}}],
...     },
... ]
>>> messages2 = messages1 + [
...     {"role": "tool", "name": "multiply", "content": "6"},
... ]
>>> tokenizer.apply_chat_template(messages1, tokenize=False)
'<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'

>>> tokenizer.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True)
'<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'

>>> #                                                        ^ think tags missing
>>> chat_template = get_training_chat_template(tokenizer)
>>> tokenizer.apply_chat_template(messages1, tokenize=False, chat_template=chat_template)
'<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n'

>>> tokenizer.apply_chat_template(
...     messages2, tokenize=False, add_generation_prompt=True, chat_template=chat_template
... )
'<|im_start|>user\nWhat is 2 * 3?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n<tool_call>\n{"name": "multiply", "arguments": {"a": 2, "b": 3}}\n</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n6\n</tool_response><|im_end|>\n<|im_start|>assistant\n'
```

