"test/srt/test_two_batch_overlap.py" did not exist on "3196999f63dcab1ddbe9af86183241ae0a2281b7"
llm.py 16.2 KB
Newer Older
1
2
3
4
5
import ctypes;
import math
import os;
import threading
from typing import Optional, Tuple, Union, List, Callable, Dict, Any;
zhouxiang's avatar
zhouxiang committed
6
7
8
9
10
11
12
13
14
15

import platform
if platform.system() == 'Windows':
    fastllm_lib = ctypes.cdll.LoadLibrary(os.path.join(os.path.split(os.path.realpath(__file__))[0], "fastllm_tools.dll"))
else:
    fastllm_lib = ctypes.cdll.LoadLibrary(os.path.join(os.path.split(os.path.realpath(__file__))[0], "libfastllm_tools.so"))

fastllm_lib.create_llm_model.argtypes = [ctypes.c_char_p]
fastllm_lib.create_llm_model.restype = ctypes.c_int

16
17
18
19
20
21
fastllm_lib.token_decode.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_char_p]
fastllm_lib.token_decode.restype = ctypes.c_int

fastllm_lib.token_encode_string.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
fastllm_lib.token_encode_string.restype = ctypes.c_int

zhouxiang's avatar
zhouxiang committed
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
fastllm_lib.launch_response_llm_model.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p,
                                                  ctypes.c_int, ctypes.c_bool, ctypes.c_float, ctypes.c_int,
                                                  ctypes.c_float, ctypes.c_float, ctypes.c_bool]
fastllm_lib.launch_response_llm_model.restype = ctypes.c_int

fastllm_lib.fetch_response_llm_model.argtypes = [ctypes.c_int, ctypes.c_int]
fastllm_lib.fetch_response_llm_model.restype = ctypes.c_int

fastllm_lib.fetch_response_logits_llm_model.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_float)]
fastllm_lib.fetch_response_logits_llm_model.restype = ctypes.c_int

fastllm_lib.response_str_llm_model.argtypes = [ctypes.c_int, ctypes.c_char_p,
                                               ctypes.c_int, ctypes.c_bool, ctypes.c_float, ctypes.c_int,
                                               ctypes.c_float, ctypes.c_float, ctypes.c_bool]
fastllm_lib.response_str_llm_model.restype = ctypes.c_char_p

fastllm_lib.launch_response_str_llm_model.argtype = [ctypes.c_int, ctypes.c_char_p,
                                                     ctypes.c_int, ctypes.c_bool, ctypes.c_float, ctypes.c_int,
                                                     ctypes.c_float, ctypes.c_float, ctypes.c_bool]
fastllm_lib.launch_response_str_llm_model.restype = ctypes.c_int

fastllm_lib.fetch_response_str_llm_model.argtypes = [ctypes.c_int, ctypes.c_int]
fastllm_lib.fetch_response_str_llm_model.restype = ctypes.c_char_p

fastllm_lib.make_history_llm_model.argtype = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p]
fastllm_lib.make_history_llm_model.restype = ctypes.c_char_p

fastllm_lib.make_input_llm_model.argtype = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p]
fastllm_lib.make_input_llm_model.restype = ctypes.c_char_p

fastllm_lib.add_tokenizer_word_llm_model.argtype = [ctypes.c_int, ctypes.c_char_p, ctypes.c_float, ctypes.c_int]

fastllm_lib.set_device_map.argtype = [ctypes.c_int, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]

def set_cpu_threads(threads: int):
57
    fastllm_lib.set_cpu_threads(threads);
zhouxiang's avatar
zhouxiang committed
58
59

def get_cpu_threads() -> int:
60
    return fastllm_lib.get_cpu_threads();
zhouxiang's avatar
zhouxiang committed
61
62

def print_ins_info():
63
    fastllm_lib.print_cpu_ins();
zhouxiang's avatar
zhouxiang committed
64
65

def set_cpu_kvcache(cpu_kvcache):
66
    fastllm_lib.set_kvcache_in_cpu(ctypes.c_bool(cpu_kvcache));
zhouxiang's avatar
zhouxiang committed
67
68

def get_cpu_kvcache():
69
    return fastllm_lib.get_kvcache_in_cpu();
zhouxiang's avatar
zhouxiang committed
70
71

def set_cpu_low_mem(low_mem):
72
    fastllm_lib.set_cpu_low_mem(ctypes.c_bool(low_mem));
zhouxiang's avatar
zhouxiang committed
73
74

def get_cpu_low_mem():
75
    return fastllm_lib.get_cpu_low_mem();
zhouxiang's avatar
zhouxiang committed
76
77

def set_device_map(device_map):
78
79
    devices = [];
    values = [];
zhouxiang's avatar
zhouxiang committed
80
    if (isinstance(device_map, str)):
81
82
        devices.append(device_map);
        values.append(1);
zhouxiang's avatar
zhouxiang committed
83
    elif (isinstance(device_map, list)):
84
85
        devices = [str(x) for x in device_map];
        values = [1 for x in device_map];
zhouxiang's avatar
zhouxiang committed
86
    elif (isinstance(device_map, dict)):
87
88
        devices = [str(x) for x in device_map.keys()];
        values = [int(device_map[x]) for x in device_map.keys()];
zhouxiang's avatar
zhouxiang committed
89
    else:
90
91
92
93
        print("set_device_map error.");
        return;
    device_str = ''.join(devices);
    device_len = [len(x) for x in devices];
zhouxiang's avatar
zhouxiang committed
94
95
96
    fastllm_lib.set_device_map(len(device_len),
                               (ctypes.c_int * len(device_len))(*device_len),
                               device_str.encode(),
97
                               (ctypes.c_int * len(values))(*values));
zhouxiang's avatar
zhouxiang committed
98
99
100
def from_hf(model,
            tokenizer = None,
            dtype = "float16"):
101
102
    from fastllm_pytools import hf_model;
    return hf_model.create(model, tokenizer, dtype = dtype);
zhouxiang's avatar
zhouxiang committed
103
104
105
106
107

class model:
    def __init__ (self, path : str,
                  id : int = -99999):
        if (id != -99999):
108
            self.model = id;
zhouxiang's avatar
zhouxiang committed
109
        else:
110
111
112
113
114
115
116
117
118
119
120
121
            self.model = fastllm_lib.create_llm_model(path.encode());
        self.direct_query = False;

        # 为了减少重复申请释放buffer对象而使用的线程局部存储区对象池
        self.thread_local_obj = threading.local()
        self.thread_local_obj.tokenizer_encode_string__output_buffer = None
        self.thread_local_obj.tokenizer_decode_token__output_buffer = None

        # tokenizer_decode_token 输出结果的静态缓存,手工触发构建
        # 由于token数量有限且不太多,所以缓存该结果来减少调用较为适合。
        # 不做成自动缓存是为了避免在多线程调用的时候对缓存dict加锁,同时也为不同场景提供选择空间
        self.tokenizer_decode_token_cache = None
zhouxiang's avatar
zhouxiang committed
122
123
124
125
126

    def get_prompt(self,
                   query: str,
                   history: List[Tuple[str, str]] = None) -> str:
        if (not(history)):
127
128
            history = [];
        prompt = "";
zhouxiang's avatar
zhouxiang committed
129
        for i, (old_query, response) in enumerate(history):
130
131
132
            prompt = fastllm_lib.make_history_llm_model(self.model, prompt.encode(), i, old_query.encode(), response.encode()).decode();
        prompt = fastllm_lib.make_input_llm_model(self.model, prompt.encode(), len(history), query.encode()).decode();
        return prompt;
zhouxiang's avatar
zhouxiang committed
133
134

    def save(self, path : str):
135
        fastllm_lib.save_llm_model(self.model, path.encode());
zhouxiang's avatar
zhouxiang committed
136
137

    def eval(self):
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
        pass;

    def build_tokenizer_decode_token_cache(self):
        if self.tokenizer_decode_token_cache is not None:
            return

        cache_dict = dict()
        vocab_size = fastllm_lib.get_tokenizer_vocab_size(self.model)
        for token_id in range(vocab_size):
            cache_dict[token_id] = self.tokenizer_decode_token(token_id)

        self.tokenizer_decode_token_cache = cache_dict

    def tokenizer_encode_string(self, content: str) -> List[int]:
        output_buffer_init_len = 1024
        if self.thread_local_obj.tokenizer_encode_string__output_buffer is None:
            self.thread_local_obj.tokenizer_encode_string__output_buffer = (ctypes.c_int * output_buffer_init_len)()

        buffer = self.thread_local_obj.tokenizer_encode_string__output_buffer
        buffer_len = len(buffer)
        result_len = fastllm_lib.token_encode_string(self.model, content.encode(), buffer_len, buffer)
        if result_len > buffer_len:
            if result_len > 10240:
                # 要处理的数据过长,使用一次性的buffer
                temp_buffer = (ctypes.c_int * result_len)()
                ret = fastllm_lib.token_encode_string(self.model, content.encode(), result_len, temp_buffer)
                return [i for i in temp_buffer]
            else:
                # 扩展buffer大小
                new_buffer_len = round(math.ceil(result_len / 1024.0)) * 1024
                buffer = (ctypes.c_int * new_buffer_len)()
                self.thread_local_obj.tokenizer_encode_string__output_buffer = buffer
                result_len = fastllm_lib.token_encode_string(self.model, content.encode(), new_buffer_len, buffer)

        return [buffer[i] for i in range(result_len)]

    def tokenizer_decode_token(self, token_id: int) -> bytes:
        if self.tokenizer_decode_token_cache is not None:
            cache_result = self.tokenizer_decode_token_cache.get(token_id)
            if cache_result is not None:
                return cache_result

        output_buffer_init_len = 256
        if self.thread_local_obj.tokenizer_decode_token__output_buffer is None:
            self.thread_local_obj.tokenizer_decode_token__output_buffer = ctypes.create_string_buffer(output_buffer_init_len)

        buffer = self.thread_local_obj.tokenizer_decode_token__output_buffer
        ret = fastllm_lib.token_decode(self.model, token_id, len(buffer), buffer)
        if ret > 0:
            # buffer长度不够,扩展buffer大小
            new_buffer_len = round(math.ceil(ret / 16.0)) * 16
            buffer = ctypes.create_string_buffer(new_buffer_len)
            self.thread_local_obj.tokenizer_decode_token__output_buffer = buffer
            ret = fastllm_lib.token_decode(self.model, token_id, len(buffer), buffer)
            assert ret == 0

        buffer_bytes = buffer.raw
        result_len = len(buffer_bytes)
        for i in range(len(buffer_bytes)):
            if buffer_bytes[i] == 0:
                result_len = i
                break
        return buffer_bytes[:result_len]
