sdadas commited on
Commit
71a5b04
·
verified ·
1 Parent(s): 8907d49

Upload 19 files

Browse files
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 1536,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
2_Dense/config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "in_features": 1536,
3
+ "out_features": 1024,
4
+ "bias": true,
5
+ "activation_function": "torch.nn.modules.linear.Identity"
6
+ }
2_Dense/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06c7eefb8ed1001b66c96999936414d8a84662168af5485d2d725e55f8264c7e
3
+ size 6295712
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
chat_template.jinja ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {% for message in messages %}{{'<|im_start|>' + message['role'] + '
2
+ ' + message['content'] + '<|im_end|>' + '
3
+ '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
4
+ ' }}{% endif %}
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoModel": "modeling_qwen.Qwen2Model",
8
+ "AutoModelForCausalLM": "modeling_qwen.Qwen2ForCausalLM",
9
+ "AutoModelForSequenceClassification": "modeling_qwen.Qwen2ForSequenceClassification"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "eos_token_id": 151643,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 1536,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 8960,
17
+ "max_position_embeddings": 131072,
18
+ "max_window_layers": 21,
19
+ "model_type": "qwen2",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 28,
22
+ "num_key_value_heads": 2,
23
+ "rms_norm_eps": 1e-06,
24
+ "rope_theta": 1000000.0,
25
+ "sliding_window": 131072,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.42.3",
29
+ "use_cache": true,
30
+ "use_sliding_window": false,
31
+ "vocab_size": 151646
32
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "3.0.1",
4
+ "transformers": "4.42.3",
5
+ "pytorch": "2.3.1+cu121"
6
+ },
7
+ "prompts": {
8
+ "s2p_query": "Instruct: Given a web search query, retrieve relevant passages that answer the query.\nQuery: ",
9
+ "s2s_query": "Instruct: Retrieve semantically similar text.\nQuery: "
10
+ },
11
+ "default_prompt_name": null,
12
+ "similarity_fn_name": "cosine"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:605498dad77d08f7d749cb8f76f5d7c8fb666e128f7e3aa7f4571cf9531a7958
3
+ size 4994887136
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a137a414fb5f82d7408149462482a60fdb1d467051ab0c7494b2b905440a02c
3
+ size 1178224504
model.safetensors.index.json ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_parameters": 1543268864,
4
+ "total_size": 6173075456
5
+ },
6
+ "weight_map": {
7
+ "embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
11
+ "layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
12
+ "layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
13
+ "layers.0.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
14
+ "layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
15
+ "layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
16
+ "layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
17
+ "layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
18
+ "layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
19
+ "layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
20
+ "layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
23
+ "layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
24
+ "layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
25
+ "layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
26
+ "layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
27
+ "layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
28
+ "layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
29
+ "layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
30
+ "layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
31
+ "layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
32
+ "layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
35
+ "layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
36
+ "layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
37
+ "layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
38
+ "layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
39
+ "layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
40
+ "layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
41
+ "layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
42
+ "layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
43
+ "layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
44
+ "layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
47
+ "layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
48
+ "layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
49
+ "layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
50
+ "layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
51
+ "layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
52
+ "layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
53
+ "layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
54
+ "layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
55
+ "layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
56
+ "layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
59
+ "layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
60
+ "layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
61
+ "layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
62
+ "layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
63
+ "layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
64
+ "layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
65
+ "layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
66
+ "layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
67
+ "layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
68
+ "layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
71
+ "layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
72
+ "layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
73
+ "layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
74
+ "layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
75
+ "layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
76
+ "layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
77
+ "layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
78
+ "layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
79
+ "layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
80
+ "layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
83
+ "layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
84
+ "layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
85
+ "layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
86
+ "layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
87
+ "layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
88
+ "layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
89
+ "layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
90
+ "layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
91
+ "layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
92
+ "layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
93
+ "layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
94
+ "layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
95
+ "layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
96
+ "layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
97
+ "layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
98
+ "layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
99
+ "layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
100
+ "layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
101
+ "layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
102
+ "layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
103
+ "layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
104
+ "layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
105
+ "layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
106
+ "layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
107
+ "layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
108
+ "layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
109
+ "layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
110
+ "layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
111
+ "layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
112
+ "layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
113
+ "layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
114
+ "layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
115
+ "layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
116
+ "layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
118
+ "layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
119
+ "layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
120
+ "layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
121
+ "layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
122
+ "layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
123
+ "layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
124
+ "layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
125
+ "layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
126
+ "layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
127
+ "layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
128
+ "layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
129
+ "layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
130
+ "layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
131
+ "layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
132
+ "layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
133
+ "layers.18.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
134
+ "layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
135
+ "layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
136
+ "layers.18.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
137
+ "layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
138
+ "layers.18.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
139
+ "layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
140
+ "layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
141
+ "layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
142
+ "layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
143
+ "layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
144
+ "layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
145
+ "layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
146
+ "layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
147
+ "layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
148
+ "layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
149
+ "layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
150
+ "layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
151
+ "layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
152
+ "layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
153
+ "layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
154
+ "layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
155
+ "layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
156
+ "layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
157
+ "layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
158
+ "layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
159
+ "layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
160
+ "layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
161
+ "layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
162
+ "layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
163
+ "layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
164
+ "layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
165
+ "layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
166
+ "layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
167
+ "layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
168
+ "layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
169
+ "layers.20.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
170
+ "layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
171
+ "layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
172
+ "layers.20.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
173
+ "layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
174
+ "layers.20.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
175
+ "layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
176
+ "layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
177
+ "layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
178
+ "layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
179
+ "layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
180
+ "layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
181
+ "layers.21.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
182
+ "layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
183
+ "layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
184
+ "layers.21.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
185
+ "layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
186
+ "layers.21.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
187
+ "layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
188
+ "layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
189
+ "layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
190
+ "layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
191
+ "layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
192
+ "layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
193
+ "layers.22.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
194
+ "layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
195
+ "layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
196
+ "layers.22.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
197
+ "layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
198
+ "layers.22.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
199
+ "layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
200
+ "layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
201
+ "layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
202
+ "layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
203
+ "layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
204
+ "layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
205
+ "layers.23.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
206
+ "layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
207
+ "layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
208
+ "layers.23.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
209
+ "layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
210
+ "layers.23.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
211
+ "layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
212
+ "layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
213
+ "layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
214
+ "layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
215
+ "layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
216
+ "layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
217
+ "layers.24.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
218
+ "layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
219
+ "layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
220
+ "layers.24.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
221
+ "layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
222
+ "layers.24.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
223
+ "layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
224
+ "layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
225
+ "layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
226
+ "layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
227
+ "layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
228
+ "layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
229
+ "layers.25.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
230
+ "layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
231
+ "layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
232
+ "layers.25.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
233
+ "layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
234
+ "layers.25.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
235
+ "layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
236
+ "layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
237
+ "layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
238
+ "layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
239
+ "layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
240
+ "layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
241
+ "layers.26.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
242
+ "layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
243
+ "layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
244
+ "layers.26.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
245
+ "layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
246
+ "layers.26.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
247
+ "layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
248
+ "layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
249
+ "layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
250
+ "layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
251
+ "layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
252
+ "layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
253
+ "layers.27.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
254
+ "layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
255
+ "layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
256
+ "layers.27.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
257
+ "layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
258
+ "layers.27.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
259
+ "layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
260
+ "layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
261
+ "layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
262
+ "layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
263
+ "layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
264
+ "layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
265
+ "layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
266
+ "layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
267
+ "layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
268
+ "layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
269
+ "layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
270
+ "layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
271
+ "layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
272
+ "layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
273
+ "layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
274
+ "layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
275
+ "layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
276
+ "layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
277
+ "layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
278
+ "layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
279
+ "layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
280
+ "layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
281
+ "layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
282
+ "layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
283
+ "layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
284
+ "layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
285
+ "layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
286
+ "layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
287
+ "layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
288
+ "layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
289
+ "layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
290
+ "layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
291
+ "layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
292
+ "layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
293
+ "layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
294
+ "layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
295
+ "layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
296
+ "layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
297
+ "layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
298
+ "layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
299
+ "layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
300
+ "layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
301
+ "layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
302
+ "layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
303
+ "layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
304
+ "layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
305
+ "layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
306
+ "layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
307
+ "layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
308
+ "layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
309
+ "layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
310
+ "layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
311
+ "layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
312
+ "layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
313
+ "layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
314
+ "layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
315
+ "layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
316
+ "layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
317
+ "layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
318
+ "layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
319
+ "layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
320
+ "layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
321
+ "layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
322
+ "layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
323
+ "layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
324
+ "layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
325
+ "layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
326
+ "layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
327
+ "layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
328
+ "layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
329
+ "layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
330
+ "layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
331
+ "layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
332
+ "layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
333
+ "layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
334
+ "layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
335
+ "layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
336
+ "layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
337
+ "layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
338
+ "layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
339
+ "layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
340
+ "layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
341
+ "layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
342
+ "layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
343
+ "layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
344
+ "norm.weight": "model-00002-of-00002.safetensors"
345
+ }
346
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Qwen2 model."""
21
+ from transformers import Qwen2Config
22
+ import inspect
23
+ import math
24
+ import os
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
37
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+
48
+
49
+ if is_flash_attn_2_available():
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+
59
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
60
+ _CONFIG_FOR_DOC = "Qwen2Config"
61
+
62
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
63
+ "Qwen/Qwen2-7B-beta",
64
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
65
+ ]
66
+
67
+
68
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
69
+ def _get_unpad_data(attention_mask):
70
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
71
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
72
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
73
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
74
+ return (
75
+ indices,
76
+ cu_seqlens,
77
+ max_seqlen_in_batch,
78
+ )
79
+
80
+
81
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
82
+ class Qwen2RMSNorm(nn.Module):
83
+ def __init__(self, hidden_size, eps=1e-6):
84
+ """
85
+ Qwen2RMSNorm is equivalent to T5LayerNorm
86
+ """
87
+ super().__init__()
88
+ self.weight = nn.Parameter(torch.ones(hidden_size))
89
+ self.variance_epsilon = eps
90
+
91
+ def forward(self, hidden_states):
92
+ input_dtype = hidden_states.dtype
93
+ hidden_states = hidden_states.to(torch.float32)
94
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
95
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
96
+ return self.weight * hidden_states.to(input_dtype)
97
+
98
+
99
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
100
+ class Qwen2RotaryEmbedding(nn.Module):
101
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
102
+ super().__init__()
103
+
104
+ self.dim = dim
105
+ self.max_position_embeddings = max_position_embeddings
106
+ self.base = base
107
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
108
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
109
+
110
+ # Build here to make `torch.jit.trace` work.
111
+ self._set_cos_sin_cache(
112
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
113
+ )
114
+
115
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
116
+ self.max_seq_len_cached = seq_len
117
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
118
+
119
+ freqs = torch.outer(t, self.inv_freq)
120
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
121
+ emb = torch.cat((freqs, freqs), dim=-1)
122
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
123
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
124
+
125
+ def forward(self, x, seq_len=None):
126
+ # x: [bs, num_attention_heads, seq_len, head_size]
127
+ if seq_len > self.max_seq_len_cached:
128
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
129
+
130
+ return (
131
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
132
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
133
+ )
134
+
135
+
136
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
137
+ def rotate_half(x):
138
+ """Rotates half the hidden dims of the input."""
139
+ x1 = x[..., : x.shape[-1] // 2]
140
+ x2 = x[..., x.shape[-1] // 2 :]
141
+ return torch.cat((-x2, x1), dim=-1)
142
+
143
+
144
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
145
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
146
+ """Applies Rotary Position Embedding to the query and key tensors.
147
+
148
+ Args:
149
+ q (`torch.Tensor`): The query tensor.
150
+ k (`torch.Tensor`): The key tensor.
151
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
152
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
153
+ position_ids (`torch.Tensor`):
154
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
155
+ used to pass offsetted position ids when working with a KV-cache.
156
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
157
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
158
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
159
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
160
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
161
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
162
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
163
+ Returns:
164
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
165
+ """
166
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
167
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
168
+ q_embed = (q * cos) + (rotate_half(q) * sin)
169
+ k_embed = (k * cos) + (rotate_half(k) * sin)
170
+ return q_embed, k_embed
171
+
172
+
173
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
174
+ class Qwen2MLP(nn.Module):
175
+ def __init__(self, config):
176
+ super().__init__()
177
+ self.config = config
178
+ self.hidden_size = config.hidden_size
179
+ self.intermediate_size = config.intermediate_size
180
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
181
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
182
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
183
+ self.act_fn = ACT2FN[config.hidden_act]
184
+
185
+ def forward(self, x):
186
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
187
+
188
+
189
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
190
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
191
+ """
192
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
193
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
194
+ """
195
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
196
+ if n_rep == 1:
197
+ return hidden_states
198
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
199
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
200
+
201
+
202
+ class Qwen2Attention(nn.Module):
203
+ """
204
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
205
+ and "Generating Long Sequences with Sparse Transformers".
206
+ """
207
+
208
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
209
+ super().__init__()
210
+ self.config = config
211
+ self.layer_idx = layer_idx
212
+ if layer_idx is None:
213
+ logger.warning_once(
214
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
215
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
216
+ "when creating this class."
217
+ )
218
+
219
+ self.hidden_size = config.hidden_size
220
+ self.num_heads = config.num_attention_heads
221
+ self.head_dim = self.hidden_size // self.num_heads
222
+ self.num_key_value_heads = config.num_key_value_heads
223
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
224
+ self.max_position_embeddings = config.max_position_embeddings
225
+ self.rope_theta = config.rope_theta
226
+ self.is_causal = True
227
+ self.attention_dropout = config.attention_dropout
228
+
229
+ if (self.head_dim * self.num_heads) != self.hidden_size:
230
+ raise ValueError(
231
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
232
+ f" and `num_heads`: {self.num_heads})."
233
+ )
234
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
235
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
236
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
237
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
238
+
239
+ self.rotary_emb = Qwen2RotaryEmbedding(
240
+ self.head_dim,
241
+ max_position_embeddings=self.max_position_embeddings,
242
+ base=self.rope_theta,
243
+ )
244
+
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ attention_mask: Optional[torch.Tensor] = None,
249
+ position_ids: Optional[torch.LongTensor] = None,
250
+ past_key_value: Optional[Cache] = None,
251
+ output_attentions: bool = False,
252
+ use_cache: bool = False,
253
+ **kwargs,
254
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
255
+ if "padding_mask" in kwargs:
256
+ warnings.warn(
257
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
258
+ )
259
+ bsz, q_len, _ = hidden_states.size()
260
+
261
+ query_states = self.q_proj(hidden_states)
262
+ key_states = self.k_proj(hidden_states)
263
+ value_states = self.v_proj(hidden_states)
264
+
265
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
266
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
267
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
268
+
269
+ kv_seq_len = key_states.shape[-2]
270
+ if past_key_value is not None:
271
+ if self.layer_idx is None:
272
+ raise ValueError(
273
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
274
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
275
+ "with a layer index."
276
+ )
277
+ # kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
278
+ past_len = past_key_value.get_seq_length(self.layer_idx) if past_key_value is not None else 0
279
+ kv_seq_len += past_len
280
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
281
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
282
+
283
+ if past_key_value is not None:
284
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
285
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
286
+
287
+ # repeat k/v heads if n_kv_heads < n_heads
288
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
289
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
290
+
291
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
292
+
293
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
294
+ raise ValueError(
295
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
296
+ f" {attn_weights.size()}"
297
+ )
298
+
299
+ if attention_mask is not None:
300
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
301
+ raise ValueError(
302
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
303
+ )
304
+
305
+ attn_weights = attn_weights + attention_mask
306
+
307
+ # upcast attention to fp32
308
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
309
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
310
+ attn_output = torch.matmul(attn_weights, value_states)
311
+
312
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
313
+ raise ValueError(
314
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
315
+ f" {attn_output.size()}"
316
+ )
317
+
318
+ attn_output = attn_output.transpose(1, 2).contiguous()
319
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
320
+
321
+ attn_output = self.o_proj(attn_output)
322
+
323
+ if not output_attentions:
324
+ attn_weights = None
325
+
326
+ return attn_output, attn_weights, past_key_value
327
+
328
+
329
+ class Qwen2FlashAttention2(Qwen2Attention):
330
+ """
331
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
332
+ as the weights of the module stays untouched. The only required change would be on the forward pass
333
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
334
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
335
+ config.max_window_layers layers.
336
+ """
337
+
338
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
339
+ def __init__(self, *args, **kwargs):
340
+ super().__init__(*args, **kwargs)
341
+
342
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
343
+ # 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.
344
+ # 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).
345
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ attention_mask: Optional[torch.Tensor] = None,
351
+ position_ids: Optional[torch.LongTensor] = None,
352
+ past_key_value: Optional[Cache] = None,
353
+ output_attentions: bool = False,
354
+ use_cache: bool = False,
355
+ is_causal: bool = False,
356
+ **kwargs,
357
+ ):
358
+ if "padding_mask" in kwargs:
359
+ warnings.warn(
360
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
361
+ )
362
+
363
+ # overwrite attention_mask with padding_mask
364
+ attention_mask = kwargs.pop("padding_mask")
365
+ bsz, q_len, _ = hidden_states.size()
366
+
367
+ query_states = self.q_proj(hidden_states)
368
+ key_states = self.k_proj(hidden_states)
369
+ value_states = self.v_proj(hidden_states)
370
+
371
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
372
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
373
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
374
+
375
+ kv_seq_len = key_states.shape[-2]
376
+ if past_key_value is not None:
377
+ if self.layer_idx is None:
378
+ raise ValueError(
379
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
380
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
381
+ "with a layer index."
382
+ )
383
+ # kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
384
+ past_len = past_key_value.get_seq_length(self.layer_idx) if past_key_value is not None else 0
385
+ kv_seq_len += past_len
386
+
387
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
388
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
389
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
390
+
391
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
392
+
393
+ use_sliding_windows = (
394
+ _flash_supports_window_size
395
+ and getattr(self.config, "sliding_window", None) is not None
396
+ and kv_seq_len > self.config.sliding_window
397
+ and self.config.use_sliding_window
398
+ )
399
+
400
+ if not _flash_supports_window_size:
401
+ logger.warning_once(
402
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
403
+ " make sure to upgrade flash-attn library."
404
+ )
405
+
406
+ if past_key_value is not None:
407
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
408
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
409
+ if (
410
+ getattr(self.config, "sliding_window", None) is not None
411
+ and kv_seq_len > self.config.sliding_window
412
+ and cache_has_contents
413
+ ):
414
+ slicing_tokens = 1 - self.config.sliding_window
415
+
416
+ past_key = past_key_value[self.layer_idx][0]
417
+ past_value = past_key_value[self.layer_idx][1]
418
+
419
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
420
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
421
+
422
+ if past_key.shape[-2] != self.config.sliding_window - 1:
423
+ raise ValueError(
424
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
425
+ f" {past_key.shape}"
426
+ )
427
+
428
+ if attention_mask is not None:
429
+ attention_mask = attention_mask[:, slicing_tokens:]
430
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
431
+
432
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
433
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
434
+
435
+ # repeat k/v heads if n_kv_heads < n_heads
436
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
437
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
438
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
439
+
440
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
441
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
442
+ # cast them back in float16 just to be sure everything works as expected.
443
+ input_dtype = query_states.dtype
444
+ if input_dtype == torch.float32:
445
+ if torch.is_autocast_enabled():
446
+ target_dtype = torch.get_autocast_gpu_dtype()
447
+ # Handle the case where the model is quantized
448
+ elif hasattr(self.config, "_pre_quantization_dtype"):
449
+ target_dtype = self.config._pre_quantization_dtype
450
+ else:
451
+ target_dtype = self.q_proj.weight.dtype
452
+
453
+ logger.warning_once(
454
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
455
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
456
+ f" {target_dtype}."
457
+ )
458
+
459
+ query_states = query_states.to(target_dtype)
460
+ key_states = key_states.to(target_dtype)
461
+ value_states = value_states.to(target_dtype)
462
+
463
+ # Reashape to the expected shape for Flash Attention
464
+ query_states = query_states.transpose(1, 2)
465
+ key_states = key_states.transpose(1, 2)
466
+ value_states = value_states.transpose(1, 2)
467
+
468
+ attn_output = self._flash_attention_forward(
469
+ query_states,
470
+ key_states,
471
+ value_states,
472
+ attention_mask,
473
+ q_len,
474
+ dropout=dropout_rate,
475
+ use_sliding_windows=use_sliding_windows,
476
+ is_causal=is_causal
477
+ )
478
+
479
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
480
+ attn_output = self.o_proj(attn_output)
481
+
482
+ if not output_attentions:
483
+ attn_weights = None
484
+
485
+ return attn_output, attn_weights, past_key_value
486
+
487
+ def _flash_attention_forward(
488
+ self,
489
+ query_states,
490
+ key_states,
491
+ value_states,
492
+ attention_mask,
493
+ query_length,
494
+ dropout=0.0,
495
+ softmax_scale=None,
496
+ use_sliding_windows=False,
497
+ is_causal=True,
498
+ ):
499
+ """
500
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
501
+ first unpad the input, then computes the attention scores and pad the final attention scores.
502
+
503
+ Args:
504
+ query_states (`torch.Tensor`):
505
+ Input query states to be passed to Flash Attention API
506
+ key_states (`torch.Tensor`):
507
+ Input key states to be passed to Flash Attention API
508
+ value_states (`torch.Tensor`):
509
+ Input value states to be passed to Flash Attention API
510
+ attention_mask (`torch.Tensor`):
511
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
512
+ position of padding tokens and 1 for the position of non-padding tokens.
513
+ dropout (`int`, *optional*):
514
+ Attention dropout
515
+ softmax_scale (`float`, *optional*):
516
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
517
+ use_sliding_windows (`bool`, *optional*):
518
+ Whether to activate sliding window attention.
519
+ """
520
+ if not self._flash_attn_uses_top_left_mask:
521
+ causal = is_causal
522
+ else:
523
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
524
+ causal = is_causal and query_length != 1
525
+
526
+ # Decide whether to use SWA or not by layer index.
527
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
528
+ use_sliding_windows = False
529
+
530
+ # Contains at least one padding token in the sequence
531
+ if attention_mask is not None:
532
+ batch_size = query_states.shape[0]
533
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
534
+ query_states, key_states, value_states, attention_mask, query_length
535
+ )
536
+
537
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
538
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
539
+
540
+ if not use_sliding_windows:
541
+ attn_output_unpad = flash_attn_varlen_func(
542
+ query_states,
543
+ key_states,
544
+ value_states,
545
+ cu_seqlens_q=cu_seqlens_q,
546
+ cu_seqlens_k=cu_seqlens_k,
547
+ max_seqlen_q=max_seqlen_in_batch_q,
548
+ max_seqlen_k=max_seqlen_in_batch_k,
549
+ dropout_p=dropout,
550
+ softmax_scale=softmax_scale,
551
+ causal=causal,
552
+ )
553
+ else:
554
+ attn_output_unpad = flash_attn_varlen_func(
555
+ query_states,
556
+ key_states,
557
+ value_states,
558
+ cu_seqlens_q=cu_seqlens_q,
559
+ cu_seqlens_k=cu_seqlens_k,
560
+ max_seqlen_q=max_seqlen_in_batch_q,
561
+ max_seqlen_k=max_seqlen_in_batch_k,
562
+ dropout_p=dropout,
563
+ softmax_scale=softmax_scale,
564
+ causal=causal,
565
+ window_size=(self.config.sliding_window, self.config.sliding_window),
566
+ )
567
+
568
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
569
+ else:
570
+ if not use_sliding_windows:
571
+ attn_output = flash_attn_func(
572
+ query_states,
573
+ key_states,
574
+ value_states,
575
+ dropout,
576
+ softmax_scale=softmax_scale,
577
+ causal=causal,
578
+ )
579
+ else:
580
+ attn_output = flash_attn_func(
581
+ query_states,
582
+ key_states,
583
+ value_states,
584
+ dropout,
585
+ softmax_scale=softmax_scale,
586
+ causal=causal,
587
+ window_size=(self.config.sliding_window, self.config.sliding_window),
588
+ )
589
+
590
+ return attn_output
591
+
592
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
593
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
594
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
595
+
596
+ # On the first iteration we need to properly re-create the padding mask
597
+ # by slicing it on the proper place
598
+ if kv_seq_len != attention_mask.shape[-1]:
599
+ attention_mask_num_tokens = attention_mask.shape[-1]
600
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
601
+
602
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
603
+
604
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
605
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
606
+
607
+ if query_length == kv_seq_len:
608
+ query_layer = index_first_axis(
609
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
610
+ )
611
+ cu_seqlens_q = cu_seqlens_k
612
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
613
+ indices_q = indices_k
614
+ elif query_length == 1:
615
+ max_seqlen_in_batch_q = 1
616
+ cu_seqlens_q = torch.arange(
617
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
618
+ ) # There is a memcpy here, that is very bad.
619
+ indices_q = cu_seqlens_q[:-1]
620
+ query_layer = query_layer.squeeze(1)
621
+ else:
622
+ # The -q_len: slice assumes left padding.
623
+ attention_mask = attention_mask[:, -query_length:]
624
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
625
+
626
+ return (
627
+ query_layer,
628
+ key_layer,
629
+ value_layer,
630
+ indices_q,
631
+ (cu_seqlens_q, cu_seqlens_k),
632
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
633
+ )
634
+
635
+
636
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
637
+ class Qwen2SdpaAttention(Qwen2Attention):
638
+ """
639
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
640
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
641
+ SDPA API.
642
+ """
643
+
644
+ # Adapted from Qwen2Attention.forward
645
+ def forward(
646
+ self,
647
+ hidden_states: torch.Tensor,
648
+ attention_mask: Optional[torch.Tensor] = None,
649
+ position_ids: Optional[torch.LongTensor] = None,
650
+ past_key_value: Optional[Cache] = None,
651
+ output_attentions: bool = False,
652
+ use_cache: bool = False,
653
+ is_causal: bool = True,
654
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
655
+ if output_attentions:
656
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
657
+ logger.warning_once(
658
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
659
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
660
+ )
661
+ return super().forward(
662
+ hidden_states=hidden_states,
663
+ attention_mask=attention_mask,
664
+ position_ids=position_ids,
665
+ past_key_value=past_key_value,
666
+ output_attentions=output_attentions,
667
+ use_cache=use_cache,
668
+ is_causal=is_causal
669
+ )
670
+
671
+ bsz, q_len, _ = hidden_states.size()
672
+
673
+ query_states = self.q_proj(hidden_states)
674
+ key_states = self.k_proj(hidden_states)
675
+ value_states = self.v_proj(hidden_states)
676
+
677
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
678
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
679
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
680
+
681
+ kv_seq_len = key_states.shape[-2]
682
+ if past_key_value is not None:
683
+ # kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
684
+ past_len = past_key_value.get_seq_length(self.layer_idx) if past_key_value is not None else 0
685
+ kv_seq_len += past_len
686
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
687
+
688
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
689
+
690
+ if past_key_value is not None:
691
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
692
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
693
+
694
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
695
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
696
+
697
+ if attention_mask is not None:
698
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
699
+ raise ValueError(
700
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
701
+ )
702
+
703
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
704
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
705
+ if query_states.device.type == "cuda" and attention_mask is not None:
706
+ query_states = query_states.contiguous()
707
+ key_states = key_states.contiguous()
708
+ value_states = value_states.contiguous()
709
+
710
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
711
+ query_states,
712
+ key_states,
713
+ value_states,
714
+ attn_mask=attention_mask,
715
+ dropout_p=self.attention_dropout if self.training else 0.0,
716
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
717
+ is_causal=is_causal and attention_mask is None and q_len > 1,
718
+ )
719
+
720
+ attn_output = attn_output.transpose(1, 2).contiguous()
721
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
722
+
723
+ attn_output = self.o_proj(attn_output)
724
+
725
+ return attn_output, None, past_key_value
726
+
727
+
728
+ QWEN2_ATTENTION_CLASSES = {
729
+ "eager": Qwen2Attention,
730
+ "flash_attention_2": Qwen2FlashAttention2,
731
+ "sdpa": Qwen2SdpaAttention,
732
+ }
733
+
734
+
735
+ class Qwen2DecoderLayer(nn.Module):
736
+ def __init__(self, config: Qwen2Config, layer_idx: int):
737
+ super().__init__()
738
+ self.hidden_size = config.hidden_size
739
+
740
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
741
+ logger.warning_once(
742
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
743
+ "unexpected results may be encountered."
744
+ )
745
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
746
+
747
+ self.mlp = Qwen2MLP(config)
748
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
749
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
750
+
751
+ def forward(
752
+ self,
753
+ hidden_states: torch.Tensor,
754
+ attention_mask: Optional[torch.Tensor] = None,
755
+ position_ids: Optional[torch.LongTensor] = None,
756
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
757
+ output_attentions: Optional[bool] = False,
758
+ use_cache: Optional[bool] = False,
759
+ is_causal: Optional[bool] = True,
760
+ **kwargs,
761
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
762
+ if "padding_mask" in kwargs:
763
+ warnings.warn(
764
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
765
+ "Please make sure use `attention_mask` instead.`"
766
+ )
767
+ """
768
+ Args:
769
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
770
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
771
+ `(batch, sequence_length)` where padding elements are indicated by 0.
772
+ output_attentions (`bool`, *optional*):
773
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
774
+ returned tensors for more detail.
775
+ use_cache (`bool`, *optional*):
776
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
777
+ (see `past_key_values`).
778
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
779
+ """
780
+
781
+ residual = hidden_states
782
+
783
+ hidden_states = self.input_layernorm(hidden_states)
784
+
785
+ # Self Attention
786
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
787
+ hidden_states=hidden_states,
788
+ attention_mask=attention_mask,
789
+ position_ids=position_ids,
790
+ past_key_value=past_key_value,
791
+ output_attentions=output_attentions,
792
+ use_cache=use_cache,
793
+ is_causal=is_causal,
794
+ )
795
+ hidden_states = residual + hidden_states
796
+
797
+ # Fully Connected
798
+ residual = hidden_states
799
+ hidden_states = self.post_attention_layernorm(hidden_states)
800
+ hidden_states = self.mlp(hidden_states)
801
+ hidden_states = residual + hidden_states
802
+
803
+ outputs = (hidden_states,)
804
+
805
+ if output_attentions:
806
+ outputs += (self_attn_weights,)
807
+
808
+ if use_cache:
809
+ outputs += (present_key_value,)
810
+
811
+ return outputs
812
+
813
+
814
+ QWEN2_START_DOCSTRING = r"""
815
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
816
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
817
+ etc.)
818
+
819
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
820
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
821
+ and behavior.
822
+
823
+ Parameters:
824
+ config ([`Qwen2Config`]):
825
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
826
+ load the weights associated with the model, only the configuration. Check out the
827
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
828
+ """
829
+
830
+
831
+ @add_start_docstrings(
832
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
833
+ QWEN2_START_DOCSTRING,
834
+ )
835
+ class Qwen2PreTrainedModel(PreTrainedModel):
836
+ config_class = Qwen2Config
837
+ base_model_prefix = "model"
838
+ supports_gradient_checkpointing = True
839
+ _no_split_modules = ["Qwen2DecoderLayer"]
840
+ _skip_keys_device_placement = "past_key_values"
841
+ _supports_flash_attn_2 = True
842
+ _supports_sdpa = True
843
+ _supports_cache_class = True
844
+
845
+ def _init_weights(self, module):
846
+ std = self.config.initializer_range
847
+ if isinstance(module, nn.Linear):
848
+ module.weight.data.normal_(mean=0.0, std=std)
849
+ if module.bias is not None:
850
+ module.bias.data.zero_()
851
+ elif isinstance(module, nn.Embedding):
852
+ module.weight.data.normal_(mean=0.0, std=std)
853
+ if module.padding_idx is not None:
854
+ module.weight.data[module.padding_idx].zero_()
855
+
856
+
857
+ QWEN2_INPUTS_DOCSTRING = r"""
858
+ Args:
859
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
860
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
861
+ it.
862
+
863
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
864
+ [`PreTrainedTokenizer.__call__`] for details.
865
+
866
+ [What are input IDs?](../glossary#input-ids)
867
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
868
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
869
+
870
+ - 1 for tokens that are **not masked**,
871
+ - 0 for tokens that are **masked**.
872
+
873
+ [What are attention masks?](../glossary#attention-mask)
874
+
875
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
876
+ [`PreTrainedTokenizer.__call__`] for details.
877
+
878
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
879
+ `past_key_values`).
880
+
881
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
882
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
883
+ information on the default strategy.
884
+
885
+ - 1 indicates the head is **not masked**,
886
+ - 0 indicates the head is **masked**.
887
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
888
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
889
+ config.n_positions - 1]`.
890
+
891
+ [What are position IDs?](../glossary#position-ids)
892
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
893
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
894
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
895
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
896
+
897
+ Two formats are allowed:
898
+ - a [`~cache_utils.Cache`] instance;
899
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
900
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
901
+ cache format.
902
+
903
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
904
+ legacy cache format will be returned.
905
+
906
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
907
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
908
+ of shape `(batch_size, sequence_length)`.
909
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
910
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
911
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
912
+ model's internal embedding lookup matrix.
913
+ use_cache (`bool`, *optional*):
914
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
915
+ `past_key_values`).
916
+ output_attentions (`bool`, *optional*):
917
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
918
+ tensors for more detail.
919
+ output_hidden_states (`bool`, *optional*):
920
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
921
+ more detail.
922
+ return_dict (`bool`, *optional*):
923
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
924
+ """
925
+
926
+
927
+ @add_start_docstrings(
928
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
929
+ QWEN2_START_DOCSTRING,
930
+ )
931
+ class Qwen2Model(Qwen2PreTrainedModel):
932
+ """
933
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
934
+
935
+ Args:
936
+ config: Qwen2Config
937
+ """
938
+
939
+ def __init__(self, config: Qwen2Config):
940
+ super().__init__(config)
941
+ self.padding_idx = config.pad_token_id
942
+ self.vocab_size = config.vocab_size
943
+
944
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
945
+ self.layers = nn.ModuleList(
946
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
947
+ )
948
+ self._attn_implementation = config._attn_implementation
949
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
950
+
951
+ self.gradient_checkpointing = False
952
+ # Initialize weights and apply final processing
953
+ self.post_init()
954
+
955
+ def get_input_embeddings(self):
956
+ return self.embed_tokens
957
+
958
+ def set_input_embeddings(self, value):
959
+ self.embed_tokens = value
960
+
961
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
962
+ def forward(
963
+ self,
964
+ input_ids: torch.LongTensor = None,
965
+ attention_mask: Optional[torch.Tensor] = None,
966
+ position_ids: Optional[torch.LongTensor] = None,
967
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
968
+ inputs_embeds: Optional[torch.FloatTensor] = None,
969
+ use_cache: Optional[bool] = None,
970
+ output_attentions: Optional[bool] = None,
971
+ output_hidden_states: Optional[bool] = None,
972
+ return_dict: Optional[bool] = None,
973
+ labels: Optional[torch.LongTensor] = None,
974
+ is_causal: Optional[bool] = False,
975
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
976
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
977
+ output_hidden_states = (
978
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
979
+ )
980
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
981
+
982
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
983
+
984
+ # retrieve input_ids and inputs_embeds
985
+ if input_ids is not None and inputs_embeds is not None:
986
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
987
+ elif input_ids is not None:
988
+ batch_size, seq_length = input_ids.shape
989
+ elif inputs_embeds is not None:
990
+ batch_size, seq_length, _ = inputs_embeds.shape
991
+ else:
992
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
993
+
994
+ if self.gradient_checkpointing and self.training:
995
+ if use_cache:
996
+ logger.warning_once(
997
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
998
+ )
999
+ use_cache = False
1000
+
1001
+ past_key_values_length = 0
1002
+ use_legacy_cache = False
1003
+
1004
+ if use_cache:
1005
+ # OLD behavior (removed in HF >= 4.55): treat anything not Cache as "legacy" but then
1006
+ # directly used legacy methods on it (would crash if None or new API).
1007
+ # use_legacy_cache = not isinstance(past_key_values, Cache)
1008
+ # if use_legacy_cache:
1009
+ # # past_key_values_length = past_key_values.get_seq_length()
1010
+ # past_key_values_length = past_key_values.get_usable_length(seq_length)
1011
+
1012
+ # NEW behavior: if a legacy tuple is passed, convert it to the new Cache API,
1013
+ # compute length via .get_seq_length(), and remember to return legacy if that’s what came in.
1014
+ if past_key_values is not None and not isinstance(past_key_values, Cache):
1015
+ use_legacy_cache = True # remember input format for return
1016
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1017
+
1018
+ if isinstance(past_key_values, Cache):
1019
+ # Layer-agnostic total length; cache_position is handled deeper if needed
1020
+ past_key_values_length = past_key_values.get_seq_length()
1021
+ else:
1022
+ # No cache given on first forward, keep length at 0
1023
+ past_key_values_length = 0
1024
+
1025
+ if position_ids is None:
1026
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1027
+ position_ids = torch.arange(
1028
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1029
+ )
1030
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1031
+ else:
1032
+ position_ids = position_ids.view(-1, seq_length).long()
1033
+
1034
+ if inputs_embeds is None:
1035
+ inputs_embeds = self.embed_tokens(input_ids)
1036
+
1037
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1038
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1039
+ if is_padding_right:
1040
+ raise ValueError(
1041
+ "You are attempting to perform batched generation with padding_side='right'"
1042
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1043
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1044
+ )
1045
+
1046
+ if self._attn_implementation == "flash_attention_2":
1047
+ # 2d mask is passed through the layers
1048
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1049
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1050
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1051
+ # the manual implementation that requires a 4D causal mask in all cases.
1052
+ if is_causal:
1053
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1054
+ attention_mask,
1055
+ (batch_size, seq_length),
1056
+ inputs_embeds,
1057
+ past_key_values_length,
1058
+ )
1059
+ else:
1060
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1061
+ attention_mask, inputs_embeds.dtype
1062
+ )
1063
+ else:
1064
+ # 4d mask is passed through the layers
1065
+ if is_causal:
1066
+ # Causal mask with -3.3895e+38 where no attention should be
1067
+ attention_mask = _prepare_4d_causal_attention_mask(
1068
+ attention_mask,
1069
+ (batch_size, seq_length),
1070
+ inputs_embeds,
1071
+ past_key_values_length,
1072
+ sliding_window=self.config.sliding_window,
1073
+ )
1074
+ else:
1075
+ # Shape: batch_size, 1, query_length, key_value_length
1076
+ attention_mask = _prepare_4d_attention_mask(
1077
+ attention_mask, inputs_embeds.dtype
1078
+ )
1079
+
1080
+ hidden_states = inputs_embeds
1081
+
1082
+ # decoder layers
1083
+ all_hidden_states = () if output_hidden_states else None
1084
+ all_self_attns = () if output_attentions else None
1085
+ next_decoder_cache = None
1086
+
1087
+ for decoder_layer in self.layers:
1088
+ if output_hidden_states:
1089
+ all_hidden_states += (hidden_states,)
1090
+
1091
+ if self.gradient_checkpointing and self.training:
1092
+ layer_outputs = self._gradient_checkpointing_func(
1093
+ decoder_layer.__call__,
1094
+ hidden_states,
1095
+ attention_mask,
1096
+ position_ids,
1097
+ past_key_values,
1098
+ output_attentions,
1099
+ use_cache,
1100
+ is_causal,
1101
+ )
1102
+ else:
1103
+ layer_outputs = decoder_layer(
1104
+ hidden_states,
1105
+ attention_mask=attention_mask,
1106
+ position_ids=position_ids,
1107
+ past_key_value=past_key_values,
1108
+ output_attentions=output_attentions,
1109
+ use_cache=use_cache,
1110
+ is_causal=is_causal,
1111
+ )
1112
+
1113
+ hidden_states = layer_outputs[0]
1114
+
1115
+ if use_cache:
1116
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1117
+
1118
+ if output_attentions:
1119
+ all_self_attns += (layer_outputs[1],)
1120
+
1121
+ hidden_states = self.norm(hidden_states)
1122
+
1123
+ # add hidden states from the last decoder layer
1124
+ if output_hidden_states:
1125
+ all_hidden_states += (hidden_states,)
1126
+
1127
+ next_cache = None
1128
+ if use_cache:
1129
+ # If the caller passed legacy, return legacy. Otherwise return the Cache object.
1130
+ next_cache = (
1131
+ next_decoder_cache.to_legacy_cache() if
1132
+ (use_legacy_cache and next_decoder_cache is not None) else next_decoder_cache
1133
+ )
1134
+
1135
+ if not return_dict:
1136
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1137
+ return BaseModelOutputWithPast(
1138
+ last_hidden_state=hidden_states,
1139
+ past_key_values=next_cache,
1140
+ hidden_states=all_hidden_states,
1141
+ attentions=all_self_attns,
1142
+ )
1143
+
1144
+
1145
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1146
+ _tied_weights_keys = ["lm_head.weight"]
1147
+
1148
+ def __init__(self, config):
1149
+ super().__init__(config)
1150
+ self.model = Qwen2Model(config)
1151
+ self.vocab_size = config.vocab_size
1152
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1153
+
1154
+ # Initialize weights and apply final processing
1155
+ self.post_init()
1156
+
1157
+ def get_input_embeddings(self):
1158
+ return self.model.embed_tokens
1159
+
1160
+ def set_input_embeddings(self, value):
1161
+ self.model.embed_tokens = value
1162
+
1163
+ def get_output_embeddings(self):
1164
+ return self.lm_head
1165
+
1166
+ def set_output_embeddings(self, new_embeddings):
1167
+ self.lm_head = new_embeddings
1168
+
1169
+ def set_decoder(self, decoder):
1170
+ self.model = decoder
1171
+
1172
+ def get_decoder(self):
1173
+ return self.model
1174
+
1175
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1176
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1177
+ def forward(
1178
+ self,
1179
+ input_ids: torch.LongTensor = None,
1180
+ attention_mask: Optional[torch.Tensor] = None,
1181
+ position_ids: Optional[torch.LongTensor] = None,
1182
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1183
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1184
+ labels: Optional[torch.LongTensor] = None,
1185
+ use_cache: Optional[bool] = None,
1186
+ output_attentions: Optional[bool] = None,
1187
+ output_hidden_states: Optional[bool] = None,
1188
+ return_dict: Optional[bool] = None,
1189
+ is_causal: Optional[bool] = False,
1190
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1191
+ r"""
1192
+ Args:
1193
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1194
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1195
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1196
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1197
+
1198
+ Returns:
1199
+
1200
+ Example:
1201
+
1202
+ ```python
1203
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1204
+
1205
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1206
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1207
+
1208
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1209
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1210
+
1211
+ >>> # Generate
1212
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1213
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1214
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1215
+ ```"""
1216
+
1217
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1218
+ output_hidden_states = (
1219
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1220
+ )
1221
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1222
+
1223
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1224
+ outputs = self.model(
1225
+ input_ids=input_ids,
1226
+ attention_mask=attention_mask,
1227
+ position_ids=position_ids,
1228
+ past_key_values=past_key_values,
1229
+ inputs_embeds=inputs_embeds,
1230
+ use_cache=use_cache,
1231
+ output_attentions=output_attentions,
1232
+ output_hidden_states=output_hidden_states,
1233
+ return_dict=return_dict,
1234
+ is_causal=is_causal,
1235
+ )
1236
+
1237
+ hidden_states = outputs[0]
1238
+ logits = self.lm_head(hidden_states)
1239
+ logits = logits.float()
1240
+
1241
+ loss = None
1242
+ if labels is not None:
1243
+ # Shift so that tokens < n predict n
1244
+ shift_logits = logits[..., :-1, :].contiguous()
1245
+ shift_labels = labels[..., 1:].contiguous()
1246
+ # Flatten the tokens
1247
+ loss_fct = CrossEntropyLoss()
1248
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1249
+ shift_labels = shift_labels.view(-1)
1250
+ # Enable model parallelism
1251
+ shift_labels = shift_labels.to(shift_logits.device)
1252
+ loss = loss_fct(shift_logits, shift_labels)
1253
+
1254
+ if not return_dict:
1255
+ output = (logits,) + outputs[1:]
1256
+ return (loss,) + output if loss is not None else output
1257
+
1258
+ return CausalLMOutputWithPast(
1259
+ loss=loss,
1260
+ logits=logits,
1261
+ past_key_values=outputs.past_key_values,
1262
+ hidden_states=outputs.hidden_states,
1263
+ attentions=outputs.attentions,
1264
+ )
1265
+
1266
+ def prepare_inputs_for_generation(
1267
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1268
+ ):
1269
+ # Omit tokens covered by past_key_values
1270
+ if past_key_values is not None:
1271
+ if isinstance(past_key_values, Cache):
1272
+ # NEW API (HF >= 4.55): use Cache methods
1273
+ cache_length = past_key_values.get_seq_length()
1274
+ past_length = cache_length # `seen_tokens` removed; use total seq length instead
1275
+ try:
1276
+ max_cache_length = past_key_values.get_max_cache_shape()
1277
+ except Exception:
1278
+ max_cache_length = None
1279
+
1280
+ # OLD API (deprecated/removed):
1281
+ # cache_length = past_key_values.get_seq_length()
1282
+ # past_length = past_key_values.seen_tokens
1283
+ # max_cache_length = past_key_values.get_max_length()
1284
+ else:
1285
+ # Legacy tuple format: keep computing lengths directly from tensors
1286
+ # (We keep it compatible without forcing a conversion here)
1287
+ cache_length = past_length = past_key_values[0][0].shape[2]
1288
+ max_cache_length = None
1289
+
1290
+ # Keep only the unprocessed tokens:
1291
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1292
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1293
+ # input)
1294
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1295
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1296
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1297
+ # input_ids based on the past_length.
1298
+ elif past_length < input_ids.shape[1]:
1299
+ input_ids = input_ids[:, past_length:]
1300
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1301
+
1302
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1303
+ if (
1304
+ max_cache_length is not None
1305
+ and attention_mask is not None
1306
+ and cache_length + input_ids.shape[1] > max_cache_length
1307
+ ):
1308
+ attention_mask = attention_mask[:, -max_cache_length:]
1309
+
1310
+ position_ids = kwargs.get("position_ids", None)
1311
+ if attention_mask is not None and position_ids is None:
1312
+ # create position_ids on the fly for batch generation
1313
+ position_ids = attention_mask.long().cumsum(-1) - 1
1314
+ position_ids.masked_fill_(attention_mask == 0, 1)
1315
+ if past_key_values:
1316
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1317
+
1318
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1319
+ if inputs_embeds is not None and past_key_values is None:
1320
+ model_inputs = {"inputs_embeds": inputs_embeds}
1321
+ else:
1322
+ model_inputs = {"input_ids": input_ids}
1323
+
1324
+ model_inputs.update(
1325
+ {
1326
+ "position_ids": position_ids,
1327
+ "past_key_values": past_key_values, # pass through unchanged (legacy or new Cache object)
1328
+ "use_cache": kwargs.get("use_cache"),
1329
+ "attention_mask": attention_mask,
1330
+ }
1331
+ )
1332
+ return model_inputs
1333
+
1334
+ @staticmethod
1335
+ def _reorder_cache(past_key_values, beam_idx):
1336
+ reordered_past = ()
1337
+ for layer_past in past_key_values:
1338
+ reordered_past += (
1339
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1340
+ )
1341
+ return reordered_past
1342
+
1343
+
1344
+ @add_start_docstrings(
1345
+ """
1346
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1347
+
1348
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1349
+ (e.g. GPT-2) do.
1350
+
1351
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1352
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1353
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1354
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1355
+ each row of the batch).
1356
+ """,
1357
+ QWEN2_START_DOCSTRING,
1358
+ )
1359
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1360
+ def __init__(self, config):
1361
+ super().__init__(config)
1362
+ self.num_labels = config.num_labels
1363
+ self.model = Qwen2Model(config)
1364
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1365
+
1366
+ # Initialize weights and apply final processing
1367
+ self.post_init()
1368
+
1369
+ def get_input_embeddings(self):
1370
+ return self.model.embed_tokens
1371
+
1372
+ def set_input_embeddings(self, value):
1373
+ self.model.embed_tokens = value
1374
+
1375
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1376
+ def forward(
1377
+ self,
1378
+ input_ids: torch.LongTensor = None,
1379
+ attention_mask: Optional[torch.Tensor] = None,
1380
+ position_ids: Optional[torch.LongTensor] = None,
1381
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1382
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1383
+ labels: Optional[torch.LongTensor] = None,
1384
+ use_cache: Optional[bool] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ is_causal: Optional[bool] = True,
1389
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1390
+ r"""
1391
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1392
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1393
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1394
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1395
+ """
1396
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1397
+
1398
+ transformer_outputs = self.model(
1399
+ input_ids,
1400
+ attention_mask=attention_mask,
1401
+ position_ids=position_ids,
1402
+ past_key_values=past_key_values,
1403
+ inputs_embeds=inputs_embeds,
1404
+ use_cache=use_cache,
1405
+ output_attentions=output_attentions,
1406
+ output_hidden_states=output_hidden_states,
1407
+ return_dict=return_dict,
1408
+ is_causal=is_causal,
1409
+ )
1410
+ hidden_states = transformer_outputs[0]
1411
+ logits = self.score(hidden_states)
1412
+
1413
+ if input_ids is not None:
1414
+ batch_size = input_ids.shape[0]
1415
+ else:
1416
+ batch_size = inputs_embeds.shape[0]
1417
+
1418
+ if self.config.pad_token_id is None and batch_size != 1:
1419
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1420
+ if self.config.pad_token_id is None:
1421
+ sequence_lengths = -1
1422
+ else:
1423
+ if input_ids is not None:
1424
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1425
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1426
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1427
+ sequence_lengths = sequence_lengths.to(logits.device)
1428
+ else:
1429
+ sequence_lengths = -1
1430
+
1431
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1432
+
1433
+ loss = None
1434
+ if labels is not None:
1435
+ labels = labels.to(logits.device)
1436
+ if self.config.problem_type is None:
1437
+ if self.num_labels == 1:
1438
+ self.config.problem_type = "regression"
1439
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1440
+ self.config.problem_type = "single_label_classification"
1441
+ else:
1442
+ self.config.problem_type = "multi_label_classification"
1443
+
1444
+ if self.config.problem_type == "regression":
1445
+ loss_fct = MSELoss()
1446
+ if self.num_labels == 1:
1447
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1448
+ else:
1449
+ loss = loss_fct(pooled_logits, labels)
1450
+ elif self.config.problem_type == "single_label_classification":
1451
+ loss_fct = CrossEntropyLoss()
1452
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1453
+ elif self.config.problem_type == "multi_label_classification":
1454
+ loss_fct = BCEWithLogitsLoss()
1455
+ loss = loss_fct(pooled_logits, labels)
1456
+ if not return_dict:
1457
+ output = (pooled_logits,) + transformer_outputs[1:]
1458
+ return ((loss,) + output) if loss is not None else output
1459
+
1460
+ return SequenceClassifierOutputWithPast(
1461
+ loss=loss,
1462
+ logits=pooled_logits,
1463
+ past_key_values=transformer_outputs.past_key_values,
1464
+ hidden_states=transformer_outputs.hidden_states,
1465
+ attentions=transformer_outputs.attentions,
1466
+ )
modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Dense",
18
+ "type": "sentence_transformers.models.Dense"
19
+ }
20
+ ]
sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 8192,
3
+ "do_lower_case": false
4
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenization_qwen.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from typing import List, Optional
3
+ from transformers.models.qwen2.tokenization_qwen2 import Qwen2Tokenizer as OriginalQwen2Tokenizer
4
+ from transformers.models.qwen2.tokenization_qwen2_fast import Qwen2TokenizerFast as OriginalQwen2TokenizerFast
5
+ from tokenizers import processors
6
+
7
+ VOCAB_FILES_NAMES = {
8
+ "vocab_file": "vocab.json",
9
+ "merges_file": "merges.txt",
10
+ "tokenizer_file": "tokenizer.json",
11
+ }
12
+
13
+ class Qwen2Tokenizer(OriginalQwen2Tokenizer):
14
+ """
15
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
16
+
17
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
18
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
19
+
20
+ ```python
21
+ >>> from transformers import Qwen2Tokenizer
22
+
23
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
24
+ >>> tokenizer("Hello world")["input_ids"]
25
+ [9707, 1879]
26
+
27
+ >>> tokenizer(" Hello world")["input_ids"]
28
+ [21927, 1879]
29
+ ```
30
+ This is expected.
31
+
32
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
33
+
34
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
35
+ this superclass for more information regarding those methods.
36
+
37
+ Args:
38
+ vocab_file (`str`):
39
+ Path to the vocabulary file.
40
+ merges_file (`str`):
41
+ Path to the merges file.
42
+ errors (`str`, *optional*, defaults to `"replace"`):
43
+ Paradigm to follow when decoding bytes to UTF-8. See
44
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
45
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
46
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
47
+ token instead.
48
+ bos_token (`str`, *optional*):
49
+ The beginning of sequence token. Not applicable for this tokenizer.
50
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
51
+ The end of sequence token.
52
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
53
+ The token used for padding, for example when batching sequences of different lengths.
54
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
55
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
56
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
57
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
58
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
59
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
60
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
61
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
62
+ add_eos_token (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to add an `eos_token` at the end of sequences.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ vocab_file,
69
+ merges_file,
70
+ errors="replace",
71
+ unk_token="<|endoftext|>",
72
+ bos_token=None,
73
+ eos_token="<|endoftext|>",
74
+ pad_token="<|endoftext|>",
75
+ clean_up_tokenization_spaces=False,
76
+ split_special_tokens=False,
77
+ add_eos_token=False,
78
+ **kwargs,
79
+ ):
80
+ # The add_eos_token code was inspired by the LlamaTokenizer
81
+ self.add_eos_token = add_eos_token
82
+
83
+ super().__init__(
84
+ vocab_file=vocab_file,
85
+ merges_file=merges_file,
86
+ errors=errors,
87
+ unk_token=unk_token,
88
+ bos_token=bos_token,
89
+ eos_token=eos_token,
90
+ pad_token=pad_token,
91
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
92
+ split_special_tokens=split_special_tokens,
93
+ add_eos_token=add_eos_token,
94
+ **kwargs,
95
+ )
96
+
97
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
98
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
99
+
100
+ output = token_ids_0 + eos_token_id
101
+
102
+ if token_ids_1 is not None:
103
+ output = output + token_ids_1 + eos_token_id
104
+
105
+ return output
106
+
107
+ def get_special_tokens_mask(
108
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
109
+ ) -> List[int]:
110
+ """
111
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
112
+ special tokens using the tokenizer `prepare_for_model` method.
113
+
114
+ Args:
115
+ token_ids_0 (`List[int]`):
116
+ List of IDs.
117
+ token_ids_1 (`List[int]`, *optional*):
118
+ Optional second list of IDs for sequence pairs.
119
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
120
+ Whether or not the token list is already formatted with special tokens for the model.
121
+
122
+ Returns:
123
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
124
+ """
125
+ if already_has_special_tokens:
126
+ return super().get_special_tokens_mask(
127
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
128
+ )
129
+
130
+ eos_token_id = [1] if self.add_eos_token else []
131
+
132
+ if token_ids_1 is None:
133
+ return ([0] * len(token_ids_0)) + eos_token_id
134
+ return (
135
+ ([0] * len(token_ids_0))
136
+ + eos_token_id
137
+ + ([0] * len(token_ids_1))
138
+ + eos_token_id
139
+ )
140
+
141
+ def create_token_type_ids_from_sequences(
142
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
143
+ ) -> List[int]:
144
+ """
145
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
146
+ sequence pair mask has the following format:
147
+
148
+ ```
149
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
150
+ | first sequence | second sequence |
151
+ ```
152
+
153
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
154
+
155
+ Args:
156
+ token_ids_0 (`List[int]`):
157
+ List of ids.
158
+ token_ids_1 (`List[int]`, *optional*):
159
+ Optional second list of IDs for sequence pairs.
160
+
161
+ Returns:
162
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
163
+ """
164
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
165
+
166
+ output = [0] * len(token_ids_0 + eos_token_id)
167
+
168
+ if token_ids_1 is not None:
169
+ output += [1] * len(token_ids_1 + eos_token_id)
170
+
171
+ return output
172
+
173
+ class Qwen2TokenizerFast(OriginalQwen2TokenizerFast):
174
+ """
175
+ Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
176
+ Byte-Pair-Encoding.
177
+
178
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
179
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
180
+
181
+ ```python
182
+ >>> from transformers import Qwen2TokenizerFast
183
+
184
+ >>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
185
+ >>> tokenizer("Hello world")["input_ids"]
186
+ [9707, 1879]
187
+
188
+ >>> tokenizer(" Hello world")["input_ids"]
189
+ [21927, 1879]
190
+ ```
191
+ This is expected.
192
+
193
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
194
+ refer to this superclass for more information regarding those methods.
195
+
196
+ Args:
197
+ vocab_file (`str`, *optional*):
198
+ Path to the vocabulary file.
199
+ merges_file (`str`, *optional*):
200
+ Path to the merges file.
201
+ tokenizer_file (`str`, *optional*):
202
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
203
+ contains everything needed to load the tokenizer.
204
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
205
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
206
+ token instead. Not applicable to this tokenizer.
207
+ bos_token (`str`, *optional*):
208
+ The beginning of sequence token. Not applicable for this tokenizer.
209
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
210
+ The end of sequence token.
211
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
212
+ The token used for padding, for example when batching sequences of different lengths.
213
+ add_eos_token (`bool`, *optional*, defaults to `False`):
214
+ Whether or not to add an `eos_token` at the end of sequences.
215
+ """
216
+
217
+ slow_tokenizer_class = Qwen2Tokenizer
218
+ padding_side = "left"
219
+
220
+ def __init__(
221
+ self,
222
+ vocab_file=None,
223
+ merges_file=None,
224
+ tokenizer_file=None,
225
+ unk_token="<|endoftext|>",
226
+ bos_token=None,
227
+ eos_token="<|endoftext|>",
228
+ pad_token="<|endoftext|>",
229
+ add_eos_token=False,
230
+ **kwargs,
231
+ ):
232
+ super().__init__(
233
+ vocab_file=vocab_file,
234
+ merges_file=merges_file,
235
+ tokenizer_file=tokenizer_file,
236
+ unk_token=unk_token,
237
+ bos_token=bos_token,
238
+ eos_token=eos_token,
239
+ pad_token=pad_token,
240
+ **kwargs,
241
+ )
242
+
243
+ self._add_eos_token = add_eos_token
244
+ self.update_post_processor()
245
+
246
+ def update_post_processor(self):
247
+ """
248
+ Updates the underlying post processor with the current `eos_token`.
249
+ """
250
+ eos = self.eos_token
251
+ eos_token_id = self.eos_token_id
252
+ if eos is None and self.add_eos_token:
253
+ raise ValueError("add_eos_token = True but eos_token = None")
254
+
255
+ single = f"$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
256
+ pair = f"{single} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
257
+
258
+ special_tokens = []
259
+ if self.add_eos_token:
260
+ special_tokens.append((eos, eos_token_id))
261
+ self._tokenizer.post_processor = processors.TemplateProcessing(
262
+ single=single, pair=pair, special_tokens=special_tokens
263
+ )
264
+
265
+ @property
266
+ def add_eos_token(self):
267
+ return self._add_eos_token
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_eos_token": true,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "additional_special_tokens": [
31
+ "<|im_start|>",
32
+ "<|im_end|>"
33
+ ],
34
+ "auto_map": {
35
+ "AutoTokenizer": ["tokenization_qwen.Qwen2Tokenizer", "tokenization_qwen.Qwen2TokenizerFast"]
36
+ },
37
+ "bos_token": null,
38
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
39
+ "clean_up_tokenization_spaces": false,
40
+ "eos_token": "<|endoftext|>",
41
+ "errors": "replace",
42
+ "model_max_length": 32768,
43
+ "pad_token": "<|endoftext|>",
44
+ "split_special_tokens": false,
45
+ "tokenizer_class": "Qwen2Tokenizer",
46
+ "unk_token": null
47
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff