yzsydlc commited on
Commit
0166c5c
1 Parent(s): bc00829

Upload 15 files

Browse files
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Qwen/Qwen-7B",
3
+ "architectures": [
4
+ "QWenLMHeadModel"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "Qwen/Qwen-7B--configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "Qwen/Qwen-7B--modeling_qwen.QWenLMHeadModel"
10
+ },
11
+ "bf16": true,
12
+ "emb_dropout_prob": 0.0,
13
+ "fp16": false,
14
+ "fp32": false,
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 22016,
18
+ "kv_channels": 128,
19
+ "layer_norm_epsilon": 1e-06,
20
+ "max_position_embeddings": 32768,
21
+ "model_type": "qwen",
22
+ "no_bias": true,
23
+ "num_attention_heads": 32,
24
+ "num_hidden_layers": 32,
25
+ "onnx_safe": null,
26
+ "rotary_emb_base": 10000,
27
+ "rotary_pct": 1.0,
28
+ "scale_attn_weights": true,
29
+ "seq_length": 8192,
30
+ "softmax_in_fp32": false,
31
+ "tie_word_embeddings": false,
32
+ "tokenizer_class": "QWenTokenizer",
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.37.2",
35
+ "use_cache": true,
36
+ "use_cache_kernel": false,
37
+ "use_cache_quantization": false,
38
+ "use_dynamic_ntk": true,
39
+ "use_flash_attn": true,
40
+ "use_logn_attn": true,
41
+ "vocab_size": 151936
42
+ }
configuration_qwen.cpython-310.pyc ADDED
Binary file (1.69 kB). View file
 