zhouxiang's avatar
zhouxiang committed
201
202
203
204
205

    def response_logits(self,
                        query: str,
                        history: List[Tuple[str, str]] = None,
                        tokenizer = None) -> str:
206
        prompt = query if self.direct_query else self.get_prompt(query, history);
zhouxiang's avatar
zhouxiang committed
207
208
209
        if (tokenizer == None):
            handle = fastllm_lib.launch_response_str_llm_model(self.model, prompt.encode(),
                                                           ctypes.c_int(1), ctypes.c_bool(False), ctypes.c_float(1), ctypes.c_int(1),
210
                                                           ctypes.c_float(1), ctypes.c_float(1), ctypes.c_bool(True));
zhouxiang's avatar
zhouxiang committed
211
        else:
212
            input = tokenizer.encode(prompt);
zhouxiang's avatar
zhouxiang committed
213
            handle = fastllm_lib.launch_response_llm_model(self.model, len(input), (ctypes.c_int * len(input))(*input),
214
215
                                                           1, False, 1, 1, 1, 1, True);
        vocab_size = fastllm_lib.get_tokenizer_vocab_size(self.model);
zhouxiang's avatar
zhouxiang committed
216
        logits = list(range(vocab_size))
217
218
219
        array = (ctypes.c_float * (vocab_size * 4))(*logits);
        ret = fastllm_lib.fetch_response_logits_llm_model(self.model, handle, array);
        out = list(array)[:vocab_size];
zhouxiang's avatar
zhouxiang committed
220
        while (ret != -1):
221
222
            ret = fastllm_lib.fetch_response_logits_llm_model(self.model, handle, array);
        return out;
zhouxiang's avatar
zhouxiang committed
223
224
225
226
227

    def response(self,
                 query: str,
                 history: List[Tuple[str, str]] = None,
                 max_length: int = 8192, do_sample = True, top_p = 0.8, top_k = 1, temperature = 1.0, repeat_penalty = 1.0) -> str:
228
        ret = "";
zhouxiang's avatar
zhouxiang committed
229
230
231
232
233
234
235
236
        for i in self.stream_response(query = query,
                                      history = history,
                                      max_length = max_length,
                                      do_sample = do_sample,
                                      top_p = top_p, top_k = top_k,
                                      temperature = temperature,
                                      repeat_penalty = repeat_penalty,
                                      one_by_one = True):
237
238
            ret += i;
        return ret;
zhouxiang's avatar
zhouxiang committed
239
240
241
242
243
244

    def stream_response(self,
                        query: str,
                        history: List[Tuple[str, str]] = None,
                        max_length: int = 8192, do_sample = True, top_p = 0.8, top_k = 1, temperature = 1.0, repeat_penalty = 1.0,
                        one_by_one = True):
245
        prompt = query if self.direct_query else self.get_prompt(query, history);
zhouxiang's avatar
zhouxiang committed
246
247
        handle = fastllm_lib.launch_response_str_llm_model(self.model, prompt.encode(),
                                                           ctypes.c_int(max_length), ctypes.c_bool(do_sample), ctypes.c_float(top_p), ctypes.c_int(top_k),
248
249
250
251
                                                           ctypes.c_float(temperature), ctypes.c_float(repeat_penalty), ctypes.c_bool(False));
        res = "";
        ret = b'';
        fail_cnt = 0;
zhouxiang's avatar
zhouxiang committed
252
        while True:
253
254
            ret += fastllm_lib.fetch_response_str_llm_model(self.model, handle);
            cur = "";
