maxosai commited on
Commit
5f395c8
1 Parent(s): 081544b

init commit

Browse files
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "BeisenAI-7B-Chat",
3
+ "architectures": [
4
+ "QWenLMHeadModel"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModel": "modeling_qwen.QWenLMHeadModel",
10
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
11
+ },
12
+ "bf16": false,
13
+ "emb_dropout_prob": 0.0,
14
+ "fp16": true,
15
+ "fp32": false,
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 22016,
19
+ "kv_channels": 128,
20
+ "layer_norm_epsilon": 1e-06,
21
+ "max_position_embeddings": 32768,
22
+ "model_type": "qwen",
23
+ "no_bias": true,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 32,
26
+ "onnx_safe": null,
27
+ "rotary_emb_base": 10000,
28
+ "rotary_pct": 1.0,
29
+ "scale_attn_weights": true,
30
+ "seq_length": 8192,
31
+ "softmax_in_fp32": false,
32
+ "tie_word_embeddings": false,
33
+ "tokenizer_class": "QWenTokenizer",
34
+ "torch_dtype": "float16",
35
+ "transformers_version": "4.40.1",
36
+ "use_cache": true,
37
+ "use_cache_kernel": false,
38
+ "use_cache_quantization": false,
39
+ "use_dynamic_ntk": true,
40
+ "use_flash_attn": true,
41
+ "use_logn_attn": true,
42
+ "vocab_size": 151936
43
+ }
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
+ )
cpp_kernels.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils import cpp_extension
2
+ import pathlib
3
+ import os
4
+ import subprocess
5
+
6
+ def _get_cuda_bare_metal_version(cuda_dir):
7
+ raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"],
8
+ universal_newlines=True)
9
+ output = raw_output.split()
10
+ release_idx = output.index("release") + 1
11
+ release = output[release_idx].split(".")
12
+ bare_metal_major = release[0]
13
+ bare_metal_minor = release[1][0]
14
+
15
+ return raw_output, bare_metal_major, bare_metal_minor
16
+
17
+ def _create_build_dir(buildpath):
18
+ try:
19
+ os.mkdir(buildpath)
20
+ except OSError:
21
+ if not os.path.isdir(buildpath):
22
+ print(f"Creation of the build directory {buildpath} failed")
23
+
24
+ # Check if cuda 11 is installed for compute capability 8.0
25
+ cc_flag = []
26
+ _, bare_metal_major, bare_metal_minor = _get_cuda_bare_metal_version(cpp_extension.CUDA_HOME)
27
+ if int(bare_metal_major) >= 11:
28
+ cc_flag.append('-gencode')
29
+ cc_flag.append('arch=compute_80,code=sm_80')
30
+ if int(bare_metal_minor) >= 7:
31
+ cc_flag.append('-gencode')
32
+ cc_flag.append('arch=compute_90,code=sm_90')
33
+
34
+ # Build path
35
+ srcpath = pathlib.Path(__file__).parent.absolute()
36
+ buildpath = srcpath / 'build'
37
+ _create_build_dir(buildpath)
38
+
39
+ def _cpp_extention_load_helper(name, sources, extra_cuda_flags):
40
+ return cpp_extension.load(
41
+ name=name,
42
+ sources=sources,
43
+ build_directory=buildpath,
44
+ extra_cflags=['-O3', ],
45
+ extra_cuda_cflags=['-O3',
46
+ '-gencode', 'arch=compute_70,code=sm_70',
47
+ '--use_fast_math'] + extra_cuda_flags + cc_flag,
48
+ verbose=1
49
+ )
50
+
51
+ extra_flags = []
52
+
53
+ cache_autogptq_cuda_256_sources = ["./cache_autogptq_cuda_256.cpp",
54
+ "./cache_autogptq_cuda_kernel_256.cu"]
55
+ cache_autogptq_cuda_256 = _cpp_extention_load_helper("cache_autogptq_cuda_256", cache_autogptq_cuda_256_sources, extra_flags)
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "do_sample": true,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 512,
6
+ "max_window_size": 24000,
7
+ "pad_token_id": 151643,
8
+ "repetition_penalty": 1.1,
9
+ "top_k": 0,
10
+ "top_p": 0.8,
11
+ "transformers_version": "4.40.1"
12
+ }
model.safetensors.index.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 15442649088
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00016-of-00016.safetensors",
7
+ "transformer.h.0.attn.c_attn.bias": "model-00002-of-00016.safetensors",
8
+ "transformer.h.0.attn.c_attn.weight": "model-00002-of-00016.safetensors",
9
+ "transformer.h.0.attn.c_proj.weight": "model-00002-of-00016.safetensors",
10
+ "transformer.h.0.ln_1.weight": "model-00002-of-00016.safetensors",
11
+ "transformer.h.0.ln_2.weight": "model-00002-of-00016.safetensors",
12
+ "transformer.h.0.mlp.c_proj.weight": "model-00002-of-00016.safetensors",
13
+ "transformer.h.0.mlp.w1.weight": "model-00002-of-00016.safetensors",
14
+ "transformer.h.0.mlp.w2.weight": "model-00002-of-00016.safetensors",
15
+ "transformer.h.1.attn.c_attn.bias": "model-00002-of-00016.safetensors",
16
+ "transformer.h.1.attn.c_attn.weight": "model-00002-of-00016.safetensors",
17
+ "transformer.h.1.attn.c_proj.weight": "model-00002-of-00016.safetensors",
18
+ "transformer.h.1.ln_1.weight": "model-00002-of-00016.safetensors",
19
+ "transformer.h.1.ln_2.weight": "model-00002-of-00016.safetensors",
20
+ "transformer.h.1.mlp.c_proj.weight": "model-00002-of-00016.safetensors",
21
+ "transformer.h.1.mlp.w1.weight": "model-00002-of-00016.safetensors",
22
+ "transformer.h.1.mlp.w2.weight": "model-00002-of-00016.safetensors",
23
+ "transformer.h.10.attn.c_attn.bias": "model-00006-of-00016.safetensors",
24
+ "transformer.h.10.attn.c_attn.weight": "model-00006-of-00016.safetensors",
25
+ "transformer.h.10.attn.c_proj.weight": "model-00006-of-00016.safetensors",
26
+ "transformer.h.10.ln_1.weight": "model-00006-of-00016.safetensors",
27
+ "transformer.h.10.ln_2.weight": "model-00006-of-00016.safetensors",
28
+ "transformer.h.10.mlp.c_proj.weight": "model-00006-of-00016.safetensors",
29
+ "transformer.h.10.mlp.w1.weight": "model-00006-of-00016.safetensors",
30
+ "transformer.h.10.mlp.w2.weight": "model-00006-of-00016.safetensors",
31
+ "transformer.h.11.attn.c_attn.bias": "model-00006-of-00016.safetensors",
32
+ "transformer.h.11.attn.c_attn.weight": "model-00006-of-00016.safetensors",
33
+ "transformer.h.11.attn.c_proj.weight": "model-00006-of-00016.safetensors",
34
+ "transformer.h.11.ln_1.weight": "model-00006-of-00016.safetensors",
35
+ "transformer.h.11.ln_2.weight": "model-00006-of-00016.safetensors",
36
+ "transformer.h.11.mlp.c_proj.weight": "model-00007-of-00016.safetensors",
37
+ "transformer.h.11.mlp.w1.weight": "model-00006-of-00016.safetensors",
38
+ "transformer.h.11.mlp.w2.weight": "model-00006-of-00016.safetensors",
39
+ "transformer.h.12.attn.c_attn.bias": "model-00007-of-00016.safetensors",
40
+ "transformer.h.12.attn.c_attn.weight": "model-00007-of-00016.safetensors",
41
+ "transformer.h.12.attn.c_proj.weight": "model-00007-of-00016.safetensors",
42
+ "transformer.h.12.ln_1.weight": "model-00007-of-00016.safetensors",
43
+ "transformer.h.12.ln_2.weight": "model-00007-of-00016.safetensors",
44
+ "transformer.h.12.mlp.c_proj.weight": "model-00007-of-00016.safetensors",
45
+ "transformer.h.12.mlp.w1.weight": "model-00007-of-00016.safetensors",
46
+ "transformer.h.12.mlp.w2.weight": "model-00007-of-00016.safetensors",
47
+ "transformer.h.13.attn.c_attn.bias": "model-00007-of-00016.safetensors",
48
+ "transformer.h.13.attn.c_attn.weight": "model-00007-of-00016.safetensors",
49
+ "transformer.h.13.attn.c_proj.weight": "model-00007-of-00016.safetensors",
50
+ "transformer.h.13.ln_1.weight": "model-00007-of-00016.safetensors",
51
+ "transformer.h.13.ln_2.weight": "model-00007-of-00016.safetensors",
52
+ "transformer.h.13.mlp.c_proj.weight": "model-00007-of-00016.safetensors",
53
+ "transformer.h.13.mlp.w1.weight": "model-00007-of-00016.safetensors",
54
+ "transformer.h.13.mlp.w2.weight": "model-00007-of-00016.safetensors",
55
+ "transformer.h.14.attn.c_attn.bias": "model-00008-of-00016.safetensors",
56
+ "transformer.h.14.attn.c_attn.weight": "model-00008-of-00016.safetensors",
57
+ "transformer.h.14.attn.c_proj.weight": "model-00008-of-00016.safetensors",
58
+ "transformer.h.14.ln_1.weight": "model-00007-of-00016.safetensors",
59
+ "transformer.h.14.ln_2.weight": "model-00008-of-00016.safetensors",
60
+ "transformer.h.14.mlp.c_proj.weight": "model-00008-of-00016.safetensors",
61
+ "transformer.h.14.mlp.w1.weight": "model-00008-of-00016.safetensors",
62
+ "transformer.h.14.mlp.w2.weight": "model-00008-of-00016.safetensors",
63
+ "transformer.h.15.attn.c_attn.bias": "model-00008-of-00016.safetensors",
64
+ "transformer.h.15.attn.c_attn.weight": "model-00008-of-00016.safetensors",
65
+ "transformer.h.15.attn.c_proj.weight": "model-00008-of-00016.safetensors",
66
+ "transformer.h.15.ln_1.weight": "model-00008-of-00016.safetensors",
67
+ "transformer.h.15.ln_2.weight": "model-00008-of-00016.safetensors",
68
+ "transformer.h.15.mlp.c_proj.weight": "model-00008-of-00016.safetensors",
69
+ "transformer.h.15.mlp.w1.weight": "model-00008-of-00016.safetensors",
70
+ "transformer.h.15.mlp.w2.weight": "model-00008-of-00016.safetensors",
71
+ "transformer.h.16.attn.c_attn.bias": "model-00008-of-00016.safetensors",
72
+ "transformer.h.16.attn.c_attn.weight": "model-00008-of-00016.safetensors",
73
+ "transformer.h.16.attn.c_proj.weight": "model-00008-of-00016.safetensors",
74
+ "transformer.h.16.ln_1.weight": "model-00008-of-00016.safetensors",
75
+ "transformer.h.16.ln_2.weight": "model-00008-of-00016.safetensors",
76
+ "transformer.h.16.mlp.c_proj.weight": "model-00009-of-00016.safetensors",
77
+ "transformer.h.16.mlp.w1.weight": "model-00009-of-00016.safetensors",
78
+ "transformer.h.16.mlp.w2.weight": "model-00009-of-00016.safetensors",
79
+ "transformer.h.17.attn.c_attn.bias": "model-00009-of-00016.safetensors",
80
+ "transformer.h.17.attn.c_attn.weight": "model-00009-of-00016.safetensors",
81
+ "transformer.h.17.attn.c_proj.weight": "model-00009-of-00016.safetensors",
82
+ "transformer.h.17.ln_1.weight": "model-00009-of-00016.safetensors",
83
+ "transformer.h.17.ln_2.weight": "model-00009-of-00016.safetensors",
84
+ "transformer.h.17.mlp.c_proj.weight": "model-00009-of-00016.safetensors",
85
+ "transformer.h.17.mlp.w1.weight": "model-00009-of-00016.safetensors",
86
+ "transformer.h.17.mlp.w2.weight": "model-00009-of-00016.safetensors",
87
+ "transformer.h.18.attn.c_attn.bias": "model-00009-of-00016.safetensors",
88
+ "transformer.h.18.attn.c_attn.weight": "model-00009-of-00016.safetensors",
89
+ "transformer.h.18.attn.c_proj.weight": "model-00009-of-00016.safetensors",
90
+ "transformer.h.18.ln_1.weight": "model-00009-of-00016.safetensors",
91
+ "transformer.h.18.ln_2.weight": "model-00009-of-00016.safetensors",
92
+ "transformer.h.18.mlp.c_proj.weight": "model-00010-of-00016.safetensors",
93
+ "transformer.h.18.mlp.w1.weight": "model-00009-of-00016.safetensors",
94
+ "transformer.h.18.mlp.w2.weight": "model-00009-of-00016.safetensors",
95
+ "transformer.h.19.attn.c_attn.bias": "model-00010-of-00016.safetensors",
96
+ "transformer.h.19.attn.c_attn.weight": "model-00010-of-00016.safetensors",
97
+ "transformer.h.19.attn.c_proj.weight": "model-00010-of-00016.safetensors",
98
+ "transformer.h.19.ln_1.weight": "model-00010-of-00016.safetensors",
99
+ "transformer.h.19.ln_2.weight": "model-00010-of-00016.safetensors",
100
+ "transformer.h.19.mlp.c_proj.weight": "model-00010-of-00016.safetensors",
101
+ "transformer.h.19.mlp.w1.weight": "model-00010-of-00016.safetensors",
102
+ "transformer.h.19.mlp.w2.weight": "model-00010-of-00016.safetensors",
103
+ "transformer.h.2.attn.c_attn.bias": "model-00002-of-00016.safetensors",
104
+ "transformer.h.2.attn.c_attn.weight": "model-00002-of-00016.safetensors",
105
+ "transformer.h.2.attn.c_proj.weight": "model-00002-of-00016.safetensors",
106
+ "transformer.h.2.ln_1.weight": "model-00002-of-00016.safetensors",
107
+ "transformer.h.2.ln_2.weight": "model-00002-of-00016.safetensors",
108
+ "transformer.h.2.mlp.c_proj.weight": "model-00003-of-00016.safetensors",
109
+ "transformer.h.2.mlp.w1.weight": "model-00003-of-00016.safetensors",
110
+ "transformer.h.2.mlp.w2.weight": "model-00003-of-00016.safetensors",
111
+ "transformer.h.20.attn.c_attn.bias": "model-00010-of-00016.safetensors",
112
+ "transformer.h.20.attn.c_attn.weight": "model-00010-of-00016.safetensors",
113
+ "transformer.h.20.attn.c_proj.weight": "model-00010-of-00016.safetensors",
114
+ "transformer.h.20.ln_1.weight": "model-00010-of-00016.safetensors",
115
+ "transformer.h.20.ln_2.weight": "model-00010-of-00016.safetensors",
116
+ "transformer.h.20.mlp.c_proj.weight": "model-00010-of-00016.safetensors",
117
+ "transformer.h.20.mlp.w1.weight": "model-00010-of-00016.safetensors",
118
+ "transformer.h.20.mlp.w2.weight": "model-00010-of-00016.safetensors",
119
+ "transformer.h.21.attn.c_attn.bias": "model-00011-of-00016.safetensors",
120
+ "transformer.h.21.attn.c_attn.weight": "model-00011-of-00016.safetensors",
121
+ "transformer.h.21.attn.c_proj.weight": "model-00011-of-00016.safetensors",
122
+ "transformer.h.21.ln_1.weight": "model-00010-of-00016.safetensors",
123
+ "transformer.h.21.ln_2.weight": "model-00011-of-00016.safetensors",
124
+ "transformer.h.21.mlp.c_proj.weight": "model-00011-of-00016.safetensors",
125
+ "transformer.h.21.mlp.w1.weight": "model-00011-of-00016.safetensors",
126
+ "transformer.h.21.mlp.w2.weight": "model-00011-of-00016.safetensors",
127
+ "transformer.h.22.attn.c_attn.bias": "model-00011-of-00016.safetensors",
128
+ "transformer.h.22.attn.c_attn.weight": "model-00011-of-00016.safetensors",
129
+ "transformer.h.22.attn.c_proj.weight": "model-00011-of-00016.safetensors",
130
+ "transformer.h.22.ln_1.weight": "model-00011-of-00016.safetensors",
131
+ "transformer.h.22.ln_2.weight": "model-00011-of-00016.safetensors",
132
+ "transformer.h.22.mlp.c_proj.weight": "model-00011-of-00016.safetensors",
133
+ "transformer.h.22.mlp.w1.weight": "model-00011-of-00016.safetensors",
134
+ "transformer.h.22.mlp.w2.weight": "model-00011-of-00016.safetensors",
135
+ "transformer.h.23.attn.c_attn.bias": "model-00011-of-00016.safetensors",
136
+ "transformer.h.23.attn.c_attn.weight": "model-00011-of-00016.safetensors",
137
+ "transformer.h.23.attn.c_proj.weight": "model-00011-of-00016.safetensors",
138
+ "transformer.h.23.ln_1.weight": "model-00011-of-00016.safetensors",
139
+ "transformer.h.23.ln_2.weight": "model-00011-of-00016.safetensors",
140
+ "transformer.h.23.mlp.c_proj.weight": "model-00012-of-00016.safetensors",
141
+ "transformer.h.23.mlp.w1.weight": "model-00012-of-00016.safetensors",
142
+ "transformer.h.23.mlp.w2.weight": "model-00012-of-00016.safetensors",
143
+ "transformer.h.24.attn.c_attn.bias": "model-00012-of-00016.safetensors",
144
+ "transformer.h.24.attn.c_attn.weight": "model-00012-of-00016.safetensors",
145
+ "transformer.h.24.attn.c_proj.weight": "model-00012-of-00016.safetensors",
146
+ "transformer.h.24.ln_1.weight": "model-00012-of-00016.safetensors",
147
+ "transformer.h.24.ln_2.weight": "model-00012-of-00016.safetensors",
148
+ "transformer.h.24.mlp.c_proj.weight": "model-00012-of-00016.safetensors",
149
+ "transformer.h.24.mlp.w1.weight": "model-00012-of-00016.safetensors",
150
+ "transformer.h.24.mlp.w2.weight": "model-00012-of-00016.safetensors",
151
+ "transformer.h.25.attn.c_attn.bias": "model-00012-of-00016.safetensors",
152
+ "transformer.h.25.attn.c_attn.weight": "model-00012-of-00016.safetensors",
153
+ "transformer.h.25.attn.c_proj.weight": "model-00012-of-00016.safetensors",
154
+ "transformer.h.25.ln_1.weight": "model-00012-of-00016.safetensors",
155
+ "transformer.h.25.ln_2.weight": "model-00012-of-00016.safetensors",
156
+ "transformer.h.25.mlp.c_proj.weight": "model-00013-of-00016.safetensors",
157
+ "transformer.h.25.mlp.w1.weight": "model-00012-of-00016.safetensors",
158
+ "transformer.h.25.mlp.w2.weight": "model-00012-of-00016.safetensors",
159
+ "transformer.h.26.attn.c_attn.bias": "model-00013-of-00016.safetensors",
160
+ "transformer.h.26.attn.c_attn.weight": "model-00013-of-00016.safetensors",
161
+ "transformer.h.26.attn.c_proj.weight": "model-00013-of-00016.safetensors",
162
+ "transformer.h.26.ln_1.weight": "model-00013-of-00016.safetensors",
163
+ "transformer.h.26.ln_2.weight": "model-00013-of-00016.safetensors",
164
+ "transformer.h.26.mlp.c_proj.weight": "model-00013-of-00016.safetensors",
165
+ "transformer.h.26.mlp.w1.weight": "model-00013-of-00016.safetensors",
166
+ "transformer.h.26.mlp.w2.weight": "model-00013-of-00016.safetensors",
167
+ "transformer.h.27.attn.c_attn.bias": "model-00013-of-00016.safetensors",
168
+ "transformer.h.27.attn.c_attn.weight": "model-00013-of-00016.safetensors",
169
+ "transformer.h.27.attn.c_proj.weight": "model-00013-of-00016.safetensors",
170
+ "transformer.h.27.ln_1.weight": "model-00013-of-00016.safetensors",
171
+ "transformer.h.27.ln_2.weight": "model-00013-of-00016.safetensors",
172
+ "transformer.h.27.mlp.c_proj.weight": "model-00013-of-00016.safetensors",
173
+ "transformer.h.27.mlp.w1.weight": "model-00013-of-00016.safetensors",
174
+ "transformer.h.27.mlp.w2.weight": "model-00013-of-00016.safetensors",
175
+ "transformer.h.28.attn.c_attn.bias": "model-00014-of-00016.safetensors",
176
+ "transformer.h.28.attn.c_attn.weight": "model-00014-of-00016.safetensors",
177
+ "transformer.h.28.attn.c_proj.weight": "model-00014-of-00016.safetensors",
178
+ "transformer.h.28.ln_1.weight": "model-00013-of-00016.safetensors",
179
+ "transformer.h.28.ln_2.weight": "model-00014-of-00016.safetensors",
180
+ "transformer.h.28.mlp.c_proj.weight": "model-00014-of-00016.safetensors",
181
+ "transformer.h.28.mlp.w1.weight": "model-00014-of-00016.safetensors",
182
+ "transformer.h.28.mlp.w2.weight": "model-00014-of-00016.safetensors",
183
+ "transformer.h.29.attn.c_attn.bias": "model-00014-of-00016.safetensors",
184
+ "transformer.h.29.attn.c_attn.weight": "model-00014-of-00016.safetensors",
185
+ "transformer.h.29.attn.c_proj.weight": "model-00014-of-00016.safetensors",
186
+ "transformer.h.29.ln_1.weight": "model-00014-of-00016.safetensors",
187
+ "transformer.h.29.ln_2.weight": "model-00014-of-00016.safetensors",
188
+ "transformer.h.29.mlp.c_proj.weight": "model-00014-of-00016.safetensors",
189
+ "transformer.h.29.mlp.w1.weight": "model-00014-of-00016.safetensors",
190
+ "transformer.h.29.mlp.w2.weight": "model-00014-of-00016.safetensors",
191
+ "transformer.h.3.attn.c_attn.bias": "model-00003-of-00016.safetensors",
192
+ "transformer.h.3.attn.c_attn.weight": "model-00003-of-00016.safetensors",
193
+ "transformer.h.3.attn.c_proj.weight": "model-00003-of-00016.safetensors",
194
+ "transformer.h.3.ln_1.weight": "model-00003-of-00016.safetensors",
195
+ "transformer.h.3.ln_2.weight": "model-00003-of-00016.safetensors",
196
+ "transformer.h.3.mlp.c_proj.weight": "model-00003-of-00016.safetensors",
197
+ "transformer.h.3.mlp.w1.weight": "model-00003-of-00016.safetensors",
198
+ "transformer.h.3.mlp.w2.weight": "model-00003-of-00016.safetensors",
199
+ "transformer.h.30.attn.c_attn.bias": "model-00014-of-00016.safetensors",
200
+ "transformer.h.30.attn.c_attn.weight": "model-00014-of-00016.safetensors",
201
+ "transformer.h.30.attn.c_proj.weight": "model-00014-of-00016.safetensors",
202
+ "transformer.h.30.ln_1.weight": "model-00014-of-00016.safetensors",
203
+ "transformer.h.30.ln_2.weight": "model-00014-of-00016.safetensors",
204
+ "transformer.h.30.mlp.c_proj.weight": "model-00015-of-00016.safetensors",
205
+ "transformer.h.30.mlp.w1.weight": "model-00015-of-00016.safetensors",
206
+ "transformer.h.30.mlp.w2.weight": "model-00015-of-00016.safetensors",
207
+ "transformer.h.31.attn.c_attn.bias": "model-00015-of-00016.safetensors",
208
+ "transformer.h.31.attn.c_attn.weight": "model-00015-of-00016.safetensors",
209
+ "transformer.h.31.attn.c_proj.weight": "model-00015-of-00016.safetensors",
210
+ "transformer.h.31.ln_1.weight": "model-00015-of-00016.safetensors",
211
+ "transformer.h.31.ln_2.weight": "model-00015-of-00016.safetensors",
212
+ "transformer.h.31.mlp.c_proj.weight": "model-00015-of-00016.safetensors",
213
+ "transformer.h.31.mlp.w1.weight": "model-00015-of-00016.safetensors",
214
+ "transformer.h.31.mlp.w2.weight": "model-00015-of-00016.safetensors",
215
+ "transformer.h.4.attn.c_attn.bias": "model-00003-of-00016.safetensors",
216
+ "transformer.h.4.attn.c_attn.weight": "model-00003-of-00016.safetensors",
217
+ "transformer.h.4.attn.c_proj.weight": "model-00003-of-00016.safetensors",
218
+ "transformer.h.4.ln_1.weight": "model-00003-of-00016.safetensors",
219
+ "transformer.h.4.ln_2.weight": "model-00003-of-00016.safetensors",
220
+ "transformer.h.4.mlp.c_proj.weight": "model-00004-of-00016.safetensors",
221
+ "transformer.h.4.mlp.w1.weight": "model-00003-of-00016.safetensors",
222
+ "transformer.h.4.mlp.w2.weight": "model-00003-of-00016.safetensors",
223
+ "transformer.h.5.attn.c_attn.bias": "model-00004-of-00016.safetensors",
224
+ "transformer.h.5.attn.c_attn.weight": "model-00004-of-00016.safetensors",
225
+ "transformer.h.5.attn.c_proj.weight": "model-00004-of-00016.safetensors",
226
+ "transformer.h.5.ln_1.weight": "model-00004-of-00016.safetensors",
227
+ "transformer.h.5.ln_2.weight": "model-00004-of-00016.safetensors",
228
+ "transformer.h.5.mlp.c_proj.weight": "model-00004-of-00016.safetensors",
229
+ "transformer.h.5.mlp.w1.weight": "model-00004-of-00016.safetensors",
230
+ "transformer.h.5.mlp.w2.weight": "model-00004-of-00016.safetensors",
231
+ "transformer.h.6.attn.c_attn.bias": "model-00004-of-00016.safetensors",
232
+ "transformer.h.6.attn.c_attn.weight": "model-00004-of-00016.safetensors",
233
+ "transformer.h.6.attn.c_proj.weight": "model-00004-of-00016.safetensors",
234
+ "transformer.h.6.ln_1.weight": "model-00004-of-00016.safetensors",
235
+ "transformer.h.6.ln_2.weight": "model-00004-of-00016.safetensors",
236
+ "transformer.h.6.mlp.c_proj.weight": "model-00004-of-00016.safetensors",
237
+ "transformer.h.6.mlp.w1.weight": "model-00004-of-00016.safetensors",
238
+ "transformer.h.6.mlp.w2.weight": "model-00004-of-00016.safetensors",
239
+ "transformer.h.7.attn.c_attn.bias": "model-00005-of-00016.safetensors",
240
+ "transformer.h.7.attn.c_attn.weight": "model-00005-of-00016.safetensors",
241
+ "transformer.h.7.attn.c_proj.weight": "model-00005-of-00016.safetensors",
242
+ "transformer.h.7.ln_1.weight": "model-00004-of-00016.safetensors",
243
+ "transformer.h.7.ln_2.weight": "model-00005-of-00016.safetensors",
244
+ "transformer.h.7.mlp.c_proj.weight": "model-00005-of-00016.safetensors",
245
+ "transformer.h.7.mlp.w1.weight": "model-00005-of-00016.safetensors",
246
+ "transformer.h.7.mlp.w2.weight": "model-00005-of-00016.safetensors",
247
+ "transformer.h.8.attn.c_attn.bias": "model-00005-of-00016.safetensors",
248
+ "transformer.h.8.attn.c_attn.weight": "model-00005-of-00016.safetensors",
249
+ "transformer.h.8.attn.c_proj.weight": "model-00005-of-00016.safetensors",
250
+ "transformer.h.8.ln_1.weight": "model-00005-of-00016.safetensors",
251
+ "transformer.h.8.ln_2.weight": "model-00005-of-00016.safetensors",
252
+ "transformer.h.8.mlp.c_proj.weight": "model-00005-of-00016.safetensors",
253
+ "transformer.h.8.mlp.w1.weight": "model-00005-of-00016.safetensors",
254
+ "transformer.h.8.mlp.w2.weight": "model-00005-of-00016.safetensors",
255
+ "transformer.h.9.attn.c_attn.bias": "model-00005-of-00016.safetensors",
256
+ "transformer.h.9.attn.c_attn.weight": "model-00005-of-00016.safetensors",
257
+ "transformer.h.9.attn.c_proj.weight": "model-00005-of-00016.safetensors",
258
+ "transformer.h.9.ln_1.weight": "model-00005-of-00016.safetensors",
259
+ "transformer.h.9.ln_2.weight": "model-00005-of-00016.safetensors",
260
+ "transformer.h.9.mlp.c_proj.weight": "model-00006-of-00016.safetensors",
261
+ "transformer.h.9.mlp.w1.weight": "model-00006-of-00016.safetensors",
262
+ "transformer.h.9.mlp.w2.weight": "model-00006-of-00016.safetensors",
263
+ "transformer.ln_f.weight": "model-00015-of-00016.safetensors",
264
+ "transformer.wte.weight": "model-00001-of-00016.safetensors"
265
+ }
266
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "qwen"
56
+ _CONFIG_FOR_DOC = "QWenConfig"
57
+
58
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
59
+
60
+ _ERROR_BAD_CHAT_FORMAT = """\
61
+ 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".
62
+ 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().
63
+ """
64
+
65
+ _SENTINEL = object()
66
+ _ERROR_STREAM_IN_CHAT = """\
67
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
68
+ """
69
+
70
+ _ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
71
+ 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).
72
+ """
73
+
74
+ apply_rotary_emb_func = None
75
+ rms_norm = None
76
+ flash_attn_unpadded_func = None
77
+ flash_attn_func = None
78
+
79
+ def _import_flash_attn():
80
+ global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func, flash_attn_func
81
+ try:
82
+ from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
83
+ apply_rotary_emb_func = __apply_rotary_emb_func
84
+ except ImportError:
85
+ logger.warn(
86
+ "Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
87
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
88
+ )
89
+
90
+ try:
91
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
92
+ rms_norm = __rms_norm
93
+ except ImportError:
94
+ logger.warn(
95
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
96
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
97
+ )
98
+
99
+ try:
100
+ import flash_attn
101
+ _flash_attn_func = None
102
+ if not hasattr(flash_attn, '__version__'):
103
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
104
+ else:
105
+ if int(flash_attn.__version__.split(".")[0]) >= 2:
106
+ if int(flash_attn.__version__.split(".")[1]) >= 1:
107
+ from flash_attn.flash_attn_interface import flash_attn_func as _flash_attn_func
108
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
109
+ else:
110
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
111
+ flash_attn_unpadded_func = __flash_attn_unpadded_func
112
+ flash_attn_func = _flash_attn_func
113
+ except ImportError:
114
+ logger.warn(
115
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
116
+ "https://github.com/Dao-AILab/flash-attention"
117
+ )
118
+
119
+ def quantize_cache_v(fdata, bits, qmax, qmin):
120
+ # b, s, head, h-dim->b, head, s, h-dim
121
+ qtype = torch.uint8
122
+ device = fdata.device
123
+ shape = fdata.shape
124
+
125
+ fdata_cal = torch.flatten(fdata, 2)
126
+ fmax = torch.amax(fdata_cal, dim=-1, keepdim=True)
127
+ fmin = torch.amin(fdata_cal, dim=-1, keepdim=True)
128
+ # Compute params
129
+ if qmax.device != fmax.device:
130
+ qmax = qmax.to(device)
131
+ qmin = qmin.to(device)
132
+ scale = (fmax - fmin) / (qmax - qmin)
133
+ zero = qmin - fmin / scale
134
+ scale = scale.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
135
+ zero = zero.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
136
+ # Quantize
137
+ res_data = fdata / scale + zero
138
+ qdata = torch.clamp(res_data, qmin, qmax).to(qtype)
139
+ return qdata.contiguous(), scale, zero
140
+
141
+ def dequantize_cache_torch(qdata, scale, zero):
142
+ data = scale * (qdata - zero)
143
+ return data
144
+
145
+ class FlashSelfAttention(torch.nn.Module):
146
+ def __init__(
147
+ self,
148
+ causal=False,
149
+ softmax_scale=None,
150
+ attention_dropout=0.0,
151
+ ):
152
+ super().__init__()
153
+ assert flash_attn_unpadded_func is not None, (
154
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
155
+ )
156
+ assert (
157
+ rearrange is not None
158
+ ), "Please install einops first, e.g., with pip install einops"
159
+ self.causal = causal
160
+ self.softmax_scale = softmax_scale
161
+ self.dropout_p = attention_dropout
162
+
163
+ def unpad_input(self, hidden_states, attention_mask):
164
+ valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
165
+ seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
166
+ indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
167
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
168
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
169
+ hidden_states = hidden_states[indices]
170
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
171
+
172
+ def pad_input(self, hidden_states, indices, batch, seqlen):
173
+ output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
174
+ dtype=hidden_states.dtype)
175
+ output[indices] = hidden_states
176
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
177
+
178
+ def forward(self, q, k, v, attention_mask=None):
179
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
180
+ assert all((i.is_cuda for i in (q, k, v)))
181
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
182
+ seqlen_k = k.shape[1]
183
+ seqlen_out = seqlen_q
184
+
185
+ if flash_attn_func is not None and batch_size == 1:
186
+ dropout_p = self.dropout_p if self.training else 0
187
+ output = flash_attn_func(q, k, v, dropout_p, softmax_scale=self.softmax_scale, causal=self.causal)
188
+ return output
189
+
190
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
191
+ cu_seqlens_q = torch.arange(
192
+ 0,
193
+ (batch_size + 1) * seqlen_q,
194
+ step=seqlen_q,
195
+ dtype=torch.int32,
196
+ device=q.device,
197
+ )
198
+
199
+ if batch_size > 1 and attention_mask is not None:
200
+ k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
201
+ if q.size(0) == v.size(0):
202
+ q = q[indices_k]
203
+ cu_seqlens_q = cu_seqlens_k
204
+ seqlen_q = seqlen_k
205
+ v = v[indices_k]
206
+ else:
207
+ cu_seqlens_k = torch.arange(
208
+ 0,
209
+ (batch_size + 1) * seqlen_k,
210
+ step=seqlen_k,
211
+ dtype=torch.int32,
212
+ device=q.device,
213
+ )
214
+
215
+ if self.training:
216
+ assert seqlen_k == seqlen_q
217
+ is_causal = self.causal
218
+ dropout_p = self.dropout_p
219
+ else:
220
+ is_causal = seqlen_q == seqlen_k
221
+ dropout_p = 0
222
+
223
+ output = flash_attn_unpadded_func(
224
+ q,
225
+ k,
226
+ v,
227
+ cu_seqlens_q,
228
+ cu_seqlens_k,
229
+ seqlen_q,
230
+ seqlen_k,
231
+ dropout_p,
232
+ softmax_scale=self.softmax_scale,
233
+ causal=is_causal,
234
+ )
235
+ if batch_size > 1 and attention_mask is not None and seqlen_q == seqlen_k:
236
+ output = self.pad_input(output, indices_k, batch_size, seqlen_out)
237
+ else:
238
+ new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
239
+ output = output.view(new_shape)
240
+ return output
241
+
242
+
243
+ class QWenAttention(nn.Module):
244
+ def __init__(self, config):
245
+ super().__init__()
246
+
247
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
248
+ self.seq_length = config.seq_length
249
+
250
+ self.hidden_size = config.hidden_size
251
+ self.split_size = config.hidden_size
252
+ self.num_heads = config.num_attention_heads
253
+ self.head_dim = self.hidden_size // self.num_heads
254
+
255
+ self.use_flash_attn = config.use_flash_attn
256
+ self.scale_attn_weights = True
257
+
258
+ self.projection_size = config.kv_channels * config.num_attention_heads
259
+
260
+ assert self.projection_size % config.num_attention_heads == 0
261
+ self.hidden_size_per_attention_head = (
262
+ self.projection_size // config.num_attention_heads
263
+ )
264
+
265
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
266
+
267
+ self.c_proj = nn.Linear(
268
+ config.hidden_size, self.projection_size, bias=not config.no_bias
269
+ )
270
+
271
+ self.is_fp32 = not (config.bf16 or config.fp16)
272
+ if (
273
+ self.use_flash_attn
274
+ and flash_attn_unpadded_func is not None
275
+ and not self.is_fp32
276
+ ):
277
+ self.core_attention_flash = FlashSelfAttention(
278
+ causal=True, attention_dropout=config.attn_dropout_prob
279
+ )
280
+ self.bf16 = config.bf16
281
+
282
+ self.use_dynamic_ntk = config.use_dynamic_ntk
283
+ self.use_logn_attn = config.use_logn_attn
284
+
285
+ logn_list = [
286
+ math.log(i, self.seq_length) if i > self.seq_length else 1
287
+ for i in range(1, 32768)
288
+ ]
289
+ logn_tensor = torch.tensor(logn_list)[None, :, None, None]
290
+ self.register_buffer("logn_tensor", logn_tensor, persistent=False)
291
+
292
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
293
+ self.softmax_in_fp32 = config.softmax_in_fp32 if hasattr(config, 'softmax_in_fp32') else False
294
+ self.use_cache_quantization = config.use_cache_quantization if hasattr(config, 'use_cache_quantization') else False
295
+ self.use_cache_kernel = config.use_cache_kernel if hasattr(config,'use_cache_kernel') else False
296
+ cache_dtype = torch.float
297
+ if self.bf16:
298
+ cache_dtype=torch.bfloat16
299
+ elif config.fp16:
300
+ cache_dtype = torch.float16
301
+ self.cache_qmax = torch.tensor(torch.iinfo(torch.uint8).max, dtype=cache_dtype)
302
+ self.cache_qmin = torch.tensor(torch.iinfo(torch.uint8).min, dtype=cache_dtype)
303
+
304
+ if config.use_cache_quantization and config.use_cache_kernel:
305
+ # pre check if the support files existing
306
+ module_root = pathlib.Path(__file__).parent
307
+ src_files = ("cache_autogptq_cuda_256.cpp", "cache_autogptq_cuda_kernel_256.cu")
308
+ if any(not (module_root/src).is_file() for src in src_files):
309
+ warnings.warn("KV cache kernel source files (.cpp and .cu) not found.")
310
+ self.cache_kernels = None
311
+ else:
312
+ try:
313
+ from .cpp_kernels import cache_autogptq_cuda_256
314
+ self.cache_kernels = cache_autogptq_cuda_256
315
+ except ImportError:
316
+ warnings.warn("Failed to import KV cache kernels.")
317
+ self.cache_kernels = None
318
+
319
+ def _attn(self, query, key, value, causal_mask=None, attention_mask=None, head_mask=None):
320
+ device = query.device
321
+ if self.use_cache_quantization:
322
+ qk, qk_scale, qk_zero = key
323
+ if self.use_cache_kernel and self.cache_kernels is not None:
324
+ shape = query.shape[:-1] + (qk.shape[-2],)
325
+ attn_weights = torch.zeros(shape, dtype=torch.float16, device=device)
326
+ self.cache_kernels.vecquant8matmul_batched_faster_old(
327
+ query.contiguous() if query.dtype == torch.float16 else query.to(torch.float16).contiguous(),
328
+ qk.transpose(-1, -2).contiguous(),
329
+ attn_weights,
330
+ qk_scale.contiguous() if qk_scale.dtype == torch.float16 else qk_scale.to(torch.float16).contiguous(),
331
+ qk_zero.contiguous()if qk_zero.dtype == torch.float16 else qk_zero.to(torch.float16).contiguous())
332
+ # attn_weights = attn_weights.to(query.dtype).contiguous()
333
+ else:
334
+ key = dequantize_cache_torch(qk, qk_scale, qk_zero)
335
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
336
+ else:
337
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
338
+
339
+ if self.scale_attn_weights:
340
+ if self.use_cache_quantization:
341
+ size_temp = value[0].size(-1)
342
+ else:
343
+ size_temp = value.size(-1)
344
+ attn_weights = attn_weights / (size_temp ** 0.5)
345
+
346
+ mask_value = torch.finfo(attn_weights.dtype).min
347
+ if causal_mask is not None:
348
+ attn_weights = torch.where(
349
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
350
+ )
351
+
352
+ if attention_mask is not None:
353
+ attn_weights = attn_weights + attention_mask
354
+
355
+ if self.softmax_in_fp32:
356
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
357
+ else:
358
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
359
+
360
+ attn_weights = attn_weights.type(query.dtype)
361
+ attn_weights = self.attn_dropout(attn_weights)
362
+
363
+ if head_mask is not None:
364
+ attn_weights = attn_weights * head_mask
365
+
366
+ if self.use_cache_quantization:
367
+ qv, qv_scale, qv_zero = value
368
+ if self.use_cache_kernel and self.cache_kernels is not None:
369
+ shape = attn_weights.shape[:-1] + (query.shape[-1],)
370
+ attn_output = torch.zeros(shape, dtype=torch.float16, device=device)
371
+ self.cache_kernels.vecquant8matmul_batched_column_compression_faster_old(
372
+ attn_weights.contiguous() if attn_weights.dtype == torch.float16 else attn_weights.to(torch.float16).contiguous(),
373
+ qv.contiguous(), # dtype: int32
374
+ attn_output,
375
+ qv_scale.contiguous() if qv_scale.dtype == torch.float16 else qv_scale.to(torch.float16).contiguous(),
376
+ qv_zero.contiguous() if qv_zero.dtype == torch.float16 else qv_zero.to(torch.float16).contiguous())
377
+ if attn_output.dtype != query.dtype:
378
+ attn_output = attn_output.to(query.dtype)
379
+ attn_weights = attn_weights.to(query.dtype)
380
+ else:
381
+ value = dequantize_cache_torch(qv, qv_scale, qv_zero)
382
+ attn_output = torch.matmul(attn_weights, value)
383
+ else:
384
+ attn_output = torch.matmul(attn_weights, value)
385
+
386
+ attn_output = attn_output.transpose(1, 2)
387
+
388
+ return attn_output, attn_weights
389
+
390
+ def _split_heads(self, tensor, num_heads, attn_head_size):
391
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
392
+ tensor = tensor.view(new_shape)
393
+ return tensor
394
+
395
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
396
+ tensor = tensor.contiguous()
397
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
398
+ return tensor.view(new_shape)
399
+
400
+ def forward(
401
+ self,
402
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
403
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
404
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
405
+ attention_mask: Optional[torch.FloatTensor] = None,
406
+ head_mask: Optional[torch.FloatTensor] = None,
407
+ encoder_hidden_states: Optional[torch.Tensor] = None,
408
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
409
+ output_attentions: Optional[bool] = False,
410
+ use_cache: Optional[bool] = False,
411
+ ):
412
+ mixed_x_layer = self.c_attn(hidden_states)
413
+
414
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
415
+
416
+ query = self._split_heads(query, self.num_heads, self.head_dim)
417
+ key = self._split_heads(key, self.num_heads, self.head_dim)
418
+ value = self._split_heads(value, self.num_heads, self.head_dim)
419
+
420
+ if rotary_pos_emb_list is not None:
421
+ cur_len = query.shape[1]
422
+ if len(rotary_pos_emb_list) == 1:
423
+ rotary_pos_emb = rotary_pos_emb_list[0]
424
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
425
+ rotary_pos_emb = (rotary_pos_emb,) * 2
426
+ q_pos_emb, k_pos_emb = rotary_pos_emb
427
+ # Slice the pos emb for current inference
428
+ query = apply_rotary_pos_emb(query, q_pos_emb)
429
+ key = apply_rotary_pos_emb(key, k_pos_emb)
430
+ else:
431
+ query_list = []
432
+ key_list = []
433
+ for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
434
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
435
+ rotary_pos_emb = (rotary_pos_emb,) * 2
436
+ q_pos_emb, k_pos_emb = rotary_pos_emb
437
+ # Slice the pos emb for current inference
438
+ query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
439
+ key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
440
+ query = torch.cat(query_list, dim=0)
441
+ key = torch.cat(key_list, dim=0)
442
+
443
+ if self.use_cache_quantization:
444
+ key = quantize_cache_v(key.permute(0, 2, 1, 3),
445
+ bits=8,
446
+ qmin=self.cache_qmin,
447
+ qmax=self.cache_qmax)
448
+ value = quantize_cache_v(value.permute(0, 2, 1, 3),
449
+ bits=8,
450
+ qmin=self.cache_qmin,
451
+ qmax=self.cache_qmax)
452
+
453
+
454
+ if layer_past is not None:
455
+ past_key, past_value = layer_past[0], layer_past[1]
456
+ if self.use_cache_quantization:
457
+ # use_cache_quantization:
458
+ # present=((q_key,key_scale,key_zero_point),
459
+ # (q_value,value_scale,value_zero_point))
460
+ key = (torch.cat((past_key[0], key[0]), dim=2),
461
+ torch.cat((past_key[1], key[1]), dim=2),
462
+ torch.cat((past_key[2], key[2]), dim=2))
463
+ value = (torch.cat((past_value[0], value[0]), dim=2),
464
+ torch.cat((past_value[1], value[1]), dim=2),
465
+ torch.cat((past_value[2], value[2]), dim=2))
466
+ else:
467
+ # not use_cache_quantization:
468
+ # present=(key,value)
469
+ key = torch.cat((past_key, key), dim=1)
470
+ value = torch.cat((past_value, value), dim=1)
471
+
472
+ if use_cache:
473
+ present = (key, value)
474
+ else:
475
+ present = None
476
+
477
+ key_size = key[0].size(2) if self.use_cache_quantization else key.size(1)
478
+ if key_size > self.seq_length and self.use_logn_attn and not self.training:
479
+ if self.use_cache_quantization:
480
+ seq_start = key[0].size(2) - query.size(1)
481
+ seq_end = key[0].size(2)
482
+ else:
483
+ seq_start = key.size(1) - query.size(1)
484
+ seq_end = key.size(1)
485
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :].type_as(query)
486
+ query = query * logn_tensor.expand_as(query)
487
+
488
+ if (
489
+ self.use_flash_attn
490
+ and flash_attn_unpadded_func is not None
491
+ and not self.is_fp32
492
+ and query.is_cuda
493
+ ):
494
+ q, k, v = query, key, value
495
+ attn_output = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
496
+ else:
497
+ key_size = key[0].size(2) if self.use_cache_quantization else key.size(1)
498
+ if query.size(1) == key_size:
499
+ causal_mask = torch.tril(
500
+ torch.ones((key_size, key_size), dtype=torch.bool, device=query.device)
501
+ ).view(1, 1, key_size, key_size)
502
+ else:
503
+ causal_mask = None
504
+ query = query.permute(0, 2, 1, 3)
505
+ if not self.use_cache_quantization:
506
+ key = key.permute(0, 2, 1, 3)
507
+ value = value.permute(0, 2, 1, 3)
508
+ if (
509
+ causal_mask is None
510
+ and self.use_flash_attn
511
+ and flash_attn_unpadded_func is not None
512
+ and not self.is_fp32
513
+ and not query.is_cuda
514
+ ):
515
+ raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)
516
+
517
+ if not self.use_cache_quantization and SUPPORT_TORCH2:
518
+ if attention_mask is not None:
519
+ attention_mask = attention_mask.expand(-1, -1, query.size(2), -1)
520
+ if causal_mask is not None:
521
+ attention_mask = attention_mask.masked_fill(~causal_mask, torch.finfo(query.dtype).min)
522
+ else:
523
+ attention_mask = causal_mask
524
+ attn_output = F.scaled_dot_product_attention(
525
+ query, key, value, attn_mask=attention_mask
526
+ ).transpose(1, 2)
527
+ attn_weight = None
528
+ else:
529
+ attn_output, attn_weight = self._attn(
530
+ query, key, value, causal_mask, attention_mask, head_mask
531
+ )
532
+ context_layer = self._merge_heads(
533
+ attn_output, self.num_heads, self.head_dim
534
+ )
535
+
536
+ attn_output = self.c_proj(context_layer)
537
+
538
+ outputs = (attn_output, present)
539
+ if output_attentions:
540
+ if (
541
+ self.use_flash_attn
542
+ and flash_attn_unpadded_func is not None
543
+ and not self.is_fp32
544
+ ):
545
+ raise ValueError("Cannot output attentions while using flash-attn")
546
+ elif not self.use_cache_quantization and SUPPORT_TORCH2:
547
+ raise ValueError("Cannot output attentions while using scaled_dot_product_attention")
548
+ else:
549
+ outputs += (attn_weight,)
550
+
551
+ return outputs
552
+
553
+
554
+ class QWenMLP(nn.Module):
555
+ def __init__(self, config):
556
+ super().__init__()
557
+ self.w1 = nn.Linear(
558
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
559
+ )
560
+ self.w2 = nn.Linear(
561
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
562
+ )
563
+ ff_dim_in = config.intermediate_size // 2
564
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
565
+
566
+ def forward(self, hidden_states):
567
+ a1 = self.w1(hidden_states)
568
+ a2 = self.w2(hidden_states)
569
+ intermediate_parallel = a1 * F.silu(a2)
570
+ output = self.c_proj(intermediate_parallel)
571
+ return output
572
+
573
+
574
+ class QWenBlock(nn.Module):
575
+ def __init__(self, config):
576
+ super().__init__()
577
+ hidden_size = config.hidden_size
578
+ self.bf16 = config.bf16
579
+
580
+ self.ln_1 = RMSNorm(
581
+ hidden_size,
582
+ eps=config.layer_norm_epsilon,
583
+ )
584
+ self.attn = QWenAttention(config)
585
+ self.ln_2 = RMSNorm(
586
+ hidden_size,
587
+ eps=config.layer_norm_epsilon,
588
+ )
589
+
590
+ self.mlp = QWenMLP(config)
591
+
592
+ def forward(
593
+ self,
594
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
595
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
596
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
597
+ attention_mask: Optional[torch.FloatTensor] = None,
598
+ head_mask: Optional[torch.FloatTensor] = None,
599
+ encoder_hidden_states: Optional[torch.Tensor] = None,
600
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
601
+ use_cache: Optional[bool] = False,
602
+ output_attentions: Optional[bool] = False,
603
+ ):
604
+ layernorm_output = self.ln_1(hidden_states)
605
+
606
+ attn_outputs = self.attn(
607
+ layernorm_output,
608
+ rotary_pos_emb_list,
609
+ layer_past=layer_past,
610
+ attention_mask=attention_mask,
611
+ head_mask=head_mask,
612
+ use_cache=use_cache,
613
+ output_attentions=output_attentions,
614
+ )
615
+ attn_output = attn_outputs[0]
616
+
617
+ outputs = attn_outputs[1:]
618
+
619
+ residual = hidden_states
620
+ layernorm_input = attn_output + residual
621
+
622
+ layernorm_output = self.ln_2(layernorm_input)
623
+
624
+ residual = layernorm_input
625
+ mlp_output = self.mlp(layernorm_output)
626
+ hidden_states = residual + mlp_output
627
+
628
+ if use_cache:
629
+ outputs = (hidden_states,) + outputs
630
+ else:
631
+ outputs = (hidden_states,) + outputs[1:]
632
+
633
+ return outputs
634
+
635
+
636
+ class QWenPreTrainedModel(PreTrainedModel):
637
+ config_class = QWenConfig
638
+ base_model_prefix = "transformer"
639
+ is_parallelizable = False
640
+ supports_gradient_checkpointing = True
641
+ _no_split_modules = ["QWenBlock"]
642
+ _skip_keys_device_placement = "past_key_values"
643
+
644
+ def __init__(self, *inputs, **kwargs):
645
+ super().__init__(*inputs, **kwargs)
646
+
647
+ def _init_weights(self, module):
648
+ """Initialize the weights."""
649
+ if isinstance(module, nn.Linear):
650
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
651
+ if module.bias is not None:
652
+ module.bias.data.zero_()
653
+ elif isinstance(module, nn.Embedding):
654
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
655
+ if module.padding_idx is not None:
656
+ module.weight.data[module.padding_idx].zero_()
657
+ elif isinstance(module, RMSNorm):
658
+ module.weight.data.fill_(1.0)
659
+
660
+ for name, p in module.named_parameters():
661
+ if name == "c_proj.weight":
662
+ p.data.normal_(
663
+ mean=0.0,
664
+ std=(
665
+ self.config.initializer_range
666
+ / math.sqrt(2 * self.config.num_hidden_layers)
667
+ ),
668
+ )
669
+
670
+ def _set_gradient_checkpointing(self, module, value=False):
671
+ if isinstance(module, QWenModel):
672
+ module.gradient_checkpointing = value
673
+
674
+
675
+ class QWenModel(QWenPreTrainedModel):
676
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
677
+
678
+ def __init__(self, config):
679
+ super().__init__(config)
680
+ self.vocab_size = config.vocab_size
681
+ self.num_hidden_layers = config.num_hidden_layers
682
+ self.embed_dim = config.hidden_size
683
+ self.use_cache_quantization = self.config.use_cache_quantization if hasattr(self.config, 'use_cache_quantization') else False
684
+
685
+ self.gradient_checkpointing = False
686
+ self.use_dynamic_ntk = config.use_dynamic_ntk
687
+ self.seq_length = config.seq_length
688
+
689
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
690
+
691
+ self.drop = nn.Dropout(config.emb_dropout_prob)
692
+
693
+ if config.rotary_pct == 1.0:
694
+ self.rotary_ndims = None
695
+ else:
696
+ assert config.rotary_pct < 1
697
+ self.rotary_ndims = int(
698
+ config.kv_channels * config.rotary_pct
699
+ )
700
+ dim = (
701
+ self.rotary_ndims
702
+ if self.rotary_ndims is not None
703
+ else config.kv_channels
704
+ )
705
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
706
+
707
+ self.use_flash_attn = config.use_flash_attn
708
+ self.is_fp32 = not (config.bf16 or config.fp16)
709
+
710
+ self.h = nn.ModuleList(
711
+ [
712
+ QWenBlock(
713
+ config
714
+ )
715
+ for i in range(config.num_hidden_layers)
716
+ ]
717
+ )
718
+ self.ln_f = RMSNorm(
719
+ self.embed_dim,
720
+ eps=config.layer_norm_epsilon,
721
+ )
722
+
723
+ self.post_init()
724
+
725
+ def get_input_embeddings(self):
726
+ return self.wte
727
+
728
+ def set_input_embeddings(self, new_embeddings):
729
+ self.wte = new_embeddings
730
+
731
+ def get_ntk_alpha(self, true_seq_len):
732
+ context_value = math.log(true_seq_len / self.seq_length, 2) + 1
733
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
734
+ ntk_alpha = max(ntk_alpha, 1)
735
+ return ntk_alpha
736
+
737
+ def forward(
738
+ self,
739
+ input_ids: Optional[torch.LongTensor] = None,
740
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
741
+ attention_mask: Optional[torch.FloatTensor] = None,
742
+ token_type_ids: Optional[torch.LongTensor] = None,
743
+ position_ids: Optional[torch.LongTensor] = None,
744
+ head_mask: Optional[torch.FloatTensor] = None,
745
+ inputs_embeds: Optional[torch.FloatTensor] = None,
746
+ encoder_hidden_states: Optional[torch.Tensor] = None,
747
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
748
+ use_cache: Optional[bool] = None,
749
+ output_attentions: Optional[bool] = None,
750
+ output_hidden_states: Optional[bool] = None,
751
+ return_dict: Optional[bool] = None,
752
+ ):
753
+ output_attentions = (
754
+ output_attentions
755
+ if output_attentions is not None
756
+ else self.config.output_attentions
757
+ )
758
+ output_hidden_states = (
759
+ output_hidden_states
760
+ if output_hidden_states is not None
761
+ else self.config.output_hidden_states
762
+ )
763
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
764
+ return_dict = (
765
+ return_dict if return_dict is not None else self.config.use_return_dict
766
+ )
767
+
768
+ if input_ids is not None and inputs_embeds is not None:
769
+ raise ValueError(
770
+ "You cannot specify both input_ids and inputs_embeds at the same time"
771
+ )
772
+ elif input_ids is not None:
773
+ input_shape = input_ids.size()
774
+ input_ids = input_ids.view(-1, input_shape[-1])
775
+ batch_size = input_ids.shape[0]
776
+ elif inputs_embeds is not None:
777
+ input_shape = inputs_embeds.size()[:-1]
778
+ batch_size = inputs_embeds.shape[0]
779
+ else:
780
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
781
+
782
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
783
+
784
+ if token_type_ids is not None:
785
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
786
+ if position_ids is not None:
787
+ position_ids = position_ids.view(-1, input_shape[-1])
788
+
789
+ if past_key_values is None:
790
+ past_length = 0
791
+ past_key_values = tuple([None] * len(self.h))
792
+ else:
793
+ if self.use_cache_quantization:
794
+ past_length = past_key_values[0][0][0].size(2)
795
+ else:
796
+ past_length = past_key_values[0][0].size(-2)
797
+ if position_ids is None:
798
+ position_ids = torch.arange(
799
+ past_length,
800
+ input_shape[-1] + past_length,
801
+ dtype=torch.long,
802
+ device=device,
803
+ )
804
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
805
+
806
+ if attention_mask is not None:
807
+ if batch_size <= 0:
808
+ raise ValueError("batch_size has to be defined and > 0")
809
+ attention_mask = attention_mask.view(batch_size, -1)
810
+ attention_mask = attention_mask[:, None, None, :]
811
+ attention_mask = attention_mask.to(dtype=self.dtype)
812
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
813
+
814
+ encoder_attention_mask = None
815
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
816
+
817
+ if inputs_embeds is None:
818
+ inputs_embeds = self.wte(input_ids)
819
+ hidden_states = inputs_embeds
820
+
821
+ kv_seq_len = hidden_states.size()[1]
822
+ if past_key_values[0] is not None:
823
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
824
+ if self.use_cache_quantization:
825
+ kv_seq_len += past_key_values[0][0][0].shape[2]
826
+ else:
827
+ kv_seq_len += past_key_values[0][0].shape[1]
828
+
829
+ if self.training or not self.use_dynamic_ntk:
830
+ ntk_alpha_list = [1.0]
831
+ elif kv_seq_len != hidden_states.size()[1]:
832
+ ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
833
+ else:
834
+ ntk_alpha_list = []
835
+ if attention_mask is not None and kv_seq_len > self.seq_length:
836
+ true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
837
+ for i in range(hidden_states.size()[0]):
838
+ true_seq_len = true_seq_lens[i].item()
839
+ ntk_alpha = self.get_ntk_alpha(true_seq_len)
840
+ ntk_alpha_list.append(ntk_alpha)
841
+ else:
842
+ ntk_alpha = self.get_ntk_alpha(kv_seq_len)
843
+ ntk_alpha_list.append(ntk_alpha)
844
+ self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
845
+ rotary_pos_emb_list = [
846
+ self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) for ntk_alpha in ntk_alpha_list
847
+ ]
848
+
849
+ hidden_states = self.drop(hidden_states)
850
+ output_shape = input_shape + (hidden_states.size(-1),)
851
+
852
+ if self.gradient_checkpointing and self.training:
853
+ if use_cache:
854
+ logger.warning_once(
855
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
856
+ )
857
+ use_cache = False
858
+
859
+ presents = () if use_cache else None
860
+ all_self_attentions = () if output_attentions else None
861
+ all_hidden_states = () if output_hidden_states else None
862
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
863
+
864
+ if output_hidden_states:
865
+ all_hidden_states = all_hidden_states + (hidden_states,)
866
+
867
+ if self.gradient_checkpointing and self.training:
868
+
869
+ def create_custom_forward(module):
870
+ def custom_forward(*inputs):
871
+ # None for past_key_value
872
+ return module(*inputs, use_cache, output_attentions)
873
+
874
+ return custom_forward
875
+
876
+ outputs = torch.utils.checkpoint.checkpoint(
877
+ create_custom_forward(block),
878
+ hidden_states,
879
+ rotary_pos_emb_list,
880
+ None,
881
+ attention_mask,
882
+ head_mask[i],
883
+ encoder_hidden_states,
884
+ encoder_attention_mask,
885
+ )
886
+ else:
887
+ outputs = block(
888
+ hidden_states,
889
+ layer_past=layer_past,
890
+ rotary_pos_emb_list=rotary_pos_emb_list,
891
+ attention_mask=attention_mask,
892
+ head_mask=head_mask[i],
893
+ encoder_hidden_states=encoder_hidden_states,
894
+ encoder_attention_mask=encoder_attention_mask,
895
+ use_cache=use_cache,
896
+ output_attentions=output_attentions,
897
+ )
898
+
899
+ hidden_states = outputs[0]
900
+ if use_cache is True:
901
+ presents = presents + (outputs[1],)
902
+
903
+ if output_attentions:
904
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
905
+
906
+ hidden_states = self.ln_f(hidden_states)
907
+ hidden_states = hidden_states.view(output_shape)
908
+ # Add last hidden state
909
+ if output_hidden_states:
910
+ all_hidden_states = all_hidden_states + (hidden_states,)
911
+
912
+ if not return_dict:
913
+ return tuple(
914
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
915
+ )
916
+
917
+ return BaseModelOutputWithPast(
918
+ last_hidden_state=hidden_states,
919
+ past_key_values=presents,
920
+ hidden_states=all_hidden_states,
921
+ attentions=all_self_attentions,
922
+ )
923
+
924
+
925
+ class QWenLMHeadModel(QWenPreTrainedModel):
926
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
927
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
928
+
929
+ def __init__(self, config):
930
+ super().__init__(config)
931
+ assert (
932
+ config.bf16 + config.fp16 + config.fp32 <= 1
933
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
934
+
935
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
936
+
937
+ if autoset_precision:
938
+ if SUPPORT_BF16:
939
+ logger.warn(
940
+ "The model is automatically converting to bf16 for faster inference. "
941
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
942
+ )
943
+ config.bf16 = True
944
+ elif SUPPORT_FP16:
945
+ logger.warn(
946
+ "The model is automatically converting to fp16 for faster inference. "
947
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
948
+ )
949
+ config.fp16 = True
950
+ else:
951
+ config.fp32 = True
952
+
953
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
954
+ 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\".")
955
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
956
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
957
+ if config.fp32:
958
+ if SUPPORT_BF16:
959
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
960
+ elif SUPPORT_FP16:
961
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
962
+
963
+ if config.use_flash_attn == "auto":
964
+ if config.bf16 or config.fp16:
965
+ logger.warn("Try importing flash-attention for faster inference...")
966
+ config.use_flash_attn = True
967
+ else:
968
+ config.use_flash_attn = False
969
+ if config.use_flash_attn and config.fp32:
970
+ logger.warn("Flash attention will be disabled because it does NOT support fp32.")
971
+
972
+ if config.use_flash_attn:
973
+ _import_flash_attn()
974
+
975
+ self.transformer = QWenModel(config)
976
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
977
+
978
+ if config.bf16:
979
+ self.transformer.bfloat16()
980
+ self.lm_head.bfloat16()
981
+ if config.fp16:
982
+ self.transformer.half()
983
+ self.lm_head.half()
984
+ self.post_init()
985
+
986
+ def get_output_embeddings(self):
987
+ return self.lm_head
988
+
989
+ def set_output_embeddings(self, new_embeddings):
990
+ self.lm_head = new_embeddings
991
+
992
+ def prepare_inputs_for_generation(
993
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
994
+ ):
995
+ if past_key_values:
996
+ input_ids = input_ids[:, -1].unsqueeze(-1)
997
+
998
+ if input_ids.size(0) == 1:
999
+ attention_mask = None
1000
+ else:
1001
+ attention_mask = kwargs.get("attention_mask", None)
1002
+
1003
+ if inputs_embeds is not None and past_key_values is None:
1004
+ model_inputs = {"inputs_embeds": inputs_embeds}
1005
+ else:
1006
+ model_inputs = {"input_ids": input_ids}
1007
+
1008
+ model_inputs.update(
1009
+ {
1010
+ "past_key_values": past_key_values,
1011
+ "use_cache": kwargs.get("use_cache"),
1012
+ "attention_mask": attention_mask,
1013
+ }
1014
+ )
1015
+ return model_inputs
1016
+
1017
+ def forward(
1018
+ self,
1019
+ input_ids: Optional[torch.LongTensor] = None,
1020
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1021
+ attention_mask: Optional[torch.FloatTensor] = None,
1022
+ token_type_ids: Optional[torch.LongTensor] = None,
1023
+ position_ids: Optional[torch.LongTensor] = None,
1024
+ head_mask: Optional[torch.FloatTensor] = None,
1025
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1026
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1027
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1028
+ labels: Optional[torch.LongTensor] = None,
1029
+ use_cache: Optional[bool] = None,
1030
+ output_attentions: Optional[bool] = None,
1031
+ output_hidden_states: Optional[bool] = None,
1032
+ return_dict: Optional[bool] = None,
1033
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1034
+
1035
+ return_dict = (
1036
+ return_dict if return_dict is not None else self.config.use_return_dict
1037
+ )
1038
+
1039
+ transformer_outputs = self.transformer(
1040
+ input_ids,
1041
+ past_key_values=past_key_values,
1042
+ attention_mask=attention_mask,
1043
+ token_type_ids=token_type_ids,
1044
+ position_ids=position_ids,
1045
+ head_mask=head_mask,
1046
+ inputs_embeds=inputs_embeds,
1047
+ encoder_hidden_states=encoder_hidden_states,
1048
+ encoder_attention_mask=encoder_attention_mask,
1049
+ use_cache=use_cache,
1050
+ output_attentions=output_attentions,
1051
+ output_hidden_states=output_hidden_states,
1052
+ return_dict=return_dict,
1053
+ )
1054
+ hidden_states = transformer_outputs[0]
1055
+
1056
+ lm_logits = self.lm_head(hidden_states)
1057
+
1058
+ loss = None
1059
+ if labels is not None:
1060
+ labels = labels.to(lm_logits.device)
1061
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1062
+ shift_labels = labels[..., 1:].contiguous()
1063
+ loss_fct = CrossEntropyLoss()
1064
+ loss = loss_fct(
1065
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1066
+ )
1067
+
1068
+ if not return_dict:
1069
+ output = (lm_logits,) + transformer_outputs[1:]
1070
+ return ((loss,) + output) if loss is not None else output
1071
+
1072
+ return CausalLMOutputWithPast(
1073
+ loss=loss,
1074
+ logits=lm_logits,
1075
+ past_key_values=transformer_outputs.past_key_values,
1076
+ hidden_states=transformer_outputs.hidden_states,
1077
+ attentions=transformer_outputs.attentions,
1078
+ )
1079
+
1080
+ @staticmethod
1081
+ def _reorder_cache(
1082
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1083
+ ) -> Tuple[Tuple[torch.Tensor]]:
1084
+
1085
+ return tuple(
1086
+ tuple(
1087
+ past_state.index_select(0, beam_idx.to(past_state.device))
1088
+ for past_state in layer_past
1089
+ )
1090
+ for layer_past in past_key_values
1091
+ )
1092
+
1093
+ def chat(
1094
+ self,
1095
+ tokenizer: PreTrainedTokenizer,
1096
+ query: str,
1097
+ history: Optional[HistoryType],
1098
+ system: str = "You are a helpful assistant.",
1099
+ stream: Optional[bool] = _SENTINEL,
1100
+ stop_words_ids: Optional[List[List[int]]] = None,
1101
+ generation_config: Optional[GenerationConfig] = None,
1102
+ **kwargs,
1103
+ ) -> Tuple[str, HistoryType]:
1104
+ generation_config = generation_config if generation_config is not None else self.generation_config
1105
+
1106
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
1107
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1108
+ if history is None:
1109
+ history = []
1110
+ else:
1111
+ # make a copy of the user's input such that is is left untouched
1112
+ history = copy.deepcopy(history)
1113
+
1114
+ if stop_words_ids is None:
1115
+ stop_words_ids = []
1116
+
1117
+ max_window_size = kwargs.get('max_window_size', None)
1118
+ if max_window_size is None:
1119
+ max_window_size = generation_config.max_window_size
1120
+ raw_text, context_tokens = make_context(
1121
+ tokenizer,
1122
+ query,
1123
+ history=history,
1124
+ system=system,
1125
+ max_window_size=max_window_size,
1126
+ chat_format=generation_config.chat_format,
1127
+ )
1128
+
1129
+ stop_words_ids.extend(get_stop_words_ids(
1130
+ generation_config.chat_format, tokenizer
1131
+ ))
1132
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1133
+ outputs = self.generate(
1134
+ input_ids,
1135
+ stop_words_ids=stop_words_ids,
1136
+ return_dict_in_generate=False,
1137
+ generation_config=generation_config,
1138
+ **kwargs,
1139
+ )
1140
+
1141
+ response = decode_tokens(
1142
+ outputs[0],
1143
+ tokenizer,
1144
+ raw_text_len=len(raw_text),
1145
+ context_length=len(context_tokens),
1146
+ chat_format=generation_config.chat_format,
1147
+ verbose=False,
1148
+ errors='replace'
1149
+ )
1150
+
1151
+ # as history is a copy of the user inputs,
1152
+ # we can always return the new turn to the user.
1153
+ # separating input history and output history also enables the user
1154
+ # to implement more complex history management
1155
+ history.append((query, response))
1156
+
1157
+ return response, history
1158
+
1159
+ def chat_stream(
1160
+ self,
1161
+ tokenizer: PreTrainedTokenizer,
1162
+ query: str,
1163
+ history: Optional[HistoryType],
1164
+ system: str = "You are a helpful assistant.",
1165
+ stop_words_ids: Optional[List[List[int]]] = None,
1166
+ logits_processor: Optional[LogitsProcessorList] = None,
1167
+ generation_config: Optional[GenerationConfig] = None,
1168
+ **kwargs,
1169
+ ) -> Generator[str, Any, None]:
1170
+ generation_config = generation_config if generation_config is not None else self.generation_config
1171
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1172
+ if history is None:
1173
+ history = []
1174
+ if stop_words_ids is None:
1175
+ stop_words_ids = []
1176
+
1177
+ max_window_size = kwargs.get('max_window_size', None)
1178
+ if max_window_size is None:
1179
+ max_window_size = generation_config.max_window_size
1180
+ raw_text, context_tokens = make_context(
1181
+ tokenizer,
1182
+ query,
1183
+ history=history,
1184
+ system=system,
1185
+ max_window_size=max_window_size,
1186
+ chat_format=generation_config.chat_format,
1187
+ )
1188
+
1189
+ stop_words_ids.extend(get_stop_words_ids(
1190
+ generation_config.chat_format, tokenizer
1191
+ ))
1192
+ if stop_words_ids is not None:
1193
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1194
+ stop_words_ids=stop_words_ids,
1195
+ eos_token_id=generation_config.eos_token_id,
1196
+ )
1197
+ if logits_processor is None:
1198
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1199
+ else:
1200
+ logits_processor.append(stop_words_logits_processor)
1201
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1202
+
1203
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1204
+ self.__class__.generate_stream = NewGenerationMixin.generate
1205
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1206
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1207
+
1208
+ def stream_generator():
1209
+ outputs = []
1210
+ for token in self.generate_stream(
1211
+ input_ids,
1212
+ return_dict_in_generate=False,
1213
+ generation_config=stream_config,
1214
+ logits_processor=logits_processor,
1215
+ seed=-1,
1216
+ **kwargs):
1217
+ outputs.append(token.item())
1218
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
1219
+
1220
+ return stream_generator()
1221
+
1222
+ def generate(
1223
+ self,
1224
+ inputs: Optional[torch.Tensor] = None,
1225
+ generation_config: Optional[GenerationConfig] = None,
1226
+ logits_processor: Optional[LogitsProcessorList] = None,
1227
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1228
+ prefix_allowed_tokens_fn: Optional[
1229
+ Callable[[int, torch.Tensor], List[int]]
1230
+ ] = None,
1231
+ synced_gpus: Optional[bool] = None,
1232
+ assistant_model: Optional["PreTrainedModel"] = None,
1233
+ streamer: Optional["BaseStreamer"] = None,
1234
+ **kwargs,
1235
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1236
+ generation_config = generation_config if generation_config is not None else self.generation_config
1237
+
1238
+ # Process stop_words_ids.
1239
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1240
+ if stop_words_ids is None and generation_config is not None:
1241
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1242
+ if stop_words_ids is None:
1243
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1244
+
1245
+ if stop_words_ids is not None:
1246
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1247
+ stop_words_ids=stop_words_ids,
1248
+ eos_token_id=generation_config.eos_token_id,
1249
+ )
1250
+ if logits_processor is None:
1251
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1252
+ else:
1253
+ logits_processor.append(stop_words_logits_processor)
1254
+
1255
+ return super().generate(
1256
+ inputs,
1257
+ generation_config=generation_config,
1258
+ logits_processor=logits_processor,
1259
+ stopping_criteria=stopping_criteria,
1260
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1261
+ synced_gpus=synced_gpus,
1262
+ assistant_model=assistant_model,
1263
+ streamer=streamer,
1264
+ **kwargs,
1265
+ )
1266
+
1267
+
1268
+ class RotaryEmbedding(torch.nn.Module):
1269
+ def __init__(self, dim, base=10000):
1270
+ super().__init__()
1271
+ self.dim = dim
1272
+ self.base = base
1273
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1274
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1275
+ if importlib.util.find_spec("einops") is None:
1276
+ raise RuntimeError("einops is required for Rotary Embedding")
1277
+
1278
+ self._rotary_pos_emb_cache = None
1279
+ self._seq_len_cached = 0
1280
+ self._ntk_alpha_cached = 1.0
1281
+ self._ntk_alpha_cached_list = [1.0]
1282
+
1283
+ def update_rotary_pos_emb_cache(self, seqlen, ntk_alpha=1.0):
1284
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1285
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1286
+ self.inv_freq = 1.0 / (
1287
+ base
1288
+ ** (
1289
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1290
+ / self.dim
1291
+ )
1292
+ )
1293
+ self._seq_len_cached = max(2 * seqlen, 16)
1294
+ self._ntk_alpha_cached = ntk_alpha
1295
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1296
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1297
+
1298
+ emb = torch.cat((freqs, freqs), dim=-1)
1299
+ from einops import rearrange
1300
+
1301
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1302
+
1303
+ cos, sin = emb.cos(), emb.sin()
1304
+ self._rotary_pos_emb_cache = [cos, sin]
1305
+
1306
+ def forward(self, max_seq_len, ntk_alpha=1.0):
1307
+ self.update_rotary_pos_emb_cache(max_seq_len, ntk_alpha)
1308
+ cos, sin = self._rotary_pos_emb_cache
1309
+ return [cos[:, :max_seq_len], sin[:, :max_seq_len]]
1310
+
1311
+
1312
+ def _rotate_half(x):
1313
+ from einops import rearrange
1314
+
1315
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1316
+ x1, x2 = x.unbind(dim=-2)
1317
+ return torch.cat((-x2, x1), dim=-1)
1318
+
1319
+
1320
+ def apply_rotary_pos_emb(t, freqs):
1321
+ """ Apply rotary embedding to the first rotary_dim of the iput
1322
+
1323
+ Arguments:
1324
+ t (tensor(batch_size, seq_len, n_head, head_dim)):
1325
+ the input embedding/hidden states
1326
+ freqs (list[tensor(1, seq_len, 1, rotary_dim), tensor(1, seq_len, 1, rotary_dim)]):
1327
+ the cached cos/sin position embeddings
1328
+ """
1329
+ rot_dim = freqs[0].shape[-1]
1330
+ cos, sin = freqs
1331
+ t_float = t.float()
1332
+ if apply_rotary_emb_func is not None and t.is_cuda:
1333
+ # apply_rotary_emb in flash_attn requires cos/sin to be of
1334
+ # shape (seqlen, rotary_dim / 2) and apply rotary embedding
1335
+ # to the first rotary_dim of the input
1336
+ cos = cos.squeeze(0).squeeze(1)[:, : rot_dim // 2]
1337
+ sin = sin.squeeze(0).squeeze(1)[:, : rot_dim // 2]
1338
+ return apply_rotary_emb_func(t_float, cos, sin).type_as(t)
1339
+ else:
1340
+ t_rot, t_pass = t_float[..., :rot_dim], t_float[..., rot_dim:]
1341
+ t_rot = (t_rot * cos) + (_rotate_half(t_rot) * sin)
1342
+ return torch.cat((t_rot, t_pass), dim=-1).type_as(t)
1343
+
1344
+
1345
+ class RMSNorm(torch.nn.Module):
1346
+ def __init__(self, dim: int, eps: float = 1e-6):
1347
+ super().__init__()
1348
+ self.eps = eps
1349
+ self.weight = nn.Parameter(torch.ones(dim))
1350
+
1351
+ def _norm(self, x):
1352
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1353
+
1354
+ def forward(self, x):
1355
+ if rms_norm is not None and x.is_cuda:
1356
+ return rms_norm(x, self.weight, self.eps)
1357
+ else:
1358
+ output = self._norm(x.float()).type_as(x)
1359
+ return output * self.weight
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
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,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token": {
3
+ "content": "<|im_end|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "pad_token": "<|im_end|>"
10
+ }
tokenization_qwen.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization classes for QWen."""
7
+
8
+ import base64
9
+ import logging
10
+ import os
11
+ import unicodedata
12
+ from typing import Collection, Dict, List, Set, Tuple, Union
13
+
14
+ import tiktoken
15
+ from transformers import PreTrainedTokenizer, AddedToken
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
21
+
22
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
23
+ ENDOFTEXT = "<|endoftext|>"
24
+ IMSTART = "<|im_start|>"
25
+ IMEND = "<|im_end|>"
26
+ # as the default behavior is changed to allow special tokens in
27
+ # regular texts, the surface forms of special tokens need to be
28
+ # as different as possible to minimize the impact
29
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
30
+ # changed to use actual index to avoid misconfiguration with vocabulary expansion
31
+ SPECIAL_START_ID = 151643
32
+ SPECIAL_TOKENS = tuple(
33
+ enumerate(
34
+ (
35
+ (
36
+ ENDOFTEXT,
37
+ IMSTART,
38
+ IMEND,
39
+ )
40
+ + EXTRAS
41
+ ),
42
+ start=SPECIAL_START_ID,
43
+ )
44
+ )
45
+ SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
46
+
47
+
48
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
49
+ with open(tiktoken_bpe_file, "rb") as f:
50
+ contents = f.read()
51
+ return {
52
+ base64.b64decode(token): int(rank)
53
+ for token, rank in (line.split() for line in contents.splitlines() if line)
54
+ }
55
+
56
+
57
+ class QWenTokenizer(PreTrainedTokenizer):
58
+ """QWen tokenizer."""
59
+
60
+ vocab_files_names = VOCAB_FILES_NAMES
61
+
62
+ def __init__(
63
+ self,
64
+ vocab_file,
65
+ errors="replace",
66
+ extra_vocab_file=None,
67
+ **kwargs,
68
+ ):
69
+ super().__init__(**kwargs)
70
+
71
+ # how to handle errors in decoding UTF-8 byte sequences
72
+ # use ignore if you are in streaming inference
73
+ self.errors = errors
74
+
75
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
76
+ self.special_tokens = {
77
+ token: index
78
+ for index, token in SPECIAL_TOKENS
79
+ }
80
+
81
+ # try load extra vocab from file
82
+ if extra_vocab_file is not None:
83
+ used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
84
+ extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
85
+ for token, index in extra_mergeable_ranks.items():
86
+ if token in self.mergeable_ranks:
87
+ logger.info(f"extra token {token} exists, skipping")
88
+ continue
89
+ if index in used_ids:
90
+ logger.info(f'the index {index} for extra token {token} exists, skipping')
91
+ continue
92
+ self.mergeable_ranks[token] = index
93
+ # the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
94
+
95
+ enc = tiktoken.Encoding(
96
+ "Qwen",
97
+ pat_str=PAT_STR,
98
+ mergeable_ranks=self.mergeable_ranks,
99
+ special_tokens=self.special_tokens,
100
+ )
101
+ assert (
102
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
103
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
104
+
105
+ self.decoder = {
106
+ v: k for k, v in self.mergeable_ranks.items()
107
+ } # type: dict[int, bytes|str]
108
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
109
+
110
+ self.tokenizer = enc # type: tiktoken.Encoding
111
+
112
+ self.eod_id = self.tokenizer.eot_token
113
+ self.im_start_id = self.special_tokens[IMSTART]
114
+ self.im_end_id = self.special_tokens[IMEND]
115
+
116
+ def __getstate__(self):
117
+ # for pickle lovers
118
+ state = self.__dict__.copy()
119
+ del state["tokenizer"]
120
+ return state
121
+
122
+ def __setstate__(self, state):
123
+ # tokenizer is not python native; don't pass it; rebuild it
124
+ self.__dict__.update(state)
125
+ enc = tiktoken.Encoding(
126
+ "Qwen",
127
+ pat_str=PAT_STR,
128
+ mergeable_ranks=self.mergeable_ranks,
129
+ special_tokens=self.special_tokens,
130
+ )
131
+ self.tokenizer = enc
132
+
133
+ def __len__(self) -> int:
134
+ return self.tokenizer.n_vocab
135
+
136
+ def get_vocab(self) -> Dict[bytes, int]:
137
+ return self.mergeable_ranks
138
+
139
+ def convert_tokens_to_ids(
140
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
141
+ ) -> List[int]:
142
+ ids = []
143
+ if isinstance(tokens, (str, bytes)):
144
+ if tokens in self.special_tokens:
145
+ return self.special_tokens[tokens]
146
+ else:
147
+ return self.mergeable_ranks.get(tokens)
148
+ for token in tokens:
149
+ if token in self.special_tokens:
150
+ ids.append(self.special_tokens[token])
151
+ else:
152
+ ids.append(self.mergeable_ranks.get(token))
153
+ return ids
154
+
155
+ def _add_tokens(
156
+ self,
157
+ new_tokens: Union[List[str], List[AddedToken]],
158
+ special_tokens: bool = False,
159
+ ) -> int:
160
+ if not special_tokens and new_tokens:
161
+ raise ValueError("Adding regular tokens is not supported")
162
+ for token in new_tokens:
163
+ surface_form = token.content if isinstance(token, AddedToken) else token
164
+ if surface_form not in SPECIAL_TOKENS_SET:
165
+ raise ValueError("Adding unknown special tokens is not supported")
166
+ return 0
167
+
168
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
169
+ """
170
+ Save only the vocabulary of the tokenizer (vocabulary).
171
+
172
+ Returns:
173
+ `Tuple(str)`: Paths to the files saved.
174
+ """
175
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
176
+ with open(file_path, "w", encoding="utf8") as w:
177
+ for k, v in self.mergeable_ranks.items():
178
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
179
+ w.write(line)
180
+ return (file_path,)
181
+
182
+ def tokenize(
183
+ self,
184
+ text: str,
185
+ allowed_special: Union[Set, str] = "all",
186
+ disallowed_special: Union[Collection, str] = (),
187
+ **kwargs,
188
+ ) -> List[Union[bytes, str]]:
189
+ """
190
+ Converts a string in a sequence of tokens.
191
+
192
+ Args:
193
+ text (`str`):
194
+ The sequence to be encoded.
195
+ allowed_special (`Literal["all"]` or `set`):
196
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
197
+ Default to "all".
198
+ disallowed_special (`Literal["all"]` or `Collection`):
199
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
200
+ Default to an empty tuple.
201
+
202
+ kwargs (additional keyword arguments, *optional*):
203
+ Will be passed to the underlying model specific encode method.
204
+
205
+ Returns:
206
+ `List[bytes|str]`: The list of tokens.
207
+ """
208
+ tokens = []
209
+ text = unicodedata.normalize("NFC", text)
210
+
211
+ # this implementation takes a detour: text -> token id -> token surface forms
212
+ for t in self.tokenizer.encode(
213
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
214
+ ):
215
+ tokens.append(self.decoder[t])
216
+ return tokens
217
+
218
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
219
+ """
220
+ Converts a sequence of tokens in a single string.
221
+ """
222
+ text = ""
223
+ temp = b""
224
+ for t in tokens:
225
+ if isinstance(t, str):
226
+ if temp:
227
+ text += temp.decode("utf-8", errors=self.errors)
228
+ temp = b""
229
+ text += t
230
+ elif isinstance(t, bytes):
231
+ temp += t
232
+ else:
233
+ raise TypeError("token should only be of type types or str")
234
+ if temp:
235
+ text += temp.decode("utf-8", errors=self.errors)
236
+ return text
237
+
238
+ @property
239
+ def vocab_size(self):
240
+ return self.tokenizer.n_vocab
241
+
242
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
243
+ """Converts an id to a token, special tokens included"""
244
+ if index in self.decoder:
245
+ return self.decoder[index]
246
+ raise ValueError("unknown ids")
247
+
248
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
249
+ """Converts a token to an id using the vocab, special tokens included"""
250
+ if token in self.special_tokens:
251
+ return self.special_tokens[token]
252
+ if token in self.mergeable_ranks:
253
+ return self.mergeable_ranks[token]
254
+ raise ValueError("unknown token")
255
+
256
+ def _tokenize(self, text: str, **kwargs):
257
+ """
258
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
259
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
260
+
261
+ Do NOT take care of added tokens.
262
+ """
263
+ raise NotImplementedError
264
+
265
+ def _decode(
266
+ self,
267
+ token_ids: Union[int, List[int]],
268
+ skip_special_tokens: bool = False,
269
+ errors: str = None,
270
+ **kwargs,
271
+ ) -> str:
272
+ if isinstance(token_ids, int):
273
+ token_ids = [token_ids]
274
+ if skip_special_tokens:
275
+ token_ids = [i for i in token_ids if i < self.eod_id]
276
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {},
3
+ "auto_map": {
4
+ "AutoTokenizer": [
5
+ "tokenization_qwen.QWenTokenizer",
6
+ null
7
+ ]
8
+ },
9
+ "chat_template": "{% set system_message = 'You are a helpful assistant.' %}{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ '<|im_start|>system\\n' + system_message + '<|im_end|>\\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\\n' + content + '<|im_end|>\\n<|im_start|>assistant\\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\\n' }}{% endif %}{% endfor %}",
10
+ "clean_up_tokenization_spaces": true,
11
+ "eos_token": "<|im_end|>",
12
+ "model_max_length": 32768,
13
+ "pad_token": "<|im_end|>",
14
+ "padding_side": "left",
15
+ "split_special_tokens": false,
16
+ "tokenizer_class": "QWenTokenizer"
17
+ }