xumingyu16
commited on
Upload 12 files
Browse files- __init__.py +8 -0
- added_tokens.json +3 -0
- config.json +29 -0
- configuration_baichuan.py +69 -0
- generation_config.json +14 -0
- generation_utils.py +83 -0
- modeling_baichuan.py +702 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +30 -0
- tokenization_baichuan.py +251 -0
- tokenizer.model +3 -0
- tokenizer_config.json +36 -0
__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
@Time : 2023/12/15 22:11
|
4 |
+
@FileName: __init__.py.py
|
5 |
+
@author: 王炳宁
|
6 |
+
@contact: [email protected]
|
7 |
+
"""
|
8 |
+
|
added_tokens.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<pad>": 48000
|
3 |
+
}
|
config.json
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"BaichuanForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_baichuan.BaiChuanConfig",
|
7 |
+
"AutoModelForCausalLM": "modeling_baichuan.BaiChuanForCausalLM"
|
8 |
+
},
|
9 |
+
"bos_token_id": 1,
|
10 |
+
"eos_token_id": 2,
|
11 |
+
"hidden_act": "silu",
|
12 |
+
"hidden_size": 2560,
|
13 |
+
"initializer_range": 0.02,
|
14 |
+
"intermediate_size": 8704,
|
15 |
+
"num_kv_heads": 4,
|
16 |
+
"max_position_embeddings": 5000,
|
17 |
+
"model_max_length": 5000,
|
18 |
+
"model_type": "baichuan",
|
19 |
+
"num_attention_heads": 20,
|
20 |
+
"num_hidden_layers": 32,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"rms_norm_eps": 1e-06,
|
23 |
+
"_from_model_config": true,
|
24 |
+
"tie_word_embeddings": false,
|
25 |
+
"torch_dtype": "bfloat16",
|
26 |
+
"transformers_version": "4.29.2",
|
27 |
+
"use_cache": true,
|
28 |
+
"vocab_size": 48000
|
29 |
+
}
|
configuration_baichuan.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
|
20 |
+
from transformers.configuration_utils import PretrainedConfig
|
21 |
+
from transformers.utils import logging
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
class BaiChuanConfig(PretrainedConfig):
|
27 |
+
model_type = "baichuan"
|
28 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
vocab_size=64000,
|
33 |
+
hidden_size=4096,
|
34 |
+
intermediate_size=11008,
|
35 |
+
num_hidden_layers=32,
|
36 |
+
num_attention_heads=32,
|
37 |
+
hidden_act="silu",
|
38 |
+
max_position_embeddings=4096,
|
39 |
+
num_kv_heads=8,
|
40 |
+
mha_layers=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 45,
|
41 |
+
46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
|
42 |
+
initializer_range=0.02,
|
43 |
+
rms_norm_eps=1e-6,
|
44 |
+
use_cache=True,
|
45 |
+
pad_token_id=0,
|
46 |
+
bos_token_id=1,
|
47 |
+
eos_token_id=2,
|
48 |
+
tie_word_embeddings=False,
|
49 |
+
**kwargs,
|
50 |
+
):
|
51 |
+
self.mha_layers = mha_layers
|
52 |
+
self.num_kv_heads = num_kv_heads
|
53 |
+
self.vocab_size = vocab_size
|
54 |
+
self.max_position_embeddings = max_position_embeddings
|
55 |
+
self.hidden_size = hidden_size
|
56 |
+
self.intermediate_size = intermediate_size
|
57 |
+
self.num_hidden_layers = num_hidden_layers
|
58 |
+
self.num_attention_heads = num_attention_heads
|
59 |
+
self.hidden_act = hidden_act
|
60 |
+
self.initializer_range = initializer_range
|
61 |
+
self.rms_norm_eps = rms_norm_eps
|
62 |
+
self.use_cache = use_cache
|
63 |
+
super().__init__(
|
64 |
+
pad_token_id=pad_token_id,
|
65 |
+
bos_token_id=bos_token_id,
|
66 |
+
eos_token_id=eos_token_id,
|
67 |
+
tie_word_embeddings=tie_word_embeddings,
|
68 |
+
**kwargs,
|
69 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"pad_token_id": 0,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"user_token_id": 195,
|
6 |
+
"assistant_token_id": 196,
|
7 |
+
"max_new_tokens": 2048,
|
8 |
+
"temperature": 0.3,
|
9 |
+
"top_k": 5,
|
10 |
+
"top_p": 0.85,
|
11 |
+
"repetition_penalty": 1.05,
|
12 |
+
"do_sample": false,
|
13 |
+
"transformers_version": "4.29.2"
|
14 |
+
}
|
generation_utils.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
from queue import Queue
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
|
7 |
+
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
8 |
+
def _parse_messages(messages, split_role="user"):
|
9 |
+
system, rounds = "", []
|
10 |
+
round = []
|
11 |
+
for i, message in enumerate(messages):
|
12 |
+
if message["role"] == "system":
|
13 |
+
assert i == 0
|
14 |
+
system = message["content"]
|
15 |
+
continue
|
16 |
+
if message["role"] == split_role and round:
|
17 |
+
rounds.append(round)
|
18 |
+
round = []
|
19 |
+
round.append(message)
|
20 |
+
if round:
|
21 |
+
rounds.append(round)
|
22 |
+
return system, rounds
|
23 |
+
|
24 |
+
max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
25 |
+
max_input_tokens = model.config.model_max_length - max_new_tokens
|
26 |
+
system, rounds = _parse_messages(messages, split_role="user")
|
27 |
+
system_tokens = tokenizer.encode(system)
|
28 |
+
max_history_tokens = max_input_tokens - len(system_tokens)
|
29 |
+
|
30 |
+
history_tokens = []
|
31 |
+
for round in rounds[::-1]:
|
32 |
+
round_tokens = []
|
33 |
+
for message in round:
|
34 |
+
if message["role"] == "user":
|
35 |
+
round_tokens.append(model.generation_config.user_token_id)
|
36 |
+
else:
|
37 |
+
round_tokens.append(model.generation_config.assistant_token_id)
|
38 |
+
round_tokens.extend(tokenizer.encode(message["content"]))
|
39 |
+
if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
|
40 |
+
history_tokens = round_tokens + history_tokens # concat left
|
41 |
+
if len(history_tokens) < max_history_tokens:
|
42 |
+
continue
|
43 |
+
break
|
44 |
+
|
45 |
+
input_tokens = system_tokens + history_tokens
|
46 |
+
if messages[-1]["role"] != "assistant":
|
47 |
+
input_tokens.append(model.generation_config.assistant_token_id)
|
48 |
+
input_tokens = input_tokens[-max_input_tokens:] # truncate left
|
49 |
+
return torch.LongTensor([input_tokens]).to(model.device)
|
50 |
+
|
51 |
+
|
52 |
+
class TextIterStreamer:
|
53 |
+
def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
|
54 |
+
self.tokenizer = tokenizer
|
55 |
+
self.skip_prompt = skip_prompt
|
56 |
+
self.skip_special_tokens = skip_special_tokens
|
57 |
+
self.tokens = []
|
58 |
+
self.text_queue = Queue()
|
59 |
+
self.next_tokens_are_prompt = True
|
60 |
+
|
61 |
+
def put(self, value):
|
62 |
+
if self.skip_prompt and self.next_tokens_are_prompt:
|
63 |
+
self.next_tokens_are_prompt = False
|
64 |
+
else:
|
65 |
+
if len(value.shape) > 1:
|
66 |
+
value = value[0]
|
67 |
+
self.tokens.extend(value.tolist())
|
68 |
+
self.text_queue.put(
|
69 |
+
self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
|
70 |
+
|
71 |
+
def end(self):
|
72 |
+
self.text_queue.put(None)
|
73 |
+
|
74 |
+
def __iter__(self):
|
75 |
+
return self
|
76 |
+
|
77 |
+
def __next__(self):
|
78 |
+
value = self.text_queue.get()
|
79 |
+
if value is None:
|
80 |
+
raise StopIteration()
|
81 |
+
else:
|
82 |
+
return value
|
83 |
+
|
modeling_baichuan.py
ADDED
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
2 |
+
#
|
3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
4 |
+
# and OPT implementations in this library. It has been modified from its
|
5 |
+
# original forms to accommodate minor architectural differences compared
|
6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
|
20 |
+
import math
|
21 |
+
from typing import List, Optional, Tuple, Union
|
22 |
+
|
23 |
+
import torch
|
24 |
+
from torch import nn
|
25 |
+
import torch.nn.functional as F
|
26 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
27 |
+
import torch.utils.checkpoint
|
28 |
+
from transformers import PreTrainedModel, add_start_docstrings
|
29 |
+
from transformers.activations import ACT2FN
|
30 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
31 |
+
from transformers.modeling_outputs import SequenceClassifierOutputWithPast
|
32 |
+
from transformers.utils import logging, add_start_docstrings_to_model_forward, replace_return_docstrings
|
33 |
+
from transformers.configuration_utils import PretrainedConfig
|
34 |
+
from einops import rearrange, repeat
|
35 |
+
from .configuration_baichuan import BaiChuanConfig
|
36 |
+
|
37 |
+
logger = logging.get_logger(__name__)
|
38 |
+
HAS_FLASH_ATTN = False
|
39 |
+
try:
|
40 |
+
from flash_attn import flash_attn_varlen_func, flash_attn_with_kvcache, flash_attn_func
|
41 |
+
from flash_attn.layers.rotary import apply_rotary_emb_func
|
42 |
+
|
43 |
+
HAS_FLASH_ATTN = True
|
44 |
+
except ImportError:
|
45 |
+
logger.warning(
|
46 |
+
"flash-attention is not installed correctly. "
|
47 |
+
)
|
48 |
+
|
49 |
+
|
50 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
51 |
+
def _make_causal_mask(
|
52 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
53 |
+
):
|
54 |
+
"""
|
55 |
+
Make causal mask used for bi-directional self-attention.
|
56 |
+
"""
|
57 |
+
bsz, tgt_len = input_ids_shape
|
58 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
59 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
60 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
61 |
+
mask = mask.to(dtype)
|
62 |
+
|
63 |
+
if past_key_values_length > 0:
|
64 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
65 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
66 |
+
|
67 |
+
|
68 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
69 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
70 |
+
"""
|
71 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
72 |
+
"""
|
73 |
+
bsz, src_len = mask.size()
|
74 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
75 |
+
|
76 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
77 |
+
|
78 |
+
inverted_mask = 1.0 - expanded_mask
|
79 |
+
|
80 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
81 |
+
|
82 |
+
|
83 |
+
class RMSNorm(nn.Module):
|
84 |
+
def __init__(self, hidden_size, eps=1e-6):
|
85 |
+
"""
|
86 |
+
RMSNorm is equivalent to T5LayerNorm
|
87 |
+
"""
|
88 |
+
super().__init__()
|
89 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
90 |
+
self.variance_epsilon = eps
|
91 |
+
|
92 |
+
def forward(self, hidden_states):
|
93 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
94 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
95 |
+
|
96 |
+
# convert into half-precision if necessary
|
97 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
98 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
99 |
+
|
100 |
+
return self.weight * hidden_states
|
101 |
+
|
102 |
+
|
103 |
+
class RotaryEmbedding(torch.nn.Module):
|
104 |
+
def __init__(self, dim, max_position_embeddings=2048, base=1e6, device=None, interleaved=False):
|
105 |
+
super().__init__()
|
106 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
107 |
+
self.base = base
|
108 |
+
self.dim = dim
|
109 |
+
# Build here to make `torch.jit.trace` work.
|
110 |
+
self.max_seq_len_cached = 0
|
111 |
+
self.interleaved = interleaved
|
112 |
+
|
113 |
+
def forward(self, q, k, seqlen_offset=None):
|
114 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
115 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
116 |
+
|
117 |
+
seq_len = q.shape[1] + seqlen_offset
|
118 |
+
if seq_len > self.max_seq_len_cached:
|
119 |
+
self.max_seq_len_cached = seq_len
|
120 |
+
self.inv_freq = 1.0 / (
|
121 |
+
self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim))
|
122 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
123 |
+
# freqs = torch.einsum("i,j->ij", t, self.inv_freq) # dont use this, bug in fp16
|
124 |
+
freqs = torch.outer(t, self.inv_freq)
|
125 |
+
self.cos_cached = freqs.cos().to(q.device)
|
126 |
+
self.sin_cached = freqs.sin().to(k.device)
|
127 |
+
|
128 |
+
return apply_rotary_emb_func(
|
129 |
+
q.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
|
130 |
+
self.interleaved, True # inplace=True
|
131 |
+
).to(q.dtype), apply_rotary_emb_func(
|
132 |
+
k.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
|
133 |
+
self.interleaved, True # inplace=True
|
134 |
+
).to(k.dtype)
|
135 |
+
|
136 |
+
|
137 |
+
class MLP(nn.Module):
|
138 |
+
def __init__(
|
139 |
+
self,
|
140 |
+
hidden_size: int,
|
141 |
+
intermediate_size: int,
|
142 |
+
hidden_act: str,
|
143 |
+
):
|
144 |
+
super().__init__()
|
145 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
146 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
147 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
148 |
+
self.act_fn = ACT2FN[hidden_act]
|
149 |
+
|
150 |
+
def forward(self, x):
|
151 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
152 |
+
|
153 |
+
|
154 |
+
class Attention(nn.Module):
|
155 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
156 |
+
|
157 |
+
def __init__(self, config: BaiChuanConfig, num_heads):
|
158 |
+
super().__init__()
|
159 |
+
self.config = config
|
160 |
+
# print(num_heads)
|
161 |
+
self.num_heads = config.num_attention_heads
|
162 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
163 |
+
self.hidden_size = config.hidden_size
|
164 |
+
self.max_position_embeddings = config.max_position_embeddings
|
165 |
+
self.num_kv_heads = config.num_kv_heads
|
166 |
+
self.W_pack = nn.Linear(config.hidden_size, self.hidden_size + 2 * self.num_kv_heads * self.head_dim,
|
167 |
+
bias=False)
|
168 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
169 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
170 |
+
self.cos, self.sin = None, None
|
171 |
+
|
172 |
+
def forward(
|
173 |
+
self,
|
174 |
+
hidden_states: torch.Tensor,
|
175 |
+
attention_mask: Optional[torch.Tensor] = None,
|
176 |
+
position_ids: Optional[torch.LongTensor] = None,
|
177 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
178 |
+
output_attentions: bool = False,
|
179 |
+
use_cache: bool = False,
|
180 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
181 |
+
|
182 |
+
bsz, seqlen_q, _ = hidden_states.size()
|
183 |
+
past_len = 0
|
184 |
+
attn_weights = None
|
185 |
+
|
186 |
+
if past_key_value is not None:
|
187 |
+
cache_k, cache_v, past_len = past_key_value
|
188 |
+
new_len = past_len + hidden_states.size(1)
|
189 |
+
if new_len > cache_k.size(1):
|
190 |
+
cache_k = torch.cat([cache_k,
|
191 |
+
torch.empty(bsz, 256, cache_k.size(2), cache_k.size(3), dtype=cache_k.dtype,
|
192 |
+
device=cache_k.device)], 1)
|
193 |
+
cache_v = torch.cat([cache_v,
|
194 |
+
torch.empty(bsz, 256, cache_v.size(2), cache_v.size(3), dtype=cache_v.dtype,
|
195 |
+
device=cache_v.device)], 1)
|
196 |
+
|
197 |
+
proj = self.W_pack(hidden_states)
|
198 |
+
|
199 |
+
proj = rearrange(proj, 'bs seq_len (n_head head_dim) -> n_head bs seq_len head_dim', head_dim=self.head_dim)
|
200 |
+
q = rearrange(proj[:self.num_heads], 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
|
201 |
+
k = rearrange(proj[self.num_heads:self.num_heads + self.num_kv_heads],
|
202 |
+
'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
|
203 |
+
v = rearrange(proj[self.num_heads + self.num_kv_heads:],
|
204 |
+
'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
|
205 |
+
|
206 |
+
# proj = rearrange(proj, 'bs seq_len (qkv n_head head_dim) -> qkv bs seq_len n_head head_dim',
|
207 |
+
# head_dim=self.head_dim, n_head=self.num_heads)
|
208 |
+
# q, k, v = proj
|
209 |
+
|
210 |
+
q, k = self.rotary_emb(q, k, seqlen_offset=past_len)
|
211 |
+
if HAS_FLASH_ATTN and q.dtype != torch.float32:
|
212 |
+
if past_key_value is not None:
|
213 |
+
attn_output = flash_attn_with_kvcache(
|
214 |
+
q,
|
215 |
+
cache_k,
|
216 |
+
cache_v,
|
217 |
+
k,
|
218 |
+
v,
|
219 |
+
causal=False,
|
220 |
+
cache_seqlens=past_len
|
221 |
+
)
|
222 |
+
else:
|
223 |
+
attn_outputs = flash_attn_func(
|
224 |
+
q,
|
225 |
+
k,
|
226 |
+
v,
|
227 |
+
causal=True,
|
228 |
+
return_attn_probs=output_attentions
|
229 |
+
)
|
230 |
+
attn_output = attn_outputs[0] if output_attentions else attn_outputs
|
231 |
+
attn_weights = attn_outputs[2] if output_attentions else None
|
232 |
+
else: # fallback to pytorch impl
|
233 |
+
if past_key_value is not None:
|
234 |
+
cache_k[:, past_len:new_len] = k
|
235 |
+
cache_v[:, past_len:new_len] = v
|
236 |
+
attn_output = F.scaled_dot_product_attention(
|
237 |
+
q.transpose(1, 2),
|
238 |
+
cache_k[:, :new_len].transpose(1, 2),
|
239 |
+
cache_v[:, :new_len].transpose(1, 2),
|
240 |
+
attn_mask=attention_mask
|
241 |
+
)
|
242 |
+
else:
|
243 |
+
attn_output = F.scaled_dot_product_attention(
|
244 |
+
q.transpose(1, 2),
|
245 |
+
k.transpose(1, 2),
|
246 |
+
v.transpose(1, 2),
|
247 |
+
attn_mask=attention_mask
|
248 |
+
)
|
249 |
+
attn_output = attn_output.transpose(1, 2)
|
250 |
+
if use_cache:
|
251 |
+
if past_key_value is not None:
|
252 |
+
past_key_value = (cache_k, cache_v, past_len + seqlen_q)
|
253 |
+
else:
|
254 |
+
past_key_value = (k, v, seqlen_q)
|
255 |
+
|
256 |
+
attn_output = attn_output.reshape(bsz, seqlen_q, self.hidden_size)
|
257 |
+
attn_output = self.o_proj(attn_output)
|
258 |
+
return attn_output, attn_weights, past_key_value
|
259 |
+
|
260 |
+
|
261 |
+
class DecoderLayer(nn.Module):
|
262 |
+
def __init__(self, config: BaiChuanConfig, num_heads):
|
263 |
+
super().__init__()
|
264 |
+
self.hidden_size = config.hidden_size
|
265 |
+
self.self_attn = Attention(config=config, num_heads=num_heads)
|
266 |
+
self.mlp = MLP(
|
267 |
+
hidden_size=self.hidden_size,
|
268 |
+
intermediate_size=config.intermediate_size,
|
269 |
+
hidden_act=config.hidden_act,
|
270 |
+
)
|
271 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
272 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
273 |
+
|
274 |
+
def forward(
|
275 |
+
self,
|
276 |
+
hidden_states: torch.Tensor,
|
277 |
+
attention_mask: Optional[torch.Tensor] = None,
|
278 |
+
position_ids: Optional[torch.LongTensor] = None,
|
279 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
280 |
+
output_attentions: Optional[bool] = False,
|
281 |
+
use_cache: Optional[bool] = False,
|
282 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
283 |
+
"""
|
284 |
+
Args:
|
285 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
286 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
287 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
288 |
+
output_attentions (`bool`, *optional*):
|
289 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
290 |
+
returned tensors for more detail.
|
291 |
+
use_cache (`bool`, *optional*):
|
292 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
293 |
+
(see `past_key_values`).
|
294 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
295 |
+
"""
|
296 |
+
|
297 |
+
residual = hidden_states
|
298 |
+
|
299 |
+
hidden_states = self.input_layernorm(hidden_states)
|
300 |
+
|
301 |
+
# Self Attention
|
302 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
303 |
+
hidden_states=hidden_states,
|
304 |
+
attention_mask=attention_mask,
|
305 |
+
position_ids=position_ids,
|
306 |
+
past_key_value=past_key_value,
|
307 |
+
output_attentions=output_attentions,
|
308 |
+
use_cache=use_cache,
|
309 |
+
)
|
310 |
+
hidden_states = residual + hidden_states
|
311 |
+
|
312 |
+
# Fully Connected
|
313 |
+
residual = hidden_states
|
314 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
315 |
+
hidden_states = self.mlp(hidden_states)
|
316 |
+
hidden_states = residual + hidden_states
|
317 |
+
|
318 |
+
outputs = (hidden_states,)
|
319 |
+
|
320 |
+
if output_attentions:
|
321 |
+
outputs += (self_attn_weights,)
|
322 |
+
|
323 |
+
if use_cache:
|
324 |
+
outputs += (present_key_value,)
|
325 |
+
|
326 |
+
return outputs
|
327 |
+
|
328 |
+
|
329 |
+
class PreTrainedModel(PreTrainedModel):
|
330 |
+
config_class = BaiChuanConfig
|
331 |
+
base_model_prefix = "model"
|
332 |
+
supports_gradient_checkpointing = True
|
333 |
+
_no_split_modules = ["DecoderLayer"]
|
334 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
335 |
+
|
336 |
+
def _init_weights(self, module):
|
337 |
+
std = self.config.initializer_range
|
338 |
+
if isinstance(module, nn.Linear):
|
339 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
340 |
+
if module.bias is not None:
|
341 |
+
module.bias.data.zero_()
|
342 |
+
elif isinstance(module, nn.Embedding):
|
343 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
344 |
+
if module.padding_idx is not None:
|
345 |
+
module.weight.data[module.padding_idx].zero_()
|
346 |
+
|
347 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
348 |
+
if isinstance(module, Model):
|
349 |
+
module.gradient_checkpointing = value
|
350 |
+
|
351 |
+
|
352 |
+
class Model(PreTrainedModel):
|
353 |
+
"""
|
354 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
|
355 |
+
|
356 |
+
Args:
|
357 |
+
config: BaiChuanConfig
|
358 |
+
"""
|
359 |
+
|
360 |
+
def __init__(self, config: BaiChuanConfig):
|
361 |
+
super().__init__(config)
|
362 |
+
self.padding_idx = config.pad_token_id
|
363 |
+
self.vocab_size = config.vocab_size
|
364 |
+
|
365 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
366 |
+
self.layers = nn.ModuleList([DecoderLayer(config, num_heads=self.get_num_heads(layer_id)) for layer_id in
|
367 |
+
range(config.num_hidden_layers)])
|
368 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
369 |
+
|
370 |
+
self.gradient_checkpointing = False
|
371 |
+
# Initialize weights and apply final processing
|
372 |
+
self.post_init()
|
373 |
+
def get_num_heads(self, layer_index: int):
|
374 |
+
return self.config.num_attention_heads
|
375 |
+
if 0 <= layer_index < self.config.num_hidden_layers // 4 or layer_index == self.config.num_hidden_layers-1:
|
376 |
+
return 8
|
377 |
+
elif self.config.num_hidden_layers // 4 <= layer_index < self.config.num_hidden_layers // 2:
|
378 |
+
return 4
|
379 |
+
elif self.config.num_hidden_layers // 2 <= layer_index < self.config.num_hidden_layers*3 // 4:
|
380 |
+
return 2
|
381 |
+
else:
|
382 |
+
return 1
|
383 |
+
def get_input_embeddings(self):
|
384 |
+
return self.embed_tokens
|
385 |
+
|
386 |
+
def set_input_embeddings(self, value):
|
387 |
+
self.embed_tokens = value
|
388 |
+
|
389 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
390 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
391 |
+
# create causal mask
|
392 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
393 |
+
combined_attention_mask = None
|
394 |
+
if input_shape[-1] > 1:
|
395 |
+
combined_attention_mask = _make_causal_mask(
|
396 |
+
input_shape,
|
397 |
+
inputs_embeds.dtype,
|
398 |
+
device=inputs_embeds.device,
|
399 |
+
past_key_values_length=past_key_values_length,
|
400 |
+
)
|
401 |
+
|
402 |
+
if attention_mask is not None:
|
403 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
404 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
405 |
+
inputs_embeds.device
|
406 |
+
)
|
407 |
+
combined_attention_mask = (
|
408 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
409 |
+
)
|
410 |
+
|
411 |
+
return combined_attention_mask
|
412 |
+
|
413 |
+
def forward(
|
414 |
+
self,
|
415 |
+
input_ids: torch.LongTensor = None,
|
416 |
+
attention_mask: Optional[torch.Tensor] = None,
|
417 |
+
position_ids: Optional[torch.LongTensor] = None,
|
418 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
419 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
420 |
+
use_cache: Optional[bool] = None,
|
421 |
+
output_attentions: Optional[bool] = None,
|
422 |
+
output_hidden_states: Optional[bool] = None,
|
423 |
+
return_dict: Optional[bool] = None,
|
424 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
425 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
426 |
+
output_hidden_states = (
|
427 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
428 |
+
)
|
429 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
430 |
+
|
431 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
432 |
+
|
433 |
+
# retrieve input_ids and inputs_embeds
|
434 |
+
if input_ids is not None and inputs_embeds is not None:
|
435 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
436 |
+
elif input_ids is not None:
|
437 |
+
batch_size, seq_length = input_ids.shape
|
438 |
+
elif inputs_embeds is not None:
|
439 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
440 |
+
else:
|
441 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
442 |
+
|
443 |
+
seq_length_with_past = seq_length
|
444 |
+
past_key_values_length = 0
|
445 |
+
|
446 |
+
if past_key_values is not None:
|
447 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
448 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
449 |
+
|
450 |
+
if position_ids is None:
|
451 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
452 |
+
position_ids = torch.arange(
|
453 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
454 |
+
)
|
455 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
456 |
+
else:
|
457 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
458 |
+
|
459 |
+
if inputs_embeds is None:
|
460 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
461 |
+
# embed positions
|
462 |
+
if attention_mask is None:
|
463 |
+
attention_mask = torch.ones(
|
464 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
465 |
+
)
|
466 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
467 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
468 |
+
)
|
469 |
+
|
470 |
+
hidden_states = inputs_embeds
|
471 |
+
|
472 |
+
if self.gradient_checkpointing and self.training:
|
473 |
+
if use_cache:
|
474 |
+
logger.warning_once(
|
475 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
476 |
+
)
|
477 |
+
use_cache = False
|
478 |
+
|
479 |
+
# decoder layers
|
480 |
+
all_hidden_states = () if output_hidden_states else None
|
481 |
+
all_self_attns = () if output_attentions else None
|
482 |
+
next_decoder_cache = () if use_cache else None
|
483 |
+
|
484 |
+
for idx, decoder_layer in enumerate(self.layers):
|
485 |
+
if output_hidden_states:
|
486 |
+
all_hidden_states += (hidden_states,)
|
487 |
+
|
488 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
489 |
+
|
490 |
+
if self.gradient_checkpointing and self.training:
|
491 |
+
|
492 |
+
def create_custom_forward(module):
|
493 |
+
def custom_forward(*inputs):
|
494 |
+
# None for past_key_value
|
495 |
+
return module(*inputs, output_attentions, None)
|
496 |
+
|
497 |
+
return custom_forward
|
498 |
+
|
499 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
500 |
+
create_custom_forward(decoder_layer),
|
501 |
+
hidden_states,
|
502 |
+
attention_mask,
|
503 |
+
position_ids,
|
504 |
+
None,
|
505 |
+
)
|
506 |
+
else:
|
507 |
+
layer_outputs = decoder_layer(
|
508 |
+
hidden_states,
|
509 |
+
attention_mask=attention_mask,
|
510 |
+
position_ids=position_ids,
|
511 |
+
past_key_value=past_key_value,
|
512 |
+
output_attentions=output_attentions,
|
513 |
+
use_cache=use_cache,
|
514 |
+
)
|
515 |
+
|
516 |
+
hidden_states = layer_outputs[0]
|
517 |
+
|
518 |
+
if use_cache:
|
519 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
520 |
+
|
521 |
+
if output_attentions:
|
522 |
+
all_self_attns += (layer_outputs[1],)
|
523 |
+
|
524 |
+
hidden_states = self.norm(hidden_states)
|
525 |
+
|
526 |
+
# add hidden states from the last decoder layer
|
527 |
+
if output_hidden_states:
|
528 |
+
all_hidden_states += (hidden_states,)
|
529 |
+
|
530 |
+
next_cache = next_decoder_cache if use_cache else None
|
531 |
+
if not return_dict:
|
532 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
533 |
+
return BaseModelOutputWithPast(
|
534 |
+
last_hidden_state=hidden_states,
|
535 |
+
past_key_values=next_cache,
|
536 |
+
hidden_states=all_hidden_states,
|
537 |
+
attentions=all_self_attns,
|
538 |
+
)
|
539 |
+
|
540 |
+
|
541 |
+
class NormHead(nn.Module):
|
542 |
+
def __init__(self, hidden_size, vocab_size, bias=False):
|
543 |
+
super().__init__()
|
544 |
+
self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
|
545 |
+
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
546 |
+
|
547 |
+
def forward(self, hidden_states):
|
548 |
+
norm_weight = nn.functional.normalize(self.weight)
|
549 |
+
return nn.functional.linear(hidden_states, norm_weight)
|
550 |
+
|
551 |
+
|
552 |
+
class BaiChuanForCausalLM(PreTrainedModel):
|
553 |
+
def __init__(self, config):
|
554 |
+
super().__init__(config)
|
555 |
+
self.model = Model(config)
|
556 |
+
|
557 |
+
# self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
558 |
+
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
559 |
+
|
560 |
+
# Initialize weights and apply final processing
|
561 |
+
self.post_init()
|
562 |
+
|
563 |
+
def get_input_embeddings(self):
|
564 |
+
return self.model.embed_tokens
|
565 |
+
|
566 |
+
def set_input_embeddings(self, value):
|
567 |
+
self.model.embed_tokens = value
|
568 |
+
|
569 |
+
def get_output_embeddings(self):
|
570 |
+
return self.lm_head
|
571 |
+
|
572 |
+
def set_output_embeddings(self, new_embeddings):
|
573 |
+
self.lm_head = new_embeddings
|
574 |
+
|
575 |
+
def set_decoder(self, decoder):
|
576 |
+
self.model = decoder
|
577 |
+
|
578 |
+
def get_decoder(self):
|
579 |
+
return self.model
|
580 |
+
|
581 |
+
def forward(
|
582 |
+
self,
|
583 |
+
input_ids: torch.LongTensor = None,
|
584 |
+
attention_mask: Optional[torch.Tensor] = None,
|
585 |
+
position_ids: Optional[torch.LongTensor] = None,
|
586 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
587 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
588 |
+
labels: Optional[torch.LongTensor] = None,
|
589 |
+
use_cache: Optional[bool] = None,
|
590 |
+
output_attentions: Optional[bool] = None,
|
591 |
+
output_hidden_states: Optional[bool] = None,
|
592 |
+
return_dict: Optional[bool] = None,
|
593 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
594 |
+
r"""
|
595 |
+
Args:
|
596 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
597 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
598 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
599 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
600 |
+
|
601 |
+
Returns:
|
602 |
+
|
603 |
+
Example:
|
604 |
+
|
605 |
+
```python
|
606 |
+
>>> from transformers import AutoTokenizer, ModelForCausalLM
|
607 |
+
|
608 |
+
>>> model = ModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
609 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
610 |
+
|
611 |
+
>>> prompt = "Hey, are you consciours? Can you talk to me?"
|
612 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
613 |
+
|
614 |
+
>>> # Generate
|
615 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
616 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
617 |
+
"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
|
618 |
+
```"""
|
619 |
+
|
620 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
621 |
+
output_hidden_states = (
|
622 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
623 |
+
)
|
624 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
625 |
+
|
626 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
627 |
+
outputs = self.model(
|
628 |
+
input_ids=input_ids,
|
629 |
+
attention_mask=attention_mask,
|
630 |
+
position_ids=position_ids,
|
631 |
+
past_key_values=past_key_values,
|
632 |
+
inputs_embeds=inputs_embeds,
|
633 |
+
use_cache=use_cache,
|
634 |
+
output_attentions=output_attentions,
|
635 |
+
output_hidden_states=output_hidden_states,
|
636 |
+
return_dict=return_dict,
|
637 |
+
)
|
638 |
+
|
639 |
+
hidden_states = outputs[0]
|
640 |
+
logits = self.lm_head(hidden_states)
|
641 |
+
|
642 |
+
loss = None
|
643 |
+
if labels is not None:
|
644 |
+
# Shift so that tokens < n predict n
|
645 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
646 |
+
shift_labels = labels[..., 1:].contiguous()
|
647 |
+
# Flatten the tokens
|
648 |
+
loss_fct = CrossEntropyLoss()
|
649 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
650 |
+
shift_labels = shift_labels.view(-1)
|
651 |
+
# Enable model parallelism
|
652 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
653 |
+
loss = loss_fct(shift_logits, shift_labels)
|
654 |
+
|
655 |
+
if not return_dict:
|
656 |
+
output = (logits,) + outputs[1:]
|
657 |
+
return (loss,) + output if loss is not None else output
|
658 |
+
|
659 |
+
return CausalLMOutputWithPast(
|
660 |
+
loss=loss,
|
661 |
+
logits=logits,
|
662 |
+
past_key_values=outputs.past_key_values,
|
663 |
+
hidden_states=outputs.hidden_states,
|
664 |
+
attentions=outputs.attentions,
|
665 |
+
)
|
666 |
+
|
667 |
+
def prepare_inputs_for_generation(
|
668 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
669 |
+
):
|
670 |
+
if past_key_values:
|
671 |
+
input_ids = input_ids[:, -1:]
|
672 |
+
position_ids = kwargs.get("position_ids", None)
|
673 |
+
|
674 |
+
if attention_mask is not None and position_ids is None:
|
675 |
+
# create position_ids on the fly for batch generation
|
676 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
677 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
678 |
+
if past_key_values:
|
679 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
680 |
+
|
681 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
682 |
+
if inputs_embeds is not None and past_key_values is None:
|
683 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
684 |
+
else:
|
685 |
+
model_inputs = {"input_ids": input_ids}
|
686 |
+
|
687 |
+
model_inputs.update(
|
688 |
+
{
|
689 |
+
"position_ids": position_ids,
|
690 |
+
"past_key_values": past_key_values,
|
691 |
+
"use_cache": kwargs.get("use_cache"),
|
692 |
+
"attention_mask": attention_mask,
|
693 |
+
}
|
694 |
+
)
|
695 |
+
return model_inputs
|
696 |
+
|
697 |
+
@staticmethod
|
698 |
+
def _reorder_cache(past_key_values, beam_idx):
|
699 |
+
reordered_past = ()
|
700 |
+
for layer_past in past_key_values:
|
701 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
702 |
+
return reordered_past
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a9533eb0d5dc2ef60bbcc32dcc48ce727611b6553335492f8972c97d45edfcd6
|
3 |
+
size 5776725422
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": true,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": true,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
tokenization_baichuan.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
2 |
+
|
3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
6 |
+
# and OPT implementations in this library. It has been modified from its
|
7 |
+
# original forms to accommodate minor architectural differences compared
|
8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
9 |
+
#
|
10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
11 |
+
# you may not use this file except in compliance with the License.
|
12 |
+
# You may obtain a copy of the License at
|
13 |
+
#
|
14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
15 |
+
#
|
16 |
+
# Unless required by applicable law or agreed to in writing, software
|
17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
19 |
+
# See the License for the specific language governing permissions and
|
20 |
+
# limitations under the License.
|
21 |
+
|
22 |
+
import os
|
23 |
+
from shutil import copyfile
|
24 |
+
from typing import Any, Dict, List, Optional, Tuple
|
25 |
+
|
26 |
+
import sentencepiece as spm
|
27 |
+
|
28 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
29 |
+
from transformers.utils import logging
|
30 |
+
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
35 |
+
|
36 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
37 |
+
"vocab_file": {},
|
38 |
+
"tokenizer_file": {},
|
39 |
+
}
|
40 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
|
41 |
+
|
42 |
+
|
43 |
+
class BaichuanTokenizer(PreTrainedTokenizer):
|
44 |
+
"""
|
45 |
+
Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_file (`str`):
|
49 |
+
Path to the vocabulary file.
|
50 |
+
"""
|
51 |
+
|
52 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
53 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
54 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
55 |
+
model_input_names = ["input_ids", "attention_mask"]
|
56 |
+
|
57 |
+
def __init__(
|
58 |
+
self,
|
59 |
+
vocab_file,
|
60 |
+
unk_token="<unk>",
|
61 |
+
bos_token="<s>",
|
62 |
+
eos_token="</s>",
|
63 |
+
pad_token=None,
|
64 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
65 |
+
add_bos_token=True,
|
66 |
+
add_eos_token=False,
|
67 |
+
clean_up_tokenization_spaces=False,
|
68 |
+
**kwargs,
|
69 |
+
):
|
70 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
71 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
72 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
73 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
74 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
75 |
+
self.vocab_file = vocab_file
|
76 |
+
self.add_bos_token = add_bos_token
|
77 |
+
self.add_eos_token = add_eos_token
|
78 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
79 |
+
self.sp_model.Load(vocab_file)
|
80 |
+
super().__init__(
|
81 |
+
bos_token=bos_token,
|
82 |
+
eos_token=eos_token,
|
83 |
+
unk_token=unk_token,
|
84 |
+
pad_token=pad_token,
|
85 |
+
add_bos_token=add_bos_token,
|
86 |
+
add_eos_token=add_eos_token,
|
87 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
88 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
89 |
+
**kwargs,
|
90 |
+
)
|
91 |
+
|
92 |
+
def __getstate__(self):
|
93 |
+
state = self.__dict__.copy()
|
94 |
+
state["sp_model"] = None
|
95 |
+
return state
|
96 |
+
|
97 |
+
def __setstate__(self, d):
|
98 |
+
self.__dict__ = d
|
99 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
100 |
+
self.sp_model.Load(self.vocab_file)
|
101 |
+
|
102 |
+
@property
|
103 |
+
def vocab_size(self):
|
104 |
+
"""Returns vocab size"""
|
105 |
+
return self.sp_model.get_piece_size()
|
106 |
+
|
107 |
+
def get_vocab(self):
|
108 |
+
"""Returns vocab as a dict"""
|
109 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
110 |
+
vocab.update(self.added_tokens_encoder)
|
111 |
+
return vocab
|
112 |
+
|
113 |
+
def _tokenize(self, text):
|
114 |
+
"""Returns a tokenized string."""
|
115 |
+
return self.sp_model.encode(text, out_type=str)
|
116 |
+
|
117 |
+
def _convert_token_to_id(self, token):
|
118 |
+
"""Converts a token (str) in an id using the vocab."""
|
119 |
+
return self.sp_model.piece_to_id(token)
|
120 |
+
|
121 |
+
def _convert_id_to_token(self, index):
|
122 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
123 |
+
token = self.sp_model.IdToPiece(index)
|
124 |
+
return token
|
125 |
+
|
126 |
+
def convert_tokens_to_string(self, tokens):
|
127 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
128 |
+
current_sub_tokens = []
|
129 |
+
out_string = ""
|
130 |
+
prev_is_special = False
|
131 |
+
for i, token in enumerate(tokens):
|
132 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
133 |
+
if token in self.all_special_tokens:
|
134 |
+
if not prev_is_special and i != 0:
|
135 |
+
out_string += " "
|
136 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
137 |
+
prev_is_special = True
|
138 |
+
current_sub_tokens = []
|
139 |
+
else:
|
140 |
+
current_sub_tokens.append(token)
|
141 |
+
prev_is_special = False
|
142 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
143 |
+
return out_string
|
144 |
+
|
145 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
146 |
+
"""
|
147 |
+
Save the vocabulary and special tokens file to a directory.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
save_directory (`str`):
|
151 |
+
The directory in which to save the vocabulary.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
`Tuple(str)`: Paths to the files saved.
|
155 |
+
"""
|
156 |
+
if not os.path.isdir(save_directory):
|
157 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
158 |
+
return
|
159 |
+
out_vocab_file = os.path.join(
|
160 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
161 |
+
)
|
162 |
+
|
163 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
164 |
+
copyfile(self.vocab_file, out_vocab_file)
|
165 |
+
elif not os.path.isfile(self.vocab_file):
|
166 |
+
with open(out_vocab_file, "wb") as fi:
|
167 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
168 |
+
fi.write(content_spiece_model)
|
169 |
+
|
170 |
+
return (out_vocab_file,)
|
171 |
+
|
172 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
173 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
174 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
175 |
+
|
176 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
177 |
+
|
178 |
+
if token_ids_1 is not None:
|
179 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
180 |
+
|
181 |
+
return output
|
182 |
+
|
183 |
+
def get_special_tokens_mask(
|
184 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
185 |
+
) -> List[int]:
|
186 |
+
"""
|
187 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
188 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
189 |
+
|
190 |
+
Args:
|
191 |
+
token_ids_0 (`List[int]`):
|
192 |
+
List of IDs.
|
193 |
+
token_ids_1 (`List[int]`, *optional*):
|
194 |
+
Optional second list of IDs for sequence pairs.
|
195 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
196 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
197 |
+
|
198 |
+
Returns:
|
199 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
200 |
+
"""
|
201 |
+
if already_has_special_tokens:
|
202 |
+
return super().get_special_tokens_mask(
|
203 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
204 |
+
)
|
205 |
+
|
206 |
+
bos_token_id = [1] if self.add_bos_token else []
|
207 |
+
eos_token_id = [1] if self.add_eos_token else []
|
208 |
+
|
209 |
+
if token_ids_1 is None:
|
210 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
211 |
+
return (
|
212 |
+
bos_token_id
|
213 |
+
+ ([0] * len(token_ids_0))
|
214 |
+
+ eos_token_id
|
215 |
+
+ bos_token_id
|
216 |
+
+ ([0] * len(token_ids_1))
|
217 |
+
+ eos_token_id
|
218 |
+
)
|
219 |
+
|
220 |
+
def create_token_type_ids_from_sequences(
|
221 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
222 |
+
) -> List[int]:
|
223 |
+
"""
|
224 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
225 |
+
sequence pair mask has the following format:
|
226 |
+
|
227 |
+
```
|
228 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
229 |
+
| first sequence | second sequence |
|
230 |
+
```
|
231 |
+
|
232 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
233 |
+
|
234 |
+
Args:
|
235 |
+
token_ids_0 (`List[int]`):
|
236 |
+
List of ids.
|
237 |
+
token_ids_1 (`List[int]`, *optional*):
|
238 |
+
Optional second list of IDs for sequence pairs.
|
239 |
+
|
240 |
+
Returns:
|
241 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
242 |
+
"""
|
243 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
244 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
245 |
+
|
246 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
247 |
+
|
248 |
+
if token_ids_1 is not None:
|
249 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
250 |
+
|
251 |
+
return output
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bf77124b06b5e70920cd455a482f79271a39bec14b75d466cd0b27a6bf82b308
|
3 |
+
size 1118898
|
tokenizer_config.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": ["tokenization_baichuan.BaichuanTokenizer", null]
|
4 |
+
},
|
5 |
+
"add_bos_token": false,
|
6 |
+
"add_eos_token": false,
|
7 |
+
"use_fast": false,
|
8 |
+
"clean_up_tokenization_spaces": false,
|
9 |
+
"eos_token": {
|
10 |
+
"__type": "AddedToken",
|
11 |
+
"content": "</s>",
|
12 |
+
"lstrip": false,
|
13 |
+
"normalized": true,
|
14 |
+
"rstrip": false,
|
15 |
+
"single_word": true
|
16 |
+
},
|
17 |
+
"model_max_length": 4000,
|
18 |
+
"sp_model_kwargs": {},
|
19 |
+
"tokenizer_class": "BaichuanTokenizer",
|
20 |
+
"pad_token": {
|
21 |
+
"__type": "AddedToken",
|
22 |
+
"content": "<unk>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": true,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": true
|
27 |
+
},
|
28 |
+
"unk_token": {
|
29 |
+
"__type": "AddedToken",
|
30 |
+
"content": "<unk>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": true,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": true
|
35 |
+
}
|
36 |
+
}
|