zhouxiang's avatar
zhouxiang committed
255
            try:
256
257
                cur = ret.decode();
                ret = b'';
zhouxiang's avatar
zhouxiang committed
258
            except:
259
                fail_cnt += 1;
zhouxiang's avatar
zhouxiang committed
260
                if (fail_cnt == 20):
261
                    break;
zhouxiang's avatar
zhouxiang committed
262
                else:
263
264
                    continue;
            fail_cnt = 0;
zhouxiang's avatar
zhouxiang committed
265
            if (cur == "<flmeos>"):
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
                break;
            if one_by_one:
                yield cur;
            else:
                res += cur;
                yield res;

    def stream_response_raw(self,
                            input_tokens: List[int],
                            max_length: int = 8192, do_sample = True, top_p = 0.8, top_k = 1, temperature = 1.0, repeat_penalty = 1.0,
                            one_by_one = True
                            ):
        handle = fastllm_lib.launch_response_llm_model(self.model, len(input_tokens),
                                                       (ctypes.c_int * len(input_tokens))(*input_tokens),
                                                       ctypes.c_int(max_length), ctypes.c_bool(do_sample), ctypes.c_float(top_p), ctypes.c_int(top_k),
                                                       ctypes.c_float(temperature), ctypes.c_float(repeat_penalty), ctypes.c_bool(False))

        # 可能遇到长尾char需要多个token才能够生成,所以只返回bytes,string.decode策略交给外部
        # 方便统计输出token数量,和控制不完整utf8时候解码的逻辑

        total_bytes = b''
        while True:
            cur_token = fastllm_lib.fetch_response_llm_model(self.model, handle)
            if cur_token == -1:
zhouxiang's avatar
zhouxiang committed
290
                break
291
292
293

            cur_bytes = self.tokenizer_decode_token(cur_token)

zhouxiang's avatar
zhouxiang committed
294
            if one_by_one:
295
                yield cur_bytes
zhouxiang's avatar
zhouxiang committed
296
            else:
297
298
                total_bytes += cur_bytes
                yield total_bytes
zhouxiang's avatar
zhouxiang committed
299
300
301
302

    def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 8192,
             do_sample = True, top_p = 0.8, top_k = 1, temperature = 1.0, repeat_penalty = 1.0, **kwargs):
        if (not(history)):
303
304
305
            history = [];
        prompt = query if self.direct_query else self.get_prompt(query, history);
        input = tokenizer.encode(prompt);
zhouxiang's avatar
zhouxiang committed
306
307
        handle = fastllm_lib.launch_response_llm_model(self.model, len(input), (ctypes.c_int * len(input))(*input),
                                                       max_length, do_sample, top_p, top_k, temperature, repeat_penalty,
308
                                                       False);
zhouxiang's avatar
zhouxiang committed
309

310
        result = [];
zhouxiang's avatar
zhouxiang committed
311
        while True:
312
            cur = fastllm_lib.fetch_response_llm_model(self.model, handle);
zhouxiang's avatar
zhouxiang committed
313
            if (cur == -1):
314
315
316
317
318
                break;
            result.append(cur);
        response = tokenizer.decode(result);
        history = history + [(query, response)];
        return response, history;
zhouxiang's avatar
zhouxiang committed
319
320
321
322
323

    def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, past_key_values = None,
                    max_length: int = 8192, do_sample = True, top_p = 0.8, top_k = 1, temperature = 1.0, repeat_penalty = 1.0,
                    return_past_key_values = False, **kwargs) -> str:
        if (not(history)):
324
325
326
            history = [];
        prompt = query if self.direct_query else self.get_prompt(query, history);
        input = tokenizer.encode(prompt);
zhouxiang's avatar
zhouxiang committed
327
328
        handle = fastllm_lib.launch_response_llm_model(self.model, len(input), (ctypes.c_int * len(input))(*input),
                                                       max_length, do_sample, top_p, top_k, temperature, repeat_penalty,
329
330
                                                       False);
        tokens = [];
zhouxiang's avatar
zhouxiang committed
331
        while True:
332
            cur = fastllm_lib.fetch_response_llm_model(self.model, handle);
zhouxiang's avatar
zhouxiang committed
333
            if (cur == -1):
334
335
336
337
                break;
            tokens.append(cur);
            response = tokenizer.decode(tokens);
            new_history = history + [(query, response)];
zhouxiang's avatar
zhouxiang committed
338
            if return_past_key_values:
339
                yield response, new_history, None;
zhouxiang's avatar
zhouxiang committed
340
            else:
341
                yield response, new_history;
zhouxiang's avatar
zhouxiang committed
342
343
344
345
346
347

    def set_adapter(self, name: str):
        fastllm_lib.set_adapter(self.model, str(name).encode())
    
    def disable_adapter(self):
        fastllm_lib.disable_adapter(self.model)