configuration_qwen.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class QWenConfig(PretrainedConfig):
10
+ model_type = "qwen"
11
+ keys_to_ignore_at_inference = ["past_key_values"]
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=151936,
16
+ hidden_size=4096,
17
+ num_hidden_layers=32,
18
+ num_attention_heads=32,
19
+ emb_dropout_prob=0.0,
20
+ attn_dropout_prob=0.0,
21
+ layer_norm_epsilon=1e-6,
22
+ initializer_range=0.02,
23
+ max_position_embeddings=8192,
24
+ scale_attn_weights=True,
25
+ use_cache=True,
26
+ bf16=False,
27
+ fp16=False,
28
+ fp32=False,
29
+ kv_channels=128,
30
+ rotary_pct=1.0,
31
+ rotary_emb_base=10000,
32
+ use_dynamic_ntk=True,
33
+ use_logn_attn=True,
34
+ use_flash_attn="auto",
35
+ intermediate_size=22016,
36
+ no_bias=True,
37
+ tie_word_embeddings=False,
38
+ use_cache_quantization=False,
39
+ use_cache_kernel=False,
40
+ softmax_in_fp32=False,
41
+ **kwargs,
42
+ ):
43
+ self.vocab_size = vocab_size
44
+ self.hidden_size = hidden_size
45
+ self.intermediate_size = intermediate_size
46
+ self.num_hidden_layers = num_hidden_layers
47
+ self.num_attention_heads = num_attention_heads
48
+ self.emb_dropout_prob = emb_dropout_prob
49
+ self.attn_dropout_prob = attn_dropout_prob
50
+ self.layer_norm_epsilon = layer_norm_epsilon
51
+ self.initializer_range = initializer_range
52
+ self.scale_attn_weights = scale_attn_weights
53
+ self.use_cache = use_cache
54
+ self.max_position_embeddings = max_position_embeddings
55
+ self.bf16 = bf16
56
+ self.fp16 = fp16
57
+ self.fp32 = fp32
58
+ self.kv_channels = kv_channels
59
+ self.rotary_pct = rotary_pct
60
+ self.rotary_emb_base = rotary_emb_base
61
+ self.use_dynamic_ntk = use_dynamic_ntk
62
+ self.use_logn_attn = use_logn_attn
63
+ self.use_flash_attn = use_flash_attn
64
+ self.no_bias = no_bias
65
+ self.use_cache_quantization = use_cache_quantization
66
+ self.use_cache_kernel = use_cache_kernel
67
+ self.softmax_in_fp32 = softmax_in_fp32
68
+ super().__init__(
69
+ tie_word_embeddings=tie_word_embeddings,
70
+ **kwargs
71
+ )
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "raw",
3
+ "do_sample": true,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 512,
6
+ "pad_token_id": 151643,
7
+ "stop_words_ids": [
8
+ [
9
+ 151643
10
+ ]
11
+ ],
12
+ "top_k": 0,
13
+ "top_p": 0.8,
14
+ "transformers_version": "4.37.2"
15
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7e087e9d5a09b2c145a89f411f119c679eb1657e53f505df4d62e37673409c9
3
+ size 4955082528
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a45e0c3f05f11d4cd65c27f264a017768558f91267d17197cbd8450c4084b33
3
+ size 4011195992
model.safetensors.index.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 8966250496
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "transformer.h.0.attn.c_attn.bias": "model-00001-of-00002.safetensors",
8
+ "transformer.h.0.attn.c_attn.weight": "model-00001-of-00002.safetensors",
9
+ "transformer.h.0.attn.c_proj.weight": "model-00001-of-00002.safetensors",
10
+ "transformer.h.0.ln_1.weight": "model-00001-of-00002.safetensors",
11
+ "transformer.h.0.ln_2.weight": "model-00001-of-00002.safetensors",
12
+ "transformer.h.0.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
13
+ "transformer.h.0.mlp.w1.weight": "model-00001-of-00002.safetensors",
14
+ "transformer.h.0.mlp.w2.weight": "model-00001-of-00002.safetensors",
15
+ "transformer.h.1.attn.c_attn.bias": "model-00001-of-00002.safetensors",
16
+ "transformer.h.1.attn.c_attn.weight": "model-00001-of-00002.safetensors",
17
+ "transformer.h.1.attn.c_proj.weight": "model-00001-of-00002.safetensors",
18
+ "transformer.h.1.ln_1.weight": "model-00001-of-00002.safetensors",
19
+ "transformer.h.1.ln_2.weight": "model-00001-of-00002.safetensors",
20
+ "transformer.h.1.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
21
+ "transformer.h.1.mlp.w1.weight": "model-00001-of-00002.safetensors",
22
+ "transformer.h.1.mlp.w2.weight": "model-00001-of-00002.safetensors",
23
+ "transformer.h.10.attn.c_attn.bias": "model-00001-of-00002.safetensors",
24
+ "transformer.h.10.attn.c_attn.weight": "model-00001-of-00002.safetensors",
25
+ "transformer.h.10.attn.c_proj.weight": "model-00001-of-00002.safetensors",
26
+ "transformer.h.10.ln_1.weight": "model-00001-of-00002.safetensors",
27
+ "transformer.h.10.ln_2.weight": "model-00001-of-00002.safetensors",
28
+ "transformer.h.10.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
29
+ "transformer.h.10.mlp.w1.weight": "model-00001-of-00002.safetensors",
30
+ "transformer.h.10.mlp.w2.weight": "model-00001-of-00002.safetensors",
31
+ "transformer.h.11.attn.c_attn.bias": "model-00001-of-00002.safetensors",
32
+ "transformer.h.11.attn.c_attn.weight": "model-00001-of-00002.safetensors",
33
+ "transformer.h.11.attn.c_proj.weight": "model-00001-of-00002.safetensors",
34
+ "transformer.h.11.ln_1.weight": "model-00001-of-00002.safetensors",
35
+ "transformer.h.11.ln_2.weight": "model-00001-of-00002.safetensors",
36
+ "transformer.h.11.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
37
+ "transformer.h.11.mlp.w1.weight": "model-00001-of-00002.safetensors",
38
+ "transformer.h.11.mlp.w2.weight": "model-00001-of-00002.safetensors",
39
+ "transformer.h.12.attn.c_attn.bias": "model-00001-of-00002.safetensors",
40
+ "transformer.h.12.attn.c_attn.weight": "model-00001-of-00002.safetensors",
41
+ "transformer.h.12.attn.c_proj.weight": "model-00001-of-00002.safetensors",
42
+ "transformer.h.12.ln_1.weight": "model-00001-of-00002.safetensors",
43
+ "transformer.h.12.ln_2.weight": "model-00001-of-00002.safetensors",
44
+ "transformer.h.12.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
45
+ "transformer.h.12.mlp.w1.weight": "model-00001-of-00002.safetensors",
46
+ "transformer.h.12.mlp.w2.weight": "model-00001-of-00002.safetensors",
47
+ "transformer.h.13.attn.c_attn.bias": "model-00001-of-00002.safetensors",
48
+ "transformer.h.13.attn.c_attn.weight": "model-00001-of-00002.safetensors",
49
+ "transformer.h.13.attn.c_proj.weight": "model-00001-of-00002.safetensors",
50
+ "transformer.h.13.ln_1.weight": "model-00001-of-00002.safetensors",
51
+ "transformer.h.13.ln_2.weight": "model-00001-of-00002.safetensors",
52
+ "transformer.h.13.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
53
+ "transformer.h.13.mlp.w1.weight": "model-00001-of-00002.safetensors",
54
+ "transformer.h.13.mlp.w2.weight": "model-00001-of-00002.safetensors",
55
+ "transformer.h.14.attn.c_attn.bias": "model-00001-of-00002.safetensors",
56
+ "transformer.h.14.attn.c_attn.weight": "model-00001-of-00002.safetensors",
57
+ "transformer.h.14.attn.c_proj.weight": "model-00001-of-00002.safetensors",
58
+ "transformer.h.14.ln_1.weight": "model-00001-of-00002.safetensors",
59
+ "transformer.h.14.ln_2.weight": "model-00001-of-00002.safetensors",
60
+ "transformer.h.14.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
61
+ "transformer.h.14.mlp.w1.weight": "model-00001-of-00002.safetensors",
62
+ "transformer.h.14.mlp.w2.weight": "model-00001-of-00002.safetensors",
63
+ "transformer.h.15.attn.c_attn.bias": "model-00001-of-00002.safetensors",
64
+ "transformer.h.15.attn.c_attn.weight": "model-00001-of-00002.safetensors",
65
+ "transformer.h.15.attn.c_proj.weight": "model-00001-of-00002.safetensors",
66
+ "transformer.h.15.ln_1.weight": "model-00001-of-00002.safetensors",
67
+ "transformer.h.15.ln_2.weight": "model-00001-of-00002.safetensors",
68
+ "transformer.h.15.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
69
+ "transformer.h.15.mlp.w1.weight": "model-00001-of-00002.safetensors",
70
+ "transformer.h.15.mlp.w2.weight": "model-00001-of-00002.safetensors",
71
+ "transformer.h.16.attn.c_attn.bias": "model-00001-of-00002.safetensors",
72
+ "transformer.h.16.attn.c_attn.weight": "model-00001-of-00002.safetensors",
73
+ "transformer.h.16.attn.c_proj.weight": "model-00001-of-00002.safetensors",
74
+ "transformer.h.16.ln_1.weight": "model-00001-of-00002.safetensors",
75
+ "transformer.h.16.ln_2.weight": "model-00001-of-00002.safetensors",
76
+ "transformer.h.16.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
77
+ "transformer.h.16.mlp.w1.weight": "model-00001-of-00002.safetensors",
78
+ "transformer.h.16.mlp.w2.weight": "model-00001-of-00002.safetensors",
79
+ "transformer.h.17.attn.c_attn.bias": "model-00001-of-00002.safetensors",
80
+ "transformer.h.17.attn.c_attn.weight": "model-00001-of-00002.safetensors",
81
+ "transformer.h.17.attn.c_proj.weight": "model-00001-of-00002.safetensors",
82
+ "transformer.h.17.ln_1.weight": "model-00001-of-00002.safetensors",
83
+ "transformer.h.17.ln_2.weight": "model-00001-of-00002.safetensors",
84
+ "transformer.h.17.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
85
+ "transformer.h.17.mlp.w1.weight": "model-00001-of-00002.safetensors",
86
+ "transformer.h.17.mlp.w2.weight": "model-00001-of-00002.safetensors",
87
+ "transformer.h.18.attn.c_attn.bias": "model-00001-of-00002.safetensors",
88
+ "transformer.h.18.attn.c_attn.weight": "model-00001-of-00002.safetensors",
89
+ "transformer.h.18.attn.c_proj.weight": "model-00001-of-00002.safetensors",
90
+ "transformer.h.18.ln_1.weight": "model-00001-of-00002.safetensors",
91
+ "transformer.h.18.ln_2.weight": "model-00001-of-00002.safetensors",
92
+ "transformer.h.18.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
93
+ "transformer.h.18.mlp.w1.weight": "model-00002-of-00002.safetensors",
94
+ "transformer.h.18.mlp.w2.weight": "model-00002-of-00002.safetensors",
95
+ "transformer.h.19.attn.c_attn.bias": "model-00002-of-00002.safetensors",
96
+ "transformer.h.19.attn.c_attn.weight": "model-00002-of-00002.safetensors",
97
+ "transformer.h.19.attn.c_proj.weight": "model-00002-of-00002.safetensors",
98
+ "transformer.h.19.ln_1.weight": "model-00002-of-00002.safetensors",
99
+ "transformer.h.19.ln_2.weight": "model-00002-of-00002.safetensors",
100
+ "transformer.h.19.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
101
+ "transformer.h.19.mlp.w1.weight": "model-00002-of-00002.safetensors",
102
+ "transformer.h.19.mlp.w2.weight": "model-00002-of-00002.safetensors",
103
+ "transformer.h.2.attn.c_attn.bias": "model-00001-of-00002.safetensors",
104
+ "transformer.h.2.attn.c_attn.weight": "model-00001-of-00002.safetensors",
105
+ "transformer.h.2.attn.c_proj.weight": "model-00001-of-00002.safetensors",
106
+ "transformer.h.2.ln_1.weight": "model-00001-of-00002.safetensors",
107
+ "transformer.h.2.ln_2.weight": "model-00001-of-00002.safetensors",
108
+ "transformer.h.2.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
109
+ "transformer.h.2.mlp.w1.weight": "model-00001-of-00002.safetensors",
110
+ "transformer.h.2.mlp.w2.weight": "model-00001-of-00002.safetensors",
111
+ "transformer.h.20.attn.c_attn.bias": "model-00002-of-00002.safetensors",
112
+ "transformer.h.20.attn.c_attn.weight": "model-00002-of-00002.safetensors",
113
+ "transformer.h.20.attn.c_proj.weight": "model-00002-of-00002.safetensors",
114
+ "transformer.h.20.ln_1.weight": "model-00002-of-00002.safetensors",
115
+ "transformer.h.20.ln_2.weight": "model-00002-of-00002.safetensors",
116
+ "transformer.h.20.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
117
+ "transformer.h.20.mlp.w1.weight": "model-00002-of-00002.safetensors",
118
+ "transformer.h.20.mlp.w2.weight": "model-00002-of-00002.safetensors",
119
+ "transformer.h.21.attn.c_attn.bias": "model-00002-of-00002.safetensors",
120
+ "transformer.h.21.attn.c_attn.weight": "model-00002-of-00002.safetensors",
121
+ "transformer.h.21.attn.c_proj.weight": "model-00002-of-00002.safetensors",
122
+ "transformer.h.21.ln_1.weight": "model-00002-of-00002.safetensors",
123
+ "transformer.h.21.ln_2.weight": "model-00002-of-00002.safetensors",
124
+ "transformer.h.21.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
125
+ "transformer.h.21.mlp.w1.weight": "model-00002-of-00002.safetensors",
126
+ "transformer.h.21.mlp.w2.weight": "model-00002-of-00002.safetensors",
127
+ "transformer.h.22.attn.c_attn.bias": "model-00002-of-00002.safetensors",
128
+ "transformer.h.22.attn.c_attn.weight": "model-00002-of-00002.safetensors",
129
+ "transformer.h.22.attn.c_proj.weight": "model-00002-of-00002.safetensors",
130
+ "transformer.h.22.ln_1.weight": "model-00002-of-00002.safetensors",
131
+ "transformer.h.22.ln_2.weight": "model-00002-of-00002.safetensors",
132
+ "transformer.h.22.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
133
+ "transformer.h.22.mlp.w1.weight": "model-00002-of-00002.safetensors",
134
+ "transformer.h.22.mlp.w2.weight": "model-00002-of-00002.safetensors",
135
+ "transformer.h.23.attn.c_attn.bias": "model-00002-of-00002.safetensors",
136
+ "transformer.h.23.attn.c_attn.weight": "model-00002-of-00002.safetensors",
137
+ "transformer.h.23.attn.c_proj.weight": "model-00002-of-00002.safetensors",
138
+ "transformer.h.23.ln_1.weight": "model-00002-of-00002.safetensors",
139
+ "transformer.h.23.ln_2.weight": "model-00002-of-00002.safetensors",
140
+ "transformer.h.23.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
141
+ "transformer.h.23.mlp.w1.weight": "model-00002-of-00002.safetensors",
142
+ "transformer.h.23.mlp.w2.weight": "model-00002-of-00002.safetensors",
143
+ "transformer.h.24.attn.c_attn.bias": "model-00002-of-00002.safetensors",
144
+ "transformer.h.24.attn.c_attn.weight": "model-00002-of-00002.safetensors",
145
+ "transformer.h.24.attn.c_proj.weight": "model-00002-of-00002.safetensors",
146
+ "transformer.h.24.ln_1.weight": "model-00002-of-00002.safetensors",
147
+ "transformer.h.24.ln_2.weight": "model-00002-of-00002.safetensors",
148
+ "transformer.h.24.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
149
+ "transformer.h.24.mlp.w1.weight": "model-00002-of-00002.safetensors",
150
+ "transformer.h.24.mlp.w2.weight": "model-00002-of-00002.safetensors",
151
+ "transformer.h.25.attn.c_attn.bias": "model-00002-of-00002.safetensors",
152
+ "transformer.h.25.attn.c_attn.weight": "model-00002-of-00002.safetensors",
153
+ "transformer.h.25.attn.c_proj.weight": "model-00002-of-00002.safetensors",
154
+ "transformer.h.25.ln_1.weight": "model-00002-of-00002.safetensors",
155
+ "transformer.h.25.ln_2.weight": "model-00002-of-00002.safetensors",
156
+ "transformer.h.25.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
157
+ "transformer.h.25.mlp.w1.weight": "model-00002-of-00002.safetensors",
158
+ "transformer.h.25.mlp.w2.weight": "model-00002-of-00002.safetensors",
159
+ "transformer.h.26.attn.c_attn.bias": "model-00002-of-00002.safetensors",
160
+ "transformer.h.26.attn.c_attn.weight": "model-00002-of-00002.safetensors",
161
+ "transformer.h.26.attn.c_proj.weight": "model-00002-of-00002.safetensors",
162
+ "transformer.h.26.ln_1.weight": "model-00002-of-00002.safetensors",
163
+ "transformer.h.26.ln_2.weight": "model-00002-of-00002.safetensors",
164
+ "transformer.h.26.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
165
+ "transformer.h.26.mlp.w1.weight": "model-00002-of-00002.safetensors",
166
+ "transformer.h.26.mlp.w2.weight": "model-00002-of-00002.safetensors",
167
+ "transformer.h.27.attn.c_attn.bias": "model-00002-of-00002.safetensors",
168
+ "transformer.h.27.attn.c_attn.weight": "model-00002-of-00002.safetensors",
169
+ "transformer.h.27.attn.c_proj.weight": "model-00002-of-00002.safetensors",
170
+ "transformer.h.27.ln_1.weight": "model-00002-of-00002.safetensors",
171
+ "transformer.h.27.ln_2.weight": "model-00002-of-00002.safetensors",
172
+ "transformer.h.27.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
173
+ "transformer.h.27.mlp.w1.weight": "model-00002-of-00002.safetensors",
174
+ "transformer.h.27.mlp.w2.weight": "model-00002-of-00002.safetensors",
175
+ "transformer.h.28.attn.c_attn.bias": "model-00002-of-00002.safetensors",
176
+ "transformer.h.28.attn.c_attn.weight": "model-00002-of-00002.safetensors",
177
+ "transformer.h.28.attn.c_proj.weight": "model-00002-of-00002.safetensors",
178
+ "transformer.h.28.ln_1.weight": "model-00002-of-00002.safetensors",
179
+ "transformer.h.28.ln_2.weight": "model-00002-of-00002.safetensors",
180
+ "transformer.h.28.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
181
+ "transformer.h.28.mlp.w1.weight": "model-00002-of-00002.safetensors",
182
+ "transformer.h.28.mlp.w2.weight": "model-00002-of-00002.safetensors",
183
+ "transformer.h.29.attn.c_attn.bias": "model-00002-of-00002.safetensors",
184
+ "transformer.h.29.attn.c_attn.weight": "model-00002-of-00002.safetensors",
185
+ "transformer.h.29.attn.c_proj.weight": "model-00002-of-00002.safetensors",
186
+ "transformer.h.29.ln_1.weight": "model-00002-of-00002.safetensors",
187
+ "transformer.h.29.ln_2.weight": "model-00002-of-00002.safetensors",
188
+ "transformer.h.29.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
189
+ "transformer.h.29.mlp.w1.weight": "model-00002-of-00002.safetensors",
190
+ "transformer.h.29.mlp.w2.weight": "model-00002-of-00002.safetensors",
191
+ "transformer.h.3.attn.c_attn.bias": "model-00001-of-00002.safetensors",
192
+ "transformer.h.3.attn.c_attn.weight": "model-00001-of-00002.safetensors",
193
+ "transformer.h.3.attn.c_proj.weight": "model-00001-of-00002.safetensors",
194
+ "transformer.h.3.ln_1.weight": "model-00001-of-00002.safetensors",
195
+ "transformer.h.3.ln_2.weight": "model-00001-of-00002.safetensors",
196
+ "transformer.h.3.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
197
+ "transformer.h.3.mlp.w1.weight": "model-00001-of-00002.safetensors",
198
+ "transformer.h.3.mlp.w2.weight": "model-00001-of-00002.safetensors",
199
+ "transformer.h.30.attn.c_attn.bias": "model-00002-of-00002.safetensors",
200
+ "transformer.h.30.attn.c_attn.weight": "model-00002-of-00002.safetensors",
201
+ "transformer.h.30.attn.c_proj.weight": "model-00002-of-00002.safetensors",
202
+ "transformer.h.30.ln_1.weight": "model-00002-of-00002.safetensors",
203
+ "transformer.h.30.ln_2.weight": "model-00002-of-00002.safetensors",
204
+ "transformer.h.30.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
205
+ "transformer.h.30.mlp.w1.weight": "model-00002-of-00002.safetensors",
206
+ "transformer.h.30.mlp.w2.weight": "model-00002-of-00002.safetensors",
207
+ "transformer.h.31.attn.c_attn.bias": "model-00002-of-00002.safetensors",
208
+ "transformer.h.31.attn.c_attn.weight": "model-00002-of-00002.safetensors",
209
+ "transformer.h.31.attn.c_proj.weight": "model-00002-of-00002.safetensors",
210
+ "transformer.h.31.ln_1.weight": "model-00002-of-00002.safetensors",
211
+ "transformer.h.31.ln_2.weight": "model-00002-of-00002.safetensors",
212
+ "transformer.h.31.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
213
+ "transformer.h.31.mlp.w1.weight": "model-00002-of-00002.safetensors",
214
+ "transformer.h.31.mlp.w2.weight": "model-00002-of-00002.safetensors",
215
+ "transformer.h.4.attn.c_attn.bias": "model-00001-of-00002.safetensors",
216
+ "transformer.h.4.attn.c_attn.weight": "model-00001-of-00002.safetensors",
217
+ "transformer.h.4.attn.c_proj.weight": "model-00001-of-00002.safetensors",
218
+ "transformer.h.4.ln_1.weight": "model-00001-of-00002.safetensors",
219
+ "transformer.h.4.ln_2.weight": "model-00001-of-00002.safetensors",
220
+ "transformer.h.4.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
221
+ "transformer.h.4.mlp.w1.weight": "model-00001-of-00002.safetensors",
222
+ "transformer.h.4.mlp.w2.weight": "model-00001-of-00002.safetensors",
223
+ "transformer.h.5.attn.c_attn.bias": "model-00001-of-00002.safetensors",
224
+ "transformer.h.5.attn.c_attn.weight": "model-00001-of-00002.safetensors",
225
+ "transformer.h.5.attn.c_proj.weight": "model-00001-of-00002.safetensors",
226
+ "transformer.h.5.ln_1.weight": "model-00001-of-00002.safetensors",
227
+ "transformer.h.5.ln_2.weight": "model-00001-of-00002.safetensors",
228
+ "transformer.h.5.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
229
+ "transformer.h.5.mlp.w1.weight": "model-00001-of-00002.safetensors",
230
+ "transformer.h.5.mlp.w2.weight": "model-00001-of-00002.safetensors",
231
+ "transformer.h.6.attn.c_attn.bias": "model-00001-of-00002.safetensors",
232
+ "transformer.h.6.attn.c_attn.weight": "model-00001-of-00002.safetensors",
233
+ "transformer.h.6.attn.c_proj.weight": "model-00001-of-00002.safetensors",
234
+ "transformer.h.6.ln_1.weight": "model-00001-of-00002.safetensors",
235
+ "transformer.h.6.ln_2.weight": "model-00001-of-00002.safetensors",
236
+ "transformer.h.6.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
237
+ "transformer.h.6.mlp.w1.weight": "model-00001-of-00002.safetensors",
238
+ "transformer.h.6.mlp.w2.weight": "model-00001-of-00002.safetensors",
239
+ "transformer.h.7.attn.c_attn.bias": "model-00001-of-00002.safetensors",
240
+ "transformer.h.7.attn.c_attn.weight": "model-00001-of-00002.safetensors",
241
+ "transformer.h.7.attn.c_proj.weight": "model-00001-of-00002.safetensors",
242
+ "transformer.h.7.ln_1.weight": "model-00001-of-00002.safetensors",
243
+ "transformer.h.7.ln_2.weight": "model-00001-of-00002.safetensors",
244
+ "transformer.h.7.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
245
+ "transformer.h.7.mlp.w1.weight": "model-00001-of-00002.safetensors",
246
+ "transformer.h.7.mlp.w2.weight": "model-00001-of-00002.safetensors",
247
+ "transformer.h.8.attn.c_attn.bias": "model-00001-of-00002.safetensors",
248
+ "transformer.h.8.attn.c_attn.weight": "model-00001-of-00002.safetensors",
249
+ "transformer.h.8.attn.c_proj.weight": "model-00001-of-00002.safetensors",
250
+ "transformer.h.8.ln_1.weight": "model-00001-of-00002.safetensors",
251
+ "transformer.h.8.ln_2.weight": "model-00001-of-00002.safetensors",
252
+ "transformer.h.8.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
253
+ "transformer.h.8.mlp.w1.weight": "model-00001-of-00002.safetensors",
254
+ "transformer.h.8.mlp.w2.weight": "model-00001-of-00002.safetensors",
255
+ "transformer.h.9.attn.c_attn.bias": "model-00001-of-00002.safetensors",
256
+ "transformer.h.9.attn.c_attn.weight": "model-00001-of-00002.safetensors",
257
+ "transformer.h.9.attn.c_proj.weight": "model-00001-of-00002.safetensors",
258
+ "transformer.h.9.ln_1.weight": "model-00001-of-00002.safetensors",
259
+ "transformer.h.9.ln_2.weight": "model-00001-of-00002.safetensors",
260
+ "transformer.h.9.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
261
+ "transformer.h.9.mlp.w1.weight": "model-00001-of-00002.safetensors",
262
+ "transformer.h.9.mlp.w2.weight": "model-00001-of-00002.safetensors",
263
+ "transformer.ln_f.weight": "model-00002-of-00002.safetensors",
264
+ "transformer.wte.weight": "model-00001-of-00002.safetensors"
265
+ }
266
+ }
modeling_qwen.cpython-310.pyc ADDED
Binary file (36.4 kB). View file
 
