update
Browse files- .gitattributes +1 -0
- README.md +82 -0
- added_tokens.json +7 -0
- config.json +26 -0
- configuration.json +1 -0
- configuration_tinyllm.py +61 -0
- generation_config.json +11 -0
- generation_utils.py +285 -0
- modeling_tinyllm.py +1133 -0
- special_tokens_map.json +23 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +82 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
frameworks:
|
3 |
+
- Pytorch
|
4 |
+
license: Apache License 2.0
|
5 |
+
tasks:
|
6 |
+
- text-generation
|
7 |
+
|
8 |
+
#model-type:
|
9 |
+
##如 gpt、phi、llama、chatglm、baichuan 等
|
10 |
+
#- gpt
|
11 |
+
|
12 |
+
#domain:
|
13 |
+
##如 nlp、cv、audio、multi-modal
|
14 |
+
#- nlp
|
15 |
+
|
16 |
+
#language:
|
17 |
+
##语言代码列表 https://help.aliyun.com/document_detail/215387.html?spm=a2c4g.11186623.0.0.9f8d7467kni6Aa
|
18 |
+
#- cn
|
19 |
+
|
20 |
+
#metrics:
|
21 |
+
##如 CIDEr、Blue、ROUGE 等
|
22 |
+
#- CIDEr
|
23 |
+
|
24 |
+
#tags:
|
25 |
+
##各种自定义,包括 pretrained、fine-tuned、instruction-tuned、RL-tuned 等训练方法和其他
|
26 |
+
#- pretrained
|
27 |
+
|
28 |
+
#tools:
|
29 |
+
##如 vllm、fastchat、llamacpp、AdaSeq 等
|
30 |
+
#- vllm
|
31 |
+
---
|
32 |
+
|
33 |
+
## Tiny LLM 76M SFT
|
34 |
+
|
35 |
+
### 简介
|
36 |
+
|
37 |
+
本项目[wdndev/tiny-llm-zh (github.com)](https://github.com/wdndev/tiny-llm-zh)旨在构建一个小参数量的中文语言大模型,用于快速入门学习大模型相关知识。
|
38 |
+
|
39 |
+
模型架构:整体模型架构采用开源通用架构,包括:RMSNorm,RoPE,MHA等
|
40 |
+
|
41 |
+
实现细节:实现大模型两阶段训练及后续人类对齐,即:预训练(PTM) -> 指令微调(SFT) -> 人类对齐(RLHF, DPO) -> 测评。
|
42 |
+
|
43 |
+
注意:因资源限制,本项目的第一要务是走通大模型整个流程,而不是调教比较好的效果,故评测结果分数较低,部分生成错误。
|
44 |
+
|
45 |
+
注意:此模型采用扩充 llama2 的词表后进行训练的;使用 tiny_llm_sft_92m 模型初始化transformers层,随机初始化embedding层,继续训练10B 的token,微调后得到;
|
46 |
+
|
47 |
+
### 模型细节
|
48 |
+
|
49 |
+
大约在9B的中文预料中训练,主要包含百科内容,模型架构采用开源通用架构,包括:RMSNorm,RoPE,MHA等。
|
50 |
+
|
51 |
+
### 环境
|
52 |
+
|
53 |
+
只需要安装 `transformers` 即可运行
|
54 |
+
|
55 |
+
### 快速开始
|
56 |
+
|
57 |
+
```python
|
58 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
59 |
+
|
60 |
+
model_id = "wdndev/tiny_llm_sft_76m_llama"
|
61 |
+
|
62 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
63 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", trust_remote_code=True)
|
64 |
+
|
65 |
+
sys_text = "你是由wdndev开发的个人助手。"
|
66 |
+
# user_text = "中国的首都是哪儿?"
|
67 |
+
# user_text = "你叫什么名字?"
|
68 |
+
user_text = "介绍一下中国"
|
69 |
+
input_txt = "\n".join(["<|system|>", sys_text.strip(),
|
70 |
+
"<|user|>", user_text.strip(),
|
71 |
+
"<|assistant|>"]).strip() + "\n"
|
72 |
+
|
73 |
+
model_inputs = tokenizer(input_txt, return_tensors="pt").to(model.device)
|
74 |
+
generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=200)
|
75 |
+
generated_ids = [
|
76 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
77 |
+
]
|
78 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
79 |
+
print(response)
|
80 |
+
```
|
81 |
+
|
82 |
+
|
added_tokens.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<|assistant|>": 49955,
|
3 |
+
"<|im_end|>": 49957,
|
4 |
+
"<|im_start|>": 49956,
|
5 |
+
"<|system|>": 49953,
|
6 |
+
"<|user|>": 49954
|
7 |
+
}
|
config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TinyllmForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_tinyllm.TinyllmConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_tinyllm.TinyllmForCausalLM"
|
9 |
+
},
|
10 |
+
"hidden_act": "silu",
|
11 |
+
"hidden_size": 512,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 1408,
|
14 |
+
"max_position_embeddings": 1024,
|
15 |
+
"model_type": "tinyllm",
|
16 |
+
"num_attention_heads": 8,
|
17 |
+
"num_hidden_layers": 8,
|
18 |
+
"num_key_value_heads": 8,
|
19 |
+
"rms_norm_eps": 1e-06,
|
20 |
+
"rope_theta": 10000.0,
|
21 |
+
"tie_word_embeddings": false,
|
22 |
+
"torch_dtype": "float16",
|
23 |
+
"transformers_version": "4.38.1",
|
24 |
+
"use_cache": false,
|
25 |
+
"vocab_size": 49958
|
26 |
+
}
|
configuration.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"framework":"Pytorch","task":"text-generation"}
|
configuration_tinyllm.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
from transformers.utils import logging
|
3 |
+
|
4 |
+
|
5 |
+
logger = logging.get_logger(__name__)
|
6 |
+
|
7 |
+
|
8 |
+
class TinyllmConfig(PretrainedConfig):
|
9 |
+
""" TinyLLM 配置文件
|
10 |
+
"""
|
11 |
+
|
12 |
+
model_type = "tinyllm"
|
13 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
14 |
+
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
vocab_size=64797,
|
18 |
+
hidden_size=4096,
|
19 |
+
intermediate_size=11008,
|
20 |
+
num_hidden_layers=32,
|
21 |
+
num_attention_heads=32,
|
22 |
+
num_key_value_heads=None,
|
23 |
+
hidden_act="silu",
|
24 |
+
max_position_embeddings=2048,
|
25 |
+
initializer_range=0.02,
|
26 |
+
rms_norm_eps=1e-6,
|
27 |
+
use_cache=True,
|
28 |
+
pad_token_id=None,
|
29 |
+
bos_token_id=None,
|
30 |
+
eos_token_id=None,
|
31 |
+
tie_word_embeddings=False,
|
32 |
+
rope_theta=10000.0,
|
33 |
+
attention_dropout=0.0,
|
34 |
+
**kwargs
|
35 |
+
):
|
36 |
+
self.vocab_size = vocab_size
|
37 |
+
self.max_position_embeddings = max_position_embeddings
|
38 |
+
self.hidden_size = hidden_size
|
39 |
+
self.intermediate_size = intermediate_size
|
40 |
+
self.num_hidden_layers = num_hidden_layers
|
41 |
+
self.num_attention_heads = num_attention_heads
|
42 |
+
|
43 |
+
# for backward compatibility
|
44 |
+
if num_key_value_heads is None:
|
45 |
+
num_key_value_heads = num_attention_heads
|
46 |
+
|
47 |
+
self.num_key_value_heads = num_key_value_heads
|
48 |
+
self.hidden_act = hidden_act
|
49 |
+
self.initializer_range = initializer_range
|
50 |
+
self.rms_norm_eps = rms_norm_eps
|
51 |
+
self.use_cache = use_cache
|
52 |
+
self.rope_theta = rope_theta
|
53 |
+
self.attention_dropout = attention_dropout
|
54 |
+
|
55 |
+
super().__init__(
|
56 |
+
pad_token_id=pad_token_id,
|
57 |
+
bos_token_id=bos_token_id,
|
58 |
+
eos_token_id=eos_token_id,
|
59 |
+
tie_word_embeddings=tie_word_embeddings,
|
60 |
+
**kwargs
|
61 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
from queue import Queue
|
5 |
+
from typing import Tuple, List, Union, Iterable
|
6 |
+
from transformers.utils import logging, add_start_docstrings
|
7 |
+
from transformers.generation.logits_process import LogitsProcessor, LOGITS_PROCESSOR_INPUTS_DOCSTRING, LogitsProcessorList
|
8 |
+
|
9 |
+
def make_context(model, tokenizer,
|
10 |
+
messages: List[dict],
|
11 |
+
system: str = "You are a helpful assistant.",
|
12 |
+
max_new_tokens: int=0,
|
13 |
+
):
|
14 |
+
# 确定新生成的token数量,优先使用传入参数,否则使用模型配置中的默认值
|
15 |
+
max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
16 |
+
# 计算模型允许的最大输入长度(模型最大长度减去新生成的token数)
|
17 |
+
max_input_length = model.config.max_position_embeddings - max_new_tokens
|
18 |
+
|
19 |
+
nl_tokens = tokenizer.encode("\n", add_special_tokens=False)
|
20 |
+
|
21 |
+
def _parse_messages(messages):
|
22 |
+
""" 解析消息列表,分离系统消息、查询和对话历史
|
23 |
+
"""
|
24 |
+
system, query, history = "", "", []
|
25 |
+
## system
|
26 |
+
if messages[0]["role"] == "system":
|
27 |
+
system = messages[0]["content"]
|
28 |
+
messages = messages[1:]
|
29 |
+
## query
|
30 |
+
### 确保最后一项是用户消息
|
31 |
+
assert messages[-1]["role"] == "user"
|
32 |
+
query = messages[-1]["content"]
|
33 |
+
messages = messages[:-1]
|
34 |
+
## history
|
35 |
+
assert len(messages) % 2 == 0
|
36 |
+
for i in range(0, len(messages), 2):
|
37 |
+
assert messages[i]["role"] == "user" and messages[i+1]["role"] == "assistant"
|
38 |
+
history.append([messages[i]["content"], messages[i+1]["content"]])
|
39 |
+
|
40 |
+
return system, query, history
|
41 |
+
|
42 |
+
# 调用_parse_messages解析消息
|
43 |
+
_system, query, history = _parse_messages(messages)
|
44 |
+
|
45 |
+
## system
|
46 |
+
system_text = _system if _system != "" else system
|
47 |
+
system_tokens = []
|
48 |
+
if system_text:
|
49 |
+
# system_tokens = tokenizer.build_single_message("system", "", system_text.strip())
|
50 |
+
system_tokens = tokenizer.encode(text=("<|system|>\n"+system_text.strip()), add_special_tokens=True, truncation=True) + nl_tokens
|
51 |
+
## query
|
52 |
+
# query_tokens = tokenizer.build_single_message("user", "", query.strip())
|
53 |
+
query_tokens = tokenizer.encode(text=("<|user|>\n"+query.strip()), add_special_tokens=False, truncation=True) + nl_tokens
|
54 |
+
## final assistant
|
55 |
+
# final_tokens = tokenizer.build_single_message("assistant", "", "")
|
56 |
+
final_tokens = tokenizer.encode("<|assistant|>", add_special_tokens=False, truncation=True) + nl_tokens
|
57 |
+
|
58 |
+
## max_history_tokens
|
59 |
+
max_history_length = max_input_length - len(system_tokens) - len(query_tokens) - len(final_tokens)
|
60 |
+
|
61 |
+
## history
|
62 |
+
## 逆序遍历对话历史,构建token序列
|
63 |
+
context_tokens = []
|
64 |
+
for turn_query, turn_response in reversed(history):
|
65 |
+
## query tokens
|
66 |
+
history_query_tokens = tokenizer.encode("<|user|>\n"+turn_query.strip(), add_special_tokens=False, truncation=True) + nl_tokens
|
67 |
+
## answer tokens
|
68 |
+
histroy_response_tokens = tokenizer.encode("<|assistant|>\n"+turn_response.strip(), add_special_tokens=False, truncation=True) + nl_tokens
|
69 |
+
## this round tokens
|
70 |
+
next_context_tokens = history_query_tokens + histroy_response_tokens
|
71 |
+
## concat
|
72 |
+
## 确保加入这些token后总长度不超过允许的最大历史长度
|
73 |
+
current_context_size = len(next_context_tokens) + len(context_tokens)
|
74 |
+
if current_context_size < max_history_length:
|
75 |
+
context_tokens = next_context_tokens + context_tokens
|
76 |
+
else:
|
77 |
+
break
|
78 |
+
input_tokens = system_tokens + context_tokens + query_tokens + final_tokens
|
79 |
+
|
80 |
+
return torch.LongTensor([input_tokens]).to(model.device)
|
81 |
+
|
82 |
+
def parse_pot_no_stream(inputs):
|
83 |
+
""" 解析并处理输入字符串中特定格式(形如 <<...>>)的代码片段。
|
84 |
+
这些代码片段可以是简单的数学表达式赋值,也可以是定义和调用函数。
|
85 |
+
1. 对于包含 "func" 的代码片段,它会识别函数定义,执行该函数,
|
86 |
+
并将函数返回的结果替换到原始字符串中的相应位置。
|
87 |
+
如果函数涉及到 sympy(一个符号计算库),
|
88 |
+
则还会做一些特定的字符串替换处理。
|
89 |
+
2. 对于不包含 "func" 的代码片段,它会直接计算等号右边的表达式,
|
90 |
+
并将计算结果替换到原始字符串中,同时也会进行一些类型转换
|
91 |
+
(如将浮点数转为整数)。
|
92 |
+
"""
|
93 |
+
try:
|
94 |
+
# 尝试从输入字符串中找到形如 "<<...>>" 的模式
|
95 |
+
s = re.findall(r'<<(.*?)>>', inputs, re.DOTALL)
|
96 |
+
# 如果没有找到匹配项,则直接返回原始输入
|
97 |
+
if not s:
|
98 |
+
#print("err inputs: ", origin_inputs, flush=True)
|
99 |
+
return inputs
|
100 |
+
|
101 |
+
index = 0
|
102 |
+
# 遍历所有匹配到的模式
|
103 |
+
for k in s:
|
104 |
+
try:
|
105 |
+
# 检查模式内是否包含 "func"
|
106 |
+
if "func" in k:
|
107 |
+
# 分割并处理函数定义
|
108 |
+
var = k.split("=", 1)
|
109 |
+
try:
|
110 |
+
# 去除空白字符并执行函数定义
|
111 |
+
var[1] = var[1].strip(" ")
|
112 |
+
exec(var[1], globals())
|
113 |
+
# 调用函数获取结果
|
114 |
+
ans = func()
|
115 |
+
except:
|
116 |
+
# 特殊处理包含 'sympy' 的情况
|
117 |
+
if 'sympy' in var[1]:
|
118 |
+
var[1] = var[1].replace('res[x]', 'res[0][0]').replace('res[y]', 'res[0][1]')
|
119 |
+
exec(var[1], globals())
|
120 |
+
ans = func()
|
121 |
+
pass
|
122 |
+
var_list = [c.strip(" ") for c in var[0].split(",")]
|
123 |
+
# 如果只有一个变量名,则将结果放入列表
|
124 |
+
if len(var_list) == 1:
|
125 |
+
ans = [ans]
|
126 |
+
|
127 |
+
# 将结果转换为浮点数或整数形式,并替换到输入字符串中
|
128 |
+
for i in range(len(ans)):
|
129 |
+
try:
|
130 |
+
ans[i] = float(ans[i])
|
131 |
+
if abs(ans[i] - int(ans[i])) < 1e-10:
|
132 |
+
ans[i] = str(int(ans[i]))
|
133 |
+
except:
|
134 |
+
pass
|
135 |
+
|
136 |
+
# 替换原字符串中的模式和变量名
|
137 |
+
inputs = inputs.replace("<<"+k+">>", "")
|
138 |
+
for i in range(len(var_list)):
|
139 |
+
inputs = inputs.replace(var_list[i], str(ans[i]))
|
140 |
+
index += 1
|
141 |
+
# 更新后续模式中的变量值
|
142 |
+
for c in range(index, len(s)):
|
143 |
+
for i in range(len(var_list)):
|
144 |
+
s[c] = s[c].replace(var_list[i], str(ans[i]))
|
145 |
+
else:
|
146 |
+
# 处理非函数的情况,直接计算并替换
|
147 |
+
var = k.replace(" ", "").split("=")
|
148 |
+
var[1] = var[1].replace("eval", "")
|
149 |
+
ans = round(eval(var[1]), 10)
|
150 |
+
ans = float(ans)
|
151 |
+
if abs(ans - int(ans)) < 1e-10:
|
152 |
+
ans = str(int(ans))
|
153 |
+
# 替换原字符串中的模式和变量名
|
154 |
+
inputs = inputs.replace("<<"+k+">>", "").replace(var[0], str(ans))
|
155 |
+
index += 1
|
156 |
+
# 更新后续模式中的变量值
|
157 |
+
for c in range(index, len(s)):
|
158 |
+
s[c] = s[c].replace(var[0], str(ans))
|
159 |
+
except:
|
160 |
+
return inputs
|
161 |
+
except Exception as e:
|
162 |
+
return inputs
|
163 |
+
|
164 |
+
return inputs
|
165 |
+
|
166 |
+
|
167 |
+
class TextIterStreamer:
|
168 |
+
""" 实现文本的流式处理
|
169 |
+
能够逐个或逐段生成和输出文本,而不是一次性输出全部内容
|
170 |
+
"""
|
171 |
+
def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False, use_pot=True):
|
172 |
+
self.tokenizer = tokenizer
|
173 |
+
self.skip_prompt = skip_prompt
|
174 |
+
self.skip_special_tokens = skip_special_tokens
|
175 |
+
self.tokens = []
|
176 |
+
# 使用队列来缓存生成的文本片段,以便于逐块输出
|
177 |
+
self.text_queue = Queue()
|
178 |
+
self.next_tokens_are_prompt = True
|
179 |
+
# 是否使用特定的后处理技术(例如翻译或优化),默认为True
|
180 |
+
self.use_pot = use_pot
|
181 |
+
|
182 |
+
def put(self, value):
|
183 |
+
# 接收并处理生成的token值
|
184 |
+
if self.skip_prompt and self.next_tokens_are_prompt:
|
185 |
+
self.next_tokens_are_prompt = False
|
186 |
+
else:
|
187 |
+
if len(value.shape) > 1:
|
188 |
+
value = value[0]
|
189 |
+
self.tokens.extend(value.tolist())
|
190 |
+
tokens_str = self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens, errors='ignore')
|
191 |
+
if self.use_pot:
|
192 |
+
tokens_str = parse_pot_no_stream(tokens_str)
|
193 |
+
self.text_queue.put(tokens_str)
|
194 |
+
|
195 |
+
def end(self):
|
196 |
+
self.text_queue.put(None)
|
197 |
+
|
198 |
+
def __iter__(self):
|
199 |
+
return self
|
200 |
+
|
201 |
+
def __next__(self):
|
202 |
+
# 实现迭代器的下一步方法,从队列中获取并返回文本,
|
203 |
+
# 或在无更多内容时抛出StopIteration异常
|
204 |
+
value = self.text_queue.get()
|
205 |
+
if value is None:
|
206 |
+
raise StopIteration()
|
207 |
+
else:
|
208 |
+
return value
|
209 |
+
|
210 |
+
|
211 |
+
class OutputRepetitionPenaltyLogitsProcessor(LogitsProcessor):
|
212 |
+
r"""
|
213 |
+
[`OutputLogitsProcessor`] that prevents the repetition of previous tokens through a penalty. This penalty is applied at
|
214 |
+
most once per token. Note that, for decoder-only models like most LLMs, the considered tokens include the prompt.
|
215 |
+
|
216 |
+
In the original [paper](https://arxiv.org/pdf/1909.05858.pdf), the authors suggest the use of a penalty of around
|
217 |
+
1.2 to achieve a good balance between truthful generation and lack of repetition. To penalize and reduce
|
218 |
+
repetition, use `penalty` values above 1.0, where a higher value penalizes more strongly. To reward and encourage
|
219 |
+
repetition, use `penalty` values between 0.0 and 1.0, where a lower value rewards more strongly.
|
220 |
+
|
221 |
+
Args:
|
222 |
+
penalty (`float`):
|
223 |
+
The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 penalizes previously generated
|
224 |
+
tokens. Between 0.0 and 1.0 rewards previously generated tokens.
|
225 |
+
"""
|
226 |
+
|
227 |
+
def __init__(self, input_length: int,
|
228 |
+
presence_penalties: float = 1.0,
|
229 |
+
frequency_penalties: float = 0,
|
230 |
+
repetition_penalties: float = 0):
|
231 |
+
if not (repetition_penalties > 0):
|
232 |
+
raise ValueError(f"`repetition_penalties` has to be a strictly positive float, but is {repetition_penalties}")
|
233 |
+
if not ( (frequency_penalties >= -2) and (frequency_penalties <= 2) ):
|
234 |
+
raise ValueError(f"`frequency_penalties` has to be [-2, 2], but is {frequency_penalties}")
|
235 |
+
if not ( (presence_penalties >= -2) and (presence_penalties <= 2) ):
|
236 |
+
raise ValueError(f"`presence_penalties` has to be [-2, 2], but is {presence_penalties}")
|
237 |
+
|
238 |
+
self.repetition_penalties = repetition_penalties
|
239 |
+
self.frequency_penalties = frequency_penalties
|
240 |
+
self.presence_penalties = presence_penalties
|
241 |
+
self.input_length = input_length
|
242 |
+
|
243 |
+
def _get_bin_counts_and_mask(
|
244 |
+
self,
|
245 |
+
tokens: torch.Tensor,
|
246 |
+
vocab_size: int,
|
247 |
+
num_seqs: int,
|
248 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
249 |
+
# Compute the bin counts for the tokens.
|
250 |
+
# vocab_size + 1 for padding.
|
251 |
+
bin_counts = torch.zeros((num_seqs, vocab_size + 1),
|
252 |
+
dtype=torch.long,
|
253 |
+
device=tokens.device)
|
254 |
+
bin_counts.scatter_add_(1, tokens, torch.ones_like(tokens))
|
255 |
+
bin_counts = bin_counts[:, :vocab_size]
|
256 |
+
mask = bin_counts > 0
|
257 |
+
|
258 |
+
return bin_counts, mask
|
259 |
+
|
260 |
+
@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
|
261 |
+
def __call__(self, input_ids: torch.LongTensor, logits: torch.FloatTensor) -> torch.FloatTensor:
|
262 |
+
prompt_tokens_tensor = input_ids[:, :self.input_length+1]
|
263 |
+
output_tokens_tensor = input_ids[:, self.input_length+1:]
|
264 |
+
|
265 |
+
num_seqs, vocab_size = logits.shape
|
266 |
+
_, prompt_mask = self._get_bin_counts_and_mask(
|
267 |
+
prompt_tokens_tensor, vocab_size, num_seqs)
|
268 |
+
output_bin_counts, output_mask = self._get_bin_counts_and_mask(
|
269 |
+
output_tokens_tensor, vocab_size, num_seqs)
|
270 |
+
|
271 |
+
repetition_penalties = torch.Tensor([self.repetition_penalties]).to(logits.device)
|
272 |
+
frequency_penalties = torch.Tensor([self.frequency_penalties]).to(logits.device)
|
273 |
+
presence_penalties = torch.Tensor([self.presence_penalties]).to(logits.device)
|
274 |
+
|
275 |
+
repetition_penalties = repetition_penalties[:, None].repeat(1, vocab_size)
|
276 |
+
repetition_penalties[~(prompt_mask | output_mask)] = 1.0
|
277 |
+
logits = torch.where(logits > 0, logits / repetition_penalties,
|
278 |
+
logits * repetition_penalties)
|
279 |
+
|
280 |
+
# We follow the definition in OpenAI API.
|
281 |
+
# Refer to https://platform.openai.com/docs/api-reference/parameter-details
|
282 |
+
logits -= frequency_penalties.unsqueeze_(dim=1) * output_bin_counts
|
283 |
+
logits -= presence_penalties.unsqueeze_(dim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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tiny LLM 模型架构
|
3 |
+
|
4 |
+
到处抄,整体还是Llama2的模型架构
|
5 |
+
"""
|
6 |
+
|
7 |
+
import math
|
8 |
+
import warnings
|
9 |
+
from threading import Thread
|
10 |
+
from typing import List, Optional, Tuple, Union
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torch.utils.checkpoint
|
15 |
+
from torch import nn
|
16 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
17 |
+
|
18 |
+
from transformers.activations import ACT2FN
|
19 |
+
from transformers.cache_utils import Cache, DynamicCache
|
20 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
21 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
22 |
+
from transformers.modeling_utils import PreTrainedModel
|
23 |
+
from transformers.utils import logging
|
24 |
+
from transformers.generation.utils import GenerationConfig
|
25 |
+
from transformers.generation.logits_process import LogitsProcessorList
|
26 |
+
|
27 |
+
from .configuration_tinyllm import TinyllmConfig
|
28 |
+
from .generation_utils import TextIterStreamer, make_context, OutputRepetitionPenaltyLogitsProcessor, parse_pot_no_stream
|
29 |
+
|
30 |
+
logger = logging.get_logger(__name__)
|
31 |
+
|
32 |
+
def debug(key, value):
|
33 |
+
"""
|
34 |
+
"""
|
35 |
+
try:
|
36 |
+
res = {"var": torch.var(value).item(), "mean": torch.mean(value).item(),
|
37 |
+
"max":torch.max(value).item(), "size": value.size(), "dtype": value.dtype}
|
38 |
+
except:
|
39 |
+
res = value
|
40 |
+
print("debug", key, res, sep="\t")
|
41 |
+
|
42 |
+
|
43 |
+
def report_memory(name):
|
44 |
+
"""Simple GPU memory report."""
|
45 |
+
mega_bytes = 1024.0 * 1024.0
|
46 |
+
string = name + ' memory (MB)'
|
47 |
+
# 变量分配显存
|
48 |
+
string += ' | allocated: {}'.format(
|
49 |
+
torch.cuda.memory_allocated() / mega_bytes)
|
50 |
+
string += ' | max allocated: {}'.format(
|
51 |
+
torch.cuda.max_memory_allocated() / mega_bytes)
|
52 |
+
# 缓存和变量分配显存,实际显存还需要+pytorch context
|
53 |
+
string += ' | reserved: {}'.format(
|
54 |
+
torch.cuda.memory_reserved() / mega_bytes)
|
55 |
+
string += ' | max reserved: {}'.format(
|
56 |
+
torch.cuda.max_memory_reserved() / mega_bytes)
|
57 |
+
try:
|
58 |
+
if torch.distributed.get_rank() == 0:
|
59 |
+
print("[Rank {}] {}".format(torch.distributed.get_rank(), string),
|
60 |
+
flush=True)
|
61 |
+
pass
|
62 |
+
except:
|
63 |
+
pass
|
64 |
+
|
65 |
+
class TinyllmRMSNorm(nn.Module):
|
66 |
+
def __init__(self, hidden_size, eps=1e-6):
|
67 |
+
""" TinyllmRMSNorm
|
68 |
+
"""
|
69 |
+
super().__init__()
|
70 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
71 |
+
self.variance_epsilon = eps
|
72 |
+
|
73 |
+
def forward(self, hidden_states):
|
74 |
+
input_dtype = hidden_states.dtype
|
75 |
+
hidden_states = hidden_states.to(torch.float32)
|
76 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
77 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
78 |
+
return self.weight * hidden_states.to(input_dtype)
|
79 |
+
|
80 |
+
class TinyllmRotaryEmbedding(nn.Module):
|
81 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
82 |
+
""" 旋转位置编码
|
83 |
+
- dim (int): 旋转嵌入的维度大小。
|
84 |
+
- max_position_embeddings (int): 预计算的最大位置嵌入数,默认为2048。
|
85 |
+
- base (int): 用于计算逆频率的基本频率,默认为10000。
|
86 |
+
"""
|
87 |
+
super().__init__()
|
88 |
+
|
89 |
+
self.dim = dim
|
90 |
+
self.max_position_embeddings = max_position_embeddings
|
91 |
+
self.base = base
|
92 |
+
# 计算逆频率值,并将其注册为模型的缓冲区
|
93 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
94 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
95 |
+
|
96 |
+
# 为了支持`torch.jit.trace`功能,立即计算预存储的余弦和正弦缓存
|
97 |
+
self._set_cos_sin_cache(
|
98 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
99 |
+
)
|
100 |
+
|
101 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
102 |
+
""" 预计算的余弦和正弦缓存
|
103 |
+
"""
|
104 |
+
self.max_seq_len_cached = seq_len
|
105 |
+
# 创建一个从0到最大序列长度-1的整数张量,与 inv_freq 具有相同的设备和数据类型
|
106 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
107 |
+
|
108 |
+
# 计算每个位置与每个维度的频率,形成频谱矩阵
|
109 |
+
freqs = torch.outer(t, self.inv_freq)
|
110 |
+
|
111 |
+
# 不同于论文中的实现,这里采用了不同的排列方式以获得相同的计算结果
|
112 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
113 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
114 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
115 |
+
|
116 |
+
def forward(self, x, seq_len=None):
|
117 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
118 |
+
if seq_len > self.max_seq_len_cached:
|
119 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
120 |
+
|
121 |
+
return (
|
122 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
123 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
124 |
+
)
|
125 |
+
|
126 |
+
def rotate_half(x):
|
127 |
+
""" 旋转输入一半的 hidden dim
|
128 |
+
"""
|
129 |
+
x1 = x[..., : x.shape[-1] // 2]
|
130 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
131 |
+
return torch.cat((-x2, x1), dim=-1)
|
132 |
+
|
133 |
+
|
134 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
135 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
136 |
+
""" 在 qk 应用旋转位置编码
|
137 |
+
|
138 |
+
Args:
|
139 |
+
q (`torch.Tensor`): q
|
140 |
+
k (`torch.Tensor`): k
|
141 |
+
cos (`torch.Tensor`): 旋转位置嵌入的余弦部分
|
142 |
+
sin (`torch.Tensor`): 旋转位置嵌入的正弦部分
|
143 |
+
position_ids (`torch.Tensor`): 与q和k对应位置的标记索引。例如,在处理KV缓存时,可以使用偏移过的位置ID。
|
144 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1): 'unsqueeze_dim' 参数指定了沿哪个维度对 cos[position_ids]
|
145 |
+
和 sin[position_ids] 进行扩展,以便它们能够适当地广播到 q 和 k 的维度上。
|
146 |
+
例如,注意 cos[position_ids] 和 sin[position_ids] 具有形状 [batch_size, seq_len, head_dim]。
|
147 |
+
那么,如果 q 和 k 的形状分别为 [batch_size, heads, seq_len, head_dim],
|
148 |
+
则设置 unsqueeze_dim=1 可使 cos[position_ids] 和 sin[position_ids] 可以广播到 q 和 k 的形状上。
|
149 |
+
同样地,如果 q 和 k 的形状为 [batch_size, seq_len, heads, head_dim],则应将 unsqueeze_dim 设置为 2
|
150 |
+
Returns:
|
151 |
+
包含使用旋转位置嵌入变换后的q和k张量的 `tuple(torch.Tensor)`。
|
152 |
+
"""
|
153 |
+
# print("ori cos: ", cos.shape)
|
154 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
155 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
156 |
+
|
157 |
+
# print("q: ", q.shape)
|
158 |
+
# print("cos: ", cos.shape)
|
159 |
+
# print("sin: ", sin.shape)
|
160 |
+
# print("rotate_half: ", rotate_half(q).shape)
|
161 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
162 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
163 |
+
return q_embed, k_embed
|
164 |
+
|
165 |
+
|
166 |
+
class TinyllmMLP(nn.Module):
|
167 |
+
def __init__(self, config):
|
168 |
+
super().__init__()
|
169 |
+
self.config = config
|
170 |
+
self.hidden_size = config.hidden_size
|
171 |
+
self.intermediate_size = config.intermediate_size
|
172 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
173 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
174 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
175 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
176 |
+
|
177 |
+
def forward(self, x):
|
178 |
+
intermediate = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
|
179 |
+
down_proj = self.down_proj(intermediate)
|
180 |
+
return down_proj
|
181 |
+
|
182 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
183 |
+
"""
|
184 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
185 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
186 |
+
"""
|
187 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
188 |
+
if n_rep == 1:
|
189 |
+
return hidden_states
|
190 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
191 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
192 |
+
|
193 |
+
class TinyllmAttention(nn.Module):
|
194 |
+
""" 多头注意力
|
195 |
+
"""
|
196 |
+
|
197 |
+
def __init__(self, config: TinyllmConfig, layer_idx: Optional[int] = None):
|
198 |
+
super().__init__()
|
199 |
+
self.config = config
|
200 |
+
self.layer_idx = layer_idx
|
201 |
+
if layer_idx is None:
|
202 |
+
logger.warning_once(
|
203 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
204 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
205 |
+
"when creating this class."
|
206 |
+
)
|
207 |
+
|
208 |
+
self.hidden_size = config.hidden_size
|
209 |
+
self.num_heads = config.num_attention_heads
|
210 |
+
self.head_dim = self.hidden_size // self.num_heads
|
211 |
+
self.num_key_value_heads = config.num_key_value_heads
|
212 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
213 |
+
self.max_position_embeddings = config.max_position_embeddings
|
214 |
+
self.rope_theta = config.rope_theta
|
215 |
+
# 因果自回归模式
|
216 |
+
self.is_causal = True
|
217 |
+
self.attention_dropout = config.attention_dropout
|
218 |
+
|
219 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
220 |
+
raise ValueError(
|
221 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
222 |
+
f" and `num_heads`: {self.num_heads})."
|
223 |
+
)
|
224 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
225 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
226 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
227 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
228 |
+
|
229 |
+
self.rotary_emb = TinyllmRotaryEmbedding(
|
230 |
+
self.head_dim,
|
231 |
+
max_position_embeddings=self.max_position_embeddings,
|
232 |
+
base=self.rope_theta,
|
233 |
+
)
|
234 |
+
|
235 |
+
def forward(
|
236 |
+
self,
|
237 |
+
hidden_states: torch.Tensor,
|
238 |
+
attention_mask: Optional[torch.Tensor] = None,
|
239 |
+
position_ids: Optional[torch.LongTensor] = None,
|
240 |
+
past_key_value: Optional[Cache] = None,
|
241 |
+
output_attentions: bool = False,
|
242 |
+
use_cache: bool = False,
|
243 |
+
**kwargs,
|
244 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
245 |
+
if "padding_mask" in kwargs:
|
246 |
+
warnings.warn(
|
247 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
248 |
+
)
|
249 |
+
bsz, q_len, _ = hidden_states.size()
|
250 |
+
|
251 |
+
query_states = self.q_proj(hidden_states)
|
252 |
+
key_states = self.k_proj(hidden_states)
|
253 |
+
value_states = self.v_proj(hidden_states)
|
254 |
+
|
255 |
+
# 重新投影,变成多头注意力结构
|
256 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
257 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
258 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
259 |
+
|
260 |
+
kv_seq_len = key_states.shape[-2]
|
261 |
+
if past_key_value is not None:
|
262 |
+
if self.layer_idx is None:
|
263 |
+
raise ValueError(
|
264 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
265 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
266 |
+
"with a layer index."
|
267 |
+
)
|
268 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
269 |
+
# 应用旋转位置编码到 qk 向量
|
270 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
271 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
272 |
+
|
273 |
+
# 如果存在缓存,则更新 kv
|
274 |
+
if past_key_value is not None:
|
275 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
276 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
277 |
+
|
278 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
279 |
+
# 如果 num_key_value_heads 小于 num_heads,则重复key和value向量以匹配头数量
|
280 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
281 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
282 |
+
|
283 |
+
# 计算注意力权重
|
284 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
285 |
+
|
286 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
287 |
+
raise ValueError(
|
288 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
289 |
+
f" {attn_weights.size()}"
|
290 |
+
)
|
291 |
+
|
292 |
+
if attention_mask is not None:
|
293 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
294 |
+
raise ValueError(
|
295 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
296 |
+
)
|
297 |
+
|
298 |
+
attn_weights = attn_weights + attention_mask
|
299 |
+
|
300 |
+
# softmax归一化注意力权重,并转换至float32类型以防止数值溢出
|
301 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
302 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
303 |
+
# 注意力输出
|
304 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
305 |
+
|
306 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
307 |
+
raise ValueError(
|
308 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
309 |
+
f" {attn_output.size()}"
|
310 |
+
)
|
311 |
+
|
312 |
+
# 还原注意力输出的形状以与后续层对接
|
313 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
314 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
315 |
+
|
316 |
+
# 通过o_proj层进一步处理注意力输出
|
317 |
+
attn_output = self.o_proj(attn_output)
|
318 |
+
|
319 |
+
if not output_attentions:
|
320 |
+
attn_weights = None
|
321 |
+
|
322 |
+
return attn_output, attn_weights, past_key_value
|
323 |
+
|
324 |
+
class TinyllmSdpaAttention(TinyllmAttention):
|
325 |
+
""" 使用 torch.nn.functional.scaled_dot_product_attention 实现的注意力模块。
|
326 |
+
该模块继承自 `TinyllmAttention`,因为模块的权重保持不变。唯一的变化在于前向传播过程中适应 SDPA API。
|
327 |
+
Scaled Dot Product Attention (SDPA)
|
328 |
+
"""
|
329 |
+
|
330 |
+
def forward(
|
331 |
+
self,
|
332 |
+
hidden_states: torch.Tensor,
|
333 |
+
attention_mask: Optional[torch.Tensor] = None,
|
334 |
+
position_ids: Optional[torch.LongTensor] = None,
|
335 |
+
past_key_value: Optional[Cache] = None,
|
336 |
+
output_attentions: bool = False,
|
337 |
+
use_cache: bool = False,
|
338 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
339 |
+
# 当设置output_attentions=True时,由于torch.nn.functional.scaled_dot_product_attention不支持直接返回注意力权重
|
340 |
+
# 因此暂时降级回用父类的手动实现方式,并发出警告提示用户未来版本的更改要求
|
341 |
+
if output_attentions:
|
342 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
343 |
+
logger.warning_once(
|
344 |
+
"Model is using SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
345 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
346 |
+
)
|
347 |
+
return super().forward(
|
348 |
+
hidden_states=hidden_states,
|
349 |
+
attention_mask=attention_mask,
|
350 |
+
position_ids=position_ids,
|
351 |
+
past_key_value=past_key_value,
|
352 |
+
output_attentions=output_attentions,
|
353 |
+
use_cache=use_cache,
|
354 |
+
)
|
355 |
+
# 获取输入维度信息
|
356 |
+
bsz, q_len, _ = hidden_states.size()
|
357 |
+
|
358 |
+
# 对输入进行线性映射得到query、key、value向量
|
359 |
+
query_states = self.q_proj(hidden_states)
|
360 |
+
key_states = self.k_proj(hidden_states)
|
361 |
+
value_states = self.v_proj(hidden_states)
|
362 |
+
|
363 |
+
# 将映射后的向量调整为多头注意力所需格式
|
364 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
365 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
366 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
367 |
+
|
368 |
+
# 计算有效的 kv 序列长度(考虑缓存的情况)
|
369 |
+
kv_seq_len = key_states.shape[-2]
|
370 |
+
if past_key_value is not None:
|
371 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
372 |
+
|
373 |
+
# 应用旋转位置嵌入(RoPE)
|
374 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
375 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
376 |
+
|
377 |
+
# 如果有缓存,更新key和value状态
|
378 |
+
if past_key_value is not None:
|
379 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
380 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
381 |
+
|
382 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
383 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
384 |
+
|
385 |
+
if attention_mask is not None:
|
386 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
387 |
+
raise ValueError(
|
388 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
389 |
+
)
|
390 |
+
|
391 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
392 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
393 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
394 |
+
query_states = query_states.contiguous()
|
395 |
+
key_states = key_states.contiguous()
|
396 |
+
value_states = value_states.contiguous()
|
397 |
+
|
398 |
+
# 使用scaled_dot_product_attention进行计算
|
399 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
400 |
+
query_states,
|
401 |
+
key_states,
|
402 |
+
value_states,
|
403 |
+
attn_mask=attention_mask,
|
404 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
405 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
406 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
407 |
+
)
|
408 |
+
|
409 |
+
# 还原注意力输出的形状
|
410 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
411 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
412 |
+
|
413 |
+
# 将注意力输出通过最终的线性层(o_proj层)
|
414 |
+
attn_output = self.o_proj(attn_output)
|
415 |
+
|
416 |
+
return attn_output, None, past_key_value
|
417 |
+
|
418 |
+
TINYLLM_ATTENTION_CLASSES = {
|
419 |
+
"eager": TinyllmAttention,
|
420 |
+
"sdpa": TinyllmSdpaAttention,
|
421 |
+
}
|
422 |
+
|
423 |
+
class TinyllmDecoderLayer(nn.Module):
|
424 |
+
def __init__(self, config: TinyllmConfig, layer_idx: int):
|
425 |
+
super().__init__()
|
426 |
+
self.hidden_size = config.hidden_size
|
427 |
+
|
428 |
+
self.self_attn = TINYLLM_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
429 |
+
self.mlp = TinyllmMLP(config)
|
430 |
+
self.input_layernorm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
431 |
+
self.post_attention_layernorm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
432 |
+
|
433 |
+
def forward(
|
434 |
+
self,
|
435 |
+
hidden_states: torch.Tensor,
|
436 |
+
attention_mask: Optional[torch.Tensor] = None,
|
437 |
+
position_ids: Optional[torch.LongTensor] = None,
|
438 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
439 |
+
output_attentions: Optional[bool] = False,
|
440 |
+
use_cache: Optional[bool] = False,
|
441 |
+
**kwargs,
|
442 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
443 |
+
"""
|
444 |
+
Args:
|
445 |
+
hidden_states (`torch.FloatTensor`): 输入形状 `(batch, seq_len, embed_dim)`
|
446 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask 形状`(batch, sequence_length)`,
|
447 |
+
填充使用0表示
|
448 |
+
output_attentions (`bool`, *optional*): 是否返回所有注意力层的注意力张量。
|
449 |
+
use_cache (`bool`, *optional*): 如果设置为 `True`,则返回 `past_key_values` 关键值状态,可用于加速解码
|
450 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): 缓存的之前kv状态
|
451 |
+
"""
|
452 |
+
|
453 |
+
residual = hidden_states
|
454 |
+
|
455 |
+
hidden_states = self.input_layernorm(hidden_states)
|
456 |
+
|
457 |
+
# Self Attention
|
458 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
459 |
+
hidden_states=hidden_states,
|
460 |
+
attention_mask=attention_mask,
|
461 |
+
position_ids=position_ids,
|
462 |
+
past_key_value=past_key_value,
|
463 |
+
output_attentions=output_attentions,
|
464 |
+
use_cache=use_cache,
|
465 |
+
)
|
466 |
+
hidden_states = residual + hidden_states
|
467 |
+
|
468 |
+
# Fully Connected
|
469 |
+
residual = hidden_states
|
470 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
471 |
+
hidden_states = self.mlp(hidden_states)
|
472 |
+
hidden_states = residual + hidden_states
|
473 |
+
|
474 |
+
outputs = (hidden_states,)
|
475 |
+
|
476 |
+
if output_attentions:
|
477 |
+
outputs += (self_attn_weights,)
|
478 |
+
|
479 |
+
if use_cache:
|
480 |
+
outputs += (present_key_value,)
|
481 |
+
|
482 |
+
return outputs
|
483 |
+
|
484 |
+
|
485 |
+
class TinyllmPreTrainedModel(PreTrainedModel):
|
486 |
+
config_class = TinyllmConfig
|
487 |
+
# 定义了模型内部子模块命名的基础前缀,当加载或保存模型时,这个前缀将用于识别模型主体部分。
|
488 |
+
base_model_prefix = "model"
|
489 |
+
# 表明该模型支持梯度检查点技术,这是一种内存优化策略,可减少模型训练时所需的显存
|
490 |
+
supports_gradient_checkpointing = True
|
491 |
+
# 指定了在序列化过程中不应被拆分的模块列表,即在模型保存与加载时保持这些模块作为一个整体。
|
492 |
+
_no_split_modules = ["TinyllmDecoderLayer"]
|
493 |
+
# 在跨设备数据移动时,指示哪些关键字(key)对应的数据应该跳过设备放置步骤。
|
494 |
+
_skip_keys_device_placement = "past_key_values"
|
495 |
+
# Scaled Dot Product Attention (SDPA)
|
496 |
+
_supports_sdpa = True
|
497 |
+
# 表示模型支持缓存机制,这在自回归模型(如Transformer解码器)中很常见,
|
498 |
+
# 用于存储先前计算的结果以加快后续时间步长的计算速度。
|
499 |
+
_supports_cache_class = True
|
500 |
+
|
501 |
+
def _init_weights(self, module):
|
502 |
+
std = self.config.initializer_range
|
503 |
+
if isinstance(module, nn.Linear):
|
504 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
505 |
+
if module.bias is not None:
|
506 |
+
module.bias.data.zero_()
|
507 |
+
elif isinstance(module, nn.Embedding):
|
508 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
509 |
+
if module.padding_idx is not None:
|
510 |
+
module.weight.data[module.padding_idx].zero_()
|
511 |
+
|
512 |
+
class TinyllmModel(TinyllmPreTrainedModel):
|
513 |
+
""" 根据配置文件堆叠 TinyllmDecoderLayer
|
514 |
+
Args:
|
515 |
+
config: TinyllmConfig
|
516 |
+
"""
|
517 |
+
|
518 |
+
def __init__(self, config: TinyllmConfig):
|
519 |
+
super().__init__(config)
|
520 |
+
self.padding_idx = config.pad_token_id
|
521 |
+
self.vocab_size = config.vocab_size
|
522 |
+
|
523 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
524 |
+
self.layers = nn.ModuleList(
|
525 |
+
[TinyllmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
526 |
+
)
|
527 |
+
self._attn_implementation = config._attn_implementation
|
528 |
+
self.norm = TinyllmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
529 |
+
|
530 |
+
self.gradient_checkpointing = False
|
531 |
+
# Initialize weights and apply final processing
|
532 |
+
self.post_init()
|
533 |
+
|
534 |
+
def get_input_embeddings(self):
|
535 |
+
return self.embed_tokens
|
536 |
+
|
537 |
+
def set_input_embeddings(self, value):
|
538 |
+
self.embed_tokens = value
|
539 |
+
|
540 |
+
def forward(
|
541 |
+
self,
|
542 |
+
input_ids: torch.LongTensor = None,
|
543 |
+
attention_mask: Optional[torch.Tensor] = None,
|
544 |
+
position_ids: Optional[torch.LongTensor] = None, # 每个输入序列词元在位置嵌入中的位置索引
|
545 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None, # 可用于加速序列解码预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值)
|
546 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
547 |
+
use_cache: Optional[bool] = None,
|
548 |
+
output_attentions: Optional[bool] = None,
|
549 |
+
output_hidden_states: Optional[bool] = None,
|
550 |
+
return_dict: Optional[bool] = None,
|
551 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
552 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
553 |
+
output_hidden_states = (
|
554 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
555 |
+
)
|
556 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
557 |
+
|
558 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
559 |
+
|
560 |
+
# retrieve input_ids and inputs_embeds
|
561 |
+
if input_ids is not None and inputs_embeds is not None:
|
562 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
563 |
+
elif input_ids is not None:
|
564 |
+
batch_size, seq_length = input_ids.shape
|
565 |
+
elif inputs_embeds is not None:
|
566 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
567 |
+
else:
|
568 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
569 |
+
|
570 |
+
if self.gradient_checkpointing and self.training:
|
571 |
+
if use_cache:
|
572 |
+
logger.warning_once(
|
573 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
574 |
+
)
|
575 |
+
use_cache = False
|
576 |
+
|
577 |
+
past_key_values_length = 0
|
578 |
+
|
579 |
+
if use_cache:
|
580 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
581 |
+
if use_legacy_cache:
|
582 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
583 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
584 |
+
|
585 |
+
if position_ids is None:
|
586 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
587 |
+
# 生成一个从past_key_values_length到seq_length + past_key_values_length的整数序列
|
588 |
+
position_ids = torch.arange(
|
589 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
590 |
+
)
|
591 |
+
# 将生成的序列重塑为形状为(1, seq_length)的张量,然后展平为形状为(-1, seq_length)的张量
|
592 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
593 |
+
else:
|
594 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
595 |
+
|
596 |
+
if inputs_embeds is None:
|
597 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
598 |
+
|
599 |
+
# 适应不同注意力机制对注意力掩码的不同要求而设计的
|
600 |
+
if self._attn_implementation == "sdpa" and not output_attentions:
|
601 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
602 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
603 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
604 |
+
attention_mask,
|
605 |
+
(batch_size, seq_length),
|
606 |
+
inputs_embeds,
|
607 |
+
past_key_values_length,
|
608 |
+
)
|
609 |
+
else:
|
610 |
+
# 4d mask is passed through the layers
|
611 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
612 |
+
attention_mask,
|
613 |
+
(batch_size, seq_length),
|
614 |
+
inputs_embeds,
|
615 |
+
past_key_values_length,
|
616 |
+
)
|
617 |
+
|
618 |
+
hidden_states = inputs_embeds
|
619 |
+
|
620 |
+
# decoder layers
|
621 |
+
all_hidden_states = () if output_hidden_states else None
|
622 |
+
all_self_attns = () if output_attentions else None
|
623 |
+
next_decoder_cache = None
|
624 |
+
|
625 |
+
for decoder_layer in self.layers:
|
626 |
+
# 1.隐藏状态保存
|
627 |
+
if output_hidden_states:
|
628 |
+
all_hidden_states += (hidden_states,)
|
629 |
+
# 2.梯度检查,方便在反向传播时只激活部分层,节省内存资源
|
630 |
+
# 3.解码层:
|
631 |
+
if self.gradient_checkpointing and self.training:
|
632 |
+
layer_outputs = self._gradient_checkpointing_func(
|
633 |
+
decoder_layer.__call__,
|
634 |
+
hidden_states,
|
635 |
+
attention_mask,
|
636 |
+
position_ids,
|
637 |
+
past_key_values,
|
638 |
+
output_attentions,
|
639 |
+
use_cache,
|
640 |
+
)
|
641 |
+
else:
|
642 |
+
layer_outputs = decoder_layer(
|
643 |
+
hidden_states,
|
644 |
+
attention_mask=attention_mask,
|
645 |
+
position_ids=position_ids,
|
646 |
+
past_key_value=past_key_values,
|
647 |
+
output_attentions=output_attentions,
|
648 |
+
use_cache=use_cache,
|
649 |
+
)
|
650 |
+
# 4.更新隐藏状态
|
651 |
+
hidden_states = layer_outputs[0]
|
652 |
+
# 5.更新缓存
|
653 |
+
if use_cache:
|
654 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
655 |
+
# 6.注意力输出保存
|
656 |
+
if output_attentions:
|
657 |
+
all_self_attns += (layer_outputs[1],)
|
658 |
+
|
659 |
+
hidden_states = self.norm(hidden_states)
|
660 |
+
|
661 |
+
# add hidden states from the last decoder layer
|
662 |
+
if output_hidden_states:
|
663 |
+
all_hidden_states += (hidden_states,)
|
664 |
+
|
665 |
+
next_cache = None
|
666 |
+
if use_cache:
|
667 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
668 |
+
|
669 |
+
if not return_dict:
|
670 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
671 |
+
return BaseModelOutputWithPast(
|
672 |
+
last_hidden_state=hidden_states,
|
673 |
+
past_key_values=next_cache,
|
674 |
+
hidden_states=all_hidden_states,
|
675 |
+
attentions=all_self_attns,
|
676 |
+
)
|
677 |
+
|
678 |
+
class TinyllmForCausalLM(TinyllmPreTrainedModel):
|
679 |
+
_tied_weights_keys = ["lm_head.weight"]
|
680 |
+
|
681 |
+
def __init__(self, config):
|
682 |
+
super().__init__(config)
|
683 |
+
self.model = TinyllmModel(config)
|
684 |
+
self.vocab_size = config.vocab_size
|
685 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
686 |
+
|
687 |
+
# Initialize weights and apply final processing
|
688 |
+
self.post_init()
|
689 |
+
|
690 |
+
def get_input_embeddings(self):
|
691 |
+
return self.model.embed_tokens
|
692 |
+
|
693 |
+
def set_input_embeddings(self, value):
|
694 |
+
self.model.embed_tokens = value
|
695 |
+
|
696 |
+
def get_output_embeddings(self):
|
697 |
+
return self.lm_head
|
698 |
+
|
699 |
+
def set_output_embeddings(self, new_embeddings):
|
700 |
+
self.lm_head = new_embeddings
|
701 |
+
|
702 |
+
def set_decoder(self, decoder):
|
703 |
+
self.model = decoder
|
704 |
+
|
705 |
+
def get_decoder(self):
|
706 |
+
return self.model
|
707 |
+
|
708 |
+
def forward(
|
709 |
+
self,
|
710 |
+
input_ids: torch.LongTensor = None,
|
711 |
+
attention_mask: Optional[torch.Tensor] = None,
|
712 |
+
position_ids: Optional[torch.LongTensor] = None,
|
713 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
714 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
715 |
+
labels: Optional[torch.LongTensor] = None,
|
716 |
+
use_cache: Optional[bool] = None,
|
717 |
+
output_attentions: Optional[bool] = None,
|
718 |
+
output_hidden_states: Optional[bool] = None,
|
719 |
+
return_dict: Optional[bool] = None,
|
720 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
721 |
+
|
722 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
723 |
+
output_hidden_states = (
|
724 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
725 |
+
)
|
726 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
727 |
+
|
728 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
729 |
+
outputs = self.model(
|
730 |
+
input_ids=input_ids,
|
731 |
+
attention_mask=attention_mask,
|
732 |
+
position_ids=position_ids,
|
733 |
+
past_key_values=past_key_values,
|
734 |
+
inputs_embeds=inputs_embeds,
|
735 |
+
use_cache=use_cache,
|
736 |
+
output_attentions=output_attentions,
|
737 |
+
output_hidden_states=output_hidden_states,
|
738 |
+
return_dict=return_dict,
|
739 |
+
)
|
740 |
+
|
741 |
+
hidden_states = outputs[0]
|
742 |
+
logits = self.lm_head(hidden_states)
|
743 |
+
logits = logits.float()
|
744 |
+
|
745 |
+
loss = None
|
746 |
+
if labels is not None:
|
747 |
+
# Shift so that tokens < n predict n
|
748 |
+
# 对于自回归模型(如GPT系列),我们需要将模型输出的logits向前移动一位,
|
749 |
+
# 这样使得模型预测的是当前时刻 t 的下一个词,而非当前词本身
|
750 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
751 |
+
# 同时,也需要将真实标签(labels)向前移动一位以与调整后的logits对齐
|
752 |
+
shift_labels = labels[..., 1:].contiguous()
|
753 |
+
# Flatten the tokens
|
754 |
+
loss_fct = CrossEntropyLoss(ignore_index=-100)
|
755 |
+
|
756 |
+
# 将移位后的 logits 和 labels 扁平化,即将它们展平为一维张量
|
757 |
+
# 其中shift_logits变成 (batch_size * sequence_length, vocab_size) 的形式
|
758 |
+
# shift_labels变为 (batch_size * sequence_length) 的形式
|
759 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
760 |
+
shift_labels = shift_labels.view(-1)
|
761 |
+
|
762 |
+
# Enable model parallelism
|
763 |
+
# 确保模型并行计算时,labels的数据存储位置与logits一致
|
764 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
765 |
+
loss = loss_fct(shift_logits, shift_labels)
|
766 |
+
|
767 |
+
if not return_dict:
|
768 |
+
output = (logits,) + outputs[1:]
|
769 |
+
return (loss,) + output if loss is not None else output
|
770 |
+
|
771 |
+
return CausalLMOutputWithPast(
|
772 |
+
loss=loss,
|
773 |
+
logits=logits,
|
774 |
+
past_key_values=outputs.past_key_values,
|
775 |
+
hidden_states=outputs.hidden_states,
|
776 |
+
attentions=outputs.attentions,
|
777 |
+
)
|
778 |
+
|
779 |
+
def prepare_inputs_for_generation(
|
780 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
781 |
+
):
|
782 |
+
""" 准备模型的输入参数
|
783 |
+
包括处理input_ids、past_key_values(历史隐藏状态缓存)、attention_mask以及可选的inputs_embeds。
|
784 |
+
"""
|
785 |
+
# Omit tokens covered by past_key_values
|
786 |
+
if past_key_values is not None:
|
787 |
+
if isinstance(past_key_values, Cache):
|
788 |
+
cache_length = past_key_values.get_seq_length()
|
789 |
+
past_length = past_key_values.seen_tokens
|
790 |
+
max_cache_length = past_key_values.get_max_length()
|
791 |
+
else:
|
792 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
793 |
+
max_cache_length = None
|
794 |
+
|
795 |
+
# 根据缓存情况裁剪input_ids,只保留未处理的token:
|
796 |
+
# # 1. 如果 attention_mask 比 input_ids 更长,说明部分输入已通过缓存传递(如仅传入inputs_embeds)
|
797 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
798 |
+
# 取最后未处理的部分
|
799 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
800 |
+
# 2. 若已处理的 token 数小于input_ids中的总数,表明input_ids包含全部输入,从中去掉已处理的部分
|
801 |
+
elif past_length < input_ids.shape[1]:
|
802 |
+
input_ids = input_ids[:, past_length:]
|
803 |
+
# 3. 否则,认为input_ids中只有待处理的新token
|
804 |
+
|
805 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
806 |
+
if (
|
807 |
+
max_cache_length is not None
|
808 |
+
and attention_mask is not None
|
809 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
810 |
+
):
|
811 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
812 |
+
|
813 |
+
# 初始化或处理position_ids
|
814 |
+
position_ids = kwargs.get("position_ids", None)
|
815 |
+
# 如果attention_mask存在但position_ids不存在,则基于attention_mask动态创建position_ids
|
816 |
+
if attention_mask is not None and position_ids is None:
|
817 |
+
# create position_ids on the fly for batch generation
|
818 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
819 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
820 |
+
if past_key_values:
|
821 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
822 |
+
|
823 |
+
# 根据inputs_embeds和past_key_values的存在与否来决定模型输入
|
824 |
+
# 如果提供了inputs_embeds且没有past_key_values(首次生成步骤),则直接使用inputs_embeds作为模型输入
|
825 |
+
if inputs_embeds is not None and past_key_values is None:
|
826 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
827 |
+
else:
|
828 |
+
model_inputs = {"input_ids": input_ids}
|
829 |
+
|
830 |
+
model_inputs.update(
|
831 |
+
{
|
832 |
+
"position_ids": position_ids,
|
833 |
+
"past_key_values": past_key_values,
|
834 |
+
"use_cache": kwargs.get("use_cache"),
|
835 |
+
"attention_mask": attention_mask,
|
836 |
+
}
|
837 |
+
)
|
838 |
+
return model_inputs
|
839 |
+
|
840 |
+
@staticmethod
|
841 |
+
def _reorder_cache(past_key_values, beam_idx):
|
842 |
+
""" 用于重新排序缓存中的历史隐藏状态,以适应束搜索(beam search)算法
|
843 |
+
"""
|
844 |
+
reordered_past = ()
|
845 |
+
# 遍历每一层的隐藏状态
|
846 |
+
for layer_past in past_key_values:
|
847 |
+
# 对于每一层的每个隐藏状态向量,执行索引选择操作
|
848 |
+
reordered_past += (
|
849 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
850 |
+
)
|
851 |
+
return reordered_past
|
852 |
+
|
853 |
+
def generate(
|
854 |
+
self,
|
855 |
+
inputs: Optional[torch.Tensor] = None,
|
856 |
+
generation_config: Optional[GenerationConfig] = None,
|
857 |
+
streamer = None,
|
858 |
+
**kwargs,
|
859 |
+
):
|
860 |
+
if generation_config is None:
|
861 |
+
response = super().generate(
|
862 |
+
inputs,
|
863 |
+
generation_config=generation_config,
|
864 |
+
streamer=streamer,
|
865 |
+
**kwargs,
|
866 |
+
)
|
867 |
+
|
868 |
+
return response
|
869 |
+
|
870 |
+
repetition_penalty = kwargs.pop("repetition_penalty", generation_config.repetition_penalty)
|
871 |
+
generation_config.repetition_penalty = 1.0
|
872 |
+
|
873 |
+
logits_processor = None
|
874 |
+
if repetition_penalty > 1.0:
|
875 |
+
# warnings.warn("We highly recommend using OpenAI's frequency and presence penalty instead of the original repetition penalty. The original repetition penalty penalizes prompt tokens, which may lead to various potential issues. Therefore, your repetition penalty coefficient will be transformed into frequency penalty and presence penalty.", UserWarning)
|
876 |
+
presence_penalty = repetition_penalty - 1.0
|
877 |
+
frequency_penalty = repetition_penalty - 1.0
|
878 |
+
logits_processor = LogitsProcessorList(
|
879 |
+
[OutputRepetitionPenaltyLogitsProcessor(inputs.size(1), presence_penalty, frequency_penalty, 1.0)]
|
880 |
+
)
|
881 |
+
|
882 |
+
response = super().generate(
|
883 |
+
inputs,
|
884 |
+
generation_config=generation_config,
|
885 |
+
logits_processor=logits_processor,
|
886 |
+
streamer=streamer,
|
887 |
+
**kwargs,
|
888 |
+
)
|
889 |
+
generation_config.repetition_penalty = repetition_penalty
|
890 |
+
return response
|
891 |
+
|
892 |
+
def chat(
|
893 |
+
self,
|
894 |
+
tokenizer,
|
895 |
+
messages: List[dict],
|
896 |
+
system: str = "你是由wdndev开发的个人助手。",
|
897 |
+
stream=False,
|
898 |
+
use_pot=False,
|
899 |
+
generation_config: Optional[GenerationConfig]=None
|
900 |
+
):
|
901 |
+
|
902 |
+
generation_config = generation_config or self.generation_config
|
903 |
+
input_ids = make_context(
|
904 |
+
model=self, tokenizer=tokenizer, messages=messages,
|
905 |
+
system=system, max_new_tokens=generation_config.max_new_tokens
|
906 |
+
)
|
907 |
+
|
908 |
+
# for inputs in input_ids:
|
909 |
+
# print("decode: ", tokenizer.decode(inputs))
|
910 |
+
|
911 |
+
if stream:
|
912 |
+
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, use_pot=use_pot)
|
913 |
+
Thread(target=self.generate,
|
914 |
+
kwargs=dict(
|
915 |
+
inputs=input_ids,
|
916 |
+
streamer=streamer,
|
917 |
+
generation_config=generation_config,
|
918 |
+
)).start()
|
919 |
+
return streamer
|
920 |
+
else:
|
921 |
+
generated_ids = self.generate(input_ids, generation_config=generation_config)
|
922 |
+
# response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
|
923 |
+
generated_ids = [
|
924 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(input_ids, generated_ids)
|
925 |
+
]
|
926 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
927 |
+
if use_pot:
|
928 |
+
response = parse_pot_no_stream(response)
|
929 |
+
return response
|
930 |
+
|
931 |
+
class TinyllmForSequenceClassification(TinyllmPreTrainedModel):
|
932 |
+
def __init__(self, config):
|
933 |
+
super().__init__(config)
|
934 |
+
self.num_labels = config.num_labels
|
935 |
+
self.model = TinyllmModel(config)
|
936 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
937 |
+
|
938 |
+
# Initialize weights and apply final processing
|
939 |
+
self.post_init()
|
940 |
+
|
941 |
+
def get_input_embeddings(self):
|
942 |
+
return self.model.embed_tokens
|
943 |
+
|
944 |
+
def set_input_embeddings(self, value):
|
945 |
+
self.model.embed_tokens = value
|
946 |
+
|
947 |
+
def forward(
|
948 |
+
self,
|
949 |
+
input_ids: torch.LongTensor = None,
|
950 |
+
attention_mask: Optional[torch.Tensor] = None,
|
951 |
+
position_ids: Optional[torch.LongTensor] = None,
|
952 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
953 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
954 |
+
labels: Optional[torch.LongTensor] = None,
|
955 |
+
use_cache: Optional[bool] = None,
|
956 |
+
output_attentions: Optional[bool] = None,
|
957 |
+
output_hidden_states: Optional[bool] = None,
|
958 |
+
return_dict: Optional[bool] = None,
|
959 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
960 |
+
|
961 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
962 |
+
|
963 |
+
transformer_outputs = self.model(
|
964 |
+
input_ids,
|
965 |
+
attention_mask=attention_mask,
|
966 |
+
position_ids=position_ids,
|
967 |
+
past_key_values=past_key_values,
|
968 |
+
inputs_embeds=inputs_embeds,
|
969 |
+
use_cache=use_cache,
|
970 |
+
output_attentions=output_attentions,
|
971 |
+
output_hidden_states=output_hidden_states,
|
972 |
+
return_dict=return_dict,
|
973 |
+
)
|
974 |
+
hidden_states = transformer_outputs[0]
|
975 |
+
logits = self.score(hidden_states)
|
976 |
+
|
977 |
+
if input_ids is not None:
|
978 |
+
batch_size = input_ids.shape[0]
|
979 |
+
else:
|
980 |
+
batch_size = inputs_embeds.shape[0]
|
981 |
+
|
982 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
983 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
984 |
+
# 确定输入序列的有效长度,即从起始到第一个填充符出现之前的所有非填充字符的数量
|
985 |
+
if self.config.pad_token_id is None:
|
986 |
+
# 无法计算有效长度
|
987 |
+
sequence_lengths = -1
|
988 |
+
else:
|
989 |
+
if input_ids is not None:
|
990 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
991 |
+
# 对于给定的输入IDs(input_ids),查找其中等于填充符ID的位置
|
992 |
+
# argmax(-1)作用在最后一个维度上,找到每个序列中填充符首次出现的最大索引位置
|
993 |
+
# 因为索引是从0开始的,减去1可得���每个序列的有效字符数(不含填充符)
|
994 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
995 |
+
# 为了保证与ONNX兼容以及防止越界,当序列尾部被完全填充时,采用模运算来保持有效长度
|
996 |
+
# 即使索引超过了输入序列的实际长度,也会自动对应回到有效的范围之内
|
997 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
998 |
+
# 确保计算出的序列长度在与logits相同的设备上,便于后续操作
|
999 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1000 |
+
else:
|
1001 |
+
sequence_lengths = -1
|
1002 |
+
|
1003 |
+
# 提取实际标签对应的logits
|
1004 |
+
# 使用arange函数生成一个从0到batch_size-1的索引,并与sequence_lengths结合,
|
1005 |
+
# 选取每个样本的有效logit
|
1006 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1007 |
+
|
1008 |
+
loss = None
|
1009 |
+
if labels is not None:
|
1010 |
+
labels = labels.to(logits.device)
|
1011 |
+
# 若模型配置没有明确指定 problem_type ,则根据num_labels和labels的数据类型推断 problem_type
|
1012 |
+
if self.config.problem_type is None:
|
1013 |
+
if self.num_labels == 1:
|
1014 |
+
self.config.problem_type = "regression"
|
1015 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1016 |
+
self.config.problem_type = "single_label_classification"
|
1017 |
+
else:
|
1018 |
+
self.config.problem_type = "multi_label_classification"
|
1019 |
+
|
1020 |
+
if self.config.problem_type == "regression":
|
1021 |
+
# 使用均方误差损失函数
|
1022 |
+
loss_fct = MSELoss()
|
1023 |
+
# 如果num_labels为1,则直接计算单输出的损失;否则,按列计算所有输出的损失
|
1024 |
+
if self.num_labels == 1:
|
1025 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1026 |
+
else:
|
1027 |
+
loss = loss_fct(pooled_logits, labels)
|
1028 |
+
elif self.config.problem_type == "single_label_classification":
|
1029 |
+
# 单标签分类任务,使用交叉熵损失函数
|
1030 |
+
loss_fct = CrossEntropyLoss()
|
1031 |
+
# 将pooled_logits展平为(batch_size * num_labels)的形式,与同样展平后的labels进行比较
|
1032 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1033 |
+
elif self.config.problem_type == "multi_label_classification":
|
1034 |
+
# 多标签分类任务,使用带Sigmoid激活的二元交叉熵损失函数
|
1035 |
+
loss_fct = BCEWithLogitsLoss()
|
1036 |
+
# 直接计算sigmoid之前的logits与标签之间的损失
|
1037 |
+
loss = loss_fct(pooled_logits, labels)
|
1038 |
+
|
1039 |
+
if not return_dict:
|
1040 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1041 |
+
return ((loss,) + output) if loss is not None else output
|
1042 |
+
|
1043 |
+
return SequenceClassifierOutputWithPast(
|
1044 |
+
loss=loss,
|
1045 |
+
logits=pooled_logits,
|
1046 |
+
past_key_values=transformer_outputs.past_key_values,
|
1047 |
+
hidden_states=transformer_outputs.hidden_states,
|
1048 |
+
attentions=transformer_outputs.attentions,
|
1049 |
+
)
|
1050 |
+
|
1051 |
+
def print_model_parameters(model):
|
1052 |
+
""" 打印模型各个层参数
|
1053 |
+
"""
|
1054 |
+
param_sum = 0
|
1055 |
+
for name, param in model.named_parameters():
|
1056 |
+
if param.requires_grad:
|
1057 |
+
param_sum += param.numel()
|
1058 |
+
print(f"Layer: {name}, Parameters: {param.numel()}")
|
1059 |
+
print(f"Total of parameters: {param_sum}")
|
1060 |
+
|
1061 |
+
if __name__ == "__main__":
|
1062 |
+
# vocav size https://github.com/THUDM/ChatGLM3/issues/634
|
1063 |
+
args_1480m = TinyllmConfig(
|
1064 |
+
hidden_size=2048,
|
1065 |
+
num_hidden_layers=24,
|
1066 |
+
num_attention_heads=16,
|
1067 |
+
intermediate_size=5504,
|
1068 |
+
rope_theta=10000.0,
|
1069 |
+
max_position_embeddings=1024,
|
1070 |
+
vocab_size=64798,
|
1071 |
+
)
|
1072 |
+
|
1073 |
+
args_440m = TinyllmConfig(
|
1074 |
+
hidden_size=1024,
|
1075 |
+
num_hidden_layers=24,
|
1076 |
+
num_attention_heads=16,
|
1077 |
+
intermediate_size=2816,
|
1078 |
+
rope_theta=10000.0,
|
1079 |
+
max_position_embeddings=1024,
|
1080 |
+
vocab_size=64798,
|
1081 |
+
)
|
1082 |
+
|
1083 |
+
args_210m = TinyllmConfig(
|
1084 |
+
hidden_size=768,
|
1085 |
+
num_hidden_layers=16,
|
1086 |
+
num_attention_heads=12,
|
1087 |
+
intermediate_size=2048,
|
1088 |
+
rope_theta=10000.0,
|
1089 |
+
max_position_embeddings=1024,
|
1090 |
+
vocab_size=64798,
|
1091 |
+
)
|
1092 |
+
|
1093 |
+
args_92m = TinyllmConfig(
|
1094 |
+
hidden_size=512,
|
1095 |
+
num_hidden_layers=8,
|
1096 |
+
num_attention_heads=8,
|
1097 |
+
intermediate_size=1408,
|
1098 |
+
rope_theta=10000.0,
|
1099 |
+
max_position_embeddings=1024,
|
1100 |
+
vocab_size=64798,
|
1101 |
+
)
|
1102 |
+
|
1103 |
+
args_42m = TinyllmConfig(
|
1104 |
+
hidden_size=288,
|
1105 |
+
num_hidden_layers=6,
|
1106 |
+
num_attention_heads=6,
|
1107 |
+
intermediate_size=768,
|
1108 |
+
rope_theta=10000.0,
|
1109 |
+
max_position_embeddings=512,
|
1110 |
+
vocab_size=64798,
|
1111 |
+
)
|
1112 |
+
|
1113 |
+
args_16m = TinyllmConfig(
|
1114 |
+
hidden_size=120,
|
1115 |
+
num_hidden_layers=6,
|
1116 |
+
num_attention_heads=6,
|
1117 |
+
intermediate_size=384,
|
1118 |
+
rope_theta=10000.0,
|
1119 |
+
max_position_embeddings=512,
|
1120 |
+
vocab_size=64798,
|
1121 |
+
)
|
1122 |
+
|
1123 |
+
model = TinyllmForCausalLM(args_210m)
|
1124 |
+
|
1125 |
+
inputs_ids = torch.tensor([[1,2,4],[4,3,2]])
|
1126 |
+
labels = torch.tensor([[1,4,3],[2,3,1]])
|
1127 |
+
print(inputs_ids.shape)
|
1128 |
+
outputs = model(input_ids=inputs_ids, labels=labels)
|
1129 |
+
print(outputs.logits)
|
1130 |
+
print(outputs.loss)
|
1131 |
+
|
1132 |
+
# print_model_parameters(model)
|
1133 |
+
|
special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"unk_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c742a58f0ae0274a560714397530b3dafbdadf5c5f0e901ba1ce14dd27c99d3e
|
3 |
+
size 757958
|
tokenizer_config.json
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": true,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "<unk>",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": false,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": true
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<s>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"2": {
|
23 |
+
"content": "</s>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": true
|
29 |
+
},
|
30 |
+
"49953": {
|
31 |
+
"content": "<|system|>",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": true,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false,
|
36 |
+
"special": false
|
37 |
+
},
|
38 |
+
"49954": {
|
39 |
+
"content": "<|user|>",
|
40 |
+
"lstrip": false,
|
41 |
+
"normalized": true,
|
42 |
+
"rstrip": false,
|
43 |
+
"single_word": false,
|
44 |
+
"special": false
|
45 |
+
},
|
46 |
+
"49955": {
|
47 |
+
"content": "<|assistant|>",
|
48 |
+
"lstrip": false,
|
49 |
+
"normalized": true,
|
50 |
+
"rstrip": false,
|
51 |
+
"single_word": false,
|
52 |
+
"special": false
|
53 |
+
},
|
54 |
+
"49956": {
|
55 |
+
"content": "<|im_start|>",
|
56 |
+
"lstrip": false,
|
57 |
+
"normalized": true,
|
58 |
+
"rstrip": false,
|
59 |
+
"single_word": false,
|
60 |
+
"special": false
|
61 |
+
},
|
62 |
+
"49957": {
|
63 |
+
"content": "<|im_end|>",
|
64 |
+
"lstrip": false,
|
65 |
+
"normalized": true,
|
66 |
+
"rstrip": false,
|
67 |
+
"single_word": false,
|
68 |
+
"special": false
|
69 |
+
}
|
70 |
+
},
|
71 |
+
"bos_token": "<s>",
|
72 |
+
"clean_up_tokenization_spaces": false,
|
73 |
+
"eos_token": "</s>",
|
74 |
+
"legacy": true,
|
75 |
+
"model_max_length": 1000000000000000019884624838656,
|
76 |
+
"pad_token": null,
|
77 |
+
"sp_model_kwargs": {},
|
78 |
+
"spaces_between_special_tokens": false,
|
79 |
+
"tokenizer_class": "LlamaTokenizer",
|
80 |
+
"unk_token": "<unk>",
|
81 |
+
"use_default_system_prompt": false
|
82 |
+
}
|