Repository navigation
Expand file tree
/
Copy pathtest_runtime.py
More file actions
1648 lines (1476 loc) · 73.5 KB
/
Copy pathtest_runtime.py
File metadata and controls
1648 lines (1476 loc) · 73.5 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import ctypes
import json
import multiprocessing
import threading
import gc
import weakref
from types import SimpleNamespace
from unittest.mock import Mock
from contextlib import closing, contextmanager
import pytest
import numpy as np
import llama_cpp
import llama_cpp._internals as internals
from llama_cpp.llama_embedding import LlamaEmbedding, LLAMA_POOLING_TYPE_NONE
MODEL = "./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf"
def test_model_suppress_tokens_copies_native_storage(monkeypatch):
for tokens in ([], [3, 1, 3]):
storage = (ctypes.c_int32 * len(tokens))(*tokens)
calls = []
def get_suppressed(vocab, count):
calls.append(vocab)
ctypes.cast(count, ctypes.POINTER(ctypes.c_int32))[0] = len(tokens)
return storage if tokens else None
monkeypatch.setattr(internals.llama_cpp, "llama_vocab_get_suppress_tokens", get_suppressed)
model = SimpleNamespace(vocab=123)
result = internals.LlamaModel.suppress_tokens(model)
if tokens:
storage[0] = 99
assert result == tokens
model.vocab = None
with pytest.raises(RuntimeError, match="vocab is None"):
internals.LlamaModel.suppress_tokens(model)
assert calls == [123]
@pytest.fixture
def sampling_model(monkeypatch):
internals.llama_cpp.llama_backend_init()
monkeypatch.setattr(internals.llama_cpp, "llama_model_get_vocab", lambda _: None)
return SimpleNamespace(model=None, n_vocab=lambda: 32,
suppress_tokens=Mock(return_value=[31]))
@pytest.mark.parametrize("suppressed", [[], [31], [31, 30]])
@pytest.mark.parametrize("temp", [0.0, 1.0])
@pytest.mark.parametrize("probability_filters", [False, True], ids=["top-k", "top-p-min-p-temp"])
def test_sampling_suppression_and_bias_match_native_chain(sampling_model, suppressed, temp, probability_filters):
lib = internals.llama_cpp
sampling_model.suppress_tokens.return_value = suppressed
logits = np.arange(32, dtype=np.float32) * 0.25
saved = logits.copy()
# Without suppression, doubling this bias incorrectly moves token 29 to first.
biases = [lib.llama_logit_bias(29, 0.3)]
if suppressed:
biases.append(lib.llama_logit_bias(31, 100.0))
original_biases = [(item.token, item.bias) for item in biases]
samplers = [internals.CommonSamplerType.TOP_K]
if probability_filters:
samplers.extend([internals.CommonSamplerType.TOP_P, internals.CommonSamplerType.MIN_P,
internals.CommonSamplerType.TEMPERATURE])
params = internals.LlamaSamplingParams(
temp=temp, top_k=10, top_p=0.8, min_p=0.12, min_keep=1, seed=42,
logit_bias=biases, samplers=samplers,
)
native = internals.LlamaTokenDataArray(n_vocab=32)
native.copy_logits(logits)
with closing(internals.LlamaSampler()) as reference:
reference.add_logit_bias(32, biases + [lib.llama_logit_bias(token, float("-inf")) for token in suppressed])
reference.add_top_k(10)
if probability_filters:
reference.add_top_p(0.8, 1)
reference.add_min_p(0.12, 1)
reference.add_temp(temp)
if temp == 0:
reference.add_greedy()
else:
reference.add_dist(42)
lib.llama_sampler_apply(reference.sampler, ctypes.byref(native.candidates))
expected = native.candidates_data[:native.candidates.size]
token = int(expected["id"][native.candidates.selected])
assert token not in suppressed
context = SimpleNamespace(
get_sampled_token_ith=lambda _: lib.LLAMA_TOKEN_NULL,
get_logits_ith=lambda _: logits.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
)
with closing(internals.LlamaSamplingContext(params, sampling_model)) as sampler:
for source in (None, logits): # Context outputs and restored snapshots.
sampler.reset()
with closing(sampler.cp()) as clone:
for current in (sampler, clone):
assert current.sample(context, logits=source) == token
actual = current._cur_p.candidates_data[:current._cur_p.candidates.size]
np.testing.assert_array_equal(actual["id"], expected["id"])
# Greedy selection does not populate probabilities.
for field in (("logit", "p") if temp else ("logit",)):
np.testing.assert_allclose(actual[field], expected[field], rtol=2e-6, atol=1e-8)
sampling_model.suppress_tokens.assert_called_once_with()
assert [(item.token, item.bias) for item in params.logit_bias] == original_biases
np.testing.assert_array_equal(logits, saved)
@pytest.mark.parametrize("grammar_first", [False, True])
def test_sampling_suppression_survives_grammar_resampling(sampling_model, grammar_first):
lib = internals.llama_cpp
logits = np.arange(32, dtype=np.float32)
params = internals.LlamaSamplingParams(temp=0.0, top_k=1,
samplers=[internals.CommonSamplerType.TOP_K])
with closing(internals.LlamaSampler()) as grammar, closing(internals.LlamaSamplingContext(params, sampling_model)) as sampler:
# A native mask stands in for a grammar that rejects the first allowed token.
grammar.add_logit_bias(32, [lib.llama_logit_bias(30, float("-inf"))])
sampler.grammar_sampler = SimpleNamespace(grammar=grammar.sampler, close=lambda: None)
assert sampler.sample(SimpleNamespace(), logits=logits, grammar_first=grammar_first) == 29
np.testing.assert_array_equal(logits, np.arange(32, dtype=np.float32))
def test_sampling_backend_selected_token_skips_cpu_suppression(sampling_model):
context = SimpleNamespace(get_sampled_token_ith=lambda _: 31,
get_logits_ith=Mock(side_effect=AssertionError("CPU fallback is not allowed")))
params = internals.LlamaSamplingParams(samplers=[internals.CommonSamplerType.TOP_K])
with closing(internals.LlamaSamplingContext(params, sampling_model)) as sampler:
assert sampler.sample(context) == 31
assert sampler._cur_p is None
context.get_logits_ith.assert_not_called()
@pytest.mark.parametrize("suppressed", [[31], [30], [30, 31]])
def test_sampling_reasoning_budget_preserves_native_logits_and_suppression(sampling_model, suppressed):
lib = internals.llama_cpp
sampling_model.suppress_tokens.return_value = suppressed
sampling_model.tokenize = lambda *args, **kwargs: [30]
params = internals.LlamaSamplingParams(
temp=1.0, top_k=32, seed=42, reasoning_budget=0,
reasoning_start_in_prompt=True, logit_bias=[lib.llama_logit_bias(30, 0.5)],
samplers=[internals.CommonSamplerType.TOP_K],
)
logits = np.arange(32, dtype=np.float32) * 0.25
# common_reasoning_budget_apply masks other tokens and preserves the forced
# token's original score; common_sampler_sample then applies the bias chain.
expected = np.full(32, -np.inf, dtype=np.float32)
expected[30] = logits[30] + 0.5
expected[suppressed] = -np.inf
candidates = internals.LlamaTokenDataArray(n_vocab=32)
candidates.copy_logits(logits)
with closing(internals.LlamaSamplingContext(params, sampling_model)) as sampler:
chain = sampler.sampler_chain.sampler
# Inspect preprocessing before top-k/dist, including the all-masked
# conflict case for which no valid sampling distribution exists.
for index in range(lib.llama_sampler_chain_n(chain) - 2):
lib.llama_sampler_apply(lib.llama_sampler_chain_get(chain, index), ctypes.byref(candidates.candidates))
np.testing.assert_array_equal(candidates._logit_view, expected)
assert not np.isnan(candidates._logit_view).any()
if 30 not in suppressed:
assert sampler.sample(SimpleNamespace(), logits=logits) == 30
probabilities = [sampler._cur_p.candidates.data[i].p for i in range(32)]
assert np.isfinite(probabilities).all() and sum(probabilities) == pytest.approx(1.0)
np.testing.assert_array_equal(logits, np.arange(32, dtype=np.float32) * 0.25)
def test_multimodal_embedding_requires_initialization():
model = LlamaEmbedding.__new__(LlamaEmbedding)
with pytest.raises(RuntimeError, match="not initialized"):
model.embed_multimodal("hello")
model._ctx = SimpleNamespace(ctx=123)
try:
with pytest.raises(ValueError, match="mmproj_path"):
model.embed_multimodal("hello")
finally:
model._ctx = None
@pytest.mark.parametrize("profile,width,pooling,causal", [
("MULTIMODAL", 768, llama_cpp.LLAMA_POOLING_TYPE_MEAN, False),
("QWEN3VL", 4096, llama_cpp.LLAMA_POOLING_TYPE_LAST, True),
])
def test_real_multimodal_embedding_entrypoint_readiness(profile, width, pooling, causal):
import io
from PIL import Image
from llama_cpp.llama_multimodal import MTMDEmbeddingHandler
model_path = os.environ.get(f"LLAMA_TEST_{profile}_EMBEDDING_MODEL")
mmproj_path = os.environ.get(f"LLAMA_TEST_{profile}_EMBEDDING_MMPROJ")
if not model_path or not mmproj_path:
pytest.skip(f"Set LLAMA_TEST_{profile}_EMBEDDING_MODEL/MMPROJ paths")
image = io.BytesIO()
Image.new("RGB", (224, 224), "red").save(image, format="PNG")
handler = MTMDEmbeddingHandler(mmproj_path, use_gpu=False,
image_max_tokens=64 if causal else 70, verbose=False)
try:
with closing(LlamaEmbedding(model_path, embedding_handler=handler, n_ctx=256,
n_batch=256, n_ubatch=256, n_threads=4, verbose=False,
n_gpu_layers=int(os.environ.get("LLAMA_TEST_N_GPU_LAYERS", "0")),
pooling_type=pooling)) as model:
assert handler.mtmd_ctx is None
prefix = ("<|im_start|>system\nRepresent the user's input.<|im_end|>\n"
"<|im_start|>user\n") if causal else "title: none | text: "
suffix = "<|im_end|>\n<|im_start|>assistant\n" if causal else ""
parts = [prefix, image.getvalue(), suffix]
# Call directly after construction; no manual projector initialization.
vector = model.embed_multimodal(parts=parts)
assert len(vector) == width and np.isfinite(vector).all()
assert model._ctx.get_causal_attn() is causal
np.testing.assert_allclose(model.embed_multimodal(parts=parts), vector, atol=1e-5)
if causal:
# Match a direct native submission using the same decode shape.
model.reset()
with handler.tokenize_parts(model, parts) as request:
encoded = request.encode()
for chunk in encoded:
if chunk.tokens:
assert all(isinstance(pos, int) for pos in chunk.positions)
else:
assert all(len(pos) == 4 for pos in chunk.positions)
native = llama_cpp.llama_batch_ext_init(model._ctx.ctx)
assert native
try:
for chunk in encoded:
rows = chunk.tokens if chunk.tokens else chunk.embeddings
for row, pos in zip(rows, chunk.positions):
if chunk.tokens:
idx = llama_cpp.llama_batch_ext_add_token(native, 0, row)
coords = (llama_cpp.llama_pos * 1)(pos)
else:
embd = llama_cpp.llama_embd(row.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 1, len(row))
idx = llama_cpp.llama_batch_ext_add_embd(native, 0, embd)
coords = (llama_cpp.llama_pos * 4)(*pos)
assert idx >= 0 and llama_cpp.llama_batch_ext_set_pos(native, idx, coords)
assert llama_cpp.llama_batch_ext_set_output_logits(native, idx, True)
assert llama_cpp.llama_process(model._ctx.ctx, llama_cpp.llama_process_type.LLAMA_PROCESS_TYPE_DECODE, native) == 0
raw = np.ctypeslib.as_array(model._ctx.get_embeddings_seq(0), shape=(width,)).copy()
assert np.dot(vector, raw / np.linalg.norm(raw)) > 0.99999
finally:
llama_cpp.llama_batch_ext_free(native)
model.reset()
handler.is_support_vision = False
with pytest.raises(ValueError, match="does not support image"):
model.embed_multimodal(parts=["title: none | text: ", image.getvalue()])
handler.is_support_vision = True
model._ctx.set_embeddings(False)
vector = model.embed_multimodal(prefix + "hello" + suffix)
assert len(vector) == width and np.linalg.norm(vector) == pytest.approx(1, abs=1e-6)
assert model._ctx.get_causal_attn() is causal
assert handler.mtmd_ctx is None
with pytest.raises(RuntimeError, match="closed"):
model.embed_multimodal("hello")
finally:
handler.close()
@pytest.fixture
def runtime_context(monkeypatch):
ctx = internals.LlamaContext.__new__(internals.LlamaContext)
ctx.ctx = 123
ctx.model = SimpleNamespace(
n_vocab=lambda: 100,
rope_type=lambda: internals.llama_cpp.llama_rope_type.LLAMA_ROPE_TYPE_MROPE,
)
ctx.params = object()
ctx.verbose = False
ctx._loras_applied = False
ctx._cvec_applied = False
ctx._lora_refs = ()
monkeypatch.setattr(internals.llama_cpp, "llama_free", Mock())
monkeypatch.setattr(internals.llama_cpp, "llama_n_batch", lambda _: 3)
monkeypatch.setattr(internals.llama_cpp, "llama_n_seq_max", lambda _: 2)
try:
yield ctx
finally:
ctx.ctx = None
ctx._batch_ext_refs = []
ctx._checkpoint_caches = []
@pytest.fixture
def batch_runtime(runtime_context, monkeypatch):
lib = internals.llama_cpp
rows, calls, freed = [], [], []
state = SimpleNamespace(fail=False, status=0)
context = runtime_context
monkeypatch.setattr(lib, "llama_batch_ext_init", lambda _: 456)
monkeypatch.setattr(lib, "llama_batch_ext_free", lambda p: freed.append(p))
monkeypatch.setattr(lib, "llama_batch_ext_clear", lambda _: rows.clear())
def add(_, sid, token):
rows.append(dict(token=token, seq_ids=[sid]))
return len(rows) - 1
def payload(_, idx, embd, field):
if state.fail == field:
return False
rows[idx][field] = np.ctypeslib.as_array(embd.data, shape=(embd.n_rows * embd.n_embd,)).copy()
return True
def add_embd(p, sid, embd):
idx = add(p, sid, None)
return idx if payload(p, idx, embd, "embedding") else -2
def sequence(_, idx, sid):
rows[idx]["seq_ids"].append(sid)
return True
def position(_, idx, pos):
n = 1 if rows[idx]["token"] is not None else 4
rows[idx]["position"] = tuple(pos[i] for i in range(n))
return True
def output(_, idx, flag):
rows[idx]["output"] = flag
return True
def process(ctx, kind, native):
calls.append((ctx, kind, native))
return state.status
monkeypatch.setattr(lib, "llama_batch_ext_add_token", add)
monkeypatch.setattr(lib, "llama_batch_ext_add_embd", add_embd)
monkeypatch.setattr(lib, "llama_batch_ext_set_embd_token", lambda *args: payload(*args, "embedding"))
monkeypatch.setattr(lib, "llama_batch_ext_set_embd_state", lambda *args: payload(*args, "state"))
monkeypatch.setattr(lib, "llama_batch_ext_add_seq", sequence)
monkeypatch.setattr(lib, "llama_batch_ext_set_pos", position)
monkeypatch.setattr(lib, "llama_batch_ext_set_output_logits", output)
monkeypatch.setattr(lib, "llama_process", process)
try:
with internals.LlamaBatchExt(context=context) as batch:
yield SimpleNamespace(context=context, batch=batch, rows=rows, calls=calls, freed=freed, state=state)
finally:
context.ctx = None
def test_embedding_normalization_modes_preserve_nonzero_vectors():
from llama_cpp._utils import normalize_embedding
for mode in (-1, False, True, 0, 1, 2, 6):
for values in ([0.0, 0.0], [3.0, -4.0], [1e7, -2e7]):
case = f"mode={mode!r}, values={values}"
with np.errstate(over="raise", invalid="raise"):
result = np.asarray(normalize_embedding(values, mode), dtype=np.float64)
assert np.isfinite(result).all(), case
if mode is False or mode == -1 or not any(values):
np.testing.assert_array_equal(result, values, err_msg=case)
elif mode == 0:
assert np.max(np.abs(result)) == pytest.approx(32760, rel=1e-6), case
else:
assert np.linalg.norm(result, ord=2 if mode is True else mode) == pytest.approx(1, rel=1e-6), case
if any(values):
assert result[0] / result[1] == pytest.approx(values[0] / values[1]), case
@pytest.mark.parametrize("causal,media_non_causal", [(True, False), (True, True), (False, True), (False, False)])
def test_multimodal_pooling_attention_and_failure_contract(batch_runtime, tmp_path, monkeypatch, causal, media_non_causal):
from llama_cpp.llama_multimodal import MTMDEncodedChunk, MTMDEmbeddingHandler
r = batch_runtime
raw = np.array([3, 4], dtype=np.float32)
monkeypatch.setattr(r.context, "get_causal_attn", lambda: causal)
monkeypatch.setattr(r.context, "set_causal_attn", Mock())
monkeypatch.setattr(r.context, "pooling_type", lambda: llama_cpp.LLAMA_POOLING_TYPE_LAST)
monkeypatch.setattr(r.context, "n_ubatch", lambda: 3)
monkeypatch.setattr(r.context, "set_embeddings", Mock())
monkeypatch.setattr(r.context, "get_embeddings_seq", lambda seq: raw.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))
model = SimpleNamespace(_ctx=r.context, context_params=SimpleNamespace(embeddings=True),
n_ctx=lambda: 3, n_embd_out=lambda: 2, reset=Mock())
chunks = (
MTMDEncodedChunk(0, (1,), None, (0,), 1, False),
MTMDEncodedChunk(1, (), np.ones((1, 2), dtype=np.float32), ((1, 2, 3, 0),), 1, media_non_causal),
)
request = SimpleNamespace(n_tokens=2, n_pos=2, encode=lambda: chunks)
released = []
@contextmanager
def tokenize(*args, **kwargs):
try:
yield request
finally:
released.append(True)
with MTMDEmbeddingHandler(str(tmp_path), verbose=False) as handler:
monkeypatch.setattr(handler, "_init_mtmd_context", Mock())
monkeypatch.setattr(handler, "tokenize", tokenize)
handler.is_support_vision = True
if causal and media_non_causal:
with pytest.raises(NotImplementedError, match="chunk-local"):
handler.embed(model, "prompt")
assert not r.calls
else:
r.state.status = 1
with pytest.raises(RuntimeError, match="decode failed"):
handler.embed(model, "prompt")
r.state.status = 0
np.testing.assert_allclose(handler.embed(model, "prompt"), [0.6, 0.8])
assert model.reset.call_count == len(released) * 2
r.context.set_causal_attn.assert_not_called()
assert r.context.get_causal_attn() is causal
class MockLoraAdapter:
def __init__(self, address):
self.adapter = ctypes.cast(ctypes.c_void_p(address), internals.llama_cpp.llama_adapter_lora_p_ctypes)
def test_closed_context_rejected_before_native_call(runtime_context, monkeypatch):
runtime_context.close()
for method, args, native in (
("n_ctx", (), "llama_n_ctx"),
("n_ctx_seq", (), "llama_n_ctx_seq"),
("n_batch", (), "llama_n_batch"),
("n_ubatch", (), "llama_n_ubatch"),
("n_seq_max", (), "llama_n_seq_max"),
("n_rs_seq", (), "llama_n_rs_seq"),
("pooling_type", (), "llama_pooling_type"),
("set_n_threads", (1, 1), "llama_set_n_threads"),
("n_threads", (), "llama_n_threads"),
("n_threads_batch", (), "llama_n_threads_batch"),
("set_causal_attn", (True,), "llama_set_causal_attn"),
("get_causal_attn", (), "llama_get_causal_attn"),
("clear_loras", (), "llama_set_adapters_lora"),
("apply_loras", ([],), "llama_set_adapters_lora"),
("clear_cvec", (), "llama_set_adapter_cvec"),
("apply_cvec", ([], 1, 1, 1), "llama_set_adapter_cvec"),
("graph_reserve", (1, 1, 1), "llama_graph_reserve"),
):
with monkeypatch.context() as patch:
call = Mock(name=native)
patch.setattr(internals.llama_cpp, native, call)
with pytest.raises(RuntimeError, match="closed"):
getattr(runtime_context, method)(*args)
assert call.call_count == 0, method
def test_graph_reserve_validation_failure_and_recovery(runtime_context, monkeypatch):
context = runtime_context
events, graph = [], object()
reserve = Mock(side_effect=lambda *args: events.append(args) or graph)
sync = Mock(side_effect=lambda _: events.append('sync'))
monkeypatch.setattr(internals.llama_cpp, 'llama_synchronize', sync)
monkeypatch.setattr(internals.llama_cpp, 'llama_graph_reserve', reserve)
for dimensions, error in (
((0, 1, 1), ValueError), ((1, 0, 1), ValueError),
((1, 1, 0), ValueError), ((-1, 1, 1), ValueError),
((2**32, 1, 1), ValueError), ((1, 3, 1), ValueError),
((1, 1, 2), ValueError), ((2**31 - 1, 2, 1), ValueError),
((True, 1, 1), TypeError), ((1.5, 1, 1), TypeError),
):
with pytest.raises(error):
context.graph_reserve(*dimensions)
reserve.assert_not_called()
sync.assert_not_called()
for failure, message in ((None, 'failed to reserve'),
(RuntimeError('missing symbol'), 'missing symbol')):
reserve.side_effect = failure
reserve.return_value = None
with pytest.raises(RuntimeError, match=message):
context.graph_reserve(1, 1, 1)
assert context.ctx == 123
events.clear()
reserve.side_effect = lambda *args: events.append(args) or graph
# Reservation synchronizes first and permits native sequence rounding.
assert context.graph_reserve(3, 2, 4) is graph
assert events == ['sync', (123, 3, 2, 4)]
def test_attached_lora_survives_gc_and_failed_replacement(runtime_context, monkeypatch):
context = runtime_context
native = Mock(return_value=0)
monkeypatch.setattr(internals.llama_cpp, "llama_set_adapters_lora", native)
with pytest.raises(RuntimeError, match="closed or invalid"):
context.apply_loras([(SimpleNamespace(adapter=None), 1.0)])
native.assert_not_called()
original = MockLoraAdapter(1)
reference = weakref.ref(original)
context.apply_loras([(original, 1.0)])
del original
gc.collect()
assert reference() is not None
native.return_value = -1
with pytest.raises(RuntimeError, match="Failed to set LoRA"):
context.apply_loras([(MockLoraAdapter(2), 1.0)])
with pytest.raises(RuntimeError, match="detach failed"):
context.clear_loras()
gc.collect()
assert reference() is not None
native.return_value = 0
context.clear_loras()
gc.collect()
assert reference() is None
@pytest.mark.parametrize("failure", ["batch", "native"])
def test_context_close_attempts_all_resources_and_frees_once(runtime_context, monkeypatch, failure):
context = runtime_context
events = []
def fail():
events.append("batch")
if failure == "batch":
raise RuntimeError("batch cleanup failed")
context._batch_ext_refs = [SimpleNamespace(close=fail)]
context._checkpoint_caches = [SimpleNamespace(close=lambda: events.append("checkpoint"))]
context._exit_stack = SimpleNamespace(close=lambda: events.append("exit"))
adapter = MockLoraAdapter(1)
reference = weakref.ref(adapter)
context._lora_refs = (adapter,)
del adapter
def free(pointer):
assert pointer == 123 and reference() is not None
events.append("native")
if failure == "native":
raise RuntimeError("native cleanup failed")
monkeypatch.setattr(internals.llama_cpp, "llama_free", free)
with pytest.raises(RuntimeError, match=f"{failure} cleanup failed"):
context.close()
assert events == ["batch", "checkpoint", "native", "exit"]
assert context.ctx is None and context.model is None and context.params is None
gc.collect()
assert reference() is None
context._batch_ext_refs = []
context.close()
assert events.count("native") == 1
def test_interleaved_range_preserves_positions_and_output_mapping(batch_runtime):
r = batch_runtime
r.batch.add_token(1, 0)
source = np.arange(8, dtype=np.float32).reshape(2, 4)
r.batch.add_embeddings(source, positions=[(1, 2, 3, 0), (2, 3, 4, 0)], seq_ids=(0, 1))
source[:] = -1 # logical inputs own the data, even before rendering
r.batch.add_token(2, 3, output=True)
assert len(r.batch) == 4 > r.batch.capacity()
assert r.context.decode(r.batch, start=1, count=3) == 0
assert [e["token"] for e in r.rows] == [None, None, 2]
assert r.rows[0]["position"] == (1, 2, 3, 0)
assert r.rows[0]["seq_ids"] == [0, 1]
np.testing.assert_array_equal(r.rows[0]["embedding"], np.arange(4))
assert r.batch.submitted_indices == (1, 2, 3)
assert r.batch.output_indices == (3,)
assert r.calls == [(123, internals.llama_cpp.llama_process_type.LLAMA_PROCESS_TYPE_DECODE, 456)]
with pytest.raises(ValueError, match="exceeds"):
r.context.decode(r.batch)
def test_batch_render_failure_clears_partial_rows_and_can_retry(batch_runtime, monkeypatch):
r = batch_runtime
invalidations = []
r.context._invalidate_checkpoints = lambda: invalidations.append(True)
for failure in ("embedding", "position", "state"):
r.batch.reset()
r.calls.clear()
invalidations.clear()
for i in range(2):
r.batch.add_embedding([1, 2], (i, i, i, 0), state=[3, 4])
symbol = "llama_batch_ext_set_embd_state" if failure == "state" else "llama_batch_ext_set_pos"
with monkeypatch.context() as patch:
if failure == "embedding":
patch.setattr(r.state, "fail", "embedding")
else:
patch.setattr(internals.llama_cpp, symbol, lambda _, idx, value: idx == 0)
message = "-2" if failure == "embedding" else f"{'state embedding' if failure == 'state' else failure} at logical entry 1"
with pytest.raises(RuntimeError, match=message):
r.context.decode(r.batch)
assert r.rows == [] and r.calls == [], failure
assert invalidations == [] and len(r.batch) == 2, failure
assert r.batch.submitted_indices == r.batch.output_indices == (), failure
assert r.context.decode(r.batch) == 0, failure
def test_bulk_append_validation_is_atomic_and_paired_mode_is_distinct(batch_runtime):
r = batch_runtime
with pytest.raises(ValueError, match="vocabulary"):
r.batch.add_tokens([1, 100], positions=[0, 1])
assert len(r.batch) == 0
r.batch.add_token_embedding(1, [[1, 2], [3, 4]], 0)
assert r.context.decode(r.batch) == 0
np.testing.assert_array_equal(r.rows[0]["embedding"], [1, 2, 3, 4])
r.batch.add_token(2, 1)
with pytest.raises(ValueError, match="Paired"):
r.context.decode(r.batch)
assert len(r.calls) == 1
@pytest.mark.parametrize("kind", ["token", "embedding", "paired"])
def test_extended_batch_keeps_input_embedding_and_hidden_state_separate(batch_runtime, kind):
r = batch_runtime
hidden = np.arange(6, dtype=np.float32).reshape(2, 3)
embedding = np.arange(4, dtype=np.float32)
if kind == "token":
r.batch.add_token(1, 2, seq_ids=(0, 1), output=True, state=hidden)
elif kind == "embedding":
r.batch.add_embedding(embedding, (2, 3, 4, 0), seq_ids=(0, 1), output=True, state=hidden)
else:
r.batch.add_token_embedding(1, embedding, 2, seq_ids=(0, 1), output=True, state=hidden)
hidden[:] = -1
embedding[:] = -1
assert r.context.decode(r.batch) == 0
np.testing.assert_array_equal(r.rows[0]["state"], np.arange(6))
if kind == "token":
assert "embedding" not in r.rows[0]
else:
np.testing.assert_array_equal(r.rows[0]["embedding"], np.arange(4))
assert r.rows[0]["position"] == ((2, 3, 4, 0) if kind == "embedding" else (2,))
assert r.rows[0]["seq_ids"] == [0, 1]
assert r.batch.output_indices == (0,)
def test_lilicorr_draft_submits_separate_states_through_extended_batch(batch_runtime, monkeypatch):
from llama_cpp.llama_speculative import LlamaDFlashDecoding, SpecConfig, SpeculativeType
r = batch_runtime
engine = object.__new__(LlamaDFlashDecoding)
engine.config = SpecConfig(spec_type=SpeculativeType.DRAFT_DFLASH,
draft_model_path="lilicorr.gguf", draft_n_max=1)
engine.is_lilicorr, engine.is_dflash2, engine.is_dspark = True, False, False
engine.block_size, engine.draft_limit, engine.draft_min = 3, 1, 0
engine.lilicorr_top_k, engine.n_embd_dec, engine.mask_token_id = 2, 6, 99
anchor = np.arange(6, dtype=np.float32)
engine._lilicorr_features = {6: anchor}
engine.noise_batch, engine.draft_context = r.batch, r.context
engine.checkpoint, engine.restore = Mock(return_value={"position": 6}), Mock()
lattice = np.array([[0] * 6, [40, 41, 0, 3, 0, 3],
[50, 51, 0, 3, 0, 3]], dtype=np.float32)
monkeypatch.setattr(internals.llama_cpp, "llama_get_embeddings_nextn",
lambda _: lattice.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))
assert engine.draft([], n_past=7, id_last=42, n_max=1).tolist() == [41]
assert [row["token"] for row in r.rows] == [42, 99, 99]
assert [row["position"] for row in r.rows] == [(7,), (8,), (9,)]
assert r.calls == [(123, internals.llama_cpp.llama_process_type.LLAMA_PROCESS_TYPE_DECODE, 456)]
anchor.fill(-1)
for row in r.rows:
assert "embedding" not in row and not row.get("output", False)
np.testing.assert_array_equal(row["state"], np.arange(6))
assert r.batch.output_indices == ()
engine.restore.assert_called_once_with({"position": 6}, 0)
@pytest.mark.parametrize("kind,field", [("tokens", "state"), ("embeddings", "state"), ("embeddings", "embedding")])
def test_bulk_payload_ownership_range_and_reset(batch_runtime, kind, field):
r = batch_runtime
source = np.arange(24, dtype=np.float32).reshape(4, 6)
kwargs = {"states": source} if field == "state" else {}
if kind == "tokens":
r.batch.add_tokens([1, 2, 3, 4], positions=range(4), **kwargs)
else:
r.batch.add_embeddings(source if field == "embedding" else np.ones((4, 2)),
positions=[(i, i, i, 0) for i in range(4)], **kwargs)
snapshot = r.batch.entries
owner = getattr(snapshot[0], field).base
assert all(getattr(entry, field).base is owner and not getattr(entry, field).flags.writeable for entry in snapshot)
reference = weakref.ref(owner)
source[:] = -1
assert r.context.decode(r.batch, start=1, count=2) == 0
np.testing.assert_array_equal(r.rows[0][field], np.arange(6, 12))
np.testing.assert_array_equal(r.rows[1][field], np.arange(12, 18))
assert r.batch.submitted_indices == (1, 2)
r.batch.reset()
assert len(r.batch) == 0 and r.rows == []
assert r.batch.output_indices == r.batch.submitted_indices == ()
assert reference() is not None # retained snapshots keep their payloads alive
del snapshot, owner
gc.collect()
assert reference() is None
@pytest.mark.parametrize("kind", ["tokens", "embeddings"])
def test_invalid_bulk_states_do_not_append_partial_inputs(batch_runtime, kind):
r = batch_runtime
r.batch.add_token(3, 0)
for states in ([1, 2], [[1, 2]], np.ones((2, 1, 2)), np.empty((2, 0))):
with pytest.raises(ValueError, match="states"):
if kind == "tokens":
r.batch.add_tokens([1, 2], positions=[1, 2], states=states)
else:
r.batch.add_embeddings([[1, 2], [3, 4]], positions=[(1, 1, 1, 0), (2, 2, 2, 0)], states=states)
assert len(r.batch) == 1 and r.calls == []
@pytest.mark.parametrize("invalid", [None, [1, 2, 3]])
def test_state_presence_and_width_are_validated_per_range(batch_runtime, invalid):
r = batch_runtime
r.batch.add_token(1, 0, state=[1, 2])
r.batch.add_token(2, 1, state=invalid)
with pytest.raises(ValueError, match="State embeddings|state embeddings"):
r.context.decode(r.batch)
assert r.rows == [] and r.calls == []
assert r.context.decode(r.batch, count=1) == 0
@pytest.mark.parametrize("extended", [False, True], ids=["legacy", "extended"])
def test_context_decode_status_and_checkpoint_invalidation(batch_runtime, monkeypatch, extended):
r = batch_runtime
r.batch.add_token(1, 0, state=[1, 2] if extended else None)
invalidations = []
r.context._invalidate_checkpoints = lambda: invalidations.append(True)
kind = internals.llama_cpp.llama_process_type.LLAMA_PROCESS_TYPE_DECODE
monkeypatch.setattr(internals.llama_cpp, "llama_decode", lambda *_: r.state.status)
decode = (lambda: r.context.process(r.batch, kind)) if extended else (lambda: r.context.decode(SimpleNamespace(batch=object())))
for status in (0, 1, 2, -1, -2, 0):
r.state.status = status
invalidations.clear()
if status in (0, 1):
assert decode() == status
assert invalidations == [], status
else:
error = internals.LlamaDecodeAbort if status == 2 else RuntimeError
with pytest.raises(error):
decode()
assert invalidations == [True], status
def test_encode_context_binding_and_lifecycle(batch_runtime):
r = batch_runtime
r.batch.add_token(1, 0)
kind = internals.llama_cpp.llama_process_type.LLAMA_PROCESS_TYPE_ENCODE
assert r.context.process(r.batch, kind) == 0
r.state.status = -1
with pytest.raises(RuntimeError, match="encode returned"):
r.context.encode(r.batch)
with pytest.raises(ValueError, match="different context"):
r.batch.render(object())
with pytest.raises(ValueError, match="process type"):
r.context.process(r.batch, 99)
r.context.ctx = None
with pytest.raises(RuntimeError, match="closed"):
r.batch.render()
r.batch.close()
r.batch.close()
assert r.freed == [456]
with pytest.raises(RuntimeError, match="closed"):
r.batch.add_token(1, 0)
def test_invalid_positions_sequences_and_widths_never_reach_processing(batch_runtime):
r = batch_runtime
for position in (0, (0, 0, 0), (0, 0, 0, 2**31)):
with pytest.raises(ValueError, match="position"):
r.batch.add_embedding([1, 2], position)
for ids in ((), (-1,), (2,)):
with pytest.raises(ValueError, match="seq_ids"):
r.batch.add_token(1, 0, seq_ids=ids)
r.batch.add_embedding([1, 2], (0, 0, 0, 0))
r.batch.add_embedding([1, 2, 3], (1, 1, 1, 0))
with pytest.raises(ValueError, match="width"):
r.context.decode(r.batch)
assert r.calls == []
assert r.context.decode(r.batch, count=1) == 0
r.batch.reset()
assert len(r.batch) == 0 and r.rows == []
assert r.batch.output_indices == r.batch.submitted_indices == ()
r.batch.add_token(np.int64(3), np.int32(1))
assert r.context.decode(r.batch) == 0
@pytest.mark.parametrize("cleanup", ["close", "gc_cycle", "close_failure"])
def test_batch_cleanup_releases_payloads_context_and_native_handle(batch_runtime, monkeypatch, cleanup):
r = batch_runtime
context = internals.LlamaContext.__new__(internals.LlamaContext)
context.__dict__.update({k: v for k, v in r.context.__dict__.items() if k != "_batch_ext_refs"})
context_ref = weakref.ref(context)
if cleanup == "close_failure":
def fail(pointer):
r.freed.append(pointer)
raise RuntimeError("cleanup failed")
monkeypatch.setattr(internals.llama_cpp, "llama_batch_ext_free", fail)
batch = internals.LlamaBatchExt(context=context)
batch.add_embedding([1, 2], (0, 0, 0, 0), state=[3, 4, 5])
payload_refs = [weakref.ref(getattr(batch.entries[0], field)) for field in ("embedding", "state")]
batch_ref = weakref.ref(batch)
del context
gc.collect()
assert context_ref() is not None
if cleanup == "gc_cycle":
batch.cycle = batch
else:
if cleanup == "close_failure":
with pytest.raises(RuntimeError, match="cleanup failed"):
batch.close()
else:
batch.close()
assert len(batch) == 0 and batch._context is None
batch.close()
del batch
gc.collect()
assert batch_ref() is None and context_ref() is None
assert all(reference() is None for reference in payload_refs)
assert r.freed == [456]
gc.collect()
assert r.freed == [456]
def test_context_close_releases_batches_before_native_context(batch_runtime, monkeypatch):
r = batch_runtime
r.batch.add_embedding([1, 2], (0, 0, 0, 0))
storage = weakref.ref(r.batch.entries[0].embedding)
def free_context(_):
assert r.freed == [456]
assert storage() is None
monkeypatch.setattr(internals.llama_cpp, "llama_free", free_context)
r.context.close()
assert len(r.batch) == 0
with pytest.raises(RuntimeError, match="closed"):
r.batch.render()
r.batch.close()
assert r.freed == [456]
@pytest.mark.parametrize('resource', ['context', 'batch', 'batch_finalizer',
'model_vocab', 'legacy_batch', 'sampler'])
def test_runtime_init_failure_releases_only_owned_native_handles(runtime_context, monkeypatch, resource):
free = Mock()
owned = None
if resource == 'context':
monkeypatch.setattr(internals.llama_cpp, 'llama_init_from_model', lambda *_: None)
monkeypatch.setattr(internals.llama_cpp, 'llama_free', free)
create = lambda: internals.LlamaContext(
model=SimpleNamespace(model=123), params=internals.llama_cpp.llama_context_default_params())
error, message = RuntimeError, 'Failed to create'
elif resource in ('batch', 'batch_finalizer'):
monkeypatch.setattr(internals.llama_cpp, 'llama_batch_ext_init', lambda _: 456 if resource == 'batch_finalizer' else None)
monkeypatch.setattr(internals.llama_cpp, 'llama_batch_ext_free', free)
if resource == 'batch_finalizer':
monkeypatch.setattr(internals.weakref, 'finalize', Mock(side_effect=MemoryError('finalizer allocation failed')))
owned = 456
create = lambda: internals.LlamaBatchExt(context=runtime_context)
error, message = MemoryError, 'finalizer allocation' if resource == 'batch_finalizer' else 'init failed'
elif resource == 'model_vocab':
owned = object()
monkeypatch.setattr(internals.os.path, 'exists', lambda _: True)
monkeypatch.setattr(internals.llama_cpp, 'llama_model_load_from_file', lambda *_: owned)
monkeypatch.setattr(internals.llama_cpp, 'llama_model_get_vocab', lambda _: None)
monkeypatch.setattr(internals.llama_cpp, 'llama_model_free', free)
create = lambda: internals.LlamaModel(path_model='model.gguf', params=object(), verbose=False)
error, message = ValueError, 'Failed to get vocab'
elif resource == 'legacy_batch':
owned = SimpleNamespace(token=object(), embd=object())
monkeypatch.setattr(internals.llama_cpp, 'llama_batch_init', lambda *_: owned)
monkeypatch.setattr(internals.llama_cpp, 'llama_batch_free', free)
create = lambda: internals.LlamaBatch(n_tokens=1, embd=1, n_seq_max=1, mixed=True, verbose=False)
error, message = RuntimeError, 'expected batch.token to be NULL'
else:
sampler = SimpleNamespace(close=free)
candidates = Mock()
monkeypatch.setattr(internals, 'LlamaTokenDataArray', candidates)
monkeypatch.setattr(internals, 'LlamaSampler', lambda: sampler)
monkeypatch.setattr(internals.llama_cpp, 'llama_model_get_vocab', lambda _: object())
monkeypatch.setattr(internals.LlamaSamplingContext, '_build_sampler_chain', Mock(side_effect=RuntimeError('sampler chain build failed')))
context = internals.LlamaSamplingContext.__new__(internals.LlamaSamplingContext)
create = lambda: context.__init__(params=internals.LlamaSamplingParams(),
model=SimpleNamespace(model=object(), verbose=False, n_vocab=lambda: 8))
error, message = RuntimeError, 'sampler chain build failed'
with pytest.raises(error, match=message):
create()
gc.collect()
if resource == 'sampler':
context.close()
context.close()
free.assert_called_once_with()
candidates.assert_not_called() # Vocabulary storage is lazy.
assert context.model is context.params is context.vocab is None
elif owned is not None:
free.assert_called_once_with(owned)
else:
free.assert_not_called()
@pytest.mark.parametrize("entry", ["create_completion", "__call__", "create_chat_completion"])
def test_public_generation_options_reach_execution(entry):
for present, expected in ((0.0, 1.5), (0.7, 0.7)):
llm = object.__new__(llama_cpp.Llama)
calls = []
def completion(**kwargs):
calls.append(kwargs)
yield {"choices": [{"text": "", "finish_reason": "length"}]}
def chat(**kwargs):
calls.append(kwargs)
return {"choices": [{"message": {"content": ""}}]}
llm._create_completion = completion
llm.chat_handler, llm._chat_handlers, llm.chat_format = chat, {}, None
options = dict(present_penalty=present, presence_penalty=1.5)
if entry == "create_chat_completion":
llm.create_chat_completion(messages=[{"role": "user", "content": "Hello"}], **options)
else:
getattr(llm, entry)([1], ignore_eos=True, **options)
assert calls[0]["ignore_eos"] is True
assert calls[0]["present_penalty"] == expected
assert "presence_penalty" not in calls[0]
@pytest.mark.parametrize(
("ignore_eos", "expected_text", "expected_finish_reason"),
[(False, "", "stop"), (True, "<eog>", "length")],
)
def test_private_completion_respects_ignore_eos_at_eog_boundary(
monkeypatch, ignore_eos, expected_text, expected_finish_reason
):
llm = object.__new__(llama_cpp.Llama)
forwarded = []
def fake_generate(tokens, **kwargs):
assert tokens == [1]
forwarded.append(kwargs["ignore_eos"])
yield 2
llm._model = SimpleNamespace(
vocab=object(),
token_bos=lambda: 1,
token_eos=lambda: 2,
token_sep=lambda: -1,
token_fim_pre=lambda: -1,
token_fim_mid=lambda: -1,
token_fim_suf=lambda: -1,
get_add_sep=lambda: False,
)
llm._abort_event = threading.Event()
llm.metadata = {}
llm.spm_infill = False
llm.verbose = False
llm._n_ctx = 8
llm._logits_all = False
llm._seed = 0
llm.cache = None
llm.model_path = "fake.gguf"
llm.input_ids = np.zeros(8, dtype=np.intc)
llm.n_tokens = 1
llm.scores = np.zeros((1, 4), dtype=np.float32)
llm.generate = fake_generate
llm.detokenize = (
lambda tokens, prev_tokens=None, **kwargs: b"".join(
b"<eog>" if token == 2 else b"x" for token in tokens
)
)
monkeypatch.setattr(
"llama_cpp.llama.llama_cpp_lib.llama_token_is_eog",
lambda vocab, token: token == 2,
)
result = next(
llm._create_completion(
prompt=[1], max_tokens=1, ignore_eos=ignore_eos
)
)
assert forwarded == [ignore_eos]
assert result["choices"][0]["text"] == expected_text
assert result["choices"][0]["finish_reason"] == expected_finish_reason
def test_context_manages_borrowed_threadpool_and_abort_callback_lifetimes(runtime_context, monkeypatch):
context, calls = runtime_context, []
monkeypatch.setattr(internals.llama_cpp, 'llama_synchronize', lambda ctx: calls.append(('sync', ctx)))
monkeypatch.setattr(internals.llama_cpp, 'llama_attach_threadpool',
lambda ctx, pool, batch_pool: calls.append(('attach', ctx, pool, batch_pool)))
monkeypatch.setattr(internals.llama_cpp, 'llama_detach_threadpool', lambda ctx: calls.append(('detach', ctx)))
monkeypatch.setattr(internals.llama_cpp, 'llama_set_abort_callback',
lambda ctx, callback, data: calls.append((ctx, callback, data)))
pool, data = ctypes.c_void_p(1), ctypes.c_void_p(42)
context.attach_threadpool(pool)
assert context._threadpool_refs == (pool, pool)
assert calls[-2:] == [('sync', context.ctx), ('attach', context.ctx, pool, None)]
context.set_abort_callback(lambda user_data: user_data == data.value, data)
callback = context._abort_callback_ref
assert callback(data) is True and context._abort_callback_data_ref is data
assert calls[-1] == (context.ctx, callback, data)
context.set_abort_callback(None)
assert context._abort_callback_ref is context._abort_callback_data_ref is None
assert not calls[-1][1]
context.detach_threadpool()
assert context._threadpool_refs is None
assert calls[-2:] == [('sync', context.ctx), ('detach', context.ctx)]
def test_decode_eval_batch_resets_and_preserves_native_abort(monkeypatch):
llm = object.__new__(llama_cpp.Llama)
llm._batch = SimpleNamespace(batch=SimpleNamespace(n_tokens=0))
llm._ctx = SimpleNamespace(
decode=lambda _batch: (_ for _ in ()).throw(
internals.LlamaDecodeAbort("native abort")
)
)
llm._active_speculative_phase_stats = None
reset_calls = []
monkeypatch.setattr(llm, "reset", lambda: reset_calls.append(True))
with pytest.raises(internals.LlamaDecodeAbort, match="native abort"):
llm._decode_eval_batch([1, 2], 2)
assert reset_calls == [True]