Repository navigation
Expand file tree
/
Copy pathtest_llama.py
More file actions
367 lines (293 loc) · 10.2 KB
/
Copy pathtest_llama.py
File metadata and controls
367 lines (293 loc) · 10.2 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import ctypes
import multiprocessing
import numpy as np
from scipy.special import log_softmax
from huggingface_hub import hf_hub_download
import pytest
import llama_cpp
import llama_cpp._internals as internals
MODEL = "./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf"
def test_llama_cpp_version():
assert llama_cpp.__version__
def test_llama_cpp_tokenization():
llama = llama_cpp.Llama(model_path=MODEL, vocab_only=True, verbose=False)
assert llama
assert llama._ctx.ctx is not None
text = b"Hello World"
tokens = llama.tokenize(text)
assert tokens[0] == llama.token_bos()
assert tokens == [1, 15043, 2787]
detokenized = llama.detokenize(tokens)
assert detokenized == text
tokens = llama.tokenize(text, add_bos=False)
assert tokens[0] != llama.token_bos()
assert tokens == [15043, 2787]
detokenized = llama.detokenize(tokens)
assert detokenized != text
text = b"Hello World</s>"
tokens = llama.tokenize(text)
assert tokens[-1] != llama.token_eos()
assert tokens == [1, 15043, 2787, 829, 29879, 29958]
tokens = llama.tokenize(text, special=True)
assert tokens[-1] == llama.token_eos()
assert tokens == [1, 15043, 2787, 2]
text = b""
tokens = llama.tokenize(text, add_bos=True, special=True)
assert tokens[-1] != llama.token_eos()
assert tokens == [llama.token_bos()]
assert text == llama.detokenize(tokens)
@pytest.fixture
def llama_cpp_model_path():
repo_id = "lmstudio-community/Qwen3.5-0.8B-GGUF"
filename = "Qwen3.5-0.8B-Q8_0.gguf"
model_path = hf_hub_download(repo_id, filename)
return model_path
@pytest.fixture
def llama_cpp_embedding_model_path():
repo_id = "CompendiumLabs/bge-small-en-v1.5-gguf"
filename = "bge-small-en-v1.5-q4_k_m.gguf"
model_path = hf_hub_download(repo_id, filename)
return model_path
@pytest.fixture
def llama_cpp_recurrent_model_path():
repo_id = "QuantFactory/mamba-130m-hf-GGUF"
filename = "mamba-130m-hf.Q2_K.gguf"
model_path = hf_hub_download(repo_id, filename)
return model_path
@pytest.fixture
def llama_cpp_hybrid_model_path():
repo_id = "tiiuae/Falcon-H1-Tiny-90M-Instruct-GGUF"
filename = "Falcon-H1-Tiny-90M-Instruct-Q2_K.gguf"
model_path = hf_hub_download(repo_id, filename)
return model_path
def test_real_model(llama_cpp_model_path):
import os
assert os.path.exists(llama_cpp_model_path)
params = llama_cpp.llama_model_default_params()
params.use_mmap = llama_cpp.llama_supports_mmap()
params.use_mlock = llama_cpp.llama_supports_mlock()
params.check_tensors = False
model = internals.LlamaModel(path_model=llama_cpp_model_path, params=params)
cparams = llama_cpp.llama_context_default_params()
cparams.n_ctx = 16
cparams.n_batch = 16
cparams.n_ubatch = 16
cparams.n_threads = multiprocessing.cpu_count()
cparams.n_threads_batch = multiprocessing.cpu_count()
cparams.logits_all = False
cparams.flash_attn_type = llama_cpp.LLAMA_FLASH_ATTN_TYPE_ENABLED
context = internals.LlamaContext(model=model, params=cparams)
tokens = model.tokenize(b"Hello, world!", add_bos=True, special=True)
assert tokens == [9419, 11, 1814, 0]
tokens = model.tokenize(
b"The quick brown fox jumps over the lazy dog. The quick brown fox jumps ",
add_bos=True,
special=True,
)
prompt_token_count = len(tokens)
batch = internals.LlamaBatch(n_tokens=len(tokens), embd=0, n_seq_max=1)
seed = 1337
sampler = internals.LlamaSampler()
sampler.add_top_k(50)
sampler.add_top_p(0.9, 1)
sampler.add_temp(0.8)
sampler.add_dist(seed)
result = tokens
n_eval = 0
for _ in range(4):
batch.set_batch(tokens, n_past=n_eval, logits_all=False)
context.decode(batch)
n_eval += len(tokens)
token_id = sampler.sample(context, -1)
tokens = [token_id]
result += tokens
output = result[prompt_token_count:]
output_text = model.detokenize(output, special=True)
# Low-level sampling output varies across CPU and Metal backends.
assert len(output) == 4
assert output_text
def test_real_llama(llama_cpp_model_path):
model = llama_cpp.Llama(
llama_cpp_model_path,
n_ctx=32,
n_batch=32,
n_ubatch=32,
n_threads=multiprocessing.cpu_count(),
n_threads_batch=multiprocessing.cpu_count(),
logits_all=False,
flash_attn=True,
)
output = model.create_completion(
"The quick brown fox jumps over the lazy dog. The quick brown fox",
max_tokens=6,
top_k=50,
top_p=0.9,
temperature=0.0,
seed=1337,
)
assert output["choices"][0]["text"] == " jumps over the lazy dog."
output = model.create_completion(
"The capital of france is paris, 'true' or 'false'?:\n",
max_tokens=4,
top_k=50,
top_p=0.9,
temperature=0.8,
seed=1337,
grammar=llama_cpp.LlamaGrammar.from_string("""
root ::= "true" | "false"
"""),
)
assert output["choices"][0]["text"] == "true"
suffix = b"rot"
tokens = model.tokenize(suffix, add_bos=True, special=True)
def logit_processor_func(input_ids, logits):
for token in tokens:
logits[token] *= 1000
return logits
logit_processors = llama_cpp.LogitsProcessorList([logit_processor_func])
output = model.create_completion(
"The capital of france is par",
max_tokens=4,
top_k=50,
top_p=0.9,
temperature=0.8,
seed=1337,
logits_processor=logit_processors,
)
assert output["choices"][0]["text"].lower().startswith("rot")
model.set_seed(1337)
state = model.save_state()
output = model.create_completion(
"Pick a number from 1 to 10?:\n",
max_tokens=4,
top_k=50,
top_p=0.9,
temperature=1.0,
grammar=llama_cpp.LlamaGrammar.from_string("""
root ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "10"
"""),
)
number_1 = output["choices"][0]["text"]
output = model.create_completion(
"Pick a number from 1 to 10?:\n",
max_tokens=4,
top_k=50,
top_p=0.9,
temperature=1.0,
grammar=llama_cpp.LlamaGrammar.from_string("""
root ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "10"
"""),
)
number_2 = output["choices"][0]["text"]
model.load_state(state)
output = model.create_completion(
"Pick a number from 1 to 10?:\n",
max_tokens=4,
top_k=50,
top_p=0.9,
temperature=1.0,
grammar=llama_cpp.LlamaGrammar.from_string("""
root ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "10"
"""),
)
number_3 = output["choices"][0]["text"]
assert number_1 != number_2
assert number_1 == number_3
def test_real_llama_repeated_prompt_cache(llama_cpp_model_path):
model = llama_cpp.Llama(
llama_cpp_model_path,
n_ctx=32,
n_batch=32,
n_ubatch=32,
n_threads=multiprocessing.cpu_count(),
n_threads_batch=multiprocessing.cpu_count(),
logits_all=False,
flash_attn=True,
verbose=False,
)
prompt = "The quick brown fox jumps over the lazy dog. The quick brown fox"
output_1 = model.create_completion(
prompt,
max_tokens=6,
temperature=0.0,
seed=1337,
)
output_2 = model.create_completion(
prompt,
max_tokens=6,
temperature=0.0,
seed=1337,
)
assert output_1["choices"][0]["text"] == " jumps over the lazy dog."
assert output_2["choices"][0]["text"] == output_1["choices"][0]["text"]
def _assert_prompt_cache_reset_handles_history_edit(
model_path,
*,
is_recurrent: bool,
is_hybrid: bool,
):
model = llama_cpp.Llama(
model_path,
n_ctx=32,
n_batch=32,
n_ubatch=32,
n_threads=multiprocessing.cpu_count(),
n_threads_batch=multiprocessing.cpu_count(),
logits_all=False,
verbose=False,
)
assert model._is_recurrent is is_recurrent
assert model._is_hybrid is is_hybrid
first_prompt = "The quick brown fox"
second_prompt = "The slow brown fox"
first_tokens = model.tokenize(first_prompt.encode(), add_bos=True, special=True)
second_tokens = model.tokenize(second_prompt.encode(), add_bos=True, special=True)
assert first_tokens != second_tokens
assert first_tokens[0] == second_tokens[0]
first_output = model.create_completion(
first_prompt,
max_tokens=1,
temperature=0.0,
)
assert isinstance(first_output["choices"][0]["text"], str)
second_output = model.create_completion(
second_prompt,
max_tokens=1,
temperature=0.0,
)
assert isinstance(second_output["choices"][0]["text"], str)
def test_recurrent_model_prompt_cache_reset(llama_cpp_recurrent_model_path):
_assert_prompt_cache_reset_handles_history_edit(
llama_cpp_recurrent_model_path,
is_recurrent=True,
is_hybrid=False,
)
def test_hybrid_model_prompt_cache_reset(llama_cpp_hybrid_model_path):
_assert_prompt_cache_reset_handles_history_edit(
llama_cpp_hybrid_model_path,
is_recurrent=False,
is_hybrid=True,
)
def test_real_llama_embeddings(llama_cpp_embedding_model_path):
model = llama_cpp.Llama(
llama_cpp_embedding_model_path,
n_ctx=32,
n_batch=32,
n_ubatch=32,
n_threads=multiprocessing.cpu_count(),
n_threads_batch=multiprocessing.cpu_count(),
logits_all=False,
flash_attn=True,
embedding=True,
)
embedding = model.embed("Hello World")
assert len(embedding) > 0
prompts = ["Hello World", "A different prompt"]
individual_embeddings = [model.embed(prompt) for prompt in prompts]
batched_embeddings = model.embed(prompts)
assert len(batched_embeddings) == len(prompts)
for individual, batched in zip(individual_embeddings, batched_embeddings):
np.testing.assert_allclose(batched, individual, rtol=1e-4, atol=1e-4)
repeated_embeddings = model.embed(list(reversed(prompts)))
assert len(repeated_embeddings) == len(prompts)
assert all(len(repeated) == len(embedding) for repeated in repeated_embeddings)