GradientGuru commited on
Commit
47c31a4
·
verified ·
1 Parent(s): 68631f3

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BaichuanM1ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_baichuan.BaichuanM1Config",
8
+ "AutoModelForCausalLM": "modeling_baichuan.BaichuanM1ForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "conv_window": 2,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 5120,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 17408,
17
+ "max_position_embeddings": 32768,
18
+ "model_max_length": 32768,
19
+ "model_type": "baichuan_m1",
20
+ "num_attention_heads": 20,
21
+ "num_hidden_layers": 40,
22
+ "num_key_value_heads": 2,
23
+ "num_swa_attention_heads": 40,
24
+ "num_swa_key_value_heads": 8,
25
+ "pad_token_id": 0,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_theta": 1000000.0,
28
+ "sliding_window": 8192,
29
+ "sliding_window_layers": [
30
+ 1,
31
+ 3,
32
+ 5,
33
+ 7,
34
+ 9,
35
+ 11,
36
+ 13,
37
+ 15,
38
+ 17,
39
+ 19,
40
+ 21,
41
+ 23,
42
+ 25,
43
+ 27,
44
+ 29,
45
+ 31,
46
+ 33,
47
+ 35,
48
+ 37,
49
+ 39
50
+ ],
51
+ "tie_word_embeddings": false,
52
+ "torch_dtype": "bfloat16",
53
+ "transformers_version": "4.48.1",
54
+ "use_cache": true,
55
+ "vocab_size": 133120
56
+ }
configuration_baichuan.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from transformers import PretrainedConfig
16
+ from transformers.utils import logging
17
+
18
+ logger = logging.get_logger(__name__)
19
+
20
+
21
+ class BaichuanM1Config(PretrainedConfig):
22
+ r"""
23
+ Configuration objects inherit from [`PretrainedConfig`] and control the behavior of model outputs. For more details,
24
+ refer to the documentation of [`PretrainedConfig`].
25
+
26
+ Args:
27
+ vocab_size (`int`, *optional*, defaults to 133120):
28
+ The size of the vocabulary used by the model.
29
+ hidden_size (`int`, *optional*, defaults to 4096):
30
+ The dimensionality of the hidden representations.
31
+ intermediate_size (`int`, *optional*, defaults to 22016):
32
+ The dimensionality of the intermediate (MLP) representations.
33
+ num_hidden_layers (`int`, *optional*, defaults to 32):
34
+ The number of hidden layers in the Transformer encoder.
35
+ num_attention_heads (`int`, *optional*, defaults to 32):
36
+ The number of attention heads for each attention layer in the Transformer encoder.
37
+ num_key_value_heads (`int`, *optional*, defaults to 32):
38
+ The number of key-value heads used to implement Grouped Query Attention (GQA).
39
+ - If `num_key_value_heads == num_attention_heads`, the model uses Multi-Head Attention (MHA).
40
+ - If `num_key_value_heads == 1`, the model uses Multi-Query Attention (MQA).
41
+ - Otherwise, the model uses Grouped Query Attention (GQA).
42
+ When converting a multi-head checkpoint to a GQA checkpoint, each group's key and value heads are constructed
43
+ by mean-pooling the original heads within that group. For more details, refer to [this paper](https://arxiv.org/pdf/2305.13245.pdf).
44
+ If not specified, this defaults to `32`.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
46
+ The non-linear activation function (either a string or a callable function) used in the decoder.
47
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
48
+ The maximum sequence length the model can handle.
49
+ initializer_range (`float`, *optional*, defaults to 0.02):
50
+ The standard deviation of the truncated normal initializer for initializing all weight matrices.
51
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
52
+ The epsilon value used by the RMS normalization layers.
53
+ use_cache (`bool`, *optional*, defaults to `True`):
54
+ Whether the model should return the last key/value attentions. This is only relevant if `config.is_decoder=True`.
55
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
56
+ Whether to tie the model's input and output word embeddings.
57
+ rope_theta (`float`, *optional*, defaults to 10000.0):
58
+ The base period of the Rotary Position Embeddings (RoPE).
59
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
60
+ Whether to enable sliding window attention.
61
+ sliding_window (`int`, *optional*, defaults to 4096):
62
+ The size of the sliding window for sliding window attention (SWA). If not specified, it defaults to `2048`.
63
+ attention_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio applied to the attention probabilities.
65
+ """
66
+
67
+ model_type = "baichuan"
68
+ keys_to_ignore_at_inference = ["past_key_values"]
69
+
70
+ def __init__(
71
+ self,
72
+ vocab_size=133120,
73
+ hidden_size=5120,
74
+ intermediate_size=17408,
75
+ num_hidden_layers=40,
76
+ num_attention_heads=40,
77
+ num_key_value_heads=2,
78
+ num_swa_attention_heads: int = 20,
79
+ num_swa_key_value_heads=8,
80
+ sliding_window_layers: list = None,
81
+ hidden_act="silu",
82
+ max_position_embeddings=32768,
83
+ initializer_range=0.02,
84
+ rms_norm_eps=1e-6,
85
+ use_cache=True,
86
+ tie_word_embeddings=False,
87
+ rope_theta=100000.0,
88
+ sliding_window=2048,
89
+ attention_dropout=0.0,
90
+ conv_window = 2,
91
+ **kwargs,
92
+ ):
93
+ self.sliding_window_layers = sliding_window_layers
94
+ self.num_swa_key_value_heads = num_swa_key_value_heads
95
+ self.num_swa_attention_heads = num_swa_attention_heads
96
+ self.vocab_size = vocab_size
97
+ self.max_position_embeddings = max_position_embeddings
98
+ self.hidden_size = hidden_size
99
+ self.intermediate_size = intermediate_size
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+ self.sliding_window = sliding_window
103
+
104
+ # for backward compatibility
105
+ if num_key_value_heads is None:
106
+ num_key_value_heads = num_attention_heads
107
+
108
+ self.num_key_value_heads = num_key_value_heads
109
+ self.hidden_act = hidden_act
110
+ self.initializer_range = initializer_range
111
+ self.rms_norm_eps = rms_norm_eps
112
+ self.use_cache = use_cache
113
+ self.rope_theta = rope_theta
114
+ self.attention_dropout = attention_dropout
115
+ self.conv_window = conv_window
116
+ super().__init__(
117
+ tie_word_embeddings=tie_word_embeddings,
118
+ **kwargs,
119
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "assistant_token_id": 74,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": 2,
6
+ "max_new_tokens": 2048,
7
+ "pad_token_id": 0,
8
+ "repetition_penalty": 1.05,
9
+ "temperature": 0.3,
10
+ "top_k": 5,
11
+ "top_p": 0.85,
12
+ "transformers_version": "4.48.1",
13
+ "user_token_id": 73
14
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4877c584176284bd6fef77e51fbd2ef96c8b38852a1f08ac2cdc8ea46179a4c
3
+ size 4938901448
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d987caf8f98c6c4dedb8466840dd4fb76a615c7d831840e65d22276b33a66e85
3
+ size 4938965032
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96b9c39b7e87270ed12f2201118192c11149f9c8df7a649b4d0a334299cb7157
3
+ size 4886515392
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0c855b72caab92ee27789d09240551e5d3df8e4389c7c6d19e009cba841c5ff
3
+ size 4949450824
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0a66bd47f70c4752c32b3ae05563c62ad03a8627da0345cdd8953d244330927
3
+ size 4886515440
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:640fd7f8c27d6a8fb7c87b339d7f451075081c16b684f8b78d1dcb923a4c32f0
3
+ size 4341222272
model.safetensors.index.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 28941528640
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00006-of-00006.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00006.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
13
+ "model.layers.0.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
14
+ "model.layers.0.self_attn.conv_k": "model-00001-of-00006.safetensors",
15
+ "model.layers.0.self_attn.conv_v": "model-00001-of-00006.safetensors",
16
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
22
+ "model.layers.1.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
23
+ "model.layers.1.self_attn.conv_k": "model-00001-of-00006.safetensors",
24
+ "model.layers.1.self_attn.conv_v": "model-00001-of-00006.safetensors",
25
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00006.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
31
+ "model.layers.10.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
32
+ "model.layers.10.self_attn.conv_k": "model-00002-of-00006.safetensors",
33
+ "model.layers.10.self_attn.conv_v": "model-00002-of-00006.safetensors",
34
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00006.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
40
+ "model.layers.11.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
41
+ "model.layers.11.self_attn.conv_k": "model-00002-of-00006.safetensors",
42
+ "model.layers.11.self_attn.conv_v": "model-00002-of-00006.safetensors",
43
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00006.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
49
+ "model.layers.12.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
50
+ "model.layers.12.self_attn.conv_k": "model-00002-of-00006.safetensors",
51
+ "model.layers.12.self_attn.conv_v": "model-00002-of-00006.safetensors",
52
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00003-of-00006.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
58
+ "model.layers.13.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
59
+ "model.layers.13.self_attn.conv_k": "model-00002-of-00006.safetensors",
60
+ "model.layers.13.self_attn.conv_v": "model-00002-of-00006.safetensors",
61
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00006.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
67
+ "model.layers.14.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
68
+ "model.layers.14.self_attn.conv_k": "model-00003-of-00006.safetensors",
69
+ "model.layers.14.self_attn.conv_v": "model-00003-of-00006.safetensors",
70
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00006.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
76
+ "model.layers.15.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
77
+ "model.layers.15.self_attn.conv_k": "model-00003-of-00006.safetensors",
78
+ "model.layers.15.self_attn.conv_v": "model-00003-of-00006.safetensors",
79
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00006.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
85
+ "model.layers.16.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
86
+ "model.layers.16.self_attn.conv_k": "model-00003-of-00006.safetensors",
87
+ "model.layers.16.self_attn.conv_v": "model-00003-of-00006.safetensors",
88
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00006.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
94
+ "model.layers.17.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
95
+ "model.layers.17.self_attn.conv_k": "model-00003-of-00006.safetensors",
96
+ "model.layers.17.self_attn.conv_v": "model-00003-of-00006.safetensors",
97
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00006.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
103
+ "model.layers.18.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
104
+ "model.layers.18.self_attn.conv_k": "model-00003-of-00006.safetensors",
105
+ "model.layers.18.self_attn.conv_v": "model-00003-of-00006.safetensors",
106
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00006.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
112
+ "model.layers.19.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
113
+ "model.layers.19.self_attn.conv_k": "model-00003-of-00006.safetensors",
114
+ "model.layers.19.self_attn.conv_v": "model-00003-of-00006.safetensors",
115
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
121
+ "model.layers.2.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
122
+ "model.layers.2.self_attn.conv_k": "model-00001-of-00006.safetensors",
123
+ "model.layers.2.self_attn.conv_v": "model-00001-of-00006.safetensors",
124
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00004-of-00006.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
130
+ "model.layers.20.self_attn.W_pack.weight": "model-00003-of-00006.safetensors",
131
+ "model.layers.20.self_attn.conv_k": "model-00003-of-00006.safetensors",
132
+ "model.layers.20.self_attn.conv_v": "model-00003-of-00006.safetensors",
133
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00004-of-00006.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
139
+ "model.layers.21.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
140
+ "model.layers.21.self_attn.conv_k": "model-00004-of-00006.safetensors",
141
+ "model.layers.21.self_attn.conv_v": "model-00004-of-00006.safetensors",
142
+ "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00004-of-00006.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
148
+ "model.layers.22.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
149
+ "model.layers.22.self_attn.conv_k": "model-00004-of-00006.safetensors",
150
+ "model.layers.22.self_attn.conv_v": "model-00004-of-00006.safetensors",
151
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00004-of-00006.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
157
+ "model.layers.23.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
158
+ "model.layers.23.self_attn.conv_k": "model-00004-of-00006.safetensors",
159
+ "model.layers.23.self_attn.conv_v": "model-00004-of-00006.safetensors",
160
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00004-of-00006.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
166
+ "model.layers.24.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
167
+ "model.layers.24.self_attn.conv_k": "model-00004-of-00006.safetensors",
168
+ "model.layers.24.self_attn.conv_v": "model-00004-of-00006.safetensors",
169
+ "model.layers.24.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00006.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
175
+ "model.layers.25.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
176
+ "model.layers.25.self_attn.conv_k": "model-00004-of-00006.safetensors",
177
+ "model.layers.25.self_attn.conv_v": "model-00004-of-00006.safetensors",
178
+ "model.layers.25.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00006.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
184
+ "model.layers.26.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
185
+ "model.layers.26.self_attn.conv_k": "model-00004-of-00006.safetensors",
186
+ "model.layers.26.self_attn.conv_v": "model-00004-of-00006.safetensors",
187
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00006.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
193
+ "model.layers.27.self_attn.W_pack.weight": "model-00004-of-00006.safetensors",
194
+ "model.layers.27.self_attn.conv_k": "model-00004-of-00006.safetensors",
195
+ "model.layers.27.self_attn.conv_v": "model-00004-of-00006.safetensors",
196
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00005-of-00006.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
202
+ "model.layers.28.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
203
+ "model.layers.28.self_attn.conv_k": "model-00004-of-00006.safetensors",
204
+ "model.layers.28.self_attn.conv_v": "model-00004-of-00006.safetensors",
205
+ "model.layers.28.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00005-of-00006.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
211
+ "model.layers.29.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
212
+ "model.layers.29.self_attn.conv_k": "model-00005-of-00006.safetensors",
213
+ "model.layers.29.self_attn.conv_v": "model-00005-of-00006.safetensors",
214
+ "model.layers.29.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00006.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
220
+ "model.layers.3.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
221
+ "model.layers.3.self_attn.conv_k": "model-00001-of-00006.safetensors",
222
+ "model.layers.3.self_attn.conv_v": "model-00001-of-00006.safetensors",
223
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00005-of-00006.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
229
+ "model.layers.30.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
230
+ "model.layers.30.self_attn.conv_k": "model-00005-of-00006.safetensors",
231
+ "model.layers.30.self_attn.conv_v": "model-00005-of-00006.safetensors",
232
+ "model.layers.30.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00005-of-00006.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
238
+ "model.layers.31.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
239
+ "model.layers.31.self_attn.conv_k": "model-00005-of-00006.safetensors",
240
+ "model.layers.31.self_attn.conv_v": "model-00005-of-00006.safetensors",
241
+ "model.layers.31.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
242
+ "model.layers.32.input_layernorm.weight": "model-00005-of-00006.safetensors",
243
+ "model.layers.32.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
244
+ "model.layers.32.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
245
+ "model.layers.32.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
246
+ "model.layers.32.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
247
+ "model.layers.32.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
248
+ "model.layers.32.self_attn.conv_k": "model-00005-of-00006.safetensors",
249
+ "model.layers.32.self_attn.conv_v": "model-00005-of-00006.safetensors",
250
+ "model.layers.32.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
251
+ "model.layers.33.input_layernorm.weight": "model-00005-of-00006.safetensors",
252
+ "model.layers.33.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
253
+ "model.layers.33.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
254
+ "model.layers.33.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
255
+ "model.layers.33.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
256
+ "model.layers.33.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
257
+ "model.layers.33.self_attn.conv_k": "model-00005-of-00006.safetensors",
258
+ "model.layers.33.self_attn.conv_v": "model-00005-of-00006.safetensors",
259
+ "model.layers.33.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
260
+ "model.layers.34.input_layernorm.weight": "model-00005-of-00006.safetensors",
261
+ "model.layers.34.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
262
+ "model.layers.34.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
263
+ "model.layers.34.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
264
+ "model.layers.34.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
265
+ "model.layers.34.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
266
+ "model.layers.34.self_attn.conv_k": "model-00005-of-00006.safetensors",
267
+ "model.layers.34.self_attn.conv_v": "model-00005-of-00006.safetensors",
268
+ "model.layers.34.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
269
+ "model.layers.35.input_layernorm.weight": "model-00006-of-00006.safetensors",
270
+ "model.layers.35.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
271
+ "model.layers.35.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
272
+ "model.layers.35.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
273
+ "model.layers.35.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
274
+ "model.layers.35.self_attn.W_pack.weight": "model-00005-of-00006.safetensors",
275
+ "model.layers.35.self_attn.conv_k": "model-00005-of-00006.safetensors",
276
+ "model.layers.35.self_attn.conv_v": "model-00005-of-00006.safetensors",
277
+ "model.layers.35.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
278
+ "model.layers.36.input_layernorm.weight": "model-00006-of-00006.safetensors",
279
+ "model.layers.36.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
280
+ "model.layers.36.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
281
+ "model.layers.36.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
282
+ "model.layers.36.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
283
+ "model.layers.36.self_attn.W_pack.weight": "model-00006-of-00006.safetensors",
284
+ "model.layers.36.self_attn.conv_k": "model-00006-of-00006.safetensors",
285
+ "model.layers.36.self_attn.conv_v": "model-00006-of-00006.safetensors",
286
+ "model.layers.36.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
287
+ "model.layers.37.input_layernorm.weight": "model-00006-of-00006.safetensors",
288
+ "model.layers.37.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
289
+ "model.layers.37.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
290
+ "model.layers.37.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
291
+ "model.layers.37.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
292
+ "model.layers.37.self_attn.W_pack.weight": "model-00006-of-00006.safetensors",
293
+ "model.layers.37.self_attn.conv_k": "model-00006-of-00006.safetensors",
294
+ "model.layers.37.self_attn.conv_v": "model-00006-of-00006.safetensors",
295
+ "model.layers.37.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
296
+ "model.layers.38.input_layernorm.weight": "model-00006-of-00006.safetensors",
297
+ "model.layers.38.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
298
+ "model.layers.38.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
299
+ "model.layers.38.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
300
+ "model.layers.38.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
301
+ "model.layers.38.self_attn.W_pack.weight": "model-00006-of-00006.safetensors",
302
+ "model.layers.38.self_attn.conv_k": "model-00006-of-00006.safetensors",
303
+ "model.layers.38.self_attn.conv_v": "model-00006-of-00006.safetensors",
304
+ "model.layers.38.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
305
+ "model.layers.39.input_layernorm.weight": "model-00006-of-00006.safetensors",
306
+ "model.layers.39.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
307
+ "model.layers.39.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
308
+ "model.layers.39.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
309
+ "model.layers.39.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
310
+ "model.layers.39.self_attn.W_pack.weight": "model-00006-of-00006.safetensors",
311
+ "model.layers.39.self_attn.conv_k": "model-00006-of-00006.safetensors",
312
+ "model.layers.39.self_attn.conv_v": "model-00006-of-00006.safetensors",
313
+ "model.layers.39.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
314
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00006.safetensors",
315
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
316
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
317
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
318
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
319
+ "model.layers.4.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
320
+ "model.layers.4.self_attn.conv_k": "model-00001-of-00006.safetensors",
321
+ "model.layers.4.self_attn.conv_v": "model-00001-of-00006.safetensors",
322
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
323
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00006.safetensors",
324
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
325
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
326
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
327
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
328
+ "model.layers.5.self_attn.W_pack.weight": "model-00001-of-00006.safetensors",
329
+ "model.layers.5.self_attn.conv_k": "model-00001-of-00006.safetensors",
330
+ "model.layers.5.self_attn.conv_v": "model-00001-of-00006.safetensors",
331
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
332
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00006.safetensors",
333
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
334
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
335
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
336
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
337
+ "model.layers.6.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
338
+ "model.layers.6.self_attn.conv_k": "model-00002-of-00006.safetensors",
339
+ "model.layers.6.self_attn.conv_v": "model-00002-of-00006.safetensors",
340
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
341
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00006.safetensors",
342
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
343
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
344
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
345
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
346
+ "model.layers.7.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
347
+ "model.layers.7.self_attn.conv_k": "model-00002-of-00006.safetensors",
348
+ "model.layers.7.self_attn.conv_v": "model-00002-of-00006.safetensors",
349
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
350
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00006.safetensors",
351
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
352
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
353
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
354
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
355
+ "model.layers.8.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
356
+ "model.layers.8.self_attn.conv_k": "model-00002-of-00006.safetensors",
357
+ "model.layers.8.self_attn.conv_v": "model-00002-of-00006.safetensors",
358
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
359
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00006.safetensors",
360
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
361
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
362
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
363
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
364
+ "model.layers.9.self_attn.W_pack.weight": "model-00002-of-00006.safetensors",
365
+ "model.layers.9.self_attn.conv_k": "model-00002-of-00006.safetensors",
366
+ "model.layers.9.self_attn.conv_v": "model-00002-of-00006.safetensors",
367
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
368
+ "model.norm.weight": "model-00006-of-00006.safetensors"
369
+ }
370
+ }
modeling_baichuan.py ADDED
@@ -0,0 +1,1197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ from typing import List, Optional, Tuple, Union, Dict, Any
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from einops import rearrange
9
+ from torch import nn
10
+ from torch.nn import CrossEntropyLoss
11
+ from transformers import add_start_docstrings, PreTrainedModel, DynamicCache, \
12
+ GenerationMixin, StaticCache, GenerationConfig
13
+ from transformers.activations import ACT2FN
14
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
15
+ from transformers.modeling_flash_attention_utils import _flash_supports_window_size, \
16
+ _upad_input
17
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
18
+ from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, \
19
+ add_start_docstrings_to_model_forward, is_torchdynamo_compiling, logging, \
20
+ is_flash_attn_greater_or_equal
21
+
22
+ if is_flash_attn_2_available():
23
+ from flash_attn.bert_padding import pad_input
24
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
25
+ from flash_attn.layers.rotary import apply_rotary_emb_func
26
+ from .configuration_baichuan import BaichuanM1Config
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class CustomCache(DynamicCache):
32
+ def __init__(self):
33
+ super().__init__()
34
+ self.past_len = []
35
+
36
+ def get_past_len(self, layer_idx: Optional[int] = 0) -> int:
37
+ if len(self.past_len) <= layer_idx:
38
+ return 0
39
+ return self.past_len[layer_idx]
40
+
41
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
42
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
43
+ # TODO: deprecate this function in favor of `cache_position`
44
+ if len(self.key_cache) <= layer_idx:
45
+ return 0
46
+ return self.key_cache[layer_idx].shape[1]
47
+
48
+ def update(
49
+ self,
50
+ key_states: torch.Tensor,
51
+ value_states: torch.Tensor,
52
+ layer_idx: int,
53
+ cache_kwargs: Optional[Dict[str, Any]] = None,
54
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
55
+ """
56
+ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
57
+
58
+ Parameters:
59
+ key_states (`torch.Tensor`):
60
+ The new key states to cache.
61
+ value_states (`torch.Tensor`):
62
+ The new value states to cache.
63
+ layer_idx (`int`):
64
+ The index of the layer to cache the states for.
65
+ cache_kwargs (`Dict[str, Any]`, `optional`):
66
+ Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
67
+
68
+ Return:
69
+ A tuple containing the updated key and value states.
70
+ """
71
+ # Update the number of seen tokens
72
+ if layer_idx == 0:
73
+ self._seen_tokens += key_states.shape[1]
74
+
75
+ # Update the cache
76
+ if len(self.key_cache) <= layer_idx:
77
+ self.key_cache.append(key_states)
78
+ self.value_cache.append(value_states)
79
+ else:
80
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=1)
81
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=1)
82
+
83
+ if len(self.past_len) <= layer_idx:
84
+ self.past_len.append(key_states.shape[1])
85
+ else:
86
+ self.past_len[layer_idx] += key_states.shape[1]
87
+
88
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
89
+
90
+
91
+ def _prepare_4d_causal_attention_mask_with_cache_position(
92
+ attention_mask: torch.Tensor,
93
+ sequence_length: int,
94
+ target_length: int,
95
+ dtype: torch.dtype,
96
+ device: torch.device,
97
+ min_dtype: float,
98
+ cache_position: torch.Tensor,
99
+ batch_size: int,
100
+ ):
101
+ """
102
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
103
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
104
+
105
+ Args:
106
+ attention_mask (`torch.Tensor`):
107
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
108
+ sequence_length (`int`):
109
+ The sequence length being processed.
110
+ target_length (`int`):
111
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
112
+ dtype (`torch.dtype`):
113
+ The dtype to use for the 4D attention mask.
114
+ device (`torch.device`):
115
+ The device to plcae the 4D attention mask on.
116
+ min_dtype (`float`):
117
+ The minimum value representable with the dtype `dtype`.
118
+ cache_position (`torch.Tensor`):
119
+ Indices depicting the position of the input sequence tokens in the sequence.
120
+ batch_size (`torch.Tensor`):
121
+ Batch size.
122
+ """
123
+ if attention_mask is not None and attention_mask.dim() == 4:
124
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
125
+ causal_mask = attention_mask
126
+ else:
127
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
128
+ if sequence_length != 1:
129
+ causal_mask = torch.triu(causal_mask, diagonal=1)
130
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
131
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
132
+ if attention_mask is not None:
133
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
134
+ mask_length = attention_mask.shape[-1]
135
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
136
+ padding_mask = padding_mask == 0
137
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
138
+ padding_mask, min_dtype
139
+ )
140
+
141
+ return causal_mask
142
+
143
+
144
+ class BaichuanRMSNorm(nn.Module):
145
+ def __init__(self, hidden_size, eps=1e-6):
146
+ """
147
+ RMSNorm is equivalent to T5LayerNorm
148
+ """
149
+ super().__init__()
150
+ self.weight = nn.Parameter(torch.ones(hidden_size))
151
+ self.variance_epsilon = eps
152
+
153
+ def forward(self, hidden_states):
154
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
155
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
156
+
157
+ # convert into half-precision if necessary
158
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
159
+ hidden_states = hidden_states.to(self.weight.dtype)
160
+
161
+ return self.weight * hidden_states
162
+
163
+
164
+ class RotaryEmbedding(torch.nn.Module):
165
+ def __init__(self, dim, max_position_embeddings=2048, base=1e5, device=None, interleaved=False):
166
+ super().__init__()
167
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
168
+ self.base = base
169
+ self.dim = dim
170
+ # Build here to make `torch.jit.trace` work.
171
+ self.max_seq_len_cached = 0
172
+ self.interleaved = interleaved
173
+
174
+ def forward(self, q, k, seqlen_offset=None, cu_seqlens=None, max_seqlen=None):
175
+ # x: [bs, num_attention_heads, seq_len, head_size]
176
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
177
+ seq_len_dim = 1
178
+ seq_len = q.shape[seq_len_dim] + seqlen_offset
179
+ if seq_len > self.max_seq_len_cached:
180
+ self.max_seq_len_cached = seq_len
181
+ self.inv_freq = 1.0 / (
182
+ self.base ** (torch.arange(0, self.dim, 2).float().to(self.inv_freq.device) / self.dim))
183
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
184
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq) # dont use this, bug in fp16
185
+ freqs = torch.outer(t, self.inv_freq)
186
+ self.cos_cached = freqs.cos().to(q.device)
187
+ self.sin_cached = freqs.sin().to(k.device)
188
+ q_ori_size = q.size()
189
+ k_ori_size = k.size()
190
+ if cu_seqlens is not None:
191
+ q = flatten_one_dim(q)
192
+ k = flatten_one_dim(k)
193
+ q_new = apply_rotary_emb_func(
194
+ q.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
195
+ self.interleaved, True, # inplace=True
196
+ cu_seqlens=cu_seqlens,
197
+ max_seqlen=max_seqlen
198
+ ).to(q.dtype)
199
+ k_new = apply_rotary_emb_func(
200
+ k.float(), self.cos_cached[seqlen_offset:], self.sin_cached[seqlen_offset:],
201
+ self.interleaved, True,
202
+ cu_seqlens=cu_seqlens,
203
+ max_seqlen=max_seqlen
204
+ ).to(k.dtype)
205
+ if cu_seqlens is not None:
206
+ q_new = q_new.reshape(*q_ori_size)
207
+ k_new = k_new.reshape(*k_ori_size)
208
+ return q_new, k_new
209
+
210
+
211
+ class BaichuanMLP(nn.Module):
212
+ def __init__(self, config):
213
+ super().__init__()
214
+ self.hidden_size = config.hidden_size
215
+ self.intermediate_size = config.intermediate_size
216
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
217
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
218
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
219
+ self.act_fn = ACT2FN[config.hidden_act]
220
+
221
+ def forward(self, hidden_state):
222
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
223
+
224
+
225
+ class BaichuanAttention(nn.Module):
226
+ """
227
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
228
+ and "Generating Long Sequences with Sparse Transformers".
229
+ """
230
+
231
+ def __init__(self, config: BaichuanM1Config, layer_idx: Optional[int] = None):
232
+ super().__init__()
233
+ self.config = config
234
+ self.layer_idx = layer_idx
235
+ if layer_idx is None:
236
+ raise ValueError(
237
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
238
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
239
+ "when creating this class."
240
+ )
241
+
242
+ self.hidden_size = config.hidden_size
243
+ self.is_swa = layer_idx in self.config.sliding_window_layers
244
+ self.num_heads = config.num_swa_attention_heads if self.is_swa else config.num_attention_heads
245
+ self.head_dim = self.hidden_size // self.num_heads
246
+ self.num_key_value_heads = config.num_swa_key_value_heads if self.is_swa else config.num_key_value_heads
247
+ self.max_position_embeddings = config.max_position_embeddings
248
+ self.rope_theta = config.rope_theta
249
+ self.is_causal = True
250
+ self.attention_dropout = config.attention_dropout
251
+
252
+ if (self.head_dim * self.num_heads) != self.hidden_size:
253
+ raise ValueError(
254
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
255
+ f" and `num_heads`: {self.num_heads})."
256
+ )
257
+ self.W_pack = nn.Linear(config.hidden_size, self.hidden_size + 2 * self.num_key_value_heads * self.head_dim,
258
+ bias=False)
259
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
260
+
261
+ self.rotary_emb = RotaryEmbedding(dim=self.head_dim, base=self.config.rope_theta,
262
+ max_position_embeddings=self.config.max_position_embeddings)
263
+ self.conv_window = config.conv_window
264
+ assert self.conv_window == 2 #%% Currently, only supported window=2 when inference
265
+ self.conv_k = nn.Parameter(torch.softmax(torch.randn((1, 1, self.num_key_value_heads, 1, self.conv_window)), dim=-1))
266
+ self.conv_v = nn.Parameter(torch.softmax(torch.randn((1, 1, self.num_key_value_heads, 1, self.conv_window)), dim=-1))
267
+ self.last_k, self.last_v = None, None
268
+
269
+
270
+ def get_max_seqlen(cu_seqlens):
271
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
272
+ return max_seqlen
273
+
274
+
275
+ def flatten_one_dim(tensor):
276
+ tensor = tensor.view(-1, tensor.size(-2), tensor.size(-1))
277
+ return tensor
278
+
279
+
280
+ def prepare_for_flash_attention_varlen(query, key, value, cu_seqlens):
281
+ query = query.view(-1, query.size(-2), query.size(-1))
282
+ key = key.view(-1, key.size(-2), key.size(-1))
283
+ value = value.view(-1, value.size(-2), value.size(-1))
284
+ return query, key, value, get_max_seqlen(cu_seqlens)
285
+
286
+
287
+ def flash_attention_forward(
288
+ query_states: torch.Tensor,
289
+ key_states: torch.Tensor,
290
+ value_states: torch.Tensor,
291
+ query_length: int,
292
+ is_causal: bool,
293
+ dropout: float = 0.0,
294
+ attention_mask: Optional[torch.Tensor] = None,
295
+ position_ids: Optional[torch.Tensor] = None,
296
+ seqlens: Optional[torch.LongTensor] = None,
297
+ softmax_scale: Optional[float] = None,
298
+ sliding_window: Optional[int] = None,
299
+ use_top_left_mask: bool = False,
300
+ softcap: Optional[float] = None,
301
+ deterministic: bool = None,
302
+ ):
303
+ """
304
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
305
+ first unpad the input, then computes the attention scores and pad the final attention scores.
306
+
307
+ Args:
308
+ query_states (`torch.Tensor`):
309
+ Input query states to be passed to Flash Attention API
310
+ key_states (`torch.Tensor`):
311
+ Input key states to be passed to Flash Attention API
312
+ value_states (`torch.Tensor`):
313
+ Input value states to be passed to Flash Attention API
314
+ attention_mask (`torch.Tensor`):
315
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
316
+ position of padding tokens and 1 for the position of non-padding tokens.
317
+ dropout (`float`):
318
+ Attention dropout
319
+ softmax_scale (`float`, *optional*):
320
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
321
+ use_top_left_mask (`bool`, defaults to `False`):
322
+ flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
323
+ softcap (`float`, *optional*):
324
+ Softcap for the attention logits, used e.g. in gemma2.
325
+ deterministic (`bool`, *optional*):
326
+ Determines if the deterministic option introduced in flash_attn>=2.4.1 is enabled.
327
+ """
328
+ if not use_top_left_mask:
329
+ causal = is_causal
330
+ else:
331
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. .
332
+ causal = is_causal and query_length != 1
333
+
334
+ # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length).
335
+ use_sliding_windows = (
336
+ _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window
337
+ )
338
+ flash_kwargs = {"window_size": (sliding_window - 1, 0)} if use_sliding_windows else {}
339
+
340
+ if is_flash_attn_greater_or_equal("2.4.1"):
341
+ if deterministic is None:
342
+ deterministic = os.environ.get("FLASH_ATTENTION_DETERMINISTIC", "0") == "1"
343
+ flash_kwargs["deterministic"] = deterministic
344
+
345
+ if softcap is not None:
346
+ flash_kwargs["softcap"] = softcap
347
+ # Contains at least one padding token in the sequence
348
+ if seqlens is not None:
349
+ batch_size = query_states.shape[0]
350
+ query_states, key_states, value_states, max_seqlen = prepare_for_flash_attention_varlen(query_states,
351
+ key_states,
352
+ value_states, seqlens)
353
+ attn_output = flash_attn_varlen_func(
354
+ query_states,
355
+ key_states,
356
+ value_states,
357
+ cu_seqlens_q=seqlens,
358
+ cu_seqlens_k=seqlens,
359
+ max_seqlen_q=max_seqlen,
360
+ max_seqlen_k=max_seqlen,
361
+ dropout_p=dropout,
362
+ softmax_scale=softmax_scale,
363
+ causal=causal,
364
+ **flash_kwargs,
365
+ )
366
+
367
+ attn_output = attn_output.reshape(batch_size, -1, attn_output.size(-2), attn_output.size(-1))
368
+
369
+ elif attention_mask is not None:
370
+ batch_size = query_states.shape[0]
371
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = _upad_input(
372
+ query_states, key_states, value_states, attention_mask, query_length
373
+ )
374
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
375
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
376
+ attn_output_unpad = flash_attn_varlen_func(
377
+ query_states,
378
+ key_states,
379
+ value_states,
380
+ cu_seqlens_q=cu_seqlens_q,
381
+ cu_seqlens_k=cu_seqlens_k,
382
+ max_seqlen_q=max_seqlen_in_batch_q,
383
+ max_seqlen_k=max_seqlen_in_batch_k,
384
+ dropout_p=dropout,
385
+ softmax_scale=softmax_scale,
386
+ causal=causal,
387
+ **flash_kwargs,
388
+ )
389
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
390
+
391
+ else:
392
+ attn_output = flash_attn_func(
393
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal, **flash_kwargs
394
+ )
395
+
396
+ return attn_output
397
+
398
+
399
+ def custom_convolution(U, K):
400
+ """
401
+ U: Input matrix, shape (bs, seq, h, d)
402
+ K: Convolution kernel, shape (w, h)
403
+ Returns: Output matrix V, shape (bs, seq, h, d)
404
+ """
405
+ # h, w = K.shape
406
+ w = K.size(-1)
407
+ padding = (w - 1, 0)
408
+ U_padded = F.pad(U, (0, 0, 0, 0, *padding)) # Shape becomes (bs, seq+w-1, h, d)
409
+ U_unfolded = U_padded.unfold(1, w, 1) # Shape becomes (bs, seq+w-1, h, d, w)
410
+ V_unfolded = U_unfolded * K # Shape remains (bs, seq, h, d, w)
411
+ V = V_unfolded.sum(dim=-1) # Shape becomes (bs, seq, h, d)
412
+ return V
413
+
414
+
415
+ def custom_convolution_with_splits(U, K, cu_seqlens):
416
+ """
417
+ U: Input matrix, shape (bs, seq, h, d)
418
+ K: Convolution kernel, shape (w, h)
419
+ cu_seqlens: Cumulative sequence lengths, indicating how to split the input.
420
+ Returns: Output matrix, shape (bs, seq, h, d)
421
+ """
422
+ ori_shape = U.size() # Save the original shape of U
423
+ # Flatten U to handle variable-length sequences
424
+ U_flatten = U.reshape(1, -1, ori_shape[-2], ori_shape[-1]) # Shape: (1, total_seq, h, d)
425
+
426
+ # Perform convolution on each subsequence separately
427
+ V_parts = [] # Store the results of each subsequence
428
+ start = 0 # Start index of the current subsequence
429
+ for end in cu_seqlens[1:]:
430
+ end = end.item() # Convert scalar tensor to int
431
+ U_part = U_flatten[:, start:end, :, :] # Slice the subsequence (1, seq_sub, h, d)
432
+ V_part = custom_convolution(U_part, K) # Apply custom convolution
433
+ V_parts.append(V_part) # Append the result
434
+ start = end # Update the start index for the next subsequence
435
+
436
+ # Concatenate the results along the sequence dimension
437
+ V = torch.cat(V_parts, dim=1).to(U) # Shape: (1, total_seq, h, d)
438
+
439
+ # Reshape the output to match the original input shape
440
+ return V.reshape(ori_shape)
441
+
442
+
443
+ class BaichuanFlashAttention2(BaichuanAttention):
444
+ """
445
+ Baichuan flash attention module, following Baichuan attention module. This module inherits from `BaichuanAttention`
446
+ as the weights of the module stays untouched. The only required change would be on the forward pass
447
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
448
+ in case the input contains any of them.
449
+ """
450
+
451
+ def __init__(self, *args, **kwargs):
452
+ super().__init__(*args, **kwargs)
453
+
454
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
455
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
456
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
457
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
458
+
459
+ def forward(
460
+ self,
461
+ hidden_states: torch.Tensor,
462
+ attention_mask: Optional[torch.Tensor] = None,
463
+ position_ids: Optional[torch.LongTensor] = None,
464
+ seqlens: Optional[torch.LongTensor] = None,
465
+ past_key_value: Optional[CustomCache] = None,
466
+ output_attentions: bool = False,
467
+ use_cache: bool = False,
468
+ cache_position: Optional[torch.LongTensor] = None,
469
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
470
+ ):
471
+
472
+ bsz, q_len, _ = hidden_states.size()
473
+ proj = self.W_pack(hidden_states)
474
+ proj = rearrange(proj, 'bs seq_len (n_head head_dim) -> n_head bs seq_len head_dim', head_dim=self.head_dim)
475
+ query_states = rearrange(proj[:self.num_heads], 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
476
+ key_states = rearrange(proj[self.num_heads:self.num_heads + self.num_key_value_heads],
477
+ 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
478
+ value_states = rearrange(proj[self.num_heads + self.num_key_value_heads:],
479
+ 'n_head bs seq_len head_dim -> bs seq_len n_head head_dim')
480
+
481
+
482
+ if past_key_value is None or past_key_value.get_seq_length(self.layer_idx) == 0:# prefill
483
+ if not self.training:
484
+ self.last_k = key_states[:, -1:]
485
+ self.last_v = value_states[:, -1:]
486
+ if seqlens is None:
487
+ key_states = custom_convolution(key_states, self.conv_k)
488
+ value_states = custom_convolution(value_states, self.conv_v)
489
+ else:
490
+ assert seqlens.ndim==1
491
+ key_states=custom_convolution_with_splits(key_states,self.conv_k,seqlens)
492
+ value_states=custom_convolution_with_splits(value_states,self.conv_v,seqlens)
493
+ else: # decode
494
+ self.last_k, key_states = key_states, self.conv_k[0, 0, :, 0, :1] * self.last_k + self.conv_k[0, 0, :, 0, 1:] * key_states
495
+ self.last_v, value_states = value_states, self.conv_v[0, 0, :, 0, :1] * self.last_v + self.conv_v[0, 0, :, 0, 1:] * value_states
496
+ if seqlens is not None:
497
+ max_seqlen = get_max_seqlen(seqlens)
498
+ else:
499
+ max_seqlen = None
500
+
501
+ past_len = past_key_value.get_past_len(self.layer_idx) if past_key_value is not None else 0
502
+ query_states, key_states = self.rotary_emb(
503
+ query_states,
504
+ key_states,
505
+ seqlen_offset=past_len,
506
+ cu_seqlens=seqlens,
507
+ max_seqlen=max_seqlen
508
+ )
509
+
510
+ if past_key_value is not None:
511
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
512
+ kv_seq_len = key_states.shape[1] + past_key_value.get_seq_length(self.layer_idx)
513
+ if (
514
+ self.is_swa
515
+ and kv_seq_len > self.config.sliding_window
516
+ and cache_has_contents
517
+ ):
518
+ slicing_tokens = 1 - self.config.sliding_window
519
+ past_key = past_key_value[self.layer_idx][0]
520
+ past_value = past_key_value[self.layer_idx][1]
521
+
522
+ past_key_value.key_cache[self.layer_idx] = past_key[:, slicing_tokens:, :, :].contiguous()
523
+ past_key_value.value_cache[self.layer_idx] = past_value[:, slicing_tokens:, :, :].contiguous()
524
+
525
+ if past_key_value[self.layer_idx][0].shape[1] != self.config.sliding_window - 1:
526
+ raise ValueError(
527
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
528
+ f" {past_key.shape}"
529
+ )
530
+
531
+ # if attention_mask is not None:
532
+ # # TODO: not check!!
533
+ # attention_mask = attention_mask[:, slicing_tokens:]
534
+ # attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
535
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
536
+
537
+ input_dtype = query_states.dtype
538
+ if input_dtype == torch.float32:
539
+ if torch.is_autocast_enabled():
540
+ target_dtype = torch.get_autocast_gpu_dtype()
541
+ # Handle the case where the model is quantized
542
+ elif hasattr(self.config, "_pre_quantization_dtype"):
543
+ target_dtype = self.config._pre_quantization_dtype
544
+ else:
545
+ target_dtype = self.q_proj.weight.dtype
546
+
547
+ logger.warning_once(
548
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
549
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
550
+ f" {target_dtype}."
551
+ )
552
+
553
+ query_states = query_states.to(target_dtype)
554
+ key_states = key_states.to(target_dtype)
555
+ value_states = value_states.to(target_dtype)
556
+
557
+ if self.is_swa:
558
+ sliding_window = self.config.sliding_window
559
+ else:
560
+ sliding_window = None
561
+ attn_output = flash_attention_forward(
562
+ query_states,
563
+ key_states,
564
+ value_states,
565
+ query_length=q_len,
566
+ position_ids=position_ids,
567
+ seqlens=seqlens,
568
+ sliding_window=sliding_window,
569
+ is_causal=self.is_causal,
570
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
571
+ )
572
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
573
+ attn_output = self.o_proj(attn_output)
574
+
575
+ if not output_attentions:
576
+ attn_weights = None
577
+
578
+ return attn_output, attn_weights, past_key_value
579
+
580
+
581
+ Baichuan_ATTENTION_CLASSES = {
582
+ "eager": BaichuanAttention,
583
+ "flash_attention_2": BaichuanFlashAttention2,
584
+ }
585
+
586
+
587
+ class BaichuanDecoderLayer(nn.Module):
588
+ def __init__(self, config: BaichuanM1Config, layer_idx: int):
589
+ super().__init__()
590
+ self.hidden_size = config.hidden_size
591
+ self.layer_idx = layer_idx
592
+ self.self_attn = Baichuan_ATTENTION_CLASSES['flash_attention_2'](config, layer_idx)
593
+
594
+ self.mlp = BaichuanMLP(config)
595
+ self.input_layernorm = BaichuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
596
+ self.post_attention_layernorm = BaichuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
597
+
598
+ def forward(
599
+ self,
600
+ hidden_states: torch.Tensor,
601
+ attention_mask: Optional[torch.Tensor] = None,
602
+ position_ids: Optional[torch.LongTensor] = None,
603
+ seqlens: Optional[torch.LongTensor] = None,
604
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
605
+ output_attentions: Optional[bool] = False,
606
+ use_cache: Optional[bool] = False,
607
+ cache_position: Optional[torch.LongTensor] = None,
608
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
609
+ **kwargs,
610
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
611
+ """
612
+ Args:
613
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
614
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
615
+ `(batch, sequence_length)` where padding elements are indicated by 0.
616
+ output_attentions (`bool`, *optional*):
617
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
618
+ returned tensors for more detail.
619
+ use_cache (`bool`, *optional*):
620
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
621
+ (see `past_key_values`).
622
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
623
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
624
+ Indices depicting the position of the input sequence tokens in the sequence.
625
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
626
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
627
+ with `head_dim` being the embedding dimension of each attention head.
628
+ kwargs (`dict`, *optional*):
629
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
630
+ into the model
631
+ """
632
+
633
+ residual = hidden_states
634
+
635
+ hidden_states = self.input_layernorm(hidden_states)
636
+
637
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
638
+ hidden_states=hidden_states,
639
+ attention_mask=attention_mask,
640
+ position_ids=position_ids,
641
+ seqlens=seqlens,
642
+ past_key_value=past_key_value,
643
+ output_attentions=output_attentions,
644
+ use_cache=use_cache,
645
+ cache_position=cache_position,
646
+ position_embeddings=position_embeddings,
647
+ )
648
+ hidden_states = residual + hidden_states
649
+
650
+ # Fully Connected
651
+ residual = hidden_states
652
+ hidden_states = self.post_attention_layernorm(hidden_states)
653
+ hidden_states = self.mlp(hidden_states)
654
+ hidden_states = residual + hidden_states
655
+
656
+ outputs = (hidden_states,)
657
+
658
+ if output_attentions:
659
+ outputs += (self_attn_weights,)
660
+
661
+ if use_cache:
662
+ outputs += (present_key_value,)
663
+ return outputs
664
+
665
+
666
+ Baichuan_START_DOCSTRING = r"""
667
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
668
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
669
+ etc.)
670
+
671
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
672
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
673
+ and behavior.
674
+
675
+ Parameters:
676
+ config ([`BaichuanM1Config`]):
677
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
678
+ load the weights associated with the model, only the configuration. Check out the
679
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
680
+ """
681
+
682
+
683
+ @add_start_docstrings(
684
+ "The bare Bai chuan Model outputting raw hidden-states without any specific head on top.",
685
+ Baichuan_START_DOCSTRING,
686
+ )
687
+ class BaichuanPreTrainedModel(PreTrainedModel):
688
+ config_class = BaichuanM1Config
689
+ base_model_prefix = "model"
690
+ supports_gradient_checkpointing = True
691
+ _no_split_modules = ["BaichuanDecoderLayer"]
692
+ _skip_keys_device_placement = "past_key_values"
693
+ _supports_flash_attn_2 = True
694
+ _supports_sdpa = True
695
+ _supports_cache_class = True
696
+ _supports_quantized_cache = True
697
+ _supports_static_cache = True
698
+
699
+ def _init_weights(self, module):
700
+ std = self.config.initializer_range
701
+ if isinstance(module, nn.Linear):
702
+ module.weight.data.normal_(mean=0.0, std=std)
703
+ if module.bias is not None:
704
+ module.bias.data.zero_()
705
+ elif isinstance(module, nn.Embedding):
706
+ module.weight.data.normal_(mean=0.0, std=std)
707
+ if module.padding_idx is not None:
708
+ module.weight.data[module.padding_idx].zero_()
709
+
710
+
711
+ Baichuan_INPUTS_DOCSTRING = r"""
712
+
713
+ """
714
+
715
+
716
+ @add_start_docstrings(
717
+ "The bare Baichuan Model outputting raw hidden-states without any specific head on top.",
718
+ Baichuan_START_DOCSTRING,
719
+ )
720
+ class BaichuanModel(BaichuanPreTrainedModel):
721
+ """
722
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BaichuanDecoderLayer`]
723
+
724
+ Args:
725
+ config: BaichuanM1Config
726
+ """
727
+
728
+ def __init__(self, config: BaichuanM1Config):
729
+ super().__init__(config)
730
+ self.padding_idx = config.pad_token_id
731
+ self.vocab_size = config.vocab_size
732
+
733
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
734
+ self.layers = nn.ModuleList(
735
+ [BaichuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
736
+ )
737
+ self._attn_implementation = config._attn_implementation
738
+ self.norm = BaichuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
739
+
740
+ self.gradient_checkpointing = True
741
+ # Initialize weights and apply final processing
742
+ self.post_init()
743
+
744
+ def get_input_embeddings(self):
745
+ return self.embed_tokens
746
+
747
+ def set_input_embeddings(self, value):
748
+ self.embed_tokens = value
749
+
750
+ @add_start_docstrings_to_model_forward(Baichuan_INPUTS_DOCSTRING)
751
+ def forward(
752
+ self,
753
+ input_ids: torch.LongTensor = None,
754
+ attention_mask: Optional[torch.Tensor] = None,
755
+ position_ids: Optional[torch.LongTensor] = None,
756
+ seqlens: Optional[torch.LongTensor] = None,
757
+ past_key_values: Optional[CustomCache] = None,
758
+ inputs_embeds: Optional[torch.FloatTensor] = None,
759
+ use_cache: Optional[bool] = None,
760
+ output_attentions: Optional[bool] = None,
761
+ output_hidden_states: Optional[bool] = None,
762
+ return_dict: Optional[bool] = None,
763
+ cache_position: Optional[torch.LongTensor] = None,
764
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
765
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
766
+ output_hidden_states = (
767
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
768
+ )
769
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
770
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
771
+ if (input_ids is None) ^ (inputs_embeds is not None):
772
+ raise ValueError(
773
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
774
+ )
775
+
776
+ if self.gradient_checkpointing and self.training:
777
+ if use_cache:
778
+ logger.warning_once(
779
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
780
+ )
781
+ use_cache = False
782
+
783
+ if seqlens is not None:
784
+ assert seqlens.ndim == 2
785
+ # batch multi-pack 样本拉平
786
+ cu_seqlens = []
787
+ offset, seqlen = 0, seqlens.size(1)
788
+ for lens in seqlens:
789
+ cu_seqlens.append(offset)
790
+ cu_seqlens.extend((lens[(lens > 0) & (lens < seqlen)] + offset).tolist())
791
+ offset += seqlen
792
+ cu_seqlens.append(offset)
793
+ seqlens = torch.tensor(cu_seqlens, dtype=torch.int32, device=input_ids.device)
794
+ # unset attention_mask to save memory
795
+ attention_mask = None
796
+ # kept for BC (non `Cache` `past_key_values` inputs)
797
+ return_legacy_cache = False
798
+ if use_cache and not isinstance(past_key_values, CustomCache):
799
+ return_legacy_cache = False
800
+ if past_key_values is None:
801
+ past_key_values = CustomCache()
802
+ else:
803
+ past_key_values = CustomCache.from_legacy_cache(past_key_values)
804
+ logger.warning_once(
805
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
806
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
807
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
808
+ )
809
+ if inputs_embeds is None:
810
+ inputs_embeds = self.embed_tokens(input_ids)
811
+
812
+ if cache_position is None:
813
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
814
+ cache_position = torch.arange(
815
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
816
+ )
817
+ if position_ids is None:
818
+ position_ids = cache_position.unsqueeze(0)
819
+
820
+ causal_mask = self._update_causal_mask(
821
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
822
+ )
823
+
824
+ hidden_states = inputs_embeds
825
+
826
+ # create position embeddings to be shared across the decoder layers
827
+ # position_embeddings = self.rotary_emb(hidden_states, position_ids)
828
+ position_embeddings = None
829
+
830
+ # decoder layers
831
+ all_hidden_states = () if output_hidden_states else None
832
+ all_self_attns = () if output_attentions else None
833
+ next_decoder_cache = None
834
+
835
+ for decoder_layer in self.layers:
836
+ if output_hidden_states:
837
+ all_hidden_states += (hidden_states,)
838
+ if self.gradient_checkpointing and self.training:
839
+ layer_outputs = torch.utils.checkpoint.checkpoint(
840
+ decoder_layer,
841
+ hidden_states,
842
+ causal_mask,
843
+ position_ids,
844
+ seqlens,
845
+ past_key_values,
846
+ output_attentions,
847
+ use_cache,
848
+ cache_position,
849
+ position_embeddings,
850
+ )
851
+ else:
852
+ layer_outputs = decoder_layer(
853
+ hidden_states,
854
+ attention_mask=causal_mask,
855
+ position_ids=position_ids,
856
+ seqlens=seqlens,
857
+ past_key_value=past_key_values,
858
+ output_attentions=output_attentions,
859
+ use_cache=use_cache,
860
+ cache_position=cache_position,
861
+ position_embeddings=position_embeddings,
862
+ )
863
+
864
+ hidden_states = layer_outputs[0]
865
+ if use_cache:
866
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
867
+
868
+ if output_attentions:
869
+ all_self_attns += (layer_outputs[1],)
870
+
871
+ hidden_states = self.norm(hidden_states)
872
+
873
+ # add hidden states from the last decoder layer
874
+ if output_hidden_states:
875
+ all_hidden_states += (hidden_states,)
876
+
877
+ next_cache = next_decoder_cache if use_cache else None
878
+ if return_legacy_cache:
879
+ next_cache = next_cache.to_legacy_cache()
880
+ if not return_dict:
881
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
882
+ return BaseModelOutputWithPast(
883
+ last_hidden_state=hidden_states,
884
+ past_key_values=next_cache,
885
+ hidden_states=all_hidden_states,
886
+ attentions=all_self_attns,
887
+ )
888
+
889
+
890
+ def _update_causal_mask(
891
+ self,
892
+ attention_mask: torch.Tensor,
893
+ input_tensor: torch.Tensor,
894
+ cache_position: torch.Tensor,
895
+ past_key_values: CustomCache,
896
+ output_attentions: bool,
897
+ ):
898
+ if self.config._attn_implementation == "flash_attention_2":
899
+ if attention_mask is not None and 0.0 in attention_mask:
900
+ return attention_mask
901
+ return None
902
+
903
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
904
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
905
+ # to infer the attention mask.
906
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
907
+ using_static_cache = isinstance(past_key_values, StaticCache)
908
+
909
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
910
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
911
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
912
+ attention_mask,
913
+ inputs_embeds=input_tensor,
914
+ past_key_values_length=past_seen_tokens,
915
+ is_training=self.training,
916
+ ):
917
+ return None
918
+
919
+ dtype, device = input_tensor.dtype, input_tensor.device
920
+ min_dtype = torch.finfo(dtype).min
921
+ sequence_length = input_tensor.shape[1]
922
+ if using_static_cache:
923
+ target_length = past_key_values.get_max_length()
924
+ else:
925
+ target_length = (
926
+ attention_mask.shape[-1]
927
+ if isinstance(attention_mask, torch.Tensor)
928
+ else past_seen_tokens + sequence_length + 1
929
+ )
930
+
931
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
932
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
933
+ attention_mask,
934
+ sequence_length=sequence_length,
935
+ target_length=target_length,
936
+ dtype=dtype,
937
+ device=device,
938
+ min_dtype=min_dtype,
939
+ cache_position=cache_position,
940
+ batch_size=input_tensor.shape[0],
941
+ )
942
+
943
+ if (
944
+ self.config._attn_implementation == "sdpa"
945
+ and attention_mask is not None
946
+ and attention_mask.device.type == "cuda"
947
+ and not output_attentions
948
+ ):
949
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
950
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
951
+ # Details: https://github.com/pytorch/pytorch/issues/110213
952
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
953
+
954
+ return causal_mask
955
+
956
+
957
+ class NormHead(nn.Module):
958
+ def __init__(self, hidden_size, vocab_size, bias=False):
959
+ super().__init__()
960
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
961
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
962
+
963
+ def forward(self, hidden_states):
964
+ norm_weight = nn.functional.normalize(self.weight)
965
+ return nn.functional.linear(hidden_states, norm_weight)
966
+
967
+
968
+ class BaichuanM1ForCausalLM(BaichuanPreTrainedModel, GenerationMixin):
969
+ _tied_weights_keys = ["lm_head.weight"]
970
+
971
+ def __init__(self, config):
972
+ super().__init__(config)
973
+ self.model = BaichuanModel(config)
974
+ self.vocab_size = config.vocab_size
975
+ self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
976
+
977
+ # Initialize weights and apply final processing
978
+ self.post_init()
979
+
980
+ def get_input_embeddings(self):
981
+ return self.model.embed_tokens
982
+
983
+ def set_input_embeddings(self, value):
984
+ self.model.embed_tokens = value
985
+
986
+ def get_output_embeddings(self):
987
+ return self.lm_head
988
+
989
+ def set_output_embeddings(self, new_embeddings):
990
+ self.lm_head = new_embeddings
991
+
992
+ def set_decoder(self, decoder):
993
+ self.model = decoder
994
+
995
+ def get_decoder(self):
996
+ return self.model
997
+
998
+ @add_start_docstrings_to_model_forward(Baichuan_INPUTS_DOCSTRING)
999
+ def forward(
1000
+ self,
1001
+ input_ids: torch.LongTensor = None,
1002
+ attention_mask: Optional[torch.Tensor] = None,
1003
+ position_ids: Optional[torch.LongTensor] = None,
1004
+ seqlens: Optional[torch.LongTensor] = None,
1005
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1006
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1007
+ labels: Optional[torch.LongTensor] = None,
1008
+ use_cache: Optional[bool] = None,
1009
+ output_attentions: Optional[bool] = None,
1010
+ output_hidden_states: Optional[bool] = None,
1011
+ return_dict: Optional[bool] = None,
1012
+ cache_position: Optional[torch.LongTensor] = None,
1013
+ num_logits_to_keep: int = 0,
1014
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1015
+ r"""
1016
+ Args:
1017
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1018
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1019
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1020
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1021
+
1022
+ num_logits_to_keep (`int`, *optional*):
1023
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1024
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1025
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1026
+
1027
+ Returns:
1028
+
1029
+ Example:
1030
+
1031
+ ```python
1032
+ >>> from transformers import AutoTokenizer, BaichuanForCausalLM
1033
+
1034
+ >>> model = BaichuanForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1035
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1036
+
1037
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1038
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1039
+
1040
+ >>> # Generate
1041
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1042
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1043
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1044
+ ```"""
1045
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1046
+ output_hidden_states = (
1047
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1048
+ )
1049
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1050
+ if input_ids is not None:
1051
+ input_ids[input_ids == self.config.vocab_size] = 0
1052
+ if labels is not None:
1053
+ labels[labels == self.config.vocab_size] = 0
1054
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1055
+ outputs = self.model(
1056
+ input_ids=input_ids,
1057
+ attention_mask=attention_mask,
1058
+ position_ids=position_ids,
1059
+ seqlens=seqlens,
1060
+ past_key_values=past_key_values,
1061
+ inputs_embeds=inputs_embeds,
1062
+ use_cache=use_cache,
1063
+ output_attentions=output_attentions,
1064
+ output_hidden_states=output_hidden_states,
1065
+ return_dict=return_dict,
1066
+ cache_position=cache_position,
1067
+ )
1068
+
1069
+ hidden_states = outputs[0]
1070
+ if labels is None and not is_torchdynamo_compiling():
1071
+ logger.warning_once(
1072
+ "Starting from v4.46, the `logits` model output will have the same type as the model (except at train time, where it will always be FP32)"
1073
+ )
1074
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1075
+ # TODO: remove the float() operation in v4.46
1076
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1077
+
1078
+ loss = None
1079
+ if labels is not None:
1080
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1081
+ # logits = logits.float()
1082
+ # Shift so that tokens < n predict n
1083
+ shift_logits = logits[..., :-1, :].contiguous()
1084
+ shift_labels = labels[..., 1:].contiguous()
1085
+ #shift_logits = logits
1086
+ #shift_labels = labels
1087
+ # Flatten the tokens
1088
+ loss_fct = CrossEntropyLoss()
1089
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1090
+ shift_labels = shift_labels.view(-1)
1091
+ # Enable model parallelism
1092
+ shift_labels = shift_labels.to(shift_logits.device)
1093
+ loss = loss_fct(shift_logits, shift_labels)
1094
+
1095
+ if not return_dict:
1096
+ output = (logits,) + outputs[1:]
1097
+ return (loss,) + output if loss is not None else output
1098
+
1099
+ return CausalLMOutputWithPast(
1100
+ loss=loss,
1101
+ logits=logits,
1102
+ past_key_values=outputs.past_key_values,
1103
+ hidden_states=outputs.hidden_states,
1104
+ attentions=outputs.attentions,
1105
+ )
1106
+
1107
+ def prepare_inputs_for_generation(
1108
+ self,
1109
+ input_ids,
1110
+ past_key_values=None,
1111
+ attention_mask=None,
1112
+ inputs_embeds=None,
1113
+ cache_position=None,
1114
+ position_ids=None,
1115
+ use_cache=True,
1116
+ num_logits_to_keep=None,
1117
+ **kwargs,
1118
+ ):
1119
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1120
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1121
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1122
+ if past_key_values is not None:
1123
+ if inputs_embeds is not None: # Exception 1
1124
+ input_ids = input_ids[:, -cache_position.shape[0]:]
1125
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1126
+ input_ids = input_ids[:, cache_position]
1127
+
1128
+ if attention_mask is not None and position_ids is None:
1129
+ # create position_ids on the fly for batch generation
1130
+ position_ids = attention_mask.long().cumsum(-1) - 1
1131
+ position_ids.masked_fill_(attention_mask == 0, 1)
1132
+ if past_key_values:
1133
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1134
+
1135
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1136
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1137
+
1138
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1139
+ if inputs_embeds is not None and cache_position[0] == 0:
1140
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1141
+ else:
1142
+ # The clone here is for the same reason as for `position_ids`.
1143
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1144
+
1145
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1146
+ if model_inputs["inputs_embeds"] is not None:
1147
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1148
+ device = model_inputs["inputs_embeds"].device
1149
+ else:
1150
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1151
+ device = model_inputs["input_ids"].device
1152
+
1153
+ dtype = self.lm_head.weight.dtype
1154
+ min_dtype = torch.finfo(dtype).min
1155
+
1156
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1157
+ attention_mask,
1158
+ sequence_length=sequence_length,
1159
+ target_length=past_key_values.get_max_length(),
1160
+ dtype=dtype,
1161
+ device=device,
1162
+ min_dtype=min_dtype,
1163
+ cache_position=cache_position,
1164
+ batch_size=batch_size,
1165
+ )
1166
+
1167
+ if num_logits_to_keep is not None:
1168
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
1169
+
1170
+ model_inputs.update(
1171
+ {
1172
+ "position_ids": position_ids,
1173
+ "cache_position": cache_position,
1174
+ "past_key_values": past_key_values,
1175
+ "use_cache": use_cache,
1176
+ "attention_mask": attention_mask,
1177
+ }
1178
+ )
1179
+ return model_inputs
1180
+
1181
+ @torch.no_grad()
1182
+ def chat(self, tokenizer, messages: List[dict], stream=False,
1183
+ generation_config: Optional[GenerationConfig] = None):
1184
+ generation_config = generation_config or self.generation_config
1185
+ input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)
1186
+ input_ids = torch.LongTensor([input_ids]).to(self.device)
1187
+ if stream:
1188
+ streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
1189
+ Thread(target=self.generate, kwargs=dict(
1190
+ inputs=input_ids, streamer=streamer,
1191
+ generation_config=generation_config,
1192
+ )).start()
1193
+ return streamer
1194
+ else:
1195
+ outputs = self.generate(input_ids, generation_config=generation_config)
1196
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
1197
+ return response
special_tokens_map.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>",
16
+ "<B_SYS>",
17
+ "<B_USYS>",
18
+ "<C_Q>",
19
+ "<C_A>",
20
+ "<|im_sep|>",
21
+ "<|tool_call|>",
22
+ "<|arguments|>"
23
+ ],
24
+ "bos_token": {
25
+ "content": "<s>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "eos_token": {
32
+ "content": "</s>",
33
+ "lstrip": false,
34
+ "normalized": true,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ "pad_token": "<pad>",
39
+ "unk_token": {
40
+ "content": "<unk>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ }
46
+ }
tokenization_baichuan.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from shutil import copyfile
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import sentencepiece as spm
6
+
7
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
8
+ from transformers.utils import logging
9
+
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
14
+
15
+ PRETRAINED_VOCAB_FILES_MAP = {
16
+ "vocab_file": {},
17
+ "tokenizer_file": {},
18
+ }
19
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
20
+
21
+
22
+ class BaichuanTokenizer(PreTrainedTokenizer):
23
+ """
24
+ Construct a Baichuan tokenizer. Based on byte-level Byte-Pair-Encoding.
25
+
26
+ Args:
27
+ vocab_file (`str`):
28
+ Path to the vocabulary file.
29
+ """
30
+
31
+ vocab_files_names = VOCAB_FILES_NAMES
32
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
33
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
34
+ model_input_names = ["input_ids", "attention_mask"]
35
+
36
+ def __init__(
37
+ self,
38
+ vocab_file,
39
+ unk_token="<unk>",
40
+ bos_token="<s>",
41
+ eos_token="</s>",
42
+ pad_token=None,
43
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
44
+ add_bos_token=True,
45
+ add_eos_token=False,
46
+ clean_up_tokenization_spaces=False,
47
+ **kwargs,
48
+ ):
49
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
50
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
51
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
52
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
53
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
54
+ self.vocab_file = vocab_file
55
+ self.add_bos_token = add_bos_token
56
+ self.add_eos_token = add_eos_token
57
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
58
+ self.sp_model.Load(vocab_file)
59
+ super().__init__(
60
+ bos_token=bos_token,
61
+ eos_token=eos_token,
62
+ unk_token=unk_token,
63
+ pad_token=pad_token,
64
+ add_bos_token=add_bos_token,
65
+ add_eos_token=add_eos_token,
66
+ sp_model_kwargs=self.sp_model_kwargs,
67
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
68
+ **kwargs,
69
+ )
70
+ self.pad_token_id = self._convert_token_to_id(self.pad_token)
71
+
72
+ def __getstate__(self):
73
+ state = self.__dict__.copy()
74
+ state["sp_model"] = None
75
+ return state
76
+
77
+ def __setstate__(self, d):
78
+ self.__dict__ = d
79
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
80
+ self.sp_model.Load(self.vocab_file)
81
+
82
+ @property
83
+ def vocab_size(self):
84
+ """Returns vocab size"""
85
+ return self.sp_model.get_piece_size()
86
+
87
+ def get_vocab(self):
88
+ """Returns vocab as a dict"""
89
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
90
+ vocab.update(self.added_tokens_encoder)
91
+ return vocab
92
+
93
+ def _tokenize(self, text):
94
+ """Returns a tokenized string."""
95
+ return self.sp_model.encode(text, out_type=str)
96
+
97
+ def _convert_token_to_id(self, token):
98
+ """Converts a token (str) in an id using the vocab."""
99
+ return self.sp_model.piece_to_id(token)
100
+
101
+ def _convert_id_to_token(self, index):
102
+ """Converts an index (integer) in a token (str) using the vocab."""
103
+ token = self.sp_model.IdToPiece(index)
104
+ return token
105
+
106
+ def convert_tokens_to_string(self, tokens):
107
+ """Converts a sequence of tokens (string) in a single string."""
108
+ current_sub_tokens = []
109
+ out_string = ""
110
+ prev_is_special = False
111
+ for i, token in enumerate(tokens):
112
+ # make sure that special tokens are not decoded using sentencepiece model
113
+ if token in self.all_special_tokens:
114
+ if not prev_is_special and i != 0:
115
+ out_string += " "
116
+ out_string += self.sp_model.decode(current_sub_tokens) + token
117
+ prev_is_special = True
118
+ current_sub_tokens = []
119
+ else:
120
+ current_sub_tokens.append(token)
121
+ prev_is_special = False
122
+ out_string += self.sp_model.decode(current_sub_tokens)
123
+ return out_string
124
+
125
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
126
+ """
127
+ Save the vocabulary and special tokens file to a directory.
128
+
129
+ Args:
130
+ save_directory (`str`):
131
+ The directory in which to save the vocabulary.
132
+
133
+ Returns:
134
+ `Tuple(str)`: Paths to the files saved.
135
+ """
136
+ if not os.path.isdir(save_directory):
137
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
138
+ return
139
+ out_vocab_file = os.path.join(
140
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
141
+ )
142
+
143
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
144
+ copyfile(self.vocab_file, out_vocab_file)
145
+ elif not os.path.isfile(self.vocab_file):
146
+ with open(out_vocab_file, "wb") as fi:
147
+ content_spiece_model = self.sp_model.serialized_model_proto()
148
+ fi.write(content_spiece_model)
149
+
150
+ return (out_vocab_file,)
151
+
152
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
153
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
154
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
155
+
156
+ output = bos_token_id + token_ids_0 + eos_token_id
157
+
158
+ if token_ids_1 is not None:
159
+ output = output + bos_token_id + token_ids_1 + eos_token_id
160
+
161
+ return output
162
+
163
+ def get_special_tokens_mask(
164
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
165
+ ) -> List[int]:
166
+ """
167
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
168
+ special tokens using the tokenizer `prepare_for_model` method.
169
+
170
+ Args:
171
+ token_ids_0 (`List[int]`):
172
+ List of IDs.
173
+ token_ids_1 (`List[int]`, *optional*):
174
+ Optional second list of IDs for sequence pairs.
175
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
176
+ Whether or not the token list is already formatted with special tokens for the model.
177
+
178
+ Returns:
179
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
180
+ """
181
+ if already_has_special_tokens:
182
+ return super().get_special_tokens_mask(
183
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
184
+ )
185
+
186
+ bos_token_id = [1] if self.add_bos_token else []
187
+ eos_token_id = [1] if self.add_eos_token else []
188
+
189
+ if token_ids_1 is None:
190
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
191
+ return (
192
+ bos_token_id
193
+ + ([0] * len(token_ids_0))
194
+ + eos_token_id
195
+ + bos_token_id
196
+ + ([0] * len(token_ids_1))
197
+ + eos_token_id
198
+ )
199
+
200
+ def create_token_type_ids_from_sequences(
201
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
202
+ ) -> List[int]:
203
+ """
204
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
205
+ sequence pair mask has the following format:
206
+
207
+ ```
208
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
209
+ | first sequence | second sequence |
210
+ ```
211
+
212
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
213
+
214
+ Args:
215
+ token_ids_0 (`List[int]`):
216
+ List of ids.
217
+ token_ids_1 (`List[int]`, *optional*):
218
+ Optional second list of IDs for sequence pairs.
219
+
220
+ Returns:
221
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
222
+ """
223
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
224
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
225
+
226
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
227
+
228
+ if token_ids_1 is not None:
229
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
230
+
231
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f5af87706706ff930034b468c7f315c7da31de5f35d5b71a6458329ef5d9034
3
+ size 2224601
tokenizer_config.json ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<pad>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "50": {
38
+ "content": "<|im_start|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "51": {
46
+ "content": "<|im_end|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "52": {
54
+ "content": "<|object_ref_start|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "53": {
62
+ "content": "<|object_ref_end|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "54": {
70
+ "content": "<|box_start|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "55": {
78
+ "content": "<|box_end|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "56": {
86
+ "content": "<|quad_start|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "57": {
94
+ "content": "<|quad_end|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "58": {
102
+ "content": "<|vision_start|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "59": {
110
+ "content": "<|vision_end|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "60": {
118
+ "content": "<|vision_pad|>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "61": {
126
+ "content": "<|image_pad|>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "62": {
134
+ "content": "<|video_pad|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": true
140
+ },
141
+ "63": {
142
+ "content": "<tool_call>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "64": {
150
+ "content": "</tool_call>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "65": {
158
+ "content": "<|fim_prefix|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "66": {
166
+ "content": "<|fim_middle|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "67": {
174
+ "content": "<|fim_suffix|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "68": {
182
+ "content": "<|fim_pad|>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "69": {
190
+ "content": "<|repo_name|>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "70": {
198
+ "content": "<|file_sep|>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "71": {
206
+ "content": "<B_SYS>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": true
212
+ },
213
+ "72": {
214
+ "content": "<B_USYS>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "73": {
222
+ "content": "<C_Q>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "74": {
230
+ "content": "<C_A>",
231
+ "lstrip": false,
232
+ "normalized": true,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": false
236
+ },
237
+ "75": {
238
+ "content": "<B_FUNC>",
239
+ "lstrip": false,
240
+ "normalized": true,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": false
244
+ },
245
+ "76": {
246
+ "content": "<B_CODE>",
247
+ "lstrip": false,
248
+ "normalized": true,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": false
252
+ },
253
+ "77": {
254
+ "content": "<B_APE>",
255
+ "lstrip": false,
256
+ "normalized": true,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": false
260
+ },
261
+ "78": {
262
+ "content": "<function_calling>",
263
+ "lstrip": false,
264
+ "normalized": true,
265
+ "rstrip": false,
266
+ "single_word": false,
267
+ "special": false
268
+ },
269
+ "79": {
270
+ "content": "<calc_start>",
271
+ "lstrip": false,
272
+ "normalized": true,
273
+ "rstrip": false,
274
+ "single_word": false,
275
+ "special": false
276
+ },
277
+ "80": {
278
+ "content": "<calc_end>",
279
+ "lstrip": false,
280
+ "normalized": true,
281
+ "rstrip": false,
282
+ "single_word": false,
283
+ "special": false
284
+ },
285
+ "81": {
286
+ "content": "<inner_think>",
287
+ "lstrip": false,
288
+ "normalized": true,
289
+ "rstrip": false,
290
+ "single_word": false,
291
+ "special": false
292
+ },
293
+ "82": {
294
+ "content": "<|im_sep|>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": false,
298
+ "single_word": false,
299
+ "special": true
300
+ },
301
+ "83": {
302
+ "content": "<|tool_call|>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": false,
306
+ "single_word": false,
307
+ "special": true
308
+ },
309
+ "84": {
310
+ "content": "<|arguments|>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": false,
314
+ "single_word": false,
315
+ "special": true
316
+ },
317
+ "85": {
318
+ "content": "<|o1_step|>",
319
+ "lstrip": false,
320
+ "normalized": true,
321
+ "rstrip": false,
322
+ "single_word": false,
323
+ "special": false
324
+ },
325
+ "86": {
326
+ "content": "<|o1_answer|>",
327
+ "lstrip": false,
328
+ "normalized": true,
329
+ "rstrip": false,
330
+ "single_word": false,
331
+ "special": false
332
+ },
333
+ "87": {
334
+ "content": "<tree_node>",
335
+ "lstrip": false,
336
+ "normalized": true,
337
+ "rstrip": false,
338
+ "single_word": false,
339
+ "special": false
340
+ },
341
+ "88": {
342
+ "content": "</tree_node>",
343
+ "lstrip": false,
344
+ "normalized": true,
345
+ "rstrip": false,
346
+ "single_word": false,
347
+ "special": false
348
+ }
349
+ },
350
+ "additional_special_tokens": [
351
+ "<|im_start|>",
352
+ "<|im_end|>",
353
+ "<|object_ref_start|>",
354
+ "<|object_ref_end|>",
355
+ "<|box_start|>",
356
+ "<|box_end|>",
357
+ "<|quad_start|>",
358
+ "<|quad_end|>",
359
+ "<|vision_start|>",
360
+ "<|vision_end|>",
361
+ "<|vision_pad|>",
362
+ "<|image_pad|>",
363
+ "<|video_pad|>",
364
+ "<B_SYS>",
365
+ "<B_USYS>",
366
+ "<C_Q>",
367
+ "<C_A>",
368
+ "<|im_sep|>",
369
+ "<|tool_call|>",
370
+ "<|arguments|>"
371
+ ],
372
+ "auto_map": {
373
+ "AutoTokenizer": [
374
+ "tokenization_baichuan.BaichuanTokenizer",
375
+ null
376
+ ]
377
+ },
378
+ "bos_token": "<s>",
379
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' %}{{'<B_SYS>' + message['content']}}{% elif message['role'] == 'user_system' %}{{'<B_USYS>' + message['content']}}{% elif message['role'] == 'user' %}{{'<C_Q>' + message['content']}}{% elif message['role'] == 'assistant' %}{{'<C_A>' + message['content']}}{% elif message['role'] == 'function' %}{{'<B_FUNC>' + message['content']}}{% elif message['role'] == 'code' %}{{'<B_CODE>' + message['content']}}{% else %}{{ raise_exception('Invalid message role: ' + message['role']) }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{'<C_A>'}}{% endif %}",
380
+ "clean_up_tokenization_spaces": false,
381
+ "eos_token": "</s>",
382
+ "extra_special_tokens": {},
383
+ "model_max_length": 32768,
384
+ "pad_token": "<pad>",
385
+ "sp_model_kwargs": {},
386
+ "tokenizer_class": "BaichuanTokenizer",
387
+ "unk_token": "<unk>",
388
+ "use_fast": false
389
+ }