File size: 6,326 Bytes
9e7abb2
 
 
da4de0e
 
 
9e7abb2
da4de0e
 
9e7abb2
 
da4de0e
9e7abb2
da4de0e
9e7abb2
da4de0e
9e7abb2
da4de0e
9e7abb2
da4de0e
 
 
 
 
 
 
9e7abb2
da4de0e
9e7abb2
37fe015
da4de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e7abb2
da4de0e
9e7abb2
da4de0e
9e7abb2
37fe015
da4de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e7abb2
da4de0e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
---
license_link: https://huggingface.co/Qwen/Qwen2.5-7B-Instruct/blob/main/LICENSE
pipeline_tag: text-generation
base_model:
- Qwen/Qwen2.5-7B-Instruct
base_model_relation: quantized
tags:
- ctranslate2
- Qwen2.5
- chat
---
Conversion of https://huggingface.co/Qwen/Qwen2.5-7B-Instruct into the ```ctranslate2``` format using ```int8``` quantization.

NOTE #1: This requires a version of ```ctranslate2``` GREATER THAN 4.5.0.

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.

Requirements:

- torch 2.4.0+cu124
- nvidia-cublas-cu12 12.4.2.65
- nvidia-cuda-nvrtc-cu12 12.4.99
- nvidia-cuda-runtime-cu12 12.4.99
- nvidia-cudnn-cu12 9.1.0.70
- numpy==1.26.4 (YOU MUST DOWNGRADE FROM THE NUMPY VERSION THAT CTRANSLATE2 INSTALLS BY DEFAULT)
- All other traditional dependencies like ```transformers```, ```accelerate```, etc.

<details><summary>Sample Script #1 (non-streaming):</summary>

```Python
import sys
import os
os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
from pathlib import Path

def set_cuda_paths():
    venv_base = Path(sys.executable).parent.parent
    nvidia_base_path = venv_base / 'Lib' / 'site-packages' / 'nvidia'
    cuda_path = nvidia_base_path / 'cuda_runtime' / 'bin'
    cublas_path = nvidia_base_path / 'cublas' / 'bin'
    cudnn_path = nvidia_base_path / 'cudnn' / 'bin'
    nvrtc_path = nvidia_base_path / 'cuda_nvrtc' / 'bin'
    
    paths_to_add = [
        str(cuda_path),
        str(cublas_path),
        str(cudnn_path),
        str(nvrtc_path),
    ]

    env_vars = ['CUDA_PATH', 'CUDA_PATH_V12_4', 'PATH']
    
    for env_var in env_vars:
        current_value = os.environ.get(env_var, '')
        new_value = os.pathsep.join(paths_to_add + [current_value] if current_value else paths_to_add)
        os.environ[env_var] = new_value

set_cuda_paths()

import ctranslate2
import gc
import torch
from transformers import AutoTokenizer
import pynvml
from constants import user_message, system_message

pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(0)

model_dir = r"[INSERT PATH TO FOLDER CONTAINING THE MODEL FILES HERE]"

def build_prompt():
    prompt = f"""<|im_start|>system
{system_message}<|im_end|>
<|im_start|>user
{user_message}<|im_end|>
<|im_start|>assistant
"""
    return prompt

def main():
    model_name = os.path.basename(model_dir)
    beam_size_value = 1
    intra_threads = max(os.cpu_count() - 4, 4)
    
    generator = ctranslate2.Generator(
        model_dir,
        device="cuda",
        compute_type="int8",
        intra_threads=intra_threads
    )
    
    tokenizer = AutoTokenizer.from_pretrained(model_dir, add_prefix_space=None)
    prompt = build_prompt()
    tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(prompt))
    
    results_batch = generator.generate_batch(
        [tokens],
        include_prompt_in_result=False,
        max_batch_size=4096,
        batch_type="tokens",
        beam_size=beam_size_value,
        num_hypotheses=1,
        max_length=512,
        sampling_temperature=0.0,
    )
    
    output = tokenizer.decode(results_batch[0].sequences_ids[0])
    print("\nGenerated response:\n")
    print(output)
    
    del generator
    del tokenizer
    torch.cuda.empty_cache()
    gc.collect()
    
if __name__ == "__main__":
    main()
```
</details>

<details><summary>Sample Script #2 (streaming)</summary>

```Python
import sys
import os
os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
from pathlib import Path

def set_cuda_paths():
    venv_base = Path(sys.executable).parent.parent
    nvidia_base_path = venv_base / 'Lib' / 'site-packages' / 'nvidia'
    cuda_path = nvidia_base_path / 'cuda_runtime' / 'bin'
    cublas_path = nvidia_base_path / 'cublas' / 'bin'
    cudnn_path = nvidia_base_path / 'cudnn' / 'bin'
    nvrtc_path = nvidia_base_path / 'cuda_nvrtc' / 'bin'
    
    paths_to_add = [
        str(cuda_path),
        str(cublas_path),
        str(cudnn_path),
        str(nvrtc_path),
    ]

    env_vars = ['CUDA_PATH', 'CUDA_PATH_V12_4', 'PATH']
    
    for env_var in env_vars:
        current_value = os.environ.get(env_var, '')
        new_value = os.pathsep.join(paths_to_add + [current_value] if current_value else paths_to_add)
        os.environ[env_var] = new_value

set_cuda_paths()

import ctranslate2
import gc
import torch
from transformers import AutoTokenizer
import pynvml
from constants import user_message, system_message

pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(0)

model_dir = r"[PATH TO FOLDER CONTAINING THE MODEL FILES]"


def build_prompt():
    prompt = f"""<|im_start|>system
{system_message}<|im_end|>
<|im_start|>user
{user_message}<|im_end|>
<|im_start|>assistant
"""
    return prompt

def main():
    generator = ctranslate2.Generator(
        model_dir,
        device="cuda",
        compute_type="int8",
    )
    
    tokenizer = AutoTokenizer.from_pretrained(model_dir)
    prompt = build_prompt()
    tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(prompt))
    
    # Initialize token iterator
    token_iterator = generator.generate_tokens(
        [tokens],
        max_length=512,
        sampling_temperature=0.0
    )
    
    decoded_output = ""
    tokens_buffer = []
    
    try:
        for token_result in token_iterator:
            token_id = token_result.token_id
            token = tokenizer.convert_ids_to_tokens(token_id)
            
            if token_id == tokenizer.eos_token_id:
                break
                
            is_new_word = token.startswith("Ġ")
            if is_new_word and tokens_buffer:
                word = tokenizer.decode(tokens_buffer)
                print(word, end='', flush=True)
                decoded_output += word
                tokens_buffer = []
                
            tokens_buffer.append(token_id)
        
        if tokens_buffer:
            word = tokenizer.decode(tokens_buffer)
            print(word, end='', flush=True)
            decoded_output += word
            
    except KeyboardInterrupt:
        print("\nGeneration interrupted")
        
    del generator
    del tokenizer
    torch.cuda.empty_cache()
    gc.collect()
    
if __name__ == "__main__":
    main()
```
</details>