ctranslate2-4you commited on
Commit
3532565
1 Parent(s): 1646b7f

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +217 -129
README.md CHANGED
@@ -1,131 +1,219 @@
1
- ---
2
- license: apache-2.0
3
- license_link: https://huggingface.co/Qwen/Qwen2.5-14B-Instruct/blob/main/LICENSE
4
- language:
5
- - en
6
- pipeline_tag: text-generation
7
- base_model: Qwen/Qwen2.5-14B
8
- tags:
9
- - chat
10
- ---
11
-
12
- # Qwen2.5-14B-Instruct
13
-
14
- ## Introduction
15
-
16
- Qwen2.5 is the latest series of Qwen large language models. For Qwen2.5, we release a number of base language models and instruction-tuned language models ranging from 0.5 to 72 billion parameters. Qwen2.5 brings the following improvements upon Qwen2:
17
-
18
- - Significantly **more knowledge** and has greatly improved capabilities in **coding** and **mathematics**, thanks to our specialized expert models in these domains.
19
- - Significant improvements in **instruction following**, **generating long texts** (over 8K tokens), **understanding structured data** (e.g, tables), and **generating structured outputs** especially JSON. **More resilient to the diversity of system prompts**, enhancing role-play implementation and condition-setting for chatbots.
20
- - **Long-context Support** up to 128K tokens and can generate up to 8K tokens.
21
- - **Multilingual support** for over 29 languages, including Chinese, English, French, Spanish, Portuguese, German, Italian, Russian, Japanese, Korean, Vietnamese, Thai, Arabic, and more.
22
-
23
- **This repo contains the instruction-tuned 14B Qwen2.5 model**, which has the following features:
24
- - Type: Causal Language Models
25
- - Training Stage: Pretraining & Post-training
26
- - Architecture: transformers with RoPE, SwiGLU, RMSNorm, and Attention QKV bias
27
- - Number of Parameters: 14.7B
28
- - Number of Paramaters (Non-Embedding): 13.1B
29
- - Number of Layers: 48
30
- - Number of Attention Heads (GQA): 40 for Q and 8 for KV
31
- - Context Length: Full 131,072 tokens and generation 8192 tokens
32
- - Please refer to [this section](#processing-long-texts) for detailed instructions on how to deploy Qwen2.5 for handling long texts.
33
-
34
- For more details, please refer to our [blog](https://qwenlm.github.io/blog/qwen2.5/), [GitHub](https://github.com/QwenLM/Qwen2.5), and [Documentation](https://qwen.readthedocs.io/en/latest/).
35
-
36
- ## Requirements
37
-
38
- The code of Qwen2.5 has been in the latest Hugging face `transformers` and we advise you to use the latest version of `transformers`.
39
-
40
- With `transformers<4.37.0`, you will encounter the following error:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ```
42
- KeyError: 'qwen2'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ```
44
-
45
- ## Quickstart
46
-
47
- Here provides a code snippet with `apply_chat_template` to show you how to load the tokenizer and model and how to generate contents.
48
-
49
- ```python
50
- from transformers import AutoModelForCausalLM, AutoTokenizer
51
-
52
- model_name = "Qwen/Qwen2.5-14B-Instruct"
53
-
54
- model = AutoModelForCausalLM.from_pretrained(
55
- model_name,
56
- torch_dtype="auto",
57
- device_map="auto"
58
- )
59
- tokenizer = AutoTokenizer.from_pretrained(model_name)
60
-
61
- prompt = "Give me a short introduction to large language model."
62
- messages = [
63
- {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
64
- {"role": "user", "content": prompt}
65
- ]
66
- text = tokenizer.apply_chat_template(
67
- messages,
68
- tokenize=False,
69
- add_generation_prompt=True
70
- )
71
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
72
-
73
- generated_ids = model.generate(
74
- **model_inputs,
75
- max_new_tokens=512
76
- )
77
- generated_ids = [
78
- output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
79
- ]
80
-
81
- response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
82
- ```
83
-
84
- ### Processing Long Texts
85
-
86
- The current `config.json` is set for context length up to 32,768 tokens.
87
- To handle extensive inputs exceeding 32,768 tokens, we utilize [YaRN](https://arxiv.org/abs/2309.00071), a technique for enhancing model length extrapolation, ensuring optimal performance on lengthy texts.
88
-
89
- For supported frameworks, you could add the following to `config.json` to enable YaRN:
90
- ```json
91
- {
92
- ...,
93
- "rope_scaling": {
94
- "factor": 4.0,
95
- "original_max_position_embeddings": 32768,
96
- "type": "yarn"
97
- }
98
- }
99
- ```
100
-
101
- For deployment, we recommend using vLLM.
102
- Please refer to our [Documentation](https://qwen.readthedocs.io/en/latest/deployment/vllm.html) for usage if you are not familar with vLLM.
103
- Presently, vLLM only supports static YARN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts**.
104
- We advise adding the `rope_scaling` configuration only when processing long contexts is required.
105
-
106
- ## Evaluation & Performance
107
-
108
- Detailed evaluation results are reported in this [📑 blog](https://qwenlm.github.io/blog/qwen2.5/).
109
-
110
- For requirements on GPU memory and the respective throughput, see results [here](https://qwen.readthedocs.io/en/latest/benchmark/speed_benchmark.html).
111
-
112
- ## Citation
113
-
114
- If you find our work helpful, feel free to give us a cite.
115
-
116
- ```
117
- @misc{qwen2.5,
118
- title = {Qwen2.5: A Party of Foundation Models},
119
- url = {https://qwenlm.github.io/blog/qwen2.5/},
120
- author = {Qwen Team},
121
- month = {September},
122
- year = {2024}
123
- }
124
-
125
- @article{qwen2,
126
- title={Qwen2 Technical Report},
127
- author={An Yang and Baosong Yang and Binyuan Hui and Bo Zheng and Bowen Yu and Chang Zhou and Chengpeng Li and Chengyuan Li and Dayiheng Liu and Fei Huang and Guanting Dong and Haoran Wei and Huan Lin and Jialong Tang and Jialin Wang and Jian Yang and Jianhong Tu and Jianwei Zhang and Jianxin Ma and Jin Xu and Jingren Zhou and Jinze Bai and Jinzheng He and Junyang Lin and Kai Dang and Keming Lu and Keqin Chen and Kexin Yang and Mei Li and Mingfeng Xue and Na Ni and Pei Zhang and Peng Wang and Ru Peng and Rui Men and Ruize Gao and Runji Lin and Shijie Wang and Shuai Bai and Sinan Tan and Tianhang Zhu and Tianhao Li and Tianyu Liu and Wenbin Ge and Xiaodong Deng and Xiaohuan Zhou and Xingzhang Ren and Xinyu Zhang and Xipin Wei and Xuancheng Ren and Yang Fan and Yang Yao and Yichang Zhang and Yu Wan and Yunfei Chu and Yuqiong Liu and Zeyu Cui and Zhenru Zhang and Zhihao Fan},
128
- journal={arXiv preprint arXiv:2407.10671},
129
- year={2024}
130
- }
131
- ```
 
1
+ Conversion of https://huggingface.co/Qwen/Qwen2.5-14B-Instruct into the ```ctranslate2``` format using ```int8``` quantization.
2
+
3
+ NOTE #1: This requires a version of ```ctranslate2``` GREATER THAN 4.5.0.
4
+
5
+ NOTE #2: The sample scripts below require ```pip``` installing the necessary ```CUDA``` and ```CUDNN``` libraries. If you rely on a systemwide installation instead, adjust your code accordingly.
6
+
7
+ Requirements:
8
+
9
+ - torch 2.4.0+cu124
10
+ - nvidia-cublas-cu12 12.4.2.65
11
+ - nvidia-cuda-nvrtc-cu12 12.4.99
12
+ - nvidia-cuda-runtime-cu12 12.4.99
13
+ - nvidia-cudnn-cu12 9.1.0.70
14
+ - numpy==1.26.4 (YOU MUST DOWNGRADE FROM THE NUMPY VERSION THAT CTRANSLATE2 INSTALLS BY DEFAULT)
15
+ - All other traditional dependencies like ```transformers```, ```accelerate```, etc.
16
+
17
+ <details><summary>Sample Script #1 (non-streaming):</summary>
18
+
19
+ ```Python
20
+ import sys
21
+ import os
22
+ os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
23
+ from pathlib import Path
24
+
25
+ def set_cuda_paths():
26
+ venv_base = Path(sys.executable).parent.parent
27
+ nvidia_base_path = venv_base / 'Lib' / 'site-packages' / 'nvidia'
28
+ cuda_path = nvidia_base_path / 'cuda_runtime' / 'bin'
29
+ cublas_path = nvidia_base_path / 'cublas' / 'bin'
30
+ cudnn_path = nvidia_base_path / 'cudnn' / 'bin'
31
+ nvrtc_path = nvidia_base_path / 'cuda_nvrtc' / 'bin'
32
+
33
+ paths_to_add = [
34
+ str(cuda_path),
35
+ str(cublas_path),
36
+ str(cudnn_path),
37
+ str(nvrtc_path),
38
+ ]
39
+
40
+ env_vars = ['CUDA_PATH', 'CUDA_PATH_V12_4', 'PATH']
41
+
42
+ for env_var in env_vars:
43
+ current_value = os.environ.get(env_var, '')
44
+ new_value = os.pathsep.join(paths_to_add + [current_value] if current_value else paths_to_add)
45
+ os.environ[env_var] = new_value
46
+
47
+ set_cuda_paths()
48
+
49
+ import ctranslate2
50
+ import gc
51
+ import torch
52
+ from transformers import AutoTokenizer
53
+ import pynvml
54
+ from constants import user_message, system_message
55
+
56
+ pynvml.nvmlInit()
57
+ handle = pynvml.nvmlDeviceGetHandleByIndex(0)
58
+
59
+ model_dir = r"[INSERT PATH TO FOLDER CONTAINING THE MODEL FILES HERE]"
60
+
61
+ def build_prompt():
62
+ prompt = f"""<|im_start|>system
63
+ {system_message}<|im_end|>
64
+ <|im_start|>user
65
+ {user_message}<|im_end|>
66
+ <|im_start|>assistant
67
+ """
68
+ return prompt
69
+
70
+ def main():
71
+ model_name = os.path.basename(model_dir)
72
+ beam_size_value = 1
73
+ intra_threads = max(os.cpu_count() - 4, 4)
74
+
75
+ generator = ctranslate2.Generator(
76
+ model_dir,
77
+ device="cuda",
78
+ compute_type="int8",
79
+ intra_threads=intra_threads
80
+ )
81
+
82
+ tokenizer = AutoTokenizer.from_pretrained(model_dir, add_prefix_space=None)
83
+ prompt = build_prompt()
84
+ tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(prompt))
85
+
86
+ results_batch = generator.generate_batch(
87
+ [tokens],
88
+ include_prompt_in_result=False,
89
+ max_batch_size=4096,
90
+ batch_type="tokens",
91
+ beam_size=beam_size_value,
92
+ num_hypotheses=1,
93
+ max_length=512,
94
+ sampling_temperature=0.0,
95
+ )
96
+
97
+ output = tokenizer.decode(results_batch[0].sequences_ids[0])
98
+ print("\nGenerated response:\n")
99
+ print(output)
100
+
101
+ del generator
102
+ del tokenizer
103
+ torch.cuda.empty_cache()
104
+ gc.collect()
105
+
106
+ if __name__ == "__main__":
107
+ main()
108
  ```
109
+ </details>
110
+
111
+ <details><summary>Sample Script #2 (streaming)</summary>
112
+
113
+ ```Python
114
+ import sys
115
+ import os
116
+ os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
117
+ from pathlib import Path
118
+
119
+ def set_cuda_paths():
120
+ venv_base = Path(sys.executable).parent.parent
121
+ nvidia_base_path = venv_base / 'Lib' / 'site-packages' / 'nvidia'
122
+ cuda_path = nvidia_base_path / 'cuda_runtime' / 'bin'
123
+ cublas_path = nvidia_base_path / 'cublas' / 'bin'
124
+ cudnn_path = nvidia_base_path / 'cudnn' / 'bin'
125
+ nvrtc_path = nvidia_base_path / 'cuda_nvrtc' / 'bin'
126
+
127
+ paths_to_add = [
128
+ str(cuda_path),
129
+ str(cublas_path),
130
+ str(cudnn_path),
131
+ str(nvrtc_path),
132
+ ]
133
+
134
+ env_vars = ['CUDA_PATH', 'CUDA_PATH_V12_4', 'PATH']
135
+
136
+ for env_var in env_vars:
137
+ current_value = os.environ.get(env_var, '')
138
+ new_value = os.pathsep.join(paths_to_add + [current_value] if current_value else paths_to_add)
139
+ os.environ[env_var] = new_value
140
+
141
+ set_cuda_paths()
142
+
143
+ import ctranslate2
144
+ import gc
145
+ import torch
146
+ from transformers import AutoTokenizer
147
+ import pynvml
148
+ from constants import user_message, system_message
149
+
150
+ pynvml.nvmlInit()
151
+ handle = pynvml.nvmlDeviceGetHandleByIndex(0)
152
+
153
+ model_dir = r"[PATH TO FOLDER CONTAINING THE MODEL FILES]"
154
+
155
+
156
+ def build_prompt():
157
+ prompt = f"""<|im_start|>system
158
+ {system_message}<|im_end|>
159
+ <|im_start|>user
160
+ {user_message}<|im_end|>
161
+ <|im_start|>assistant
162
+ """
163
+ return prompt
164
+
165
+ def main():
166
+ generator = ctranslate2.Generator(
167
+ model_dir,
168
+ device="cuda",
169
+ compute_type="int8",
170
+ )
171
+
172
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
173
+ prompt = build_prompt()
174
+ tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(prompt))
175
+
176
+ # Initialize token iterator
177
+ token_iterator = generator.generate_tokens(
178
+ [tokens],
179
+ max_length=512,
180
+ sampling_temperature=0.0
181
+ )
182
+
183
+ decoded_output = ""
184
+ tokens_buffer = []
185
+
186
+ try:
187
+ for token_result in token_iterator:
188
+ token_id = token_result.token_id
189
+ token = tokenizer.convert_ids_to_tokens(token_id)
190
+
191
+ if token_id == tokenizer.eos_token_id:
192
+ break
193
+
194
+ is_new_word = token.startswith("Ġ")
195
+ if is_new_word and tokens_buffer:
196
+ word = tokenizer.decode(tokens_buffer)
197
+ print(word, end='', flush=True)
198
+ decoded_output += word
199
+ tokens_buffer = []
200
+
201
+ tokens_buffer.append(token_id)
202
+
203
+ if tokens_buffer:
204
+ word = tokenizer.decode(tokens_buffer)
205
+ print(word, end='', flush=True)
206
+ decoded_output += word
207
+
208
+ except KeyboardInterrupt:
209
+ print("\nGeneration interrupted")
210
+
211
+ del generator
212
+ del tokenizer
213
+ torch.cuda.empty_cache()
214
+ gc.collect()
215
+
216
+ if __name__ == "__main__":
217
+ main()
218
  ```
219
+ </details>