TheBloke commited on
Commit
cc23038
1 Parent(s): 2f55205

GPTQ model commit

Browse files
LICENSE ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tongyi Qianwen LICENSE AGREEMENT
2
+
3
+ Tongyi Qianwen Release Date: August 3, 2023
4
+
5
+ By clicking to agree or by using or distributing any portion or element of the Tongyi Qianwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
6
+
7
+ 1. Definitions
8
+ a. This Tongyi Qianwen LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.
9
+ b. "We"(or "Us") shall mean Alibaba Cloud.
10
+ c. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.
11
+ d. "Third Parties" shall mean individuals or legal entities that are not under common control with Us or You.
12
+ e. "Tongyi Qianwen" shall mean the large language models (including Qwen model and Qwen-Chat model), and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by Us.
13
+ f. "Materials" shall mean, collectively, Alibaba Cloud's proprietary Tongyi Qianwen and Documentation (and any portion thereof) made available under this Agreement.
14
+ g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
15
+ h. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation,
16
+ and conversions to other media types.
17
+
18
+ 2. Grant of Rights
19
+ You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Alibaba Cloud's intellectual property or other rights owned by Us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials.
20
+
21
+ 3. Redistribution
22
+ You may reproduce and distribute copies of the Materials or derivative works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
23
+ a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;
24
+ b. You shall cause any modified files to carry prominent notices stating that You changed the files;
25
+ c. You shall retain in all copies of the Materials that You distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "Tongyi Qianwen is licensed under the Tongyi Qianwen LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved."; and
26
+ d. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such derivative works as a whole, provided Your use, reproduction, and distribution of the work otherwise complies with the terms and conditions of this Agreement.
27
+
28
+ 4. Restrictions
29
+ If you are commercially using the Materials, and your product or service has more than 100 million monthly active users, You shall request a license from Us. You cannot exercise your rights under this Agreement without our express authorization.
30
+
31
+ 5. Rules of use
32
+ a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials.
33
+ b. You can not use the Materials or any output therefrom to improve any other large language model (excluding Tongyi Qianwen or derivative works thereof).
34
+
35
+ 6. Intellectual Property
36
+ a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for Us. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by you, you are and will be the owner of such derivative works and modifications.
37
+ b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of Us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.
38
+ c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licences granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.
39
+
40
+ 7. Disclaimer of Warranty and Limitation of Liability
41
+
42
+ a. We are not obligated to support, update, provide training for, or develop any further version of the Tongyi Qianwen Materials or to grant any license thereto.
43
+ b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.
44
+ c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED.
45
+ d. You will defend, indemnify and hold harmless Us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.
46
+
47
+ 8. Survival and Termination.
48
+ a. The term of this Agreement shall commence upon your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
49
+ b. We may terminate this Agreement if you breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, you must delete and cease use of the Materials. Sections 7 and 9 shall survive the termination of this Agreement.
50
+
51
+ 9. Governing Law and Jurisdiction.
52
+ a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
53
+ b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
NOTICE ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ------------- LICENSE FOR NVIDIA Megatron-LM code --------------
2
+
3
+ Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions
7
+ are met:
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+ * Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+ * Neither the name of NVIDIA CORPORATION nor the names of its
14
+ contributors may be used to endorse or promote products derived
15
+ from this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
18
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25
+ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+
30
+ ------------- LICENSE FOR OpenAI tiktoken code --------------
31
+
32
+ MIT License
33
+
34
+ Copyright (c) 2022 OpenAI, Shantanu Jain
35
+
36
+ Permission is hereby granted, free of charge, to any person obtaining a copy
37
+ of this software and associated documentation files (the "Software"), to deal
38
+ in the Software without restriction, including without limitation the rights
39
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
40
+ copies of the Software, and to permit persons to whom the Software is
41
+ furnished to do so, subject to the following conditions:
42
+
43
+ The above copyright notice and this permission notice shall be included in all
44
+ copies or substantial portions of the Software.
45
+
46
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
49
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
51
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
52
+ SOFTWARE.
config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/workspace/process/qwen_qwen-14b-chat/source",
3
+ "architectures": [
4
+ "QWenLMHeadModel"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
10
+ },
11
+ "bf16": true,
12
+ "emb_dropout_prob": 0.0,
13
+ "fp16": false,
14
+ "fp32": false,
15
+ "hidden_size": 5120,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 27392,
18
+ "kv_channels": 128,
19
+ "layer_norm_epsilon": 1e-06,
20
+ "max_position_embeddings": 8192,
21
+ "model_type": "qwen",
22
+ "no_bias": true,
23
+ "num_attention_heads": 40,
24
+ "num_hidden_layers": 40,
25
+ "onnx_safe": null,
26
+ "pad_token_id": 0,
27
+ "pretraining_tp": 1,
28
+ "quantization_config": {
29
+ "batch_size": 1,
30
+ "bits": 4,
31
+ "block_name_to_quantize": "transformer.h",
32
+ "damp_percent": 0.1,
33
+ "desc_act": true,
34
+ "disable_exllama": false,
35
+ "group_size": 128,
36
+ "max_input_length": null,
37
+ "model_seqlen": 8192,
38
+ "module_name_preceding_first_block": [
39
+ "transformer.wte",
40
+ "transformer.drop",
41
+ "transformer.rotary_emb"
42
+ ],
43
+ "pad_token_id": null,
44
+ "quant_method": "gptq",
45
+ "sym": true,
46
+ "tokenizer": null,
47
+ "true_sequential": true,
48
+ "use_cuda_fp16": false
49
+ },
50
+ "rotary_emb_base": 10000,
51
+ "rotary_pct": 1.0,
52
+ "scale_attn_weights": true,
53
+ "seq_length": 2048,
54
+ "softmax_in_fp32": false,
55
+ "tie_word_embeddings": false,
56
+ "tokenizer_class": "QWenTokenizer",
57
+ "torch_dtype": "bfloat16",
58
+ "transformers_version": "4.34.1",
59
+ "use_cache": true,
60
+ "use_cache_kernel": false,
61
+ "use_cache_quantization": false,
62
+ "use_dynamic_ntk": true,
63
+ "use_flash_attn": true,
64
+ "use_logn_attn": true,
65
+ "vocab_size": 152064
66
+ }
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
+ "eos_token_id": 151643,
4
+ "pad_token_id": 151643,
5
+ "max_window_size": 6144,
6
+ "max_new_tokens": 512,
7
+ "do_sample": true,
8
+ "top_k": 0,
9
+ "top_p": 0.8,
10
+ "repetition_penalty": 1.1,
11
+ "transformers_version": "4.31.0"
12
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c5e469637876de61dd2678c78e2653a99bf837991ce9eeb8be53cea6b501e03
3
+ size 9675758728
modeling_qwen.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ import torch.utils.checkpoint
14
+ from torch.cuda.amp import autocast
15
+
16
+ from torch.nn import CrossEntropyLoss
17
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
18
+ from transformers.generation.logits_process import LogitsProcessorList
19
+
20
+ if TYPE_CHECKING:
21
+ from transformers.generation.streamers import BaseStreamer
22
+ from transformers.generation.utils import GenerateOutput
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ )
27
+ from transformers.modeling_utils import PreTrainedModel
28
+ from transformers.utils import logging
29
+
30
+ try:
31
+ from einops import rearrange
32
+ except ImportError:
33
+ rearrange = None
34
+ from torch import nn
35
+
36
+ SUPPORT_CUDA = torch.cuda.is_available()
37
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
38
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
39
+ SUPPORT_TORCH2 = hasattr(torch, '__version__') and int(torch.__version__.split(".")[0]) >= 2
40
+
41
+
42
+ from .configuration_qwen import QWenConfig
43
+ from .qwen_generation_utils import (
44
+ HistoryType,
45
+ make_context,
46
+ decode_tokens,
47
+ get_stop_words_ids,
48
+ StopWordsLogitsProcessor,
49
+ )
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CHECKPOINT_FOR_DOC = "qwen"
55
+ _CONFIG_FOR_DOC = "QWenConfig"
56
+
57
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
58
+
59
+ _ERROR_BAD_CHAT_FORMAT = """\
60
+ 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".
61
+ 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().
62
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
63
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
64
+ """
65
+
66
+ _SENTINEL = object()
67
+ _ERROR_STREAM_IN_CHAT = """\
68
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
69
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
70
+ """
71
+
72
+ _ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
73
+ 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).
74
+ 检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。
75
+ """
76
+
77
+ apply_rotary_emb_func = None
78
+ rms_norm = None
79
+ flash_attn_unpadded_func = None
80
+
81
+ def _import_flash_attn():
82
+ global apply_rotary_emb_func, rms_norm, flash_attn_unpadded_func
83
+ try:
84
+ from flash_attn.layers.rotary import apply_rotary_emb_func as __apply_rotary_emb_func
85
+ apply_rotary_emb_func = __apply_rotary_emb_func
86
+ except ImportError:
87
+ logger.warn(
88
+ "Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency "
89
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary"
90
+ )
91
+
92
+ try:
93
+ from flash_attn.ops.rms_norm import rms_norm as __rms_norm
94
+ rms_norm = __rms_norm
95
+ except ImportError:
96
+ logger.warn(
97
+ "Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency "
98
+ "https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm"
99
+ )
100
+
101
+ try:
102
+ import flash_attn
103
+ if not hasattr(flash_attn, '__version__'):
104
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
105
+ else:
106
+ if int(flash_attn.__version__.split(".")[0]) >= 2:
107
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as __flash_attn_unpadded_func
108
+ else:
109
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func as __flash_attn_unpadded_func
110
+ flash_attn_unpadded_func = __flash_attn_unpadded_func
111
+ except ImportError:
112
+ logger.warn(
113
+ "Warning: import flash_attn fail, please install FlashAttention to get higher efficiency "
114
+ "https://github.com/Dao-AILab/flash-attention"
115
+ )
116
+
117
+ def quantize_cache_v(fdata, bits, qmax, qmin):
118
+ # b, s, head, h-dim->b, head, s, h-dim
119
+ qtype = torch.uint8
120
+ device = fdata.device
121
+ shape = fdata.shape
122
+
123
+ fdata_cal = torch.flatten(fdata, 2)
124
+ fmax = torch.amax(fdata_cal, dim=-1, keepdim=True)
125
+ fmin = torch.amin(fdata_cal, dim=-1, keepdim=True)
126
+ # Compute params
127
+ if qmax.device != fmax.device:
128
+ qmax = qmax.to(device)
129
+ qmin = qmin.to(device)
130
+ scale = (fmax - fmin) / (qmax - qmin)
131
+ zero = qmin - fmin / scale
132
+ scale = scale.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
133
+ zero = zero.unsqueeze(-1).repeat(1,1,shape[2],1).contiguous()
134
+ # Quantize
135
+ res_data = fdata / scale + zero
136
+ qdata = torch.clamp(res_data, qmin, qmax).to(qtype)
137
+ return qdata.contiguous(), scale, zero
138
+
139
+ def dequantize_cache_torch(qdata, scale, zero):
140
+ data = scale * (qdata - zero)
141
+ return data
142
+
143
+ class FlashSelfAttention(torch.nn.Module):
144
+ def __init__(
145
+ self,
146
+ causal=False,
147
+ softmax_scale=None,
148
+ attention_dropout=0.0,
149
+ ):
150
+ super().__init__()
151
+ assert flash_attn_unpadded_func is not None, (
152
+ "Please install FlashAttention first, " "e.g., with pip install flash-attn"
153
+ )
154
+ assert (
155
+ rearrange is not None
156
+ ), "Please install einops first, e.g., with pip install einops"
157
+ self.causal = causal
158
+ self.softmax_scale = softmax_scale
159
+ self.dropout_p = attention_dropout
160
+
161
+ def unpad_input(self, hidden_states, attention_mask):
162
+ valid_mask = attention_mask.squeeze(1).squeeze(1).eq(0)
163
+ seqlens_in_batch = valid_mask.sum(dim=-1, dtype=torch.int32)
164
+ indices = torch.nonzero(valid_mask.flatten(), as_tuple=False).flatten()
165
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
166
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
167
+ hidden_states = hidden_states[indices]
168
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
169
+
170
+ def pad_input(self, hidden_states, indices, batch, seqlen):
171
+ output = torch.zeros(batch * seqlen, *hidden_states.shape[1:], device=hidden_states.device,
172
+ dtype=hidden_states.dtype)
173
+ output[indices] = hidden_states
174
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
175
+
176
+ def forward(self, q, k, v, attention_mask=None):
177
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
178
+ assert all((i.is_cuda for i in (q, k, v)))
179
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
180
+ seqlen_k = k.shape[1]
181
+ seqlen_out = seqlen_q
182
+
183
+ q, k, v = [rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v]]
184
+ cu_seqlens_q = torch.arange(
185
+ 0,
186
+ (batch_size + 1) * seqlen_q,
187
+ step=seqlen_q,
188
+ dtype=torch.int32,
189
+ device=q.device,
190
+ )
191
+
192
+ if batch_size > 1 and attention_mask is not None:
193
+ k, indices_k, cu_seqlens_k, seqlen_k = self.unpad_input(k, attention_mask)
194
+ if q.size(0) == v.size(0):
195
+ q = q[indices_k]
196
+ cu_seqlens_q = cu_seqlens_k
197
+ seqlen_q = seqlen_k
198
+ v = v[indices_k]
199
+ else:
200
+ cu_seqlens_k = torch.arange(
201
+ 0,
202
+ (batch_size + 1) * seqlen_k,
203
+ step=seqlen_k,
204
+ dtype=torch.int32,
205
+ device=q.device,
206
+ )
207
+
208
+ if self.training:
209
+ assert seqlen_k == seqlen_q
210
+ is_causal = self.causal
211
+ dropout_p = self.dropout_p
212
+ else:
213
+ is_causal = seqlen_q == seqlen_k
214
+ dropout_p = 0
215
+
216
+ output = flash_attn_unpadded_func(
217
+ q,
218
+ k,
219
+ v,
220
+ cu_seqlens_q,
221
+ cu_seqlens_k,
222
+ seqlen_q,
223
+ seqlen_k,
224
+ dropout_p,
225
+ softmax_scale=self.softmax_scale,
226
+ causal=is_causal,
227
+ )
228
+ if batch_size > 1 and attention_mask is not None and seqlen_q == seqlen_k:
229
+ output = self.pad_input(output, indices_k, batch_size, seqlen_out)
230
+ else:
231
+ new_shape = (batch_size, output.shape[0] // batch_size) + output.shape[1:]
232
+ output = output.view(new_shape)
233
+ return output
234
+
235
+
236
+ class QWenAttention(nn.Module):
237
+ def __init__(self, config):
238
+ super().__init__()
239
+
240
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
241
+ self.seq_length = config.seq_length
242
+
243
+ self.hidden_size = config.hidden_size
244
+ self.split_size = config.hidden_size
245
+ self.num_heads = config.num_attention_heads
246
+ self.head_dim = self.hidden_size // self.num_heads
247
+
248
+ self.use_flash_attn = config.use_flash_attn
249
+ self.scale_attn_weights = True
250
+
251
+ self.projection_size = config.kv_channels * config.num_attention_heads
252
+
253
+ assert self.projection_size % config.num_attention_heads == 0
254
+ self.hidden_size_per_attention_head = (
255
+ self.projection_size // config.num_attention_heads
256
+ )
257
+
258
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
259
+
260
+ self.c_proj = nn.Linear(
261
+ config.hidden_size, self.projection_size, bias=not config.no_bias
262
+ )
263
+
264
+ self.is_fp32 = not (config.bf16 or config.fp16)
265
+ if (
266
+ self.use_flash_attn
267
+ and flash_attn_unpadded_func is not None
268
+ and not self.is_fp32
269
+ ):
270
+ self.core_attention_flash = FlashSelfAttention(
271
+ causal=True, attention_dropout=config.attn_dropout_prob
272
+ )
273
+ self.bf16 = config.bf16
274
+
275
+ self.use_dynamic_ntk = config.use_dynamic_ntk
276
+ self.use_logn_attn = config.use_logn_attn
277
+
278
+ logn_list = [
279
+ math.log(i, self.seq_length) if i > self.seq_length else 1
280
+ for i in range(1, 32768)
281
+ ]
282
+ logn_tensor = torch.tensor(logn_list)[None, :, None, None]
283
+ self.register_buffer("logn_tensor", logn_tensor, persistent=False)
284
+
285
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
286
+ self.softmax_in_fp32 = config.softmax_in_fp32 if hasattr(config, 'softmax_in_fp32') else False
287
+ self.use_cache_quantization = config.use_cache_quantization if hasattr(config, 'use_cache_quantization') else False
288
+ self.use_cache_kernel = config.use_cache_kernel if hasattr(config,'use_cache_kernel') else False
289
+ cache_dtype = torch.float
290
+ if self.bf16:
291
+ cache_dtype=torch.bfloat16
292
+ elif config.fp16:
293
+ cache_dtype = torch.float16
294
+ self.cache_qmax = torch.tensor(torch.iinfo(torch.uint8).max, dtype=cache_dtype)
295
+ self.cache_qmin = torch.tensor(torch.iinfo(torch.uint8).min, dtype=cache_dtype)
296
+
297
+ if config.use_cache_quantization and config.use_cache_kernel:
298
+ from .cpp_kernels import cache_autogptq_cuda_256
299
+ try:
300
+ self.cache_kernels = cache_autogptq_cuda_256
301
+ except ImportError:
302
+ self.cache_kernels = None
303
+
304
+ def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):
305
+ device = query.device
306
+ if self.use_cache_quantization:
307
+ qk, qk_scale, qk_zero = key
308
+ if self.use_cache_kernel and self.cache_kernels is not None:
309
+ shape = query.shape[:-1] + (qk.shape[-2],)
310
+ attn_weights = torch.zeros(shape, dtype=torch.float16, device=device)
311
+ self.cache_kernels.vecquant8matmul_batched_faster_old(
312
+ query.contiguous() if query.dtype == torch.float16 else query.to(torch.float16).contiguous(),
313
+ qk.transpose(-1, -2).contiguous(),
314
+ attn_weights,
315
+ qk_scale.contiguous() if qk_scale.dtype == torch.float16 else qk_scale.to(torch.float16).contiguous(),
316
+ qk_zero.contiguous()if qk_zero.dtype == torch.float16 else qk_zero.to(torch.float16).contiguous())
317
+ # attn_weights = attn_weights.to(query.dtype).contiguous()
318
+ else:
319
+ key = dequantize_cache_torch(qk, qk_scale, qk_zero)
320
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
321
+ else:
322
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
323
+
324
+ if self.scale_attn_weights:
325
+ if self.use_cache_quantization:
326
+ size_temp = value[0].size(-1)
327
+ else:
328
+ size_temp = value.size(-1)
329
+ attn_weights = attn_weights / torch.full(
330
+ [],
331
+ size_temp ** 0.5,
332
+ dtype=attn_weights.dtype,
333
+ device=attn_weights.device,
334
+ )
335
+ if self.use_cache_quantization:
336
+ query_length, key_length = query.size(-2), key[0].size(-2)
337
+ else:
338
+ query_length, key_length = query.size(-2), key.size(-2)
339
+ causal_mask = registered_causal_mask[
340
+ :, :, key_length - query_length : key_length, :key_length
341
+ ]
342
+ mask_value = torch.finfo(attn_weights.dtype).min
343
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
344
+ attn_weights.device
345
+ )
346
+ attn_weights = torch.where(
347
+ causal_mask, attn_weights.to(attn_weights.dtype), mask_value
348
+ )
349
+
350
+ if attention_mask is not None:
351
+ attn_weights = attn_weights + attention_mask
352
+
353
+ if self.softmax_in_fp32:
354
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1)
355
+ else:
356
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
357
+
358
+ attn_weights = attn_weights.type(query.dtype)
359
+ attn_weights = self.attn_dropout(attn_weights)
360
+
361
+ if head_mask is not None:
362
+ attn_weights = attn_weights * head_mask
363
+
364
+ if self.use_cache_quantization:
365
+ qv, qv_scale, qv_zero = value
366
+ if self.use_cache_kernel and self.cache_kernels is not None:
367
+ shape = attn_weights.shape[:-1] + (query.shape[-1],)
368
+ attn_output = torch.zeros(shape, dtype=torch.float16, device=device)
369
+ self.cache_kernels.vecquant8matmul_batched_column_compression_faster_old(
370
+ attn_weights.contiguous() if attn_weights.dtype == torch.float16 else attn_weights.to(torch.float16).contiguous(),
371
+ qv.contiguous(), # dtype: int32
372
+ attn_output,
373
+ qv_scale.contiguous() if qv_scale.dtype == torch.float16 else qv_scale.to(torch.float16).contiguous(),
374
+ qv_zero.contiguous() if qv_zero.dtype == torch.float16 else qv_zero.to(torch.float16).contiguous())
375
+ if attn_output.dtype != query.dtype:
376
+ attn_output = attn_output.to(query.dtype)
377
+ attn_weights = attn_weights.to(query.dtype)
378
+ else:
379
+ value = dequantize_cache_torch(qv, qv_scale, qv_zero)
380
+ attn_output = torch.matmul(attn_weights, value)
381
+ else:
382
+ attn_output = torch.matmul(attn_weights, value)
383
+
384
+ attn_output = attn_output.transpose(1, 2)
385
+
386
+ return attn_output, attn_weights
387
+
388
+ def _upcast_and_reordered_attn(
389
+ self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None
390
+ ):
391
+ bsz, num_heads, q_seq_len, dk = query.size()
392
+ _, _, k_seq_len, _ = key.size()
393
+
394
+ attn_weights = torch.empty(
395
+ bsz * num_heads,
396
+ q_seq_len,
397
+ k_seq_len,
398
+ dtype=torch.float32,
399
+ device=query.device,
400
+ )
401
+
402
+ scale_factor = 1.0
403
+ if self.scale_attn_weights:
404
+ scale_factor /= float(value.size(-1)) ** 0.5
405
+
406
+ with autocast(enabled=False):
407
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
408
+ -1, dk, k_seq_len
409
+ )
410
+ attn_weights = torch.baddbmm(
411
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
412
+ )
413
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
414
+
415
+ query_length, key_length = query.size(-2), key.size(-2)
416
+ causal_mask = registered_causal_mask[
417
+ :, :, key_length - query_length : key_length, :key_length
418
+ ]
419
+ mask_value = torch.finfo(attn_weights.dtype).min
420
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
421
+ attn_weights.device
422
+ )
423
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
424
+
425
+ if attention_mask is not None:
426
+ attn_weights = attn_weights + attention_mask
427
+
428
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
429
+
430
+ if attn_weights.dtype != torch.float32:
431
+ raise RuntimeError(
432
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
433
+ )
434
+ attn_weights = attn_weights.type(value.dtype)
435
+ attn_weights = self.attn_dropout(attn_weights)
436
+
437
+ if head_mask is not None:
438
+ attn_weights = attn_weights * head_mask
439
+
440
+ attn_output = torch.matmul(attn_weights, value)
441
+
442
+ return attn_output, attn_weights
443
+
444
+ def _split_heads(self, tensor, num_heads, attn_head_size):
445
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
446
+ tensor = tensor.view(new_shape)
447
+ return tensor
448
+
449
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
450
+ tensor = tensor.contiguous()
451
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
452
+ return tensor.view(new_shape)
453
+
454
+ def forward(
455
+ self,
456
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
457
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
458
+ registered_causal_mask: Optional[torch.Tensor] = None,
459
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
460
+ attention_mask: Optional[torch.FloatTensor] = None,
461
+ head_mask: Optional[torch.FloatTensor] = None,
462
+ encoder_hidden_states: Optional[torch.Tensor] = None,
463
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
464
+ output_attentions: Optional[bool] = False,
465
+ use_cache: Optional[bool] = False,
466
+ ):
467
+ mixed_x_layer = self.c_attn(hidden_states)
468
+
469
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
470
+
471
+ query = self._split_heads(query, self.num_heads, self.head_dim)
472
+ key = self._split_heads(key, self.num_heads, self.head_dim)
473
+ value = self._split_heads(value, self.num_heads, self.head_dim)
474
+
475
+ if rotary_pos_emb_list is not None:
476
+ cur_len = query.shape[1]
477
+ if len(rotary_pos_emb_list) == 1:
478
+ rotary_pos_emb = rotary_pos_emb_list[0]
479
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
480
+ rotary_pos_emb = (rotary_pos_emb,) * 2
481
+ q_pos_emb, k_pos_emb = rotary_pos_emb
482
+ # Slice the pos emb for current inference
483
+ query = apply_rotary_pos_emb(query, q_pos_emb)
484
+ key = apply_rotary_pos_emb(key, k_pos_emb)
485
+ else:
486
+ query_list = []
487
+ key_list = []
488
+ for i, rotary_pos_emb in enumerate(rotary_pos_emb_list):
489
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
490
+ rotary_pos_emb = (rotary_pos_emb,) * 2
491
+ q_pos_emb, k_pos_emb = rotary_pos_emb
492
+ # Slice the pos emb for current inference
493
+ query_list += [apply_rotary_pos_emb(query[i:i+1, :, :], q_pos_emb)]
494
+ key_list += [apply_rotary_pos_emb(key[i:i+1, :, :], k_pos_emb)]
495
+ query = torch.cat(query_list, dim=0)
496
+ key = torch.cat(key_list, dim=0)
497
+
498
+ if self.use_cache_quantization:
499
+ key = quantize_cache_v(key.permute(0, 2, 1, 3),
500
+ bits=8,
501
+ qmin=self.cache_qmin,
502
+ qmax=self.cache_qmax)
503
+ value = quantize_cache_v(value.permute(0, 2, 1, 3),
504
+ bits=8,
505
+ qmin=self.cache_qmin,
506
+ qmax=self.cache_qmax)
507
+
508
+
509
+ if layer_past is not None:
510
+ past_key, past_value = layer_past[0], layer_past[1]
511
+ if self.use_cache_quantization:
512
+ # use_cache_quantization:
513
+ # present=((q_key,key_scale,key_zero_point),
514
+ # (q_value,value_scale,value_zero_point))
515
+ key = (torch.cat((past_key[0], key[0]), dim=2),
516
+ torch.cat((past_key[1], key[1]), dim=2),
517
+ torch.cat((past_key[2], key[2]), dim=2))
518
+ value = (torch.cat((past_value[0], value[0]), dim=2),
519
+ torch.cat((past_value[1], value[1]), dim=2),
520
+ torch.cat((past_value[2], value[2]), dim=2))
521
+ else:
522
+ # not use_cache_quantization:
523
+ # present=(key,value)
524
+ key = torch.cat((past_key, key), dim=1)
525
+ value = torch.cat((past_value, value), dim=1)
526
+
527
+ if use_cache:
528
+ present = (key, value)
529
+ else:
530
+ present = None
531
+
532
+ if self.use_logn_attn and not self.training:
533
+ if self.use_cache_quantization:
534
+ seq_start = key[0].size(2) - query.size(1)
535
+ seq_end = key[0].size(2)
536
+ else:
537
+ seq_start = key.size(1) - query.size(1)
538
+ seq_end = key.size(1)
539
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :].type_as(query)
540
+ query = query * logn_tensor.expand_as(query)
541
+
542
+ if (
543
+ self.use_flash_attn
544
+ and flash_attn_unpadded_func is not None
545
+ and not self.is_fp32
546
+ and query.is_cuda
547
+ ):
548
+ q, k, v = query, key, value
549
+ attn_output = self.core_attention_flash(q, k, v, attention_mask=attention_mask)
550
+ else:
551
+ query = query.permute(0, 2, 1, 3)
552
+ if not self.use_cache_quantization:
553
+ key = key.permute(0, 2, 1, 3)
554
+ value = value.permute(0, 2, 1, 3)
555
+ if (
556
+ registered_causal_mask is None
557
+ and self.use_flash_attn
558
+ and flash_attn_unpadded_func is not None
559
+ and not self.is_fp32
560
+ and not query.is_cuda
561
+ ):
562
+ raise Exception(_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED)
563
+
564
+ if not self.use_cache_quantization and SUPPORT_TORCH2:
565
+ causal_mask = registered_causal_mask[
566
+ :, :, key.size(-2) - query.size(-2): key.size(-2), :key.size(-2)
567
+ ]
568
+ if attention_mask is not None:
569
+ attention_mask = attention_mask.expand(
570
+ -1, -1, causal_mask.size(2), -1
571
+ ).masked_fill(~causal_mask, torch.finfo(query.dtype).min)
572
+ else:
573
+ attention_mask = causal_mask
574
+ attn_output = F.scaled_dot_product_attention(
575
+ query, key, value, attn_mask=attention_mask
576
+ ).transpose(1, 2)
577
+ attn_weight = None
578
+ else:
579
+ attn_output, attn_weight = self._attn(
580
+ query, key, value, registered_causal_mask, attention_mask, head_mask
581
+ )
582
+ context_layer = self._merge_heads(
583
+ attn_output, self.num_heads, self.head_dim
584
+ )
585
+
586
+ attn_output = self.c_proj(context_layer)
587
+
588
+ outputs = (attn_output, present)
589
+ if output_attentions:
590
+ if (
591
+ self.use_flash_attn
592
+ and flash_attn_unpadded_func is not None
593
+ and not self.is_fp32
594
+ ):
595
+ raise ValueError("Cannot output attentions while using flash-attn")
596
+ else:
597
+ outputs += (attn_weight,)
598
+
599
+ return outputs
600
+
601
+
602
+ class QWenMLP(nn.Module):
603
+ def __init__(self, config):
604
+ super().__init__()
605
+ self.w1 = nn.Linear(
606
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
607
+ )
608
+ self.w2 = nn.Linear(
609
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
610
+ )
611
+ ff_dim_in = config.intermediate_size // 2
612
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
613
+
614
+ def forward(self, hidden_states):
615
+ a1 = self.w1(hidden_states)
616
+ a2 = self.w2(hidden_states)
617
+ intermediate_parallel = a1 * F.silu(a2)
618
+ output = self.c_proj(intermediate_parallel)
619
+ return output
620
+
621
+ class QWenBlock(nn.Module):
622
+ def __init__(self, config):
623
+ super().__init__()
624
+ hidden_size = config.hidden_size
625
+ self.bf16 = config.bf16
626
+
627
+ self.ln_1 = RMSNorm(
628
+ hidden_size,
629
+ eps=config.layer_norm_epsilon,
630
+ )
631
+ self.attn = QWenAttention(config)
632
+ self.ln_2 = RMSNorm(
633
+ hidden_size,
634
+ eps=config.layer_norm_epsilon,
635
+ )
636
+
637
+ self.mlp = QWenMLP(config)
638
+
639
+ def forward(
640
+ self,
641
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
642
+ rotary_pos_emb_list: Optional[List[List[torch.Tensor]]] = None,
643
+ registered_causal_mask: Optional[torch.Tensor] = None,
644
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
645
+ attention_mask: Optional[torch.FloatTensor] = None,
646
+ head_mask: Optional[torch.FloatTensor] = None,
647
+ encoder_hidden_states: Optional[torch.Tensor] = None,
648
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
649
+ use_cache: Optional[bool] = False,
650
+ output_attentions: Optional[bool] = False,
651
+ ):
652
+ layernorm_output = self.ln_1(hidden_states)
653
+
654
+ attn_outputs = self.attn(
655
+ layernorm_output,
656
+ rotary_pos_emb_list,
657
+ registered_causal_mask=registered_causal_mask,
658
+ layer_past=layer_past,
659
+ attention_mask=attention_mask,
660
+ head_mask=head_mask,
661
+ use_cache=use_cache,
662
+ output_attentions=output_attentions,
663
+ )
664
+ attn_output = attn_outputs[0]
665
+
666
+ outputs = attn_outputs[1:]
667
+
668
+ residual = hidden_states
669
+ layernorm_input = attn_output + residual
670
+
671
+ layernorm_output = self.ln_2(layernorm_input)
672
+
673
+ residual = layernorm_input
674
+ mlp_output = self.mlp(layernorm_output)
675
+ hidden_states = residual + mlp_output
676
+
677
+ if use_cache:
678
+ outputs = (hidden_states,) + outputs
679
+ else:
680
+ outputs = (hidden_states,) + outputs[1:]
681
+
682
+ return outputs
683
+
684
+
685
+ class QWenPreTrainedModel(PreTrainedModel):
686
+ config_class = QWenConfig
687
+ base_model_prefix = "transformer"
688
+ is_parallelizable = False
689
+ supports_gradient_checkpointing = True
690
+ _no_split_modules = ["QWenBlock"]
691
+
692
+ def __init__(self, *inputs, **kwargs):
693
+ super().__init__(*inputs, **kwargs)
694
+
695
+ def _init_weights(self, module):
696
+ """Initialize the weights."""
697
+ if isinstance(module, nn.Linear):
698
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
699
+ if module.bias is not None:
700
+ module.bias.data.zero_()
701
+ elif isinstance(module, nn.Embedding):
702
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
703
+ if module.padding_idx is not None:
704
+ module.weight.data[module.padding_idx].zero_()
705
+ elif isinstance(module, RMSNorm):
706
+ module.weight.data.fill_(1.0)
707
+
708
+ for name, p in module.named_parameters():
709
+ if name == "c_proj.weight":
710
+ p.data.normal_(
711
+ mean=0.0,
712
+ std=(
713
+ self.config.initializer_range
714
+ / math.sqrt(2 * self.config.num_hidden_layers)
715
+ ),
716
+ )
717
+
718
+ def _set_gradient_checkpointing(self, module, value=False):
719
+ if isinstance(module, QWenModel):
720
+ module.gradient_checkpointing = value
721
+
722
+
723
+ class QWenModel(QWenPreTrainedModel):
724
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
725
+
726
+ def __init__(self, config):
727
+ super().__init__(config)
728
+ self.vocab_size = config.vocab_size
729
+ self.num_hidden_layers = config.num_hidden_layers
730
+ self.embed_dim = config.hidden_size
731
+ self.use_cache_quantization = self.config.use_cache_quantization if hasattr(self.config, 'use_cache_quantization') else False
732
+
733
+ self.gradient_checkpointing = False
734
+ self.use_dynamic_ntk = config.use_dynamic_ntk
735
+ self.seq_length = config.seq_length
736
+
737
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
738
+
739
+ self.drop = nn.Dropout(config.emb_dropout_prob)
740
+
741
+ if config.rotary_pct == 1.0:
742
+ self.rotary_ndims = None
743
+ else:
744
+ assert config.rotary_pct < 1
745
+ self.rotary_ndims = int(
746
+ config.kv_channels * config.rotary_pct
747
+ )
748
+ dim = (
749
+ self.rotary_ndims
750
+ if self.rotary_ndims is not None
751
+ else config.kv_channels
752
+ )
753
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
754
+
755
+ self.use_flash_attn = config.use_flash_attn
756
+ self.is_fp32 = not (config.bf16 or config.fp16)
757
+ if (
758
+ self.use_flash_attn
759
+ and flash_attn_unpadded_func is not None
760
+ and not self.is_fp32
761
+ ):
762
+ self.registered_causal_mask = None
763
+ else:
764
+ max_positions = config.max_position_embeddings
765
+ self.register_buffer(
766
+ "registered_causal_mask",
767
+ torch.tril(
768
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
769
+ ).view(1, 1, max_positions, max_positions),
770
+ persistent=False,
771
+ )
772
+
773
+ self.h = nn.ModuleList(
774
+ [
775
+ QWenBlock(
776
+ config
777
+ )
778
+ for i in range(config.num_hidden_layers)
779
+ ]
780
+ )
781
+ self.ln_f = RMSNorm(
782
+ self.embed_dim,
783
+ eps=config.layer_norm_epsilon,
784
+ )
785
+
786
+ self.post_init()
787
+
788
+ def get_input_embeddings(self):
789
+ return self.wte
790
+
791
+ def set_input_embeddings(self, new_embeddings):
792
+ self.wte = new_embeddings
793
+
794
+ def get_ntk_alpha(self, true_seq_len):
795
+ context_value = math.log(true_seq_len / self.seq_length, 2) + 1
796
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
797
+ ntk_alpha = max(ntk_alpha, 1)
798
+ return ntk_alpha
799
+
800
+ def forward(
801
+ self,
802
+ input_ids: Optional[torch.LongTensor] = None,
803
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
804
+ attention_mask: Optional[torch.FloatTensor] = None,
805
+ token_type_ids: Optional[torch.LongTensor] = None,
806
+ position_ids: Optional[torch.LongTensor] = None,
807
+ head_mask: Optional[torch.FloatTensor] = None,
808
+ inputs_embeds: Optional[torch.FloatTensor] = None,
809
+ encoder_hidden_states: Optional[torch.Tensor] = None,
810
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
811
+ use_cache: Optional[bool] = None,
812
+ output_attentions: Optional[bool] = None,
813
+ output_hidden_states: Optional[bool] = None,
814
+ return_dict: Optional[bool] = None,
815
+ ):
816
+ output_attentions = (
817
+ output_attentions
818
+ if output_attentions is not None
819
+ else self.config.output_attentions
820
+ )
821
+ output_hidden_states = (
822
+ output_hidden_states
823
+ if output_hidden_states is not None
824
+ else self.config.output_hidden_states
825
+ )
826
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
827
+ return_dict = (
828
+ return_dict if return_dict is not None else self.config.use_return_dict
829
+ )
830
+
831
+ if input_ids is not None and inputs_embeds is not None:
832
+ raise ValueError(
833
+ "You cannot specify both input_ids and inputs_embeds at the same time"
834
+ )
835
+ elif input_ids is not None:
836
+ input_shape = input_ids.size()
837
+ input_ids = input_ids.view(-1, input_shape[-1])
838
+ batch_size = input_ids.shape[0]
839
+ elif inputs_embeds is not None:
840
+ input_shape = inputs_embeds.size()[:-1]
841
+ batch_size = inputs_embeds.shape[0]
842
+ else:
843
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
844
+
845
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
846
+
847
+ if token_type_ids is not None:
848
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
849
+ if position_ids is not None:
850
+ position_ids = position_ids.view(-1, input_shape[-1])
851
+
852
+ if past_key_values is None:
853
+ past_length = 0
854
+ past_key_values = tuple([None] * len(self.h))
855
+ else:
856
+ if self.use_cache_quantization:
857
+ past_length = past_key_values[0][0][0].size(2)
858
+ else:
859
+ past_length = past_key_values[0][0].size(-2)
860
+ if position_ids is None:
861
+ position_ids = torch.arange(
862
+ past_length,
863
+ input_shape[-1] + past_length,
864
+ dtype=torch.long,
865
+ device=device,
866
+ )
867
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
868
+
869
+ if attention_mask is not None:
870
+ if batch_size <= 0:
871
+ raise ValueError("batch_size has to be defined and > 0")
872
+ attention_mask = attention_mask.view(batch_size, -1)
873
+ attention_mask = attention_mask[:, None, None, :]
874
+ attention_mask = attention_mask.to(dtype=self.dtype)
875
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
876
+
877
+ encoder_attention_mask = None
878
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
879
+
880
+ if inputs_embeds is None:
881
+ inputs_embeds = self.wte(input_ids)
882
+ hidden_states = inputs_embeds
883
+
884
+ kv_seq_len = hidden_states.size()[1]
885
+ if past_key_values[0] is not None:
886
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
887
+ if self.use_cache_quantization:
888
+ kv_seq_len += past_key_values[0][0][0].shape[2]
889
+ else:
890
+ kv_seq_len += past_key_values[0][0].shape[1]
891
+
892
+ if self.training or not self.use_dynamic_ntk:
893
+ ntk_alpha_list = [1.0]
894
+ elif kv_seq_len != hidden_states.size()[1]:
895
+ ntk_alpha_list = self.rotary_emb._ntk_alpha_cached_list
896
+ else:
897
+ ntk_alpha_list = []
898
+ if attention_mask is not None and kv_seq_len > self.seq_length:
899
+ true_seq_lens = attention_mask.squeeze(1).squeeze(1).eq(0).sum(dim=-1, dtype=torch.int32)
900
+ for i in range(hidden_states.size()[0]):
901
+ true_seq_len = true_seq_lens[i].item()
902
+ ntk_alpha = self.get_ntk_alpha(true_seq_len)
903
+ ntk_alpha_list.append(ntk_alpha)
904
+ else:
905
+ ntk_alpha = self.get_ntk_alpha(kv_seq_len)
906
+ ntk_alpha_list.append(ntk_alpha)
907
+ self.rotary_emb._ntk_alpha_cached_list = ntk_alpha_list
908
+ rotary_pos_emb_list = [
909
+ self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha) for ntk_alpha in ntk_alpha_list
910
+ ]
911
+
912
+ hidden_states = self.drop(hidden_states)
913
+ output_shape = input_shape + (hidden_states.size(-1),)
914
+
915
+ if self.gradient_checkpointing and self.training:
916
+ if use_cache:
917
+ logger.warning_once(
918
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
919
+ )
920
+ use_cache = False
921
+
922
+ presents = () if use_cache else None
923
+ all_self_attentions = () if output_attentions else None
924
+ all_hidden_states = () if output_hidden_states else None
925
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
926
+
927
+ if output_hidden_states:
928
+ all_hidden_states = all_hidden_states + (hidden_states,)
929
+
930
+ if self.gradient_checkpointing and self.training:
931
+
932
+ def create_custom_forward(module):
933
+ def custom_forward(*inputs):
934
+ # None for past_key_value
935
+ return module(*inputs, use_cache, output_attentions)
936
+
937
+ return custom_forward
938
+
939
+ outputs = torch.utils.checkpoint.checkpoint(
940
+ create_custom_forward(block),
941
+ hidden_states,
942
+ rotary_pos_emb_list,
943
+ self.registered_causal_mask,
944
+ None,
945
+ attention_mask,
946
+ head_mask[i],
947
+ encoder_hidden_states,
948
+ encoder_attention_mask,
949
+ )
950
+ else:
951
+ outputs = block(
952
+ hidden_states,
953
+ layer_past=layer_past,
954
+ rotary_pos_emb_list=rotary_pos_emb_list,
955
+ registered_causal_mask=self.registered_causal_mask,
956
+ attention_mask=attention_mask,
957
+ head_mask=head_mask[i],
958
+ encoder_hidden_states=encoder_hidden_states,
959
+ encoder_attention_mask=encoder_attention_mask,
960
+ use_cache=use_cache,
961
+ output_attentions=output_attentions,
962
+ )
963
+
964
+ hidden_states = outputs[0]
965
+ if use_cache is True:
966
+ presents = presents + (outputs[1],)
967
+
968
+ if output_attentions:
969
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
970
+
971
+ hidden_states = self.ln_f(hidden_states)
972
+ hidden_states = hidden_states.view(output_shape)
973
+ # Add last hidden state
974
+ if output_hidden_states:
975
+ all_hidden_states = all_hidden_states + (hidden_states,)
976
+
977
+ if not return_dict:
978
+ return tuple(
979
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
980
+ )
981
+
982
+ return BaseModelOutputWithPast(
983
+ last_hidden_state=hidden_states,
984
+ past_key_values=presents,
985
+ hidden_states=all_hidden_states,
986
+ attentions=all_self_attentions,
987
+ )
988
+
989
+
990
+ class QWenLMHeadModel(QWenPreTrainedModel):
991
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
992
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
993
+
994
+ def __init__(self, config):
995
+ super().__init__(config)
996
+ assert (
997
+ config.bf16 + config.fp16 + config.fp32 <= 1
998
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
999
+ logger.warn(
1000
+ "Warning: please make sure that you are using the latest codes and checkpoints, "
1001
+ "especially if you used Qwen-7B before 09.25.2023."
1002
+ "请使用最新模型和代码,尤其如果你在9月25日前已经开始使用Qwen-7B,千万注意不要使用错误代码和模型。"
1003
+ )
1004
+
1005
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
1006
+
1007
+ if autoset_precision:
1008
+ if SUPPORT_BF16:
1009
+ logger.warn(
1010
+ "The model is automatically converting to bf16 for faster inference. "
1011
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
1012
+ )
1013
+ config.bf16 = True
1014
+ elif SUPPORT_FP16:
1015
+ logger.warn(
1016
+ "The model is automatically converting to fp16 for faster inference. "
1017
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
1018
+ )
1019
+ config.fp16 = True
1020
+ else:
1021
+ config.fp32 = True
1022
+
1023
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
1024
+ 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\".")
1025
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
1026
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
1027
+ if config.fp32:
1028
+ if SUPPORT_BF16:
1029
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
1030
+ elif SUPPORT_FP16:
1031
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
1032
+
1033
+ if config.use_flash_attn == "auto":
1034
+ if config.bf16 or config.fp16:
1035
+ logger.warn("Try importing flash-attention for faster inference...")
1036
+ config.use_flash_attn = True
1037
+ else:
1038
+ config.use_flash_attn = False
1039
+ if config.use_flash_attn and config.fp32:
1040
+ logger.warn("Flash attention will be disabled because it does NOT support fp32.")
1041
+
1042
+ if config.use_flash_attn:
1043
+ _import_flash_attn()
1044
+
1045
+ self.transformer = QWenModel(config)
1046
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1047
+
1048
+ if config.bf16:
1049
+ self.transformer.bfloat16()
1050
+ self.lm_head.bfloat16()
1051
+ if config.fp16:
1052
+ self.transformer.half()
1053
+ self.lm_head.half()
1054
+ self.post_init()
1055
+
1056
+
1057
+ def get_output_embeddings(self):
1058
+ return self.lm_head
1059
+
1060
+ def set_output_embeddings(self, new_embeddings):
1061
+ self.lm_head = new_embeddings
1062
+
1063
+ def prepare_inputs_for_generation(
1064
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
1065
+ ):
1066
+ token_type_ids = kwargs.get("token_type_ids", None)
1067
+ if past_key_values:
1068
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1069
+ if token_type_ids is not None:
1070
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1071
+
1072
+ attention_mask = kwargs.get("attention_mask", None)
1073
+ position_ids = kwargs.get("position_ids", None)
1074
+
1075
+ if attention_mask is not None and position_ids is None:
1076
+ position_ids = attention_mask.long().cumsum(-1) - 1
1077
+ position_ids.masked_fill_(attention_mask == 0, 1)
1078
+ if past_key_values:
1079
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1080
+ else:
1081
+ position_ids = None
1082
+
1083
+ if inputs_embeds is not None and past_key_values is None:
1084
+ model_inputs = {"inputs_embeds": inputs_embeds}
1085
+ else:
1086
+ model_inputs = {"input_ids": input_ids}
1087
+
1088
+ model_inputs.update(
1089
+ {
1090
+ "past_key_values": past_key_values,
1091
+ "use_cache": kwargs.get("use_cache"),
1092
+ "position_ids": position_ids,
1093
+ "attention_mask": attention_mask,
1094
+ "token_type_ids": token_type_ids,
1095
+ }
1096
+ )
1097
+ return model_inputs
1098
+
1099
+ def forward(
1100
+ self,
1101
+ input_ids: Optional[torch.LongTensor] = None,
1102
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1103
+ attention_mask: Optional[torch.FloatTensor] = None,
1104
+ token_type_ids: Optional[torch.LongTensor] = None,
1105
+ position_ids: Optional[torch.LongTensor] = None,
1106
+ head_mask: Optional[torch.FloatTensor] = None,
1107
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1108
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1109
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1110
+ labels: Optional[torch.LongTensor] = None,
1111
+ use_cache: Optional[bool] = None,
1112
+ output_attentions: Optional[bool] = None,
1113
+ output_hidden_states: Optional[bool] = None,
1114
+ return_dict: Optional[bool] = None,
1115
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1116
+
1117
+ return_dict = (
1118
+ return_dict if return_dict is not None else self.config.use_return_dict
1119
+ )
1120
+
1121
+ transformer_outputs = self.transformer(
1122
+ input_ids,
1123
+ past_key_values=past_key_values,
1124
+ attention_mask=attention_mask,
1125
+ token_type_ids=token_type_ids,
1126
+ position_ids=position_ids,
1127
+ head_mask=head_mask,
1128
+ inputs_embeds=inputs_embeds,
1129
+ encoder_hidden_states=encoder_hidden_states,
1130
+ encoder_attention_mask=encoder_attention_mask,
1131
+ use_cache=use_cache,
1132
+ output_attentions=output_attentions,
1133
+ output_hidden_states=output_hidden_states,
1134
+ return_dict=return_dict,
1135
+ )
1136
+ hidden_states = transformer_outputs[0]
1137
+
1138
+ lm_logits = self.lm_head(hidden_states)
1139
+
1140
+ loss = None
1141
+ if labels is not None:
1142
+ labels = labels.to(lm_logits.device)
1143
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1144
+ shift_labels = labels[..., 1:].contiguous()
1145
+ loss_fct = CrossEntropyLoss()
1146
+ loss = loss_fct(
1147
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1148
+ )
1149
+
1150
+ if not return_dict:
1151
+ output = (lm_logits,) + transformer_outputs[1:]
1152
+ return ((loss,) + output) if loss is not None else output
1153
+
1154
+ return CausalLMOutputWithPast(
1155
+ loss=loss,
1156
+ logits=lm_logits,
1157
+ past_key_values=transformer_outputs.past_key_values,
1158
+ hidden_states=transformer_outputs.hidden_states,
1159
+ attentions=transformer_outputs.attentions,
1160
+ )
1161
+
1162
+ @staticmethod
1163
+ def _reorder_cache(
1164
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1165
+ ) -> Tuple[Tuple[torch.Tensor]]:
1166
+
1167
+ return tuple(
1168
+ tuple(
1169
+ past_state.index_select(0, beam_idx.to(past_state.device))
1170
+ for past_state in layer_past
1171
+ )
1172
+ for layer_past in past_key_values
1173
+ )
1174
+
1175
+ def chat(
1176
+ self,
1177
+ tokenizer: PreTrainedTokenizer,
1178
+ query: str,
1179
+ history: Optional[HistoryType],
1180
+ system: str = "You are a helpful assistant.",
1181
+ stream: Optional[bool] = _SENTINEL,
1182
+ stop_words_ids: Optional[List[List[int]]] = None,
1183
+ generation_config: Optional[GenerationConfig] = None,
1184
+ **kwargs,
1185
+ ) -> Tuple[str, HistoryType]:
1186
+ generation_config = generation_config if generation_config is not None else self.generation_config
1187
+
1188
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
1189
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1190
+ if history is None:
1191
+ history = []
1192
+ else:
1193
+ # make a copy of the user's input such that is is left untouched
1194
+ history = copy.deepcopy(history)
1195
+
1196
+ if stop_words_ids is None:
1197
+ stop_words_ids = []
1198
+
1199
+ max_window_size = kwargs.get('max_window_size', None)
1200
+ if max_window_size is None:
1201
+ max_window_size = generation_config.max_window_size
1202
+ raw_text, context_tokens = make_context(
1203
+ tokenizer,
1204
+ query,
1205
+ history=history,
1206
+ system=system,
1207
+ max_window_size=max_window_size,
1208
+ chat_format=generation_config.chat_format,
1209
+ )
1210
+
1211
+ stop_words_ids.extend(get_stop_words_ids(
1212
+ generation_config.chat_format, tokenizer
1213
+ ))
1214
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1215
+ outputs = self.generate(
1216
+ input_ids,
1217
+ stop_words_ids=stop_words_ids,
1218
+ return_dict_in_generate=False,
1219
+ generation_config=generation_config,
1220
+ **kwargs,
1221
+ )
1222
+
1223
+ response = decode_tokens(
1224
+ outputs[0],
1225
+ tokenizer,
1226
+ raw_text_len=len(raw_text),
1227
+ context_length=len(context_tokens),
1228
+ chat_format=generation_config.chat_format,
1229
+ verbose=False,
1230
+ errors='replace'
1231
+ )
1232
+
1233
+ # as history is a copy of the user inputs,
1234
+ # we can always return the new turn to the user.
1235
+ # separating input history and output history also enables the user
1236
+ # to implement more complex history management
1237
+ history.append((query, response))
1238
+
1239
+ return response, history
1240
+
1241
+ def chat_stream(
1242
+ self,
1243
+ tokenizer: PreTrainedTokenizer,
1244
+ query: str,
1245
+ history: Optional[HistoryType],
1246
+ system: str = "You are a helpful assistant.",
1247
+ stop_words_ids: Optional[List[List[int]]] = None,
1248
+ logits_processor: Optional[LogitsProcessorList] = None,
1249
+ generation_config: Optional[GenerationConfig] = None,
1250
+ **kwargs,
1251
+ ) -> Generator[str, Any, None]:
1252
+ generation_config = generation_config if generation_config is not None else self.generation_config
1253
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1254
+ if history is None:
1255
+ history = []
1256
+ if stop_words_ids is None:
1257
+ stop_words_ids = []
1258
+
1259
+ max_window_size = kwargs.get('max_window_size', None)
1260
+ if max_window_size is None:
1261
+ max_window_size = generation_config.max_window_size
1262
+ raw_text, context_tokens = make_context(
1263
+ tokenizer,
1264
+ query,
1265
+ history=history,
1266
+ system=system,
1267
+ max_window_size=max_window_size,
1268
+ chat_format=generation_config.chat_format,
1269
+ )
1270
+
1271
+ stop_words_ids.extend(get_stop_words_ids(
1272
+ generation_config.chat_format, tokenizer
1273
+ ))
1274
+ if stop_words_ids is not None:
1275
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1276
+ stop_words_ids=stop_words_ids,
1277
+ eos_token_id=generation_config.eos_token_id,
1278
+ )
1279
+ if logits_processor is None:
1280
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1281
+ else:
1282
+ logits_processor.append(stop_words_logits_processor)
1283
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1284
+
1285
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1286
+ self.__class__.generate_stream = NewGenerationMixin.generate
1287
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1288
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1289
+
1290
+ def stream_generator():
1291
+ outputs = []
1292
+ for token in self.generate_stream(
1293
+ input_ids,
1294
+ return_dict_in_generate=False,
1295
+ generation_config=stream_config,
1296
+ logits_processor=logits_processor,
1297
+ seed=-1,
1298
+ **kwargs):
1299
+ outputs.append(token.item())
1300
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore')
1301
+
1302
+ return stream_generator()
1303
+
1304
+ def generate(
1305
+ self,
1306
+ inputs: Optional[torch.Tensor] = None,
1307
+ generation_config: Optional[GenerationConfig] = None,
1308
+ logits_processor: Optional[LogitsProcessorList] = None,
1309
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1310
+ prefix_allowed_tokens_fn: Optional[
1311
+ Callable[[int, torch.Tensor], List[int]]
1312
+ ] = None,
1313
+ synced_gpus: Optional[bool] = None,
1314
+ assistant_model: Optional["PreTrainedModel"] = None,
1315
+ streamer: Optional["BaseStreamer"] = None,
1316
+ **kwargs,
1317
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1318
+ generation_config = generation_config if generation_config is not None else self.generation_config
1319
+
1320
+ # Process stop_words_ids.
1321
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1322
+ if stop_words_ids is None and generation_config is not None:
1323
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1324
+ if stop_words_ids is None:
1325
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1326
+
1327
+ if stop_words_ids is not None:
1328
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1329
+ stop_words_ids=stop_words_ids,
1330
+ eos_token_id=generation_config.eos_token_id,
1331
+ )
1332
+ if logits_processor is None:
1333
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1334
+ else:
1335
+ logits_processor.append(stop_words_logits_processor)
1336
+
1337
+ return super().generate(
1338
+ inputs,
1339
+ generation_config=generation_config,
1340
+ logits_processor=logits_processor,
1341
+ stopping_criteria=stopping_criteria,
1342
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1343
+ synced_gpus=synced_gpus,
1344
+ assistant_model=assistant_model,
1345
+ streamer=streamer,
1346
+ **kwargs,
1347
+ )
1348
+
1349
+
1350
+ class RotaryEmbedding(torch.nn.Module):
1351
+ def __init__(self, dim, base=10000):
1352
+ super().__init__()
1353
+ self.dim = dim
1354
+ self.base = base
1355
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1356
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1357
+ if importlib.util.find_spec("einops") is None:
1358
+ raise RuntimeError("einops is required for Rotary Embedding")
1359
+
1360
+ self._rotary_pos_emb_cache = None
1361
+ self._seq_len_cached = 0
1362
+ self._ntk_alpha_cached = 1.0
1363
+ self._ntk_alpha_cached_list = [1.0]
1364
+
1365
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1366
+ seqlen = max_seq_len + offset
1367
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1368
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1369
+ self.inv_freq = 1.0 / (
1370
+ base
1371
+ ** (
1372
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1373
+ / self.dim
1374
+ )
1375
+ )
1376
+ self._seq_len_cached = max(2 * seqlen, 16)
1377
+ self._ntk_alpha_cached = ntk_alpha
1378
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1379
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1380
+
1381
+ emb = torch.cat((freqs, freqs), dim=-1)
1382
+ from einops import rearrange
1383
+
1384
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1385
+
1386
+ cos, sin = emb.cos(), emb.sin()
1387
+ self._rotary_pos_emb_cache = [cos, sin]
1388
+
1389
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
1390
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
1391
+ cos, sin = self._rotary_pos_emb_cache
1392
+ return [cos[:, offset : offset + max_seq_len], sin[:, offset : offset + max_seq_len]]
1393
+
1394
+
1395
+ def _rotate_half(x):
1396
+ from einops import rearrange
1397
+
1398
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1399
+ x1, x2 = x.unbind(dim=-2)
1400
+ return torch.cat((-x2, x1), dim=-1)
1401
+
1402
+
1403
+ def apply_rotary_pos_emb(t, freqs):
1404
+ cos, sin = freqs
1405
+ if apply_rotary_emb_func is not None and t.is_cuda:
1406
+ t_ = t.float()
1407
+ cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]
1408
+ sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]
1409
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1410
+ return output
1411
+ else:
1412
+ rot_dim = freqs[0].shape[-1]
1413
+ cos, sin = freqs
1414
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1415
+ t_ = t_.float()
1416
+ t_pass_ = t_pass_.float()
1417
+ t_ = (t_ * cos) + (_rotate_half(t_) * sin)
1418
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1419
+
1420
+
1421
+ class RMSNorm(torch.nn.Module):
1422
+ def __init__(self, dim: int, eps: float = 1e-6):
1423
+ super().__init__()
1424
+ self.eps = eps
1425
+ self.weight = nn.Parameter(torch.ones(dim))
1426
+
1427
+ def _norm(self, x):
1428
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1429
+
1430
+ def forward(self, x):
1431
+ if rms_norm is not None and x.is_cuda:
1432
+ return rms_norm(x, self.weight, self.eps)
1433
+ else:
1434
+ output = self._norm(x.float()).type_as(x)
1435
+ return output * self.weight
quantize_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bits": 4,
3
+ "group_size": 128,
4
+ "damp_percent": 0.01,
5
+ "desc_act": true,
6
+ "sym": true,
7
+ "true_sequential": true
8
+ }
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
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,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_max_length": 8192,
3
+ "tokenizer_class": "QWenTokenizer",
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_qwen.QWenTokenizer",
7
+ null
8
+ ]
9
+ }
10
+ }