Skip to content

Commit d152fdb

Browse files
authored
add docs for chat-template (#7270)
1 parent 90f44a9 commit d152fdb

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

docs/get_started/chat_template.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## 对话生成模板
2+
3+
PaddleNLP 支持主流LLM 对话模型,同时支持自动构建多轮对话,可通过以下脚本。
4+
5+
### 使用对话模板
6+
7+
```python
8+
from paddlenlp.transformers import AutoTokenizer
9+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b-v1.1")
10+
11+
# 单论对话
12+
query = "北京有什么好玩的"
13+
inputs = tokenizer.apply_chat_template(query, return_tensors="pd")
14+
15+
# 多轮对话
16+
query = [["1+1=", "1+1=2"], ["再加一"]]
17+
inputs = tokenizer.apply_chat_template(query, return_tensors="pd")
18+
```
19+
20+
### 自定义对话模板
21+
22+
在介绍如何自定义对话模板之前,介绍对话模板构造的逻辑:`final_query = system + conversation_history + query`
23+
24+
* system: 在最终 prompt 最前面的固定文本,比如:你是一个人工智能助手,风趣幽默,通常喜欢用比较文艺的语言风格跟人们沟通。
25+
* conversation_history: 将多轮对话构造成一个 query,不同模型通常会有不同的构造规则。
26+
* query: 用户最新的输入。
27+
28+
构建自定义对话模板非常简单,只需要创建一个 `chat_template.json` 文件即可,如下所示:
29+
30+
1. 创建 chat_template 文件
31+
32+
> 文件名默认为:`chat_template.json`
33+
34+
```json
35+
{
36+
"system": "你是一个人工智能助手,风趣幽默,通常喜欢用比较文艺的语言风格跟人们沟通。",
37+
"conversation": ["[Round {{index}}]\n问:{{user}}\n", "答:{{bot}}\n"],
38+
"query": "[Round {{index}}]\n问:{{query}}\n答:"
39+
}
40+
```
41+
42+
参数介绍
43+
44+
* 配置文件当前主要有三个字段:`system`, `conversation`, `query`
45+
* `system`: 在最终 prompt 构造时拼接到最前面固定的文本。通常不参与训练中 loss 的计算。
46+
* `conversation`: 多轮对话的配置,且必须为两个配置:[user-template, bot-template],分别对应多轮对话中用户 query 的配置和模型回复 answer 的配置。可用于训练和推理两个阶段。
47+
* `query`: 用户最新 query 的构造,配置内容和 `conversation` 大体一致,且通常仅用于推理。
48+
49+
2. 通过 tokenizer 加载自定义对话模板
50+
51+
可通过两种方式加载:
52+
*`chat_template.json` 文件放到权重文件夹下,通过 Tokenizer.from_pretrained("/path/") 进行自动加载。
53+
* 手动加载:先初始化tokenizer,再通过 `tokenizer.init_chat_template(/path/to/file)` 函数加载。
54+
55+
3. 使用对话模板
56+
57+
```python
58+
from paddlenlp.transformers import AutoTokenizer
59+
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b-v1.1")
60+
61+
# 仅返回拼接后的文本
62+
query = "北京有什么好玩的"
63+
full_query = tokenizer.apply_chat_template(query, tokenize=False)
64+
65+
# 对拼接后的文本解码
66+
inputs = tokenizer.apply_chat_template(query, tokenize=True, return_tensors="pd")
67+
```

docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
安装 <get_started/installation>
3434
10分钟完成高精度中文情感分析 <get_started/quick_start>
35+
对话模板 <get_started/chat_template>
3536

3637
.. toctree::
3738
:maxdepth: 1

0 commit comments

Comments
 (0)