modeling_qwen.py ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import copy
7
+ import importlib
8
+ import math
9
+ import pathlib
10
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ import torch.utils.checkpoint
15
+ import warnings
16
+
17
+ from torch.nn import CrossEntropyLoss
18
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
19
+ from transformers.generation.logits_process import LogitsProcessorList
20
+
21
+ if TYPE_CHECKING:
22
+ from transformers.generation.streamers import BaseStreamer
23
+ from transformers.generation.utils import GenerateOutput
24
+ from transformers.modeling_outputs import (
25
+ BaseModelOutputWithPast,
26
+ CausalLMOutputWithPast,
27
+ )
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import logging
30
+
31
+ try:
32
+ from einops import rearrange
33
+ except ImportError:
34
+ rearrange = None
35
+ from torch import nn
36
+
37
+ SUPPORT_CUDA = torch.cuda.is_available()
38
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
39
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
40
+ SUPPORT_TORCH2 = hasattr(torch, '__version__') and int(torch.__version__.split(".")[0]) >= 2
41
+
42
+
43
+ from configuration_qwen import QWenConfig
44
+ from qwen_generation_utils import (
45
+ HistoryType,
46
+ make_context,
47
+ decode_tokens,
48
+ get_stop_words_ids,
49
+ StopWordsLogitsProcessor,
50
+ )
51
+
52
+
53
+ print("\n\n\n\n\n\nddddddddddddddddddddddddd\n\n\n\n\n")
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CHECKPOINT_FOR_DOC = "qwen"
59
+ _CONFIG_FOR_DOC = "QWenConfig"
60
+
61
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
62
+
63
+ _ERROR_BAD_CHAT_FORMAT = """\
64
+ We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
65
+ If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
66
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
67
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
68
+ """
69
+
70
+ _SENTINEL = object()
71
+ _ERROR_STREAM_IN_CHAT = """\
72
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
73
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
74
+ """
75
+
76
+ _ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
77
+ We detect you have activated flash attention support, but running model computation on CPU. Please make sure that your input data has been placed on GPU. If you actually want to run CPU computation, please following the readme and set device_map="cpu" to disable flash attention when loading the model (calling AutoModelForCausalLM.from_pretrained).
78
+ 检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。
79
+ """
80
+
81
+ apply_rotary_emb_func = None
82
+ rms_norm = None
83
+ flash_attn_unpadded_func = None
84
+ flash_attn_func = None
85
+
86
+ def _import_flash_attn():
87
+ global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func, flash_attn_func
88
+ try:
89
+ from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
90
+ apply_rotary_emb_func = __apply_rotary_emb_func
91
+ except ImportError:
92
+ logger.warn(
93
+ "Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
94
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
95
+ )
96
+
97
+ try:
98
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
99
+ rms_norm = __rms_norm
100
+ except ImportError:
101
+ logger.warn(
102
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
103
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
104
+ )
105
+
106
+ try:
107
+ import flash_attn
108
+ _flash_attn_func = None
109
+ if not hasattr(flash_attn, '__version__'):
110
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
111
+ else:
112
+ if int(flash_attn.__version__.split(".")[0]) >= 2:
113
+ if int(flash_attn.__version__.split(".")[1]) >= 1:
114
+ from flash_attn.flash_attn_interface import flash_attn_func as _flash_attn_func
115
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
116
+ else:
117
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
118
+ flash_attn_unpadded_func = __flash_attn_unpadded_func
119
+ flash_attn_func = _flash_attn_func
120
+ except ImportError:
121
+ logger.warn(
122
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
123
+ "https://github.com/Dao-AILab/flash-attention"
124
+ )
125
+
126
+ def quantize_cache_v(fdata, bits, qmax, qmin):
127
+ # b, s, head, h-dim->b, head, s, h-dim
128
+ qtype = torch.uint8
129
+ device = fdata.device
130
+ shape = fdata.shape
131
+
132
+ fdata_cal = torch.flatten(fdata, 2)
133
+ fmax = torch.amax(fdata_cal, dim=-1, keepdim=True)
134
+ fmin = torch.amin(fdata_cal, dim=-1, keepdim=True)
135
+ # Compute params
136
+ if qmax.device != fmax.device:
137
+ qmax = qmax.to(device)
138
+ qmin = qmin.to(device)
139
+ scale = (fmax - fmin) / (qmax - qmin)
140
+ zero = qmin - fmin / scale
141
+ scale = scale.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
142
+ zero = zero.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
143
+ # Quantize
144
+ res_data = fdata / scale + zero
145
+ qdata = torch.clamp(res_data, qmin, qmax).to(qtype)
146
+ return qdata.contiguous(), scale, zero
147
+
148
+ def dequantize_cache_torch(qdata, scale, zero):
149
+ data = scale * (qdata - zero)
150
+ return data
151
+
152
+ class FlashSelfAttention(torch.nn.Module):
153
+ def __init__(
154
+ self,
155
+ causal=False,
156
+ softmax_scale=None,
157
+ attention_dropout=0.0,
158
+ ):
159
+ super().__init__()
160
+ assert flash_attn_unpadded_func is not None, (
161
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
162
+ )
163
+ assert (
164
+ rearrange is not None
165
+ ), "Please install einops first, e.g., with pip install einops"
166
+ self.causal = causal
167
+ self.softmax_scale = softmax_scale
168
+ self.dropout_p = attention_dropout
169
+
170
+ def unpad_input(self, hidden_states, attention_mask):
171
+ valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
172
+ seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
173
+ indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
174
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
175
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
176
+ hidden_states = hidden_states[indices]
177
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
178
+
179
+ def pad_input(self, hidden_states, indices, batch, seqlen):
180
+ output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
181
+ dtype=hidden_states.dtype)
182
+ output[indices] = hidden_states
183
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
184
+
185
+ def forward(self, q, k, v, attention_mask=None):
186
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
187
+ assert all((i.is_cuda for i in (q, k, v)))
188
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
189
+ seqlen_k = k.shape[1]
190
+ seqlen_out = seqlen_q
191
+
192
+ if flash_attn_func is not None and batch_size == 1:
193
+ dropout_p = self.dropout_p if self.training else 0
194
+ output = flash_attn_func(q, k, v, dropout_p, softmax_scale=self.softmax_scale, causal=self.causal)
195
+ return output
196
+
197
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
198
+ cu_seqlens_q = torch.arange(
199
+ 0,
200
+ (batch_size + 1) * seqlen_q,
201
+ step=seqlen_q,
202
+ dtype=torch.int32,
203
+ device=q.device,
204
+ )
205
+
206
+ if batch_size > 1 and attention_mask is not None:
207
+ k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
208
+ if q.size(0) == v.size(0):
209
+ q = q[indices_k]
210
+ cu_seqlens_q = cu_seqlens_k
211
+ seqlen_q = seqlen_k
212
+ v = v[indices_k]
213
+ else:
214
+ cu_seqlens_k = torch.arange(
215
+ 0,
216
+ (batch_size + 1) * seqlen_k,
217
+ step=seqlen_k,
218
+ dtype=torch.int32,
219
+ device=q.device,
220
+ )
221
+
222
+ if self.training:
223
+ assert seqlen_k == seqlen_q
224
+ is_causal = self.causal
225
+ dropout_p = self.dropout_p
226
+ else:
227
+ is_causal = seqlen_q == seqlen_k
228
+ dropout_p = 0
229
+
230
+ output = flash_attn_unpadded_func(
231
+ q,
232
+ k,
233
+ v,
234
+ cu_seqlens_q,
235
+ cu_seqlens_k,
236
+ seqlen_q,
237
+ seqlen_k,
238
+ dropout_p,
239
+ softmax_scale=self.softmax_scale,
240
+ causal=is_causal,
241
+ )
242
+ if batch_size > 1 and attention_mask is not None and seqlen_q == seqlen_k:
243
+ output = self.pad_input(output, indices_k, batch_size, seqlen_out)
244
+ else:
245
+ new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
246
+ output = output.view(new_shape)
247
+ return output
248
+
249
+
250
+ class QWenAttention(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+
254
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
255
+ self.seq_length = config.seq_length
256
+
257
+ self.hidden_size = config.hidden_size
258
+ self.split_size = config.hidden_size
259
+ self.num_heads = config.num_attention_heads
260
+ self.head_dim = self.hidden_size // self.num_heads
261
+
262
+ self.use_flash_attn = config.use_flash_attn
263
+ self.scale_attn_weights = True
264
+
265
+ self.projection_size = config.kv_channels * config.num_attention_heads
266
+
267
+ assert self.projection_size % config.num_attention_heads == 0
268
+ self.hidden_size_per_attention_head = (
269
+ self.projection_size // config.num_attention_heads
270
+ )
271
+
272
+ #self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
273
+ #
274
+ #self.c_proj = nn.Linear(
275
+ # config.hidden_size, self.projection_size, bias=not config.no_bias
276
+ #)
277
+
278
+ self.c_attn = nn.Linear(config.hidden_size , 3 * (self.projection_size // 2))
279
+
280
+ self.c_proj = nn.Linear(
281
+ config.hidden_size // 2, self.projection_size, bias=not config.no_bias
282
+ )
283
+
284
+ self.is_fp32 = not (config.bf16 or config.fp16)
285
+ if (
286
+ self.use_flash_attn
287
+ and flash_attn_unpadded_func is not None
288
+ and not self.is_fp32
289
+ ):
290
+ self.core_attention_flash = FlashSelfAttention(
291
+ causal=True, attention_dropout=config.attn_dropout_prob
292
+ )
293
+ self.bf16 = config.bf16
294
+
295
+ self.use_dynamic_ntk = config.use_dynamic_ntk
296
+ self.use_logn_attn = config.use_logn_attn
297
+
298
+ logn_list = [
299
+ math.log(i, self.seq_length) if i > self.seq_length else 1
300
+ for i in range(1, 32768)
301
+ ]
302
+ logn_tensor = torch.tensor(logn_list)[None, :, None, None]
303
+ self.register_buffer("logn_tensor", logn_tensor, persistent=False)
304
+
305
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
306
+ self.softmax_in_fp32 = config.softmax_in_fp32 if hasattr(config, 'softmax_in_fp32') else False
307
+ self.use_cache_quantization = config.use_cache_quantization if hasattr(config, 'use_cache_quantization') else False
308
+ self.use_cache_kernel = config.use_cache_kernel if hasattr(config,'use_cache_kernel') else False
309
+ cache_dtype = torch.float
310
+ if self.bf16:
311
+ cache_dtype=torch.bfloat16
312
+ elif config.fp16:
313
+ cache_dtype = torch.float16
314
+ self.cache_qmax = torch.tensor(torch.iinfo(torch.uint8).max, dtype=cache_dtype)
315
+ self.cache_qmin = torch.tensor(torch.iinfo(torch.uint8).min, dtype=cache_dtype)
316
+
317
+ if config.use_cache_quantization and config.use_cache_kernel:
318
+ # pre check if the support files existing
319
+ module_root = pathlib.Path(__file__).parent
320
+ src_files = ("cache_autogptq_cuda_256.cpp", "cache_autogptq_cuda_kernel_256.cu")
321
+ if any(not (module_root/src).is_file() for src in src_files):
322
+ warnings.warn("KV cache kernel source files (.cpp and .cu) not found.")
323
+ self.cache_kernels = None
324
+ else:
325
+ try:
326
+ from .cpp_kernels import cache_autogptq_cuda_256
327
+ self.cache_kernels = cache_autogptq_cuda_256
328
+ except ImportError:
329
+ warnings.warn("Failed to import KV cache kernels.")
330
+ self.cache_kernels = None
331
+
332
+ def _attn(self, query, key, value, causal_mask=None, attention_mask=None, head_mask=None):
333
+ device = query.device
334
+ if self.use_cache_quantization:
335
+ qk, qk_scale, qk_zero = key
336
+ if self.use_cache_kernel and self.cache_kernels is not None:
337
+ shape = query.shape[:-1] + (qk.shape[-2],)
338
+ attn_weights = torch.zeros(shape, dtype=torch.float16, device=device)
339
+ self.cache_kernels.vecquant8matmul_batched_faster_old(
340
+ query.contiguous() if query.dtype == torch.float16 else query.to(torch.float16).contiguous(),
341
+ qk.transpose(-1, -2).contiguous(),
342
+ attn_weights,
343
+ qk_scale.contiguous() if qk_scale.dtype == torch.float16 else qk_scale.to(torch.float16).contiguous(),
344
+ qk_zero.contiguous()if qk_zero.dtype == torch.float16 else qk_zero.to(torch.float16).contiguous())
345
+ # attn_weights = attn_weights.to(query.dtype).contiguous()
346
+ else:
347
+ key = dequantize_cache_torch(qk, qk_scale, qk_zero)
348
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
349
+ else:
350
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
351
+
352
+ if self.scale_attn_weights:
353
+ if self.use_cache_quantization:
354
+ size_temp = value[0].size(-1)
355
+ else:
356
+ size_temp = value.size(-1)
357
+ attn_weights = attn_weights / (size_temp ** 0.5)
358
+
359
+ mask_value = torch.finfo(attn_weights.dtype).min
360
+ if causal_mask is not None:
361
+ attn_weights = torch.where(
362
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
363
+ )
364
+
365
+ if attention_mask is not None:
366
+ attn_weights = attn_weights + attention_mask
367
+
368
+ if self.softmax_in_fp32:
369
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
370
+ else:
371
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
372
+
373
+ attn_weights = attn_weights.type(query.dtype)
374
+ attn_weights = self.attn_dropout(attn_weights)
375
+
376
+ if head_mask is not None:
377
+ attn_weights = attn_weights * head_mask
378
+
379
+ if self.use_cache_quantization:
380
+ qv, qv_scale, qv_zero = value
381
+ if self.use_cache_kernel and self.cache_kernels is not None:
382
+ shape = attn_weights.shape[:-1] + (query.shape[-1],)
383
+ attn_output = torch.zeros(shape, dtype=torch.float16, device=device)
384
+ self.cache_kernels.vecquant8matmul_batched_column_compression_faster_old(
385
+ attn_weights.contiguous() if attn_weights.dtype == torch.float16 else attn_weights.to(torch.float16).contiguous(),
386
+ qv.contiguous(), # dtype: int32
387
+ attn_output,
388
+ qv_scale.contiguous() if qv_scale.dtype == torch.float16 else qv_scale.to(torch.float16).contiguous(),
389
+ qv_zero.contiguous() if qv_zero.dtype == torch.float16 else qv_zero.to(torch.float16).contiguous())
390
+ if attn_output.dtype != query.dtype:
391
+ attn_output = attn_output.to(query.dtype)
392
+ attn_weights = attn_weights.to(query.dtype)
393
+ else:
394
+ value = dequantize_cache_torch(qv, qv_scale, qv_zero)
395
+ attn_output = torch.matmul(attn_weights, value)
396
+ else:
397
+ attn_output = torch.matmul(attn_weights, value)
398
+
399
+ attn_output = attn_output.transpose(1, 2)
400
+
401
+ return attn_output, attn_weights
402
+
403
+ def _split_heads(self, tensor, num_heads, attn_head_size):
404
+ new_shape = tensor.size()[:-1] + (num_heads // 2, attn_head_size)
405
+ tensor = tensor.view(new_shape)
406
+ return tensor
407
+
408
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
409
+ tensor = tensor.contiguous()
410
+ new_shape = tensor.size()[:-2] + ((num_heads // 2) * attn_head_size,)
411
+ return tensor.view(new_shape)
412
+
413
+ def forward(
414
+ self,
415
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
416
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
417
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
418
+ attention_mask: Optional[torch.FloatTensor] = None,
419
+ head_mask: Optional[torch.FloatTensor] = None,
420
+ encoder_hidden_states: Optional[torch.Tensor] = None,
421
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
422
+ output_attentions: Optional[bool] = False,
423
+ use_cache: Optional[bool] = False,
424
+ build_dp: bool = False,
425
+ ):
426
+ mixed_x_layer = self.c_attn(hidden_states)
427
+ _, _, H_3 = mixed_x_layer.size()
428
+ H = H_3 // 3
429
+ query, key, value = torch.split(mixed_x_layer, [H, H, H], dim=-1)
430
+ #query, key, value = mixed_x_layer.split(self.split_size, dim=2)
431
+
432
+ query = self._split_heads(query, self.num_heads, self.head_dim)
433
+ key = self._split_heads(key, self.num_heads, self.head_dim)
434
+ value = self._split_heads(value, self.num_heads, self.head_dim)
435
+
436
+ if rotary_pos_emb_list is not None:
437
+ cur_len = query.shape[1]
438
+ if len(rotary_pos_emb_list) == 1:
439
+ rotary_pos_emb = rotary_pos_emb_list[0]
440
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
441
+ rotary_pos_emb = (rotary_pos_emb,) * 2
442
+ q_pos_emb, k_pos_emb = rotary_pos_emb
443
+ # Slice the pos emb for current inference
444
+ if not build_dp:
445
+ query = apply_rotary_pos_emb(query, q_pos_emb)
446
+ key = apply_rotary_pos_emb(key, k_pos_emb)
447
+ else:
448
+ query_list = []
449
+ key_list = []
450
+ for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
451
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
452
+ rotary_pos_emb = (rotary_pos_emb,) * 2
453
+ q_pos_emb, k_pos_emb = rotary_pos_emb
454
+ # Slice the pos emb for current inference
455
+ if not build_dp:
456
+ query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
457
+ key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
458
+ query = torch.cat(query_list, dim=0)
459
+ key = torch.cat(key_list, dim=0)
460
+
461
+ if self.use_cache_quantization:
462
+ key = quantize_cache_v(key.permute(0, 2, 1, 3),
463
+ bits=8,
464
+ qmin=self.cache_qmin,
465
+ qmax=self.cache_qmax)
466
+ value = quantize_cache_v(value.permute(0, 2, 1, 3),
467
+ bits=8,
468
+ qmin=self.cache_qmin,
469
+ qmax=self.cache_qmax)
470
+
471
+
472
+ if layer_past is not None:
473
+ past_key, past_value = layer_past[0], layer_past[1]
474
+ if self.use_cache_quantization:
475
+ # use_cache_quantization:
476
+ # present=((q_key,key_scale,key_zero_point),
477
+ # (q_value,value_scale,value_zero_point))
478
+ key = (torch.cat((past_key[0], key[0]), dim=2),
479
+ torch.cat((past_key[1], key[1]), dim=2),
480
+ torch.cat((past_key[2], key[2]), dim=2))
481
+ value = (torch.cat((past_value[0], value[0]), dim=2),
482
+ torch.cat((past_value[1], value[1]), dim=2),
483
+ torch.cat((past_value[2], value[2]), dim=2))
484
+ else:
485
+ # not use_cache_quantization:
486
+ # present=(key,value)
487
+ key = torch.cat((past_key, key), dim=1)
488
+ value = torch.cat((past_value, value), dim=1)
489
+
490
+ if use_cache:
491
+ present = (key, value)
492
+ else:
493
+ present = None
494
+
495
+ key_size = key[0].size(2) if self.use_cache_quantization else key.size(1)
496
+ if key_size > self.seq_length and self.use_logn_attn and not self.training:
497
+ if self.use_cache_quantization:
498
+ seq_start = key[0].size(2) - query.size(1)
499
+ seq_end = key[0].size(2)
500
+ else:
501
+ seq_start = key.size(1) - query.size(1)
502
+ seq_end = key.size(1)
503
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :].type_as(query)
504
+ query = query * logn_tensor.expand_as(query)
505
+
506
+ if (
507
+ self.use_flash_attn
508
+ and flash_attn_unpadded_func is not None
509
+ and not self.is_fp32
510
+ and query.is_cuda
511
+ ):
512
+ q, k, v = query, key, value
513
+ attn_output = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
514
+ else:
515
+ key_size = key[0].size(2) if self.use_cache_quantization else key.size(1)
516
+ if query.size(1) == key_size:
517
+ causal_mask = torch.tril(
518
+ torch.ones((key_size, key_size), dtype=torch.bool, device=query.device)
519
+ ).view(1, 1, key_size, key_size)
520
+ else:
521
+ causal_mask = None
522
+ query = query.permute(0, 2, 1, 3)
523
+ if not self.use_cache_quantization:
524
+ key = key.permute(0, 2, 1, 3)
525
+ value = value.permute(0, 2, 1, 3)
526
+ if (
527
+ causal_mask is None
528
+ and self.use_flash_attn
529
+ and flash_attn_unpadded_func is not None
530
+ and not self.is_fp32
531
+ and not query.is_cuda
532
+ ):
533
+ raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)
534
+
535
+ if not self.use_cache_quantization and SUPPORT_TORCH2:
536
+ if attention_mask is not None:
537
+ attention_mask = attention_mask.expand(-1, -1, query.size(2), -1)
538
+ if causal_mask is not None:
539
+ attention_mask = attention_mask.masked_fill(~causal_mask, torch.finfo(query.dtype).min)
540
+ else:
541
+ attention_mask = causal_mask
542
+ attn_output = F.scaled_dot_product_attention(
543
+ query, key, value, attn_mask=attention_mask
544
+ ).transpose(1, 2)
545
+ attn_weight = None
546
+ else:
547
+ attn_output, attn_weight = self._attn(
548
+ query, key, value, causal_mask, attention_mask, head_mask
549
+ )
550
+ context_layer = self._merge_heads(
551
+ attn_output, self.num_heads, self.head_dim
552
+ )
553
+
554
+ attn_output = self.c_proj(context_layer)
555
+
556
+ outputs = (attn_output, present)
557
+ if output_attentions:
558
+ if (
559
+ self.use_flash_attn
560
+ and flash_attn_unpadded_func is not None
561
+ and not self.is_fp32
562
+ ):
563
+ raise ValueError("Cannot output attentions while using flash-attn")
564
+ elif not self.use_cache_quantization and SUPPORT_TORCH2:
565
+ raise ValueError("Cannot output attentions while using scaled_dot_product_attention")
566
+ else:
567
+ outputs += (attn_weight,)
568
+
569
+ return outputs
570
+
571
+
572
+ class QWenMLP(nn.Module):
573
+ def __init__(self, config):
574
+ super().__init__()
575
+ #self.w1 = nn.Linear(
576
+ # config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
577
+ #)
578
+ #self.w2 = nn.Linear(
579
+ # config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
580
+ #)
581
+ #ff_dim_in = config.intermediate_size // 2
582
+ #self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
583
+
584
+ self.w1 = nn.Linear(
585
+ config.hidden_size, config.intermediate_size // 4, bias=not config.no_bias
586
+ )
587
+ self.w2 = nn.Linear(
588
+ config.hidden_size, config.intermediate_size // 4, bias=not config.no_bias
589
+ )
590
+ ff_dim_in = config.intermediate_size // 4
591
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
592
+
593
+ def forward(self, hidden_states):
594
+ a1 = self.w1(hidden_states)
595
+ a2 = self.w2(hidden_states)
596
+ intermediate_parallel = a1 * F.silu(a2)
597
+ output = self.c_proj(intermediate_parallel)
598
+ return output
599
+
600
+
601
+ class QWenBlock(nn.Module):
602
+ def __init__(self, config):
603
+ super().__init__()
604
+ hidden_size = config.hidden_size
605
+ self.bf16 = config.bf16
606
+
607
+ self.ln_1 = RMSNorm(
608
+ hidden_size,
609
+ eps=config.layer_norm_epsilon,
610
+ )
611
+ self.attn = QWenAttention(config)
612
+ self.ln_2 = RMSNorm(
613
+ hidden_size,
614
+ eps=config.layer_norm_epsilon,
615
+ )
616
+
617
+ self.mlp = QWenMLP(config)
618
+
619
+ def forward(
620
+ self,
621
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
622
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
623
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
624
+ attention_mask: Optional[torch.FloatTensor] = None,
625
+ head_mask: Optional[torch.FloatTensor] = None,
626
+ encoder_hidden_states: Optional[torch.Tensor] = None,
627
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
628
+ use_cache: Optional[bool] = False,
629
+ output_attentions: Optional[bool] = False,
630
+ build_dp: Optional[bool] = False,
631
+ ):
632
+ layernorm_output = self.ln_1(hidden_states)
633
+
634
+ attn_outputs = self.attn(
635
+ layernorm_output,
636
+ rotary_pos_emb_list,
637
+ layer_past=layer_past,
638
+ attention_mask=attention_mask,
639
+ head_mask=head_mask,
640
+ use_cache=use_cache,
641
+ output_attentions=output_attentions,
642
+ build_dp=build_dp,
643
+ )
644
+ attn_output = attn_outputs[0]
645
+
646
+ outputs = attn_outputs[1:]
647
+
648
+ residual = hidden_states
649
+ layernorm_input = attn_output + residual
650
+
651
+ layernorm_output = self.ln_2(layernorm_input)
652
+
653
+ residual = layernorm_input
654
+ mlp_output = self.mlp(layernorm_output)
655
+ hidden_states = residual + mlp_output
656
+
657
+ if use_cache:
658
+ outputs = (hidden_states,) + outputs
659
+ else:
660
+ outputs = (hidden_states,) + outputs[1:]
661
+
662
+ return outputs
663
+
664
+
665
+ class QWenPreTrainedModel(PreTrainedModel):
666
+ config_class = QWenConfig
667
+ base_model_prefix = "transformer"
668
+ is_parallelizable = False
669
+ supports_gradient_checkpointing = True
670
+ _no_split_modules = ["QWenBlock"]
671
+ _skip_keys_device_placement = "past_key_values"
672
+
673
+ def __init__(self, *inputs, **kwargs):
674
+ super().__init__(*inputs, **kwargs)
675
+
676
+ def _init_weights(self, module):
677
+ """Initialize the weights."""
678
+ if isinstance(module, nn.Linear):
679
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
680
+ if module.bias is not None:
681
+ module.bias.data.zero_()
682
+ elif isinstance(module, nn.Embedding):
683
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
684
+ if module.padding_idx is not None:
685
+ module.weight.data[module.padding_idx].zero_()
686
+ elif isinstance(module, RMSNorm):
687
+ module.weight.data.fill_(1.0)
688
+
689
+ for name, p in module.named_parameters():
690
+ if name == "c_proj.weight":
691
+ p.data.normal_(
692
+ mean=0.0,
693
+ std=(
694
+ self.config.initializer_range
695
+ / math.sqrt(2 * self.config.num_hidden_layers)
696
+ ),
697
+ )
698
+
699
+ def _set_gradient_checkpointing(self, module, value=False):
700
+ if isinstance(module, QWenModel):
701
+ module.gradient_checkpointing = value
702
+
703
+
704
+ class QWenModel(QWenPreTrainedModel):
705
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
706
+
707
+ def __init__(self, config):
708
+ super().__init__(config)
709
+ self.vocab_size = config.vocab_size
710
+ self.num_hidden_layers = config.num_hidden_layers
711
+ self.embed_dim = config.hidden_size
712
+ self.use_cache_quantization = self.config.use_cache_quantization if hasattr(self.config, 'use_cache_quantization') else False
713
+
714
+ self.gradient_checkpointing = False
715
+ self.use_dynamic_ntk = config.use_dynamic_ntk
716
+ self.seq_length = config.seq_length
717
+
718
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
719
+
720
+ self.drop = nn.Dropout(config.emb_dropout_prob)
721
+
722
+ if config.rotary_pct == 1.0:
723
+ self.rotary_ndims = None
724
+ else:
725
+ assert config.rotary_pct < 1
726
+ self.rotary_ndims = int(
727
+ config.kv_channels * config.rotary_pct
728
+ )
729
+ dim = (
730
+ self.rotary_ndims
731
+ if self.rotary_ndims is not None
732
+ else config.kv_channels
733
+ )
734
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
735
+
736
+ self.use_flash_attn = config.use_flash_attn
737
+ self.is_fp32 = not (config.bf16 or config.fp16)
738
+
739
+ self.h = nn.ModuleList(
740
+ [
741
+ QWenBlock(
742
+ config
743
+ )
744
+ for i in range(config.num_hidden_layers)
745
+ ]
746
+ )
747
+ self.ln_f = RMSNorm(
748
+ self.embed_dim,
749
+ eps=config.layer_norm_epsilon,
750
+ )
751
+
752
+ self.post_init()
753
+
754
+ def get_input_embeddings(self):
755
+ return self.wte
756
+
757
+ def set_input_embeddings(self, new_embeddings):
758
+ self.wte = new_embeddings
759
+
760
+ def get_ntk_alpha(self, true_seq_len):
761
+ context_value = math.log(true_seq_len / self.seq_length, 2) + 1
762
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
763
+ ntk_alpha = max(ntk_alpha, 1)
764
+ return ntk_alpha
765
+
766
+ def forward(
767
+ self,
768
+ input_ids: Optional[torch.LongTensor] = None,
769
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
770
+ attention_mask: Optional[torch.FloatTensor] = None,
771
+ token_type_ids: Optional[torch.LongTensor] = None,
772
+ position_ids: Optional[torch.LongTensor] = None,
773
+ head_mask: Optional[torch.FloatTensor] = None,
774
+ inputs_embeds: Optional[torch.FloatTensor] = None,
775
+ encoder_hidden_states: Optional[torch.Tensor] = None,
776
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
777
+ use_cache: Optional[bool] = None,
778
+ output_attentions: Optional[bool] = None,
779
+ output_hidden_states: Optional[bool] = None,
780
+ return_dict: Optional[bool] = None,
781
+ build_dp: Optional[bool] = False,
782
+ ):
783
+ output_attentions = (
784
+ output_attentions
785
+ if output_attentions is not None
786
+ else self.config.output_attentions
787
+ )
788
+ output_hidden_states = (
789
+ output_hidden_states
790
+ if output_hidden_states is not None
791
+ else self.config.output_hidden_states
792
+ )
793
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
794
+ return_dict = (
795
+ return_dict if return_dict is not None else self.config.use_return_dict
796
+ )
797
+
798
+ if input_ids is not None and inputs_embeds is not None:
799
+ raise ValueError(
800
+ "You cannot specify both input_ids and inputs_embeds at the same time"
801
+ )
802
+ elif input_ids is not None:
803
+ input_shape = input_ids.size()
804
+ input_ids = input_ids.view(-1, input_shape[-1])
805
+ batch_size = input_ids.shape[0]
806
+ elif inputs_embeds is not None:
807
+ input_shape = inputs_embeds.size()[:-1]
808
+ batch_size = inputs_embeds.shape[0]
809
+ else:
810
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
811
+
812
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
813
+
814
+ if token_type_ids is not None:
815
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
816
+ if position_ids is not None:
817
+ position_ids = position_ids.view(-1, input_shape[-1])
818
+
819
+ if past_key_values is None:
820
+ past_length = 0
821
+ past_key_values = tuple([None] * len(self.h))
822
+ else:
823
+ if self.use_cache_quantization:
824
+ past_length = past_key_values[0][0][0].size(2)
825
+ else:
826
+ past_length = past_key_values[0][0].size(-2)
827
+ if position_ids is None:
828
+ position_ids = torch.arange(
829
+ past_length,
830
+ input_shape[-1] + past_length,
831
+ dtype=torch.long,
832
+ device=device,
833
+ )
834
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
835
+
836
+ if attention_mask is not None:
837
+ if batch_size <= 0:
838
+ raise ValueError("batch_size has to be defined and > 0")
839
+ attention_mask = attention_mask.view(batch_size, -1)
840
+ attention_mask = attention_mask[:, None, None, :]
841
+ attention_mask = attention_mask.to(dtype=self.dtype)
842
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
843
+
844
+ encoder_attention_mask = None
845
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
846
+
847
+ if inputs_embeds is None:
848
+ inputs_embeds = self.wte(input_ids)
849
+ hidden_states = inputs_embeds
850
+
851
+ kv_seq_len = hidden_states.size()[1]
852
+ if past_key_values[0] is not None:
853
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
854
+ if self.use_cache_quantization:
855
+ kv_seq_len += past_key_values[0][0][0].shape[2]
856
+ else:
857
+ kv_seq_len += past_key_values[0][0].shape[1]
858
+
859
+ if self.training or not self.use_dynamic_ntk:
860
+ ntk_alpha_list = [1.0]
861
+ elif kv_seq_len != hidden_states.size()[1]:
862
+ ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
863
+ else:
864
+ ntk_alpha_list = []
865
+ if attention_mask is not None and kv_seq_len > self.seq_length:
866
+ true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
867
+ for i in range(hidden_states.size()[0]):
868
+ true_seq_len = true_seq_lens[i].item()
869
+ ntk_alpha = self.get_ntk_alpha(true_seq_len)
870
+ ntk_alpha_list.append(ntk_alpha)
871
+ else:
872
+ ntk_alpha = self.get_ntk_alpha(kv_seq_len)
873
+ ntk_alpha_list.append(ntk_alpha)
874
+ self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
875
+ rotary_pos_emb_list = [
876
+ self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) for ntk_alpha in ntk_alpha_list
877
+ ]
878
+
879
+ hidden_states = self.drop(hidden_states)
880
+ output_shape = input_shape + (hidden_states.size(-1),)
881
+
882
+ if self.gradient_checkpointing and self.training:
883
+ if use_cache:
884
+ logger.warning_once(
885
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
886
+ )
887
+ use_cache = False
888
+
889
+ presents = () if use_cache else None
890
+ all_self_attentions = () if output_attentions else None
891
+ all_hidden_states = () if output_hidden_states else None
892
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
893
+
894
+ if output_hidden_states:
895
+ all_hidden_states = all_hidden_states + (hidden_states,)
896
+
897
+ if self.gradient_checkpointing and self.training:
898
+
899
+ def create_custom_forward(module):
900
+ def custom_forward(*inputs):
901
+ # None for past_key_value
902
+ return module(*inputs, use_cache, output_attentions)
903
+
904
+ return custom_forward
905
+
906
+ outputs = torch.utils.checkpoint.checkpoint(
907
+ create_custom_forward(block),
908
+ hidden_states,
909
+ rotary_pos_emb_list,
910
+ None,
911
+ attention_mask,
912
+ head_mask[i],
913
+ encoder_hidden_states,
914
+ encoder_attention_mask,
915
+ )
916
+ else:
917
+ outputs = block(
918
+ hidden_states,
919
+ layer_past=layer_past,
920
+ rotary_pos_emb_list=rotary_pos_emb_list,
921
+ attention_mask=attention_mask,
922
+ head_mask=head_mask[i],
923
+ encoder_hidden_states=encoder_hidden_states,
924
+ encoder_attention_mask=encoder_attention_mask,
925
+ use_cache=use_cache,
926
+ output_attentions=output_attentions,
927
+ build_dp=build_dp
928
+ )
929
+
930
+ hidden_states = outputs[0]
931
+ if use_cache is True:
932
+ presents = presents + (outputs[1],)
933
+
934
+ if output_attentions:
935
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
936
+
937
+ hidden_states = self.ln_f(hidden_states)
938
+ hidden_states = hidden_states.view(output_shape)
939
+ # Add last hidden state
940
+ if output_hidden_states:
941
+ all_hidden_states = all_hidden_states + (hidden_states,)
942
+
943
+ if not return_dict:
944
+ return tuple(
945
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
946
+ )
947
+
948
+ return BaseModelOutputWithPast(
949
+ last_hidden_state=hidden_states,
950
+ past_key_values=presents,
951
+ hidden_states=all_hidden_states,
952
+ attentions=all_self_attentions,
953
+ )
954
+
955
+
956
+ class QWenLMHeadModel(QWenPreTrainedModel):
957
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
958
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
959
+
960
+ def __init__(self, config):
961
+ super().__init__(config)
962
+ assert (
963
+ config.bf16 + config.fp16 + config.fp32 <= 1
964
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
965
+
966
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
967
+
968
+ if autoset_precision:
969
+ if SUPPORT_BF16:
970
+ logger.warn(
971
+ "The model is automatically converting to bf16 for faster inference. "
972
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
973
+ )
974
+ config.bf16 = True
975
+ elif SUPPORT_FP16:
976
+ logger.warn(
977
+ "The model is automatically converting to fp16 for faster inference. "
978
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
979
+ )
980
+ config.fp16 = True
981
+ else:
982
+ config.fp32 = True
983
+
984
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
985
+ logger.warn("Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \"AutoModelForCausalLM.from_pretrained\".")
986
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
987
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
988
+ if config.fp32:
989
+ if SUPPORT_BF16:
990
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
991
+ elif SUPPORT_FP16:
992
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
993
+
994
+ if config.use_flash_attn == "auto":
995
+ if config.bf16 or config.fp16:
996
+ logger.warn("Try importing flash-attention for faster inference...")
997
+ config.use_flash_attn = True
998
+ else:
999
+ config.use_flash_attn = False
1000
+ if config.use_flash_attn and config.fp32:
1001
+ logger.warn("Flash attention will be disabled because it does NOT support fp32.")
1002
+
1003
+ if config.use_flash_attn:
1004
+ _import_flash_attn()
1005
+
1006
+ self.transformer = QWenModel(config)
1007
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1008
+
1009
+ if config.bf16:
1010
+ self.transformer.bfloat16()
1011
+ self.lm_head.bfloat16()
1012
+ if config.fp16:
1013
+ self.transformer.half()
1014
+ self.lm_head.half()
1015
+ self.post_init()
1016
+
1017
+ def get_output_embeddings(self):
1018
+ return self.lm_head
1019
+
1020
+ def set_output_embeddings(self, new_embeddings):
1021
+ self.lm_head = new_embeddings
1022
+
1023
+ def prepare_inputs_for_generation(
1024
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
1025
+ ):
1026
+ if past_key_values:
1027
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1028
+
1029
+ if input_ids.size(0) == 1:
1030
+ attention_mask = None
1031
+ else:
1032
+ attention_mask = kwargs.get("attention_mask", None)
1033
+
1034
+ if inputs_embeds is not None and past_key_values is None:
1035
+ model_inputs = {"inputs_embeds": inputs_embeds}
1036
+ else:
1037
+ model_inputs = {"input_ids": input_ids}
1038
+
1039
+ model_inputs.update(
1040
+ {
1041
+ "past_key_values": past_key_values,
1042
+ "use_cache": kwargs.get("use_cache"),
1043
+ "attention_mask": attention_mask,
1044
+ }
1045
+ )
1046
+ return model_inputs
1047
+
1048
+ def forward(
1049
+ self,
1050
+ input_ids: Optional[torch.LongTensor] = None,
1051
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1052
+ attention_mask: Optional[torch.FloatTensor] = None,
1053
+ token_type_ids: Optional[torch.LongTensor] = None,
1054
+ position_ids: Optional[torch.LongTensor] = None,
1055
+ head_mask: Optional[torch.FloatTensor] = None,
1056
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1057
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1058
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1059
+ labels: Optional[torch.LongTensor] = None,
1060
+ use_cache: Optional[bool] = None,
1061
+ output_attentions: Optional[bool] = None,
1062
+ output_hidden_states: Optional[bool] = None,
1063
+ return_dict: Optional[bool] = None,
1064
+ build_dp: Optional[bool] = False,
1065
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1066
+
1067
+ return_dict = (
1068
+ return_dict if return_dict is not None else self.config.use_return_dict
1069
+ )
1070
+
1071
+ transformer_outputs = self.transformer(
1072
+ input_ids,
1073
+ past_key_values=past_key_values,
1074
+ attention_mask=attention_mask,
1075
+ token_type_ids=token_type_ids,
1076
+ position_ids=position_ids,
1077
+ head_mask=head_mask,
1078
+ inputs_embeds=inputs_embeds,
1079
+ encoder_hidden_states=encoder_hidden_states,
1080
+ encoder_attention_mask=encoder_attention_mask,
1081
+ use_cache=use_cache,
1082
+ output_attentions=output_attentions,
1083
+ output_hidden_states=output_hidden_states,
1084
+ return_dict=return_dict,
1085
+ build_dp=build_dp,
1086
+ )
1087
+ hidden_states = transformer_outputs[0]
1088
+
1089
+ lm_logits = self.lm_head(hidden_states)
1090
+
1091
+ loss = None
1092
+ if labels is not None:
1093
+ labels = labels.to(lm_logits.device)
1094
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1095
+ shift_labels = labels[..., 1:].contiguous()
1096
+ loss_fct = CrossEntropyLoss()
1097
+ loss = loss_fct(
1098
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1099
+ )
1100
+
1101
+ if not return_dict:
1102
+ output = (lm_logits,) + transformer_outputs[1:]
1103
+ return ((loss,) + output) if loss is not None else output
1104
+
1105
+ return CausalLMOutputWithPast(
1106
+ loss=loss,
1107
+ logits=lm_logits,
1108
+ past_key_values=transformer_outputs.past_key_values,
1109
+ hidden_states=transformer_outputs.hidden_states,
1110
+ attentions=transformer_outputs.attentions,
1111
+ )
1112
+
1113
+ @staticmethod
1114
+ def _reorder_cache(
1115
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1116
+ ) -> Tuple[Tuple[torch.Tensor]]:
1117
+
1118
+ return tuple(
1119
+ tuple(
1120
+ past_state.index_select(0, beam_idx.to(past_state.device))
1121
+ for past_state in layer_past
1122
+ )
1123
+ for layer_past in past_key_values
1124
+ )
1125
+
1126
+ def chat(
1127
+ self,
1128
+ tokenizer: PreTrainedTokenizer,
1129
+ query: str,
1130
+ history: Optional[HistoryType],
1131
+ system: str = "You are a helpful assistant.",
1132
+ stream: Optional[bool] = _SENTINEL,
1133
+ stop_words_ids: Optional[List[List[int]]] = None,
1134
+ generation_config: Optional[GenerationConfig] = None,
1135
+ **kwargs,
1136
+ ) -> Tuple[str, HistoryType]:
1137
+ generation_config = generation_config if generation_config is not None else self.generation_config
1138
+
1139
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
1140
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1141
+ if history is None:
1142
+ history = []
1143
+ else:
1144
+ # make a copy of the user's input such that is is left untouched
1145
+ history = copy.deepcopy(history)
1146
+
1147
+ if stop_words_ids is None:
1148
+ stop_words_ids = []
1149
+
1150
+ max_window_size = kwargs.get('max_window_size', None)
1151
+ if max_window_size is None:
1152
+ max_window_size = generation_config.max_window_size
1153
+ raw_text, context_tokens = make_context(
1154
+ tokenizer,
1155
+ query,
1156
+ history=history,
1157
+ system=system,
1158
+ max_window_size=max_window_size,
1159
+ chat_format=generation_config.chat_format,
1160
+ )
1161
+
1162
+ stop_words_ids.extend(get_stop_words_ids(
1163
+ generation_config.chat_format, tokenizer
1164
+ ))
1165
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1166
+ outputs = self.generate(
1167
+ input_ids,
1168
+ stop_words_ids=stop_words_ids,
1169
+ return_dict_in_generate=False,
1170
+ generation_config=generation_config,
1171
+ **kwargs,
1172
+ )
1173
+
1174
+ response = decode_tokens(
1175
+ outputs[0],
1176
+ tokenizer,
1177
+ raw_text_len=len(raw_text),
1178
+ context_length=len(context_tokens),
1179
+ chat_format=generation_config.chat_format,
1180
+ verbose=False,
1181
+ errors='replace'
1182
+ )
1183
+
1184
+ # as history is a copy of the user inputs,
1185
+ # we can always return the new turn to the user.
1186
+ # separating input history and output history also enables the user
1187
+ # to implement more complex history management
1188
+ history.append((query, response))
1189
+
1190
+ return response, history
1191
+
1192
+ def chat_stream(
1193
+ self,
1194
+ tokenizer: PreTrainedTokenizer,
1195
+ query: str,
1196
+ history: Optional[HistoryType],
1197
+ system: str = "You are a helpful assistant.",
1198
+ stop_words_ids: Optional[List[List[int]]] = None,
1199
+ logits_processor: Optional[LogitsProcessorList] = None,
1200
+ generation_config: Optional[GenerationConfig] = None,
1201
+ **kwargs,
1202
+ ) -> Generator[str, Any, None]:
1203
+ generation_config = generation_config if generation_config is not None else self.generation_config
1204
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1205
+ if history is None:
1206
+ history = []
1207
+ if stop_words_ids is None:
1208
+ stop_words_ids = []
1209
+
1210
+ max_window_size = kwargs.get('max_window_size', None)
1211
+ if max_window_size is None:
1212
+ max_window_size = generation_config.max_window_size
1213
+ raw_text, context_tokens = make_context(
1214
+ tokenizer,
1215
+ query,
1216
+ history=history,
1217
+ system=system,
1218
+ max_window_size=max_window_size,
1219
+ chat_format=generation_config.chat_format,
1220
+ )
1221
+
1222
+ stop_words_ids.extend(get_stop_words_ids(
1223
+ generation_config.chat_format, tokenizer
1224
+ ))
1225
+ if stop_words_ids is not None:
1226
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1227
+ stop_words_ids=stop_words_ids,
1228
+ eos_token_id=generation_config.eos_token_id,
1229
+ )
1230
+ if logits_processor is None:
1231
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1232
+ else:
1233
+ logits_processor.append(stop_words_logits_processor)
1234
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1235
+
1236
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1237
+ self.__class__.generate_stream = NewGenerationMixin.generate
1238
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1239
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1240
+
1241
+ def stream_generator():
1242
+ outputs = []
1243
+ for token in self.generate_stream(
1244
+ input_ids,
1245
+ return_dict_in_generate=False,
1246
+ generation_config=stream_config,
1247
+ logits_processor=logits_processor,
1248
+ seed=-1,
1249
+ **kwargs):
1250
+ outputs.append(token.item())
1251
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
1252
+
1253
+ return stream_generator()
1254
+
1255
+ def generate(
1256
+ self,
1257
+ inputs: Optional[torch.Tensor] = None,
1258
+ generation_config: Optional[GenerationConfig] = None,
1259
+ logits_processor: Optional[LogitsProcessorList] = None,
1260
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1261
+ prefix_allowed_tokens_fn: Optional[
1262
+ Callable[[int, torch.Tensor], List[int]]
1263
+ ] = None,
1264
+ synced_gpus: Optional[bool] = None,
1265
+ assistant_model: Optional["PreTrainedModel"] = None,
1266
+ streamer: Optional["BaseStreamer"] = None,
1267
+ **kwargs,
1268
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1269
+ generation_config = generation_config if generation_config is not None else self.generation_config
1270
+
1271
+ # Process stop_words_ids.
1272
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1273
+ if stop_words_ids is None and generation_config is not None:
1274
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1275
+ if stop_words_ids is None:
1276
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1277
+
1278
+ if stop_words_ids is not None:
1279
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1280
+ stop_words_ids=stop_words_ids,
1281
+ eos_token_id=generation_config.eos_token_id,
1282
+ )
1283
+ if logits_processor is None:
1284
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1285
+ else:
1286
+ logits_processor.append(stop_words_logits_processor)
1287
+
1288
+ return super().generate(
1289
+ inputs,
1290
+ generation_config=generation_config,
1291
+ logits_processor=logits_processor,
1292
+ stopping_criteria=stopping_criteria,
1293
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1294
+ synced_gpus=synced_gpus,
1295
+ assistant_model=assistant_model,
1296
+ streamer=streamer,
1297
+ **kwargs,
1298
+ )
1299
+
1300
+
1301
+ class RotaryEmbedding(torch.nn.Module):
1302
+ def __init__(self, dim, base=10000):
1303
+ super().__init__()
1304
+ self.dim = dim
1305
+ self.base = base
1306
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1307
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1308
+ if importlib.util.find_spec("einops") is None:
1309
+ raise RuntimeError("einops is required for Rotary Embedding")
1310
+
1311
+ self._rotary_pos_emb_cache = None
1312
+ self._seq_len_cached = 0
1313
+ self._ntk_alpha_cached = 1.0
1314
+ self._ntk_alpha_cached_list = [1.0]
1315
+
1316
+ def update_rotary_pos_emb_cache(self, seqlen, ntk_alpha=1.0):
1317
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1318
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1319
+ self.inv_freq = 1.0 / (
1320
+ base
1321
+ ** (
1322
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1323
+ / self.dim
1324
+ )
1325
+ )
1326
+ self._seq_len_cached = max(2 * seqlen, 16)
1327
+ self._ntk_alpha_cached = ntk_alpha
1328
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1329
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1330
+
1331
+ emb = torch.cat((freqs, freqs), dim=-1)
1332
+ from einops import rearrange
1333
+
1334
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1335
+
1336
+ cos, sin = emb.cos(), emb.sin()
1337
+ self._rotary_pos_emb_cache = [cos, sin]
1338
+
1339
+ def forward(self, max_seq_len, ntk_alpha=1.0):
1340
+ self.update_rotary_pos_emb_cache(max_seq_len, ntk_alpha)
1341
+ cos, sin = self._rotary_pos_emb_cache
1342
+ return [cos[:, :max_seq_len], sin[:, :max_seq_len]]
1343
+
1344
+
1345
+ def _rotate_half(x):
1346
+ from einops import rearrange
1347
+
1348
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1349
+ x1, x2 = x.unbind(dim=-2)
1350
+ return torch.cat((-x2, x1), dim=-1)
1351
+
1352
+
1353
+ def apply_rotary_pos_emb(t, freqs):
1354
+ """ Apply rotary embedding to the first rotary_dim of the iput
1355
+
1356
+ Arguments:
1357
+ t (tensor(batch_size, seq_len, n_head, head_dim)):
1358
+ the input embedding/hidden states
1359
+ freqs (list[tensor(1, seq_len, 1, rotary_dim), tensor(1, seq_len, 1, rotary_dim)]):
1360
+ the cached cos/sin position embeddings
1361
+ """
1362
+ rot_dim = freqs[0].shape[-1]
1363
+ cos, sin = freqs
1364
+ t_float = t.float()
1365
+ if apply_rotary_emb_func is not None and t.is_cuda:
1366
+ # apply_rotary_emb in flash_attn requires cos/sin to be of
1367
+ # shape (seqlen, rotary_dim / 2) and apply rotary embedding
1368
+ # to the first rotary_dim of the input
1369
+ cos = cos.squeeze(0).squeeze(1)[:, : rot_dim // 2]
1370
+ sin = sin.squeeze(0).squeeze(1)[:, : rot_dim // 2]
1371
+ return apply_rotary_emb_func(t_float, cos, sin).type_as(t)
1372
+ else:
1373
+ t_rot, t_pass = t_float[..., :rot_dim], t_float[..., rot_dim:]
1374
+ t_rot = (t_rot * cos) + (_rotate_half(t_rot) * sin)
1375
+ return torch.cat((t_rot, t_pass), dim=-1).type_as(t)
1376
+
1377
+
1378
+ class RMSNorm(torch.nn.Module):
1379
+ def __init__(self, dim: int, eps: float = 1e-6):
1380
+ super().__init__()
1381
+ self.eps = eps
1382
+ self.weight = nn.Parameter(torch.ones(dim))
1383
+
1384
+ def _norm(self, x):
1385
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1386
+
1387
+ def forward(self, x):
1388
+ if rms_norm is not None and x.is_cuda:
1389
+ return rms_norm(x, self.weight, self.eps)
1390
+ else:
1391
+ output = self._norm(x.float()).type_as(x)
1392
+ return output * self.weight
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
qwen_generation_utils.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
qwen_generation_utils.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Generation support."""
7
+
8
+ from typing import Tuple, List, Union, Iterable
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import PreTrainedTokenizer
14
+ from transformers import logging
15
+ from transformers.generation import LogitsProcessor
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ # Types.
20
+ HistoryType = List[Tuple[str, str]]
21
+ TokensType = List[int]
22
+ BatchTokensType = List[List[int]]
23
+
24
+
25
+ def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
26
+ for tokens in batch:
27
+ context_length = len(tokens)
28
+ if context_length < seq_length:
29
+ tokens.extend([pad_id] * (seq_length - context_length))
30
+ return batch
31
+
32
+
33
+ def get_ltor_masks_and_position_ids(
34
+ data,
35
+ eod_token,
36
+ reset_position_ids,
37
+ reset_attention_mask,
38
+ eod_mask_loss,
39
+ ):
40
+ """Build masks and position id for left to right model."""
41
+
42
+ # Extract batch size and sequence length.
43
+ micro_batch_size, seq_length = data.size()
44
+
45
+ # Attention mask (lower triangular).
46
+ if reset_attention_mask:
47
+ att_mask_batch = micro_batch_size
48
+ else:
49
+ att_mask_batch = 1
50
+ attention_mask = torch.tril(
51
+ torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
52
+ ).view(att_mask_batch, 1, seq_length, seq_length)
53
+
54
+ # Loss mask.
55
+ loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
56
+ if eod_mask_loss:
57
+ loss_mask[data == eod_token] = 0.0
58
+
59
+ # Position ids.
60
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
61
+ position_ids = position_ids.unsqueeze(0).expand_as(data)
62
+ # We need to clone as the ids will be modifed based on batch index.
63
+ if reset_position_ids:
64
+ position_ids = position_ids.clone()
65
+
66
+ if reset_position_ids or reset_attention_mask:
67
+ # Loop through the batches:
68
+ for b in range(micro_batch_size):
69
+
70
+ # Find indecies where EOD token is.
71
+ eod_index = position_ids[b, data[b] == eod_token]
72
+ # Detach indecies from positions if going to modify positions.
73
+ if reset_position_ids:
74
+ eod_index = eod_index.clone()
75
+
76
+ # Loop through EOD indecies:
77
+ prev_index = 0
78
+ for j in range(eod_index.size()[0]):
79
+ i = eod_index[j]
80
+ # Mask attention loss.
81
+ if reset_attention_mask:
82
+ attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
83
+ # Reset positions.
84
+ if reset_position_ids:
85
+ position_ids[b, (i + 1) :] -= i + 1 - prev_index
86
+ prev_index = i + 1
87
+
88
+ # Convert attention mask to binary:
89
+ attention_mask = attention_mask < 0.5
90
+
91
+ return attention_mask, loss_mask, position_ids
92
+
93
+
94
+ def get_batch(context_tokens: torch.LongTensor, eod_id: int):
95
+ """Generate batch from context tokens."""
96
+ # Move to GPU.
97
+ tokens = context_tokens.contiguous().to(context_tokens.device)
98
+ # Get the attention mask and postition ids.
99
+ attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
100
+ tokens,
101
+ eod_id,
102
+ reset_position_ids=False,
103
+ reset_attention_mask=False,
104
+ eod_mask_loss=False,
105
+ )
106
+ return tokens, attention_mask, position_ids
107
+
108
+
109
+ def get_stop_words_ids(chat_format, tokenizer):
110
+ if chat_format == "raw":
111
+ stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
112
+ elif chat_format == "chatml":
113
+ stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
114
+ else:
115
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
116
+ return stop_words_ids
117
+
118
+
119
+ def make_context(
120
+ tokenizer: PreTrainedTokenizer,
121
+ query: str,
122
+ history: List[Tuple[str, str]] = None,
123
+ system: str = "",
124
+ max_window_size: int = 6144,
125
+ chat_format: str = "chatml",
126
+ ):
127
+ if history is None:
128
+ history = []
129
+
130
+ if chat_format == "chatml":
131
+ im_start, im_end = "<|im_start|>", "<|im_end|>"
132
+ im_start_tokens = [tokenizer.im_start_id]
133
+ im_end_tokens = [tokenizer.im_end_id]
134
+ nl_tokens = tokenizer.encode("\n")
135
+
136
+ def _tokenize_str(role, content):
137
+ return f"{role}\n{content}", tokenizer.encode(
138
+ role, allowed_special=set()
139
+ ) + nl_tokens + tokenizer.encode(content, allowed_special=set())
140
+
141
+ system_text, system_tokens_part = _tokenize_str("system", system)
142
+ system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
143
+
144
+ raw_text = ""
145
+ context_tokens = []
146
+
147
+ for turn_query, turn_response in reversed(history):
148
+ query_text, query_tokens_part = _tokenize_str("user", turn_query)
149
+ query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
150
+ response_text, response_tokens_part = _tokenize_str(
151
+ "assistant", turn_response
152
+ )
153
+ response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
154
+
155
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
156
+ prev_chat = (
157
+ f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
158
+ )
159
+
160
+ current_context_size = (
161
+ len(system_tokens) + len(next_context_tokens) + len(context_tokens)
162
+ )
163
+ if current_context_size < max_window_size:
164
+ context_tokens = next_context_tokens + context_tokens
165
+ raw_text = prev_chat + raw_text
166
+ else:
167
+ break
168
+
169
+ context_tokens = system_tokens + context_tokens
170
+ raw_text = f"{im_start}{system_text}{im_end}" + raw_text
171
+ context_tokens += (
172
+ nl_tokens
173
+ + im_start_tokens
174
+ + _tokenize_str("user", query)[1]
175
+ + im_end_tokens
176
+ + nl_tokens
177
+ + im_start_tokens
178
+ + tokenizer.encode("assistant")
179
+ + nl_tokens
180
+ )
181
+ raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
182
+
183
+ elif chat_format == "raw":
184
+ raw_text = query
185
+ context_tokens = tokenizer.encode(raw_text)
186
+ else:
187
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
188
+
189
+ return raw_text, context_tokens
190
+
191
+
192
+ def _decode_default(
193
+ tokens: List[int],
194
+ *,
195
+ stop_words: List[str],
196
+ eod_words: List[str],
197
+ tokenizer: PreTrainedTokenizer,
198
+ raw_text_len: int,
199
+ verbose: bool = False,
200
+ return_end_reason: bool = False,
201
+ errors: str='replace',
202
+ ):
203
+ trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
204
+ if verbose:
205
+ print("\nRaw Generate: ", trim_decode_tokens)
206
+
207
+ end_reason = f"Gen length {len(tokens)}"
208
+ for stop_word in stop_words:
209
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
210
+ for eod_word in eod_words:
211
+ if eod_word in trim_decode_tokens:
212
+ end_reason = f"Gen {eod_word!r}"
213
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
214
+ trim_decode_tokens = trim_decode_tokens.strip()
215
+ if verbose:
216
+ print("\nEnd Reason:", end_reason)
217
+ print("\nGenerate: ", trim_decode_tokens)
218
+
219
+ if return_end_reason:
220
+ return trim_decode_tokens, end_reason
221
+ else:
222
+ return trim_decode_tokens
223
+
224
+
225
+ def _decode_chatml(
226
+ tokens: List[int],
227
+ *,
228
+ stop_words: List[str],
229
+ eod_token_ids: List[int],
230
+ tokenizer: PreTrainedTokenizer,
231
+ raw_text_len: int,
232
+ context_length: int,
233
+ verbose: bool = False,
234
+ return_end_reason: bool = False,
235
+ errors: str='replace'
236
+ ):
237
+ end_reason = f"Gen length {len(tokens)}"
238
+ eod_token_idx = context_length
239
+ for eod_token_idx in range(context_length, len(tokens)):
240
+ if tokens[eod_token_idx] in eod_token_ids:
241
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
242
+ break
243
+
244
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
245
+ if verbose:
246
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
247
+ print("\nRaw Generate:", trim_decode_tokens)
248
+ print("\nEnd Reason:", end_reason)
249
+ for stop_word in stop_words:
250
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
251
+ trim_decode_tokens = trim_decode_tokens.strip()
252
+ if verbose:
253
+ print("\nGenerate:", trim_decode_tokens)
254
+
255
+ if return_end_reason:
256
+ return trim_decode_tokens, end_reason
257
+ else:
258
+ return trim_decode_tokens
259
+
260
+
261
+ def decode_tokens(
262
+ tokens: Union[torch.LongTensor, TokensType],
263
+ tokenizer: PreTrainedTokenizer,
264
+ raw_text_len: int,
265
+ context_length: int,
266
+ chat_format: str,
267
+ verbose: bool = False,
268
+ return_end_reason: bool = False,
269
+ errors: str="replace",
270
+ ) -> str:
271
+ if torch.is_tensor(tokens):
272
+ tokens = tokens.cpu().numpy().tolist()
273
+
274
+ if chat_format == "chatml":
275
+ return _decode_chatml(
276
+ tokens,
277
+ stop_words=[],
278
+ eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
279
+ tokenizer=tokenizer,
280
+ raw_text_len=raw_text_len,
281
+ context_length=context_length,
282
+ verbose=verbose,
283
+ return_end_reason=return_end_reason,
284
+ errors=errors,
285
+ )
286
+ elif chat_format == "raw":
287
+ return _decode_default(
288
+ tokens,
289
+ stop_words=["<|endoftext|>"],
290
+ eod_words=["<|endoftext|>"],
291
+ tokenizer=tokenizer,
292
+ raw_text_len=raw_text_len,
293
+ verbose=verbose,
294
+ return_end_reason=return_end_reason,
295
+ errors=errors,
296
+ )
297
+ else:
298
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
299
+
300
+
301
+ class StopWordsLogitsProcessor(LogitsProcessor):
302
+ """
303
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
304
+
305
+ Args:
306
+ stop_words_ids (:obj:`List[List[int]]`):
307
+ List of list of token ids of stop ids. In order to get the tokens of the words
308
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
309
+ add_prefix_space=True).input_ids`.
310
+ eos_token_id (:obj:`int`):
311
+ The id of the `end-of-sequence` token.
312
+ """
313
+
314
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
315
+
316
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
317
+ raise ValueError(
318
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
319
+ )
320
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
321
+ raise ValueError(
322
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
323
+ )
324
+ if any(
325
+ any(
326
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
327
+ for token_id in stop_word_ids
328
+ )
329
+ for stop_word_ids in stop_words_ids
330
+ ):
331
+ raise ValueError(
332
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
333
+ )
334
+
335
+ self.stop_words_ids = list(
336
+ filter(
337
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
338
+ )
339
+ )
340
+ self.eos_token_id = eos_token_id
341
+ for stop_token_seq in self.stop_words_ids:
342
+ assert (
343
+ len(stop_token_seq) > 0
344
+ ), "Stop words token sequences {} cannot have an empty list".format(
345
+ stop_words_ids
346
+ )
347
+
348
+ def __call__(
349
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
350
+ ) -> torch.FloatTensor:
351
+ stopped_samples = self._calc_stopped_samples(input_ids)
352
+ for i, should_stop in enumerate(stopped_samples):
353
+ if should_stop:
354
+ scores[i, self.eos_token_id] = float(2**15)
355
+ return scores
356
+
357
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
358
+ if len(tokens) == 0:
359
+ # if bad word tokens is just one token always ban it
360
+ return True
361
+ elif len(tokens) > len(prev_tokens):
362
+ # if bad word tokens are longer then prev input_ids they can't be equal
363
+ return False
364
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
365
+ # if tokens match
366
+ return True
367
+ else:
368
+ return False
369
+
370
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
371
+ stopped_samples = []
372
+ for prev_input_ids_slice in prev_input_ids:
373
+ match = False
374
+ for stop_token_seq in self.stop_words_ids:
375
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
376
+ # if tokens do not match continue
377
+ match = True
378
+ break
379
+ stopped_samples.append(match)
380
+
381
+ return stopped_samples
382
+
383
+
384
+ def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
385
+ """This function has been mostly taken from huggingface conversational
386
+ ai code at
387
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
388
+ conversational-ai-with-transfer-learning-2d818ac26313"""
389
+
390
+ if top_k > 0:
391
+ # Remove all tokens with a probability less than the
392
+ # last token of the top-k
393
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
394
+ logits[indices_to_remove] = filter_value
395
+
396
+ if top_p > 0.0:
397
+ # Cconvert to 1D
398
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
399
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
400
+
401
+ # Remove tokens with cumulative probability above the threshold
402
+ sorted_indices_to_remove = cumulative_probs > top_p
403
+ # Shift the indices to the right to keep also the first token
404
+ # above the threshold
405
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
406
+ sorted_indices_to_remove[..., 0] = 0
407
+ for i in range(sorted_indices.size(0)):
408
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
409
+ logits[i][indices_to_remove] = filter_value
410
+
411
+ return logits
412
+
413
+
414
+ def switch(val1, val2, boolean):
415
+ boolean = boolean.type_as(val1)
416
+ return (1 - boolean) * val1 + boolean * val2
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
syf.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ from transformers.generation import GenerationConfig
3
+ from modeling_qwen import QWenLMHeadModel as QWEN
4
+
5
+
6
+ # Note: The default behavior now has injection attack prevention off.
7
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B", trust_remote_code=True)
8
+
9
+ # use bf16
10
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B", device_map="auto", trust_remote_code=True, bf16=True).eval()
11
+ # use fp16
12
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B", device_map="auto", trust_remote_code=True, fp16=True).eval()
13
+ # use cpu only
14
+ # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B", device_map="cpu", trust_remote_code=True).eval()
15
+ # use auto mode, automatically select precision based on the device.
16
+ #model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B", device_map="auto", trust_remote_code=True).eval()
17
+
18
+ model = QWEN.from_pretrained('/data3/user23215411/SYF/LLM-Pruner/prune_log/qwen_prune/pretrain-save',device_map="cuda")
19
+ #tokenizer.from_pretrained('/data3/user23215411/SYF/LLM-Pruner/prune_log/qwen_prune/pretrain-save')
20
+
21
+ # Specify hyperparameters for generation. But if you use transformers>=4.32.0, there is no need to do this.
22
+ # model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B", trust_remote_code=True)
23
+
24
+ inputs = tokenizer('蒙古国的首都是乌兰巴托(Ulaanbaatar)\n冰岛的首都是雷克雅未克(Reykjavik)\n埃塞俄比亚的首都是', return_tensors='pt')
25
+ inputs = inputs.to(model.device)
26
+ pred = model.generate(**inputs)
27
+ print(tokenizer.decode(pred.cpu()[0], skip_special_tokens=True))
28
+ # 蒙古国的首都是乌兰巴托(Ulaanbaatar)\n冰岛的首都是雷克雅未克(Reykjavik)\n埃塞俄比亚的首都是亚的斯亚贝巴(Addis Ababa)...
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {},
3
+ "auto_map": {
4
+ "AutoTokenizer": [
5
+ "Qwen/Qwen-7B--tokenization_qwen.QWenTokenizer",
6
+ null
7
+ ]
8
+ },
9
+ "clean_up_tokenization_spaces": true,
10
+ "model_max_length": 32768,
11
+ "tokenizer_class": "QWenTokenizer"
12
+ }