Repository navigation
Expand file tree
/
Copy pathtest_speculation.py
More file actions
1960 lines (1701 loc) · 87 KB
/
Copy pathtest_speculation.py
File metadata and controls
1960 lines (1701 loc) · 87 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
from contextlib import closing, contextmanager
import builtins
import ctypes
from types import SimpleNamespace
from unittest.mock import Mock, call
import numpy as np
import pytest
import llama_cpp
from llama_cpp import llama_cpp as llama_cpp_lib
from llama_cpp import _internals as internals
from llama_cpp.llama_speculative import (
LlamaDFlashDecoding,
LlamaMTPDecoding,
LlamaNGramMapDecoding,
SpecConfig,
SpeculativeType,
create_native_spec_engine,
speculative_output_limits,
)
def test_llama_context_wraps_backend_sampling_and_perf(monkeypatch):
context = object.__new__(internals.LlamaContext)
context.ctx = "native-context"
context._sampler_refs = {}
sampler = type("Sampler", (), {"sampler": "native-sampler"})()
calls = []
monkeypatch.setattr(
internals.llama_cpp,
"llama_set_sampler",
lambda ctx, seq_id, ptr: calls.append(("set", ctx, seq_id, ptr)) or True,
)
assert context.set_sampler(2, sampler)
assert context._sampler_refs[2] is sampler
assert context.set_sampler(2, None)
assert 2 not in context._sampler_refs
results = {
"llama_get_sampled_probs_ith": object(),
"llama_get_sampled_logits_ith": object(),
"llama_get_sampled_candidates_ith": object(),
"llama_get_sampled_token_ith": 17,
"llama_get_sampled_probs_count_ith": 3,
"llama_get_sampled_logits_count_ith": 4,
"llama_get_sampled_candidates_count_ith": 5,
}
for name, result in results.items():
monkeypatch.setattr(internals.llama_cpp, name,
lambda ctx, index, result=result, name=name: calls.append((name, ctx, index)) or result)
assert getattr(context, name.removeprefix("llama_"))(-1) == result
assert calls[-1] == (name, "native-context", -1)
perf = llama_cpp_lib.llama_perf_context_data()
perf.n_eval = 9
monkeypatch.setattr(internals.llama_cpp, "llama_perf_context", lambda ctx: perf)
assert context.perf_context().n_eval == 9
for action, method in (("print", "print_timings"), ("reset", "reset_timings")):
monkeypatch.setattr(internals.llama_cpp, f"llama_perf_context_{action}",
lambda ctx, action=action: calls.append((f"perf-{action}", ctx)))
getattr(context, method)()
assert calls[-1] == (f"perf-{action}", "native-context")
context.ctx = None
def test_ngram_map_lifecycle_and_acceptance_feedback():
decoder = LlamaNGramMapDecoding(
ngram_size=3,
num_pred_tokens=3,
spec_type=SpeculativeType.NGRAM_MAP_K,
)
history = [1, 2, 3, 7, 8, 1, 2, 3]
decoder.begin(history)
draft = decoder.draft(history, n_past=len(history), id_last=3, n_max=2)
assert draft.tolist() == [7, 8]
decoder.accept(1)
draft = decoder.draft(history, n_past=len(history), id_last=3, n_max=3)
assert draft.tolist() == [7]
def test_spec_config_requires_draft_model_for_external_architectures():
for spec_type in (
SpeculativeType.DRAFT_EAGLE3,
SpeculativeType.DRAFT_DFLASH,
SpeculativeType.DRAFT_DSPARK,
):
with pytest.raises(ValueError, match="draft_model_path"):
SpecConfig(spec_type=spec_type).validate()
@pytest.mark.parametrize(
"spec_type",
[SpeculativeType.DRAFT_DFLASH, SpeculativeType.DRAFT_DSPARK],
)
def test_native_factory_routes_dflash_family_to_shared_engine(
monkeypatch, spec_type
):
created = []
def fake_engine(config, **kwargs):
created.append((config, kwargs))
return "dflash-engine"
monkeypatch.setattr(
"llama_cpp.llama_speculative.LlamaDFlashDecoding", fake_engine
)
config = SpecConfig(
spec_type=spec_type,
draft_model_path="draft.gguf",
)
result = create_native_spec_engine(
config,
target_model="target-model",
target_context="target-context",
model_params="model-params",
context_params="context-params",
verbose=False,
)
assert result == "dflash-engine"
assert created[0][0] is config
assert created[0][1]["target_model"] == "target-model"
def test_speculative_output_limits_match_llama_cpp():
assert speculative_output_limits(32, 1, 3) == (4, 4)
assert speculative_output_limits(32, 4, 3) == (16, 4)
assert speculative_output_limits(3, 4, 8) == (3, 3)
def test_draft_context_does_not_inherit_target_embedding_mode_or_moe_cache():
target = llama_cpp_lib.llama_context_default_params()
target.embeddings = True
target.pooling_type = llama_cpp_lib.LLAMA_POOLING_TYPE_MEAN
target.moe_cache_size = 64 * 1024 * 1024
draft = LlamaMTPDecoding._copy_draft_context_params(
target, llama_cpp_lib.LLAMA_POOLING_TYPE_UNSPECIFIED
)
assert target.embeddings is True
assert target.pooling_type == llama_cpp_lib.LLAMA_POOLING_TYPE_MEAN
assert target.moe_cache_size == 64 * 1024 * 1024
assert draft.embeddings is False
assert draft.pooling_type == llama_cpp_lib.LLAMA_POOLING_TYPE_UNSPECIFIED
assert draft.moe_cache_size == 0
def test_spec_config_validates_draft_runtime_arguments():
with pytest.raises(ValueError, match="draft_n_threads"):
SpecConfig(
spec_type=SpeculativeType.DRAFT_MTP,
draft_n_threads=0,
).validate()
with pytest.raises(ValueError, match="draft_n_cpu_moe"):
SpecConfig(
spec_type=SpeculativeType.DRAFT_MTP,
draft_n_cpu_moe=-1,
).validate()
class _FakeVocabModel:
def __init__(self, tokens, *, vocab_type=1, add_bos=True, add_eos=False):
self.tokens = tokens
self._vocab_type = vocab_type
self._add_bos = add_bos
self._add_eos = add_eos
def vocab_type(self):
return self._vocab_type
def get_add_bos(self):
return self._add_bos
def get_add_eos(self):
return self._add_eos
def token_bos(self):
return 1
def token_eos(self):
return 2
def n_vocab(self):
return len(self.tokens)
def token_get_text(self, token):
return self.tokens[token]
def test_speculative_vocab_compatibility_rejects_token_mismatch():
target = _FakeVocabModel([str(i) for i in range(8)])
draft = _FakeVocabModel([str(i) for i in range(8)])
draft.tokens[6] = "different"
with pytest.raises(ValueError, match="token 6"):
LlamaMTPDecoding._validate_speculative_vocab_compatibility(
target, draft
)
class _FakeCheckpointContext:
def __init__(self, *, position=7, state_size=8):
self.position = position
self.state_size = state_size
self.removals = []
self.get_flags = []
self.set_flags = []
def memory_seq_pos_max(self, seq_id):
assert seq_id == 0
return self.position
def memory_seq_rm(self, seq_id, p0, p1):
self.removals.append((seq_id, p0, p1))
return True
def get_state_seq_size_ext(self, seq_id, flags):
assert seq_id == 0
self.get_flags.append(flags)
return self.state_size
def get_state_seq_data_ext(self, buffer, size, seq_id, flags):
assert size == self.state_size
assert seq_id == 0
assert flags == self.get_flags[-1]
return size
def set_state_seq_data_ext(self, buffer, size, seq_id, flags):
assert buffer is not None
assert size == self.state_size
assert seq_id == 0
self.set_flags.append(flags)
return size
def _checkpoint_test_engine(*, native, engine_class=LlamaMTPDecoding):
engine = object.__new__(engine_class)
engine.is_lilicorr = False
engine._lilicorr_features = {}
engine.is_mem_shared = False
engine.draft_context = _FakeCheckpointContext()
engine.n_embd = 2
engine.pending_h = np.asarray([1.0, 2.0], dtype=np.float32)
engine.verify_h = np.empty((0, 2), dtype=np.float32)
engine.verify_tokens = []
engine.verify_positions = []
engine.verify_embeddings = None
engine.verify_media_positions = None
engine.embedding_batch = None
engine._llama_cpp_lib = llama_cpp_lib
engine.n_embd_enc = engine.n_embd_dec = 2
engine.verify_features = np.ones((2, 2), dtype=np.float32)
engine._active_verification_checkpoint = None
engine._use_native_draft_rollback = native
engine._pending_verification_checkpoint = None
engine.reset_checkpoint_stats()
return engine
class _MTPCatchupBatch:
def __init__(self):
self.rows = []
def reset(self):
self.rows.clear()
def add_token_embedding(self, token, hidden, position, seq_ids, output):
self.rows.append((token, np.array(hidden, copy=True), position))
def add_embeddings(self, features, *, positions, states):
self.rows.extend((row.copy(), hidden.copy(), position)
for row, hidden, position in zip(features, states, positions))
@contextmanager
def _target_batch(positions, *, tokens=None, embeddings=None, outputs=None, seq_ids=(0,)):
"""Own a legacy target batch; accept scalar or entry-major media positions."""
count = len(positions)
width = 0 if embeddings is None else embeddings.shape[1]
coordinates = np.asarray(positions)
flags = [False] * count if outputs is None else outputs
with closing(internals.LlamaBatch(n_tokens=count, embd=width, n_seq_max=max(seq_ids) + 1)) as batch:
if embeddings is None:
batch.add_sequence(tokens, coordinates[:, 0] if coordinates.ndim == 2 else positions, seq_ids, flags)
elif coordinates.ndim == 2:
batch.add_embeddings_mrope(embeddings.reshape(-1), pos_array=coordinates.T, seq_ids=seq_ids, logits_array=flags)
else:
batch.add_embeddings(embeddings.reshape(-1), pos_array=positions, seq_ids=seq_ids, logits_array=flags)
yield batch
@pytest.fixture
def mtp_process_engine(monkeypatch):
engine = _checkpoint_test_engine(native=True)
engine.is_mem_shared = False
engine.chain_heads = False
engine.n_mtp_layers = 1
engine._llama_cpp_lib = llama_cpp_lib
engine.batch = _MTPCatchupBatch()
rows = np.array([[10, 11], [20, 21]], dtype=np.float32)
engine.target_context = SimpleNamespace(get_embeddings_nextn=lambda: rows.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))
engine.target_model = SimpleNamespace(n_embd_inp=lambda: 3, rope_type=lambda: llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_NONE)
decoded, offsets, allocations = [], [], []
engine.draft_context.decode = lambda batch: decoded.append(list(batch.rows)) or 0
engine.draft_context.set_nextn_layer_offset = offsets.append
def allocate(*, context):
assert context is engine.draft_context
allocations.append(True)
return _MTPCatchupBatch()
monkeypatch.setattr(internals, "LlamaBatchExt", allocate)
return engine, rows, decoded, offsets, allocations
@pytest.mark.parametrize("rope", [llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_NONE, llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_MROPE, llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_IMROPE])
def test_mtp_process_media_positions_and_cross_batch_hidden_shift(mtp_process_engine, rope):
engine, target_h, decoded, _, allocations = mtp_process_engine
engine.target_model.rope_type = lambda: rope
features = np.arange(6, dtype=np.float32).reshape(2, 3)
positions = [[8, 9], [2, 3], [4, 5], [0, 0]]
if rope != llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_NONE:
positions[0] = [8, 8] # image patches may share their cache position
expected_positions = positions[0] if rope == llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_NONE else np.array(positions).T.tolist()
with _target_batch(expected_positions, embeddings=features) as source:
engine.process(source.batch)
assert [row[2] for row in decoded[-1]] == expected_positions
np.testing.assert_array_equal([row[0] for row in decoded[-1]], features)
np.testing.assert_array_equal([row[1] for row in decoded[-1]], [[1, 2], target_h[0]])
np.testing.assert_array_equal(engine.pending_h, target_h[-1])
# Reuse the builder and carry the last target row across media batches.
from llama_cpp.mtmd_cpp import mtmd_helper_embd_batch
engine.process_media(mtmd_helper_embd_batch(
2, source.batch.embd, 3, source.batch.pos,
1 if rope == llama_cpp_lib.llama_rope_type.LLAMA_ROPE_TYPE_NONE else 4, 0,
))
np.testing.assert_array_equal(decoded[-1][0][1], target_h[-1])
assert allocations == [True]
np.ctypeslib.as_array(source.batch.embd, shape=(6,))[:] = -1
np.testing.assert_array_equal(engine.verify_embeddings, features)
assert engine.verify_positions == positions[0]
with _target_batch([10, 11], tokens=[1, 2]) as source:
engine.process(source.batch)
assert [row[0] for row in decoded[-1]] == [1, 2]
np.testing.assert_array_equal(decoded[-1][0][1], target_h[-1])
assert engine.verify_embeddings is None and engine.verify_media_positions is None
@pytest.mark.parametrize("mode", ["shared", "chain", "failure"])
def test_mtp_media_catchup_modes_preserve_committed_hidden_state(mtp_process_engine, mode):
engine, target_h, decoded, offsets, allocations = mtp_process_engine
engine.is_mem_shared = mode == "shared"
engine.chain_heads = mode in {"chain", "failure"}
engine.n_mtp_layers = 2 if engine.chain_heads else 1
if mode == "failure":
engine.draft_context.decode = lambda batch: 1
with _target_batch([8, 9], embeddings=np.arange(6, dtype=np.float32).reshape(2, 3)) as source:
if mode == "failure":
with pytest.raises(RuntimeError, match="catch-up decode failed"):
engine.process(source.batch)
np.testing.assert_array_equal(engine.pending_h, [1, 2])
assert engine.verify_positions == [] and offsets == [0, 0]
else:
engine.process(source.batch)
np.testing.assert_array_equal(engine.pending_h, target_h[-1])
assert len(decoded) == (0 if mode == "shared" else 2)
assert allocations == ([] if mode == "shared" else [True])
if mode == "chain":
assert offsets == [0, 1, 0]
assert engine.draft_context.removals == [(0, 8, -1)] * 2
@pytest.mark.parametrize("native", [False, True])
@pytest.mark.parametrize("pinned", [False, True])
def test_mtp_media_rollback_restores_accepted_rows_and_coordinates(mtp_process_engine, native, pinned):
engine, target_h, decoded, _, _ = mtp_process_engine
engine._use_native_draft_rollback = native
checkpoint = engine.checkpoint()
features = np.arange(6, dtype=np.float32).reshape(2, 3)
positions = [8, 8 if pinned else 9]
coordinates = [[positions[0], 2, 4, 0], [positions[1], 3, 5, 0]]
engine._process_target_rows([], positions, target_h.copy(), embeddings=features, media_positions=coordinates)
engine.rollback_verified(checkpoint, n_accepted=0)
np.testing.assert_array_equal(engine.pending_h, target_h[0])
assert engine.draft_context.removals == [(0, 9 if native and not pinned else 8, -1)]
if native and not pinned:
assert len(decoded) == 1
else:
assert engine.checkpoint_stats()["native_restores" if native else "device_restores"] == 1
assert len(decoded) == 2 and len(decoded[-1]) == 1
np.testing.assert_array_equal(decoded[-1][0][0], features[0])
np.testing.assert_array_equal(decoded[-1][0][1], [1, 2])
assert decoded[-1][0][2] == coordinates[0]
@pytest.mark.parametrize("invalid", ["position", "sequence", "membership", "media-width", "media-axes", "media-sequence"])
def test_mtp_process_rejects_invalid_metadata_before_reading_hidden_rows(mtp_process_engine, invalid):
engine, _, decoded, _, allocations = mtp_process_engine
with _target_batch([8, 9], embeddings=np.arange(6, dtype=np.float32).reshape(2, 3),
seq_ids=(0, 1) if invalid == "membership" else (0,)) as source:
batch = SimpleNamespace(n_tokens=source.batch.n_tokens, token=source.batch.token, embd=source.batch.embd,
pos=source.batch.pos, n_seq_id=source.batch.n_seq_id, seq_id=source.batch.seq_id)
if invalid == "position":
batch.pos = None
elif invalid == "sequence":
batch.seq_id[0][0] = 1
engine.target_context.get_embeddings_nextn = lambda: pytest.fail("Invalid metadata must not read target states")
if invalid.startswith("media-"):
from llama_cpp.mtmd_cpp import mtmd_helper_embd_batch
view = mtmd_helper_embd_batch(2, batch.embd,
4 if invalid == "media-width" else 3, batch.pos,
4 if invalid == "media-axes" else 1,
1 if invalid == "media-sequence" else 0)
with pytest.raises(NotImplementedError if invalid == "media-sequence" else ValueError):
engine.process_media(view)
else:
with pytest.raises(ValueError if invalid == "position" else NotImplementedError):
engine.process(batch)
assert decoded == allocations == []
np.testing.assert_array_equal(engine.pending_h, [1, 2])
@pytest.mark.parametrize("engine_class,native,shared", [
pytest.param(LlamaMTPDecoding, True, False, id="mtp-native"),
pytest.param(LlamaMTPDecoding, False, False, id="mtp-device"),
pytest.param(LlamaMTPDecoding, False, True, id="mtp-shared-device"),
pytest.param(LlamaDFlashDecoding, True, False, id="dflash-native"),
pytest.param(LlamaDFlashDecoding, False, False, id="dflash-device"),
])
def test_model_draft_checkpoint_restores_suffix_and_reuses_capture(engine_class, native, shared):
engine = _checkpoint_test_engine(native=native, engine_class=engine_class)
engine.is_mem_shared = shared
checkpoint = engine.checkpoint()
engine.pending_h.fill(0.0)
engine._active_verification_checkpoint = checkpoint
engine.restore(checkpoint)
engine._pending_verification_checkpoint = checkpoint
assert engine.take_verification_checkpoint() is checkpoint
stats = engine.checkpoint_stats()
assert stats["captures"] == stats["restores"] == stats["verification_reuses"] == 1
assert checkpoint["mode"] == ("native" if native else "on-device")
assert engine.draft_context.removals == ([] if shared else [(0, 8, -1)])
for mode in ("native", "device"):
expected = int(native == (mode == "native"))
assert stats[f"{mode}_captures"] == stats[f"{mode}_restores"] == expected
flags = llama_cpp_lib.LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY | llama_cpp_lib.LLAMA_STATE_SEQ_FLAGS_ON_DEVICE
assert engine.draft_context.get_flags == engine.draft_context.set_flags == ([] if native else [flags])
assert stats["buffer_bytes"] == (0 if native else engine.draft_context.state_size)
assert (checkpoint["buffer"] is None) == native
if engine_class is LlamaMTPDecoding:
np.testing.assert_array_equal(engine.pending_h, [1, 2])
else:
assert engine.verify_features.shape == (0, 2)
assert engine._active_verification_checkpoint is checkpoint
@pytest.mark.parametrize("engine_class", [LlamaMTPDecoding, LlamaDFlashDecoding])
@pytest.mark.parametrize("invalidate", ["capture", "clear", "restore_failure"])
def test_draft_checkpoint_rejects_invalidated_objects(engine_class, invalidate):
engine = _checkpoint_test_engine(native=True, engine_class=engine_class)
engine._closed = False
engine._backend_sampler = None
checkpoint = engine.checkpoint()
if invalidate == "capture":
engine.checkpoint()
elif invalidate == "clear":
engine.draft_context.memory_clear = lambda data: None
engine.clear()
else:
engine.draft_context.memory_seq_rm = lambda *args: False
with pytest.raises(RuntimeError, match="rollback failed"):
engine.restore(checkpoint)
with pytest.raises(RuntimeError, match="stale"):
engine.restore(checkpoint)
@pytest.mark.parametrize("with_embeddings", [False, True], ids=["tokens", "embeddings"])
def test_mtp_native_rollback_does_not_copy_accepted_feature_blocks(with_embeddings):
class NoCopy(np.ndarray):
def copy(self, *args, **kwargs):
raise AssertionError("Native rollback only needs the last accepted row")
engine = _checkpoint_test_engine(native=True)
checkpoint = engine.checkpoint()
engine.verify_tokens, engine.verify_positions = [10, 11, 12], [8, 9, 10]
engine.verify_h = np.arange(6, dtype=np.float32).reshape(3, 2).view(NoCopy)
if with_embeddings:
engine.verify_embeddings = np.ones((3, 4), dtype=np.float32).view(NoCopy)
engine.rollback_verified(checkpoint, n_accepted=1)
np.testing.assert_array_equal(engine.pending_h, [2, 3])
assert engine.draft_context.removals == [(0, 10, -1)]
stats = engine.checkpoint_stats()
assert stats["restores"] == 0
assert stats["native_verification_rollbacks"] == 1
@pytest.mark.parametrize("invalid", ["stale", "foreign", "missing", "sequence"])
def test_mtp_native_rollback_rejects_invalid_checkpoint_before_mutation(invalid):
engine = _checkpoint_test_engine(native=True)
checkpoint = engine.checkpoint()
engine.verify_tokens, engine.verify_positions = [10, 11], [8, 9]
engine.verify_h = np.arange(4, dtype=np.float32).reshape(2, 2)
if invalid == "stale":
engine.checkpoint()
elif invalid == "foreign":
checkpoint = _checkpoint_test_engine(native=True).checkpoint()
elif invalid == "missing":
checkpoint = None
with pytest.raises(NotImplementedError if invalid == "sequence" else RuntimeError):
engine.rollback_verified(checkpoint, 0, seq_id=int(invalid == "sequence"))
assert engine.draft_context.removals == []
np.testing.assert_array_equal(engine.pending_h, [1, 2])
@pytest.mark.parametrize("failure", [False, RuntimeError("partial rollback")])
def test_mtp_native_rollback_failure_invalidates_checkpoint(failure):
engine = _checkpoint_test_engine(native=True)
checkpoint = engine.checkpoint()
engine.verify_positions = [8, 9]
engine.verify_h = np.arange(4, dtype=np.float32).reshape(2, 2)
engine.draft_context.memory_seq_rm = Mock(
side_effect=failure if isinstance(failure, Exception) else None,
return_value=failure,
)
with pytest.raises(RuntimeError):
engine.rollback_verified(checkpoint, 0)
with pytest.raises(RuntimeError, match="stale"):
engine.restore(checkpoint)
def test_mtp_close_does_not_import_during_interpreter_shutdown():
class _Closable:
def __init__(self, *, context=None):
self.ctx = context
self.closed = False
self.sampler_changes = []
def set_sampler(self, seq_id, sampler):
assert self.ctx == "draft-context"
self.sampler_changes.append((seq_id, sampler))
return True
def close(self):
self.closed = True
engine = object.__new__(LlamaMTPDecoding)
engine._closed = False
engine._llama_cpp_lib = object()
engine._backend_sampler = _Closable()
engine._backend_sampling = True
engine.batch = _Closable()
engine.embedding_batch = _Closable()
engine.draft_context = _Closable(context="draft-context")
engine._owns_model = False
engine.draft_model = object()
backend_sampler = engine._backend_sampler
batch = engine.batch
embedding_batch = engine.embedding_batch
draft_context = engine.draft_context
original_import = builtins.__import__
def fail_import(*args, **kwargs):
raise ImportError("sys.meta_path is None, Python is likely shutting down")
builtins.__import__ = fail_import
try:
engine.close()
finally:
builtins.__import__ = original_import
assert draft_context.sampler_changes == [(0, None)]
assert backend_sampler.closed
assert batch.closed
assert embedding_batch.closed
assert draft_context.closed
assert engine._backend_sampler is None
assert engine.draft_context is None
class _FakeEvalBatch:
def __init__(self):
self.batch = self
self.n_tokens = 0
class _FakeEvalContext:
def __init__(self, statuses, events):
self.statuses = list(statuses)
self.events = events
self.decode_sizes = []
def decode(self, batch):
self.decode_sizes.append(batch.batch.n_tokens)
self.events.append("target-decode")
return self.statuses.pop(0)
def synchronize(self):
self.events.append("target-sync")
class _FakeSpecEngine:
def __init__(self, events):
self.events = events
def process(self, batch, seq_id=0):
assert batch is not None
assert seq_id == 0
self.events.append("spec-process")
def _eval_test_llama(*, statuses, verifying, speculative=True):
events = []
llm = object.__new__(llama_cpp.Llama)
llm._batch = _FakeEvalBatch()
llm._ctx = _FakeEvalContext(statuses, events)
llm._speculative_verifying = verifying
llm.speculative = _FakeSpecEngine(events) if speculative else None
llm._active_speculative_phase_stats = {
"target_decode_seconds": 0.0,
"target_sync_seconds": 0.0,
"process_calls": 0,
"process_seconds": 0.0,
}
llm.n_tokens = 0
llm.verbose = False
return llm, events
def test_speculative_target_sync_precedes_process_and_has_separate_timing():
llm, events = _eval_test_llama(statuses=[0], verifying=True)
assert llm._decode_eval_batch([1, 2, 3], 3) == 3
llm._process_speculative_batch()
assert events == ["target-decode", "target-sync", "spec-process"]
stats = llm._active_speculative_phase_stats
assert stats["target_decode_seconds"] >= 0.0
assert stats["target_sync_seconds"] >= 0.0
assert stats["process_seconds"] >= 0.0
assert stats["process_calls"] == 1
@pytest.mark.parametrize("verifying", [False, True], ids=["ordinary-retry", "atomic-verification"])
def test_eval_batch_retry_respects_verification_boundary(verifying):
llm, _ = _eval_test_llama(statuses=[1, 0], verifying=verifying, speculative=verifying)
if verifying:
with pytest.raises(RuntimeError, match="verification batch cannot be split"):
llm._decode_eval_batch([1, 2, 3, 4], 4)
else:
assert llm._decode_eval_batch([1, 2, 3, 4], 4) == 2
assert llm._ctx.decode_sizes == ([4] if verifying else [4, 2])
def test_speculative_verification_batch_must_fit_n_batch():
llm = object.__new__(llama_cpp.Llama)
llm._speculative_verifying = True
llm.n_batch = 3
with pytest.raises(RuntimeError, match="verification batch exceeds n_batch"):
llm.eval([1, 2, 3, 4], copy_logits=False)
@pytest.mark.parametrize("mode", ["native", "checkpoint", "truncate"])
def test_interrupted_speculation_restores_committed_boundary(mode):
llm = object.__new__(llama_cpp.Llama)
llm._ctx = _FakeCheckpointContext()
llm.speculative = SimpleNamespace(rollback_verified=Mock(), restore=Mock(), truncate=Mock())
checkpoint = SimpleNamespace(pos=6)
llm._hybrid_cache_mgr = SimpleNamespace(max_checkpoints=0 if mode == "native" else 4,
find_best_checkpoint=Mock(return_value=checkpoint),
restore_checkpoint=Mock(return_value=True))
llm.is_hybrid = mode != "truncate"
llm.input_ids = np.array([1, 2, 3, 4, 5, 6, 10, 11, 12], dtype=np.intc)
llm.n_tokens = 9
llm._last_eval_output_start, llm._last_eval_output_count = 6, 3
replayed = []
def replay(tokens, **kwargs):
replayed.append((list(tokens), kwargs))
llm.n_tokens += len(tokens)
llm.eval = replay
active_loras = [{"name": "test", "scale": 0.5}]
control_vector = {"data": [1.0]}
accepted = 0 if mode == "truncate" else 1
draft_checkpoint = None if mode == "truncate" else "draft-checkpoint"
assert llm._recover_interrupted_speculation(
verification_start=6, evaluated_tokens=[10, 11, 12], delivered_accepted=accepted,
speculative_checkpoint=draft_checkpoint, use_native_rollback=mode == "native",
active_loras=active_loras, control_vector=control_vector,
) == mode
assert llm.n_tokens == 7 + accepted
assert llm._last_eval_output_start == 6
for operation, expected_mode in (("rollback_verified", "native"), ("restore", "checkpoint"), ("truncate", "truncate")):
assert getattr(llm.speculative, operation).call_count == int(mode == expected_mode)
assert llm._hybrid_cache_mgr.find_best_checkpoint.call_count == int(mode == "checkpoint")
assert llm._hybrid_cache_mgr.restore_checkpoint.call_count == int(mode == "checkpoint")
if mode == "checkpoint":
llm._hybrid_cache_mgr.find_best_checkpoint.assert_called_once_with([1, 2, 3, 4, 5, 6], 0)
llm._hybrid_cache_mgr.restore_checkpoint.assert_called_once_with(checkpoint, seq_id=0)
llm.speculative.restore.assert_called_once_with(draft_checkpoint, seq_id=0)
assert replayed == [([10, 11], dict(active_loras=active_loras, control_vector=control_vector, copy_logits=False))]
assert llm._ctx.removals == []
else:
assert llm._ctx.removals == [(0, 7 + accepted, -1)]
assert llm._last_eval_output_count == 1 + accepted and replayed == []
if mode == "native":
llm.speculative.rollback_verified.assert_called_once_with(draft_checkpoint, accepted, seq_id=0)
else:
llm.speculative.truncate.assert_called_once_with(7, seq_id=0)
def test_mtp_truncate_fails_when_native_memory_removal_fails():
class _Model:
def is_recurrent(self):
return False
def is_hybrid(self):
return False
class _Context:
def memory_seq_rm(self, seq_id, p0, p1):
return False
engine = object.__new__(LlamaMTPDecoding)
engine.draft_model = _Model()
engine.draft_context = _Context()
with pytest.raises(RuntimeError, match="draft-context truncation failed"):
engine.truncate(12)
class _FakeDFlashBatch:
def __init__(self):
self.tokens = []
self.positions = []
self.embeddings = None
self.logits = []
self.mrope_positions = None
self.states = None
def reset(self):
self.tokens = []
self.positions = []
self.embeddings = None
self.logits = []
self.mrope_positions = None
self.states = None
def add_tokens(self, tokens, *, positions, seq_ids, states):
self.add_sequence(tokens, positions, seq_ids, [False] * len(tokens))
self.states = np.array(states, dtype=np.float32, copy=True)
def add_sequence(
self, token_array, pos_array, seq_ids, logits_array
):
assert seq_ids == [0]
assert len(token_array) == len(pos_array) == len(logits_array)
self.tokens = list(token_array)
self.positions = list(pos_array)
self.logits = list(logits_array)
def add_embeddings(
self, embeddings, *, pos_array, seq_ids, logits_array=None
):
assert seq_ids == [0]
self.embeddings = np.asarray(embeddings, dtype=np.float32).copy()
self.positions = list(pos_array)
self.logits = list(logits_array or [])
def add_embeddings_mrope(
self, embeddings, *, pos_array, seq_ids, logits_array=None
):
self.add_embeddings(
embeddings,
pos_array=pos_array[0],
seq_ids=seq_ids,
logits_array=logits_array,
)
self.mrope_positions = [list(plane) for plane in pos_array]
class _FakeDFlashDraftContext:
def __init__(self, *, fused=None, confidence=None):
self.fused = fused
self.confidence = confidence
self.decoded = []
self.synchronized = False
self.removals = []
def n_ubatch(self):
return 8
def decode(self, batch):
self.decoded.append(
(list(batch.tokens), list(batch.positions), batch.embeddings)
)
return 0
def get_embeddings_nextn(self):
values = self.confidence if self.confidence is not None else self.fused
return values.ctypes.data_as(
ctypes.POINTER(ctypes.c_float)
)
def synchronize(self):
self.synchronized = True
def memory_seq_rm(self, seq_id, p0, p1):
self.removals.append((seq_id, p0, p1))
return True
def _draft_test_dflash_engine(*, dspark, sample_from_anchor, p_min=0.0):
engine = object.__new__(LlamaDFlashDecoding)
engine.config = SpecConfig(
spec_type=(
SpeculativeType.DRAFT_DSPARK
if dspark
else SpeculativeType.DRAFT_DFLASH
),
draft_model_path="draft.gguf",
draft_n_max=3,
draft_p_min=p_min,
)
engine.is_dspark = dspark
engine.is_dflash2 = False
engine.is_lilicorr = False
engine._lilicorr_features = {}
engine.selector_top_k = 0
engine._suppressed_tokens = ()
engine.sample_from_anchor = sample_from_anchor
engine.draft_limit = 3
engine.draft_min = engine.config.draft_n_min
engine.mask_token_id = 99
engine.n_embd_dec = 2
engine.noise_batch = _FakeDFlashBatch()
engine._pending_verification_checkpoint = None
engine._candidate = lambda output_index: (100 + output_index, 0.9)
engine.checkpoint = lambda seq_id=0: {"position": 5}
engine.restore = lambda checkpoint, seq_id=0: None
return engine
def _native_draft_candidate(logits, suppressed=()):
llama_cpp_lib.llama_backend_init()
candidates = internals.LlamaTokenDataArray(n_vocab=len(logits))
candidates.copy_logits(logits)
with closing(internals.LlamaSampler()) as sampler:
sampler.add_logit_bias(len(logits), [
llama_cpp_lib.llama_logit_bias(token, float("-inf")) for token in suppressed
])
sampler.add_top_k(10)
sampler.add_dist(42)
llama_cpp_lib.llama_sampler_apply(sampler.sampler, ctypes.byref(candidates.candidates))
native = candidates.candidates.data[0]
return int(native.id), float(native.p)
def _draft_test_candidate_engine(engine_class, *, suppressed=(), backend=False, dense=None,
ids=None, logits=None, probs=None, counts=None,
selected=llama_cpp_lib.LLAMA_TOKEN_NULL):
"""Expose owned buffers through the same accessors as a native context."""
engine = object.__new__(engine_class)
engine._backend_sampling = backend
engine._llama_cpp_lib = llama_cpp_lib
engine._suppressed_tokens = suppressed
engine.n_vocab = len(dense) if dense is not None else 0
counts = counts or {}
engine.draft_context = SimpleNamespace(
get_sampled_token_ith=lambda _: selected,
get_logits_ith=(lambda _: dense.ctypes.data_as(ctypes.POINTER(ctypes.c_float))) if dense is not None else
Mock(side_effect=AssertionError("Do not expand a valid compact candidate pool")),
)
for name, values, scalar in (("candidates", ids, ctypes.c_int32),
("logits", logits, ctypes.c_float), ("probs", probs, ctypes.c_float)):
setattr(engine.draft_context, f"get_sampled_{name}_count_ith",
lambda _, name=name, values=values: counts.get(name, 0 if values is None else len(values)))
setattr(engine.draft_context, f"get_sampled_{name}_ith",
lambda _, values=values, scalar=scalar: None if values is None else
values.ctypes.data_as(ctypes.POINTER(scalar)))
return engine
@pytest.mark.parametrize("logits,suppressed", [
*[pytest.param(np.random.default_rng(12).standard_normal(n).astype(np.float32), (), id=f"vocab-{n}")
for n in (1, 7, 32)],
*[pytest.param(np.arange(32, dtype=np.float32) * 0.25, ids, id=f"suppression-{index}")
for index, ids in enumerate(((), (31,), (31, 30, 31, -1, 32)))],
])
def test_model_draft_cpu_candidates_match_native_distribution(logits, suppressed):
original = logits.copy()
token, probability = _native_draft_candidate(logits, suppressed)
assert token not in suppressed
for engine_class in (LlamaMTPDecoding, LlamaDFlashDecoding):
engine = _draft_test_candidate_engine(engine_class, suppressed=suppressed, dense=logits)
selected, actual_probability = engine._candidate(0)
assert selected == token, engine_class.__name__
assert actual_probability == pytest.approx(probability, rel=2e-6, abs=1e-8), engine_class.__name__
np.testing.assert_array_equal(logits, original, err_msg=engine_class.__name__)
@pytest.mark.parametrize("compact", ["logits", "probs", "fallback"])
def test_model_draft_suppresses_compact_cpu_candidates_and_dense_fallback(compact):
ids = np.array([3, 2, 1, 0], dtype=np.int32)
logits = np.array([5, 2, 1, 0], dtype=np.float32)
probs = np.exp(logits - logits.max())
probs /= probs.sum()
saved_logits, saved_probs = logits.copy(), probs.copy()
dense = np.array([0, 1, 2, 5], dtype=np.float32)
for engine_class in (LlamaMTPDecoding, LlamaDFlashDecoding):
engine = _draft_test_candidate_engine(
engine_class, suppressed=(3,), backend=True, dense=dense, ids=ids, logits=logits, probs=probs,
counts={"candidates": 0 if compact == "fallback" else 4,
"logits": 4 if compact == "logits" else 0, "probs": 4 if compact == "probs" else 0},
)
token, probability = engine._candidate(0)
assert token == 2, engine_class.__name__
assert probability == pytest.approx(1 / (1 + np.exp(-1) + np.exp(-2)), rel=1e-6), engine_class.__name__
np.testing.assert_array_equal(probs, saved_probs)
np.testing.assert_array_equal(logits, saved_logits)
@pytest.mark.parametrize("logits", [
np.array([110, 10, 9, 8], dtype=np.float32),
np.arange(16, dtype=np.float32) * 0.25,
], ids=["underflowed-probabilities", "top-k-after-suppression"])
def test_model_draft_compact_suppression_recomputes_native_distribution_from_logits(logits):
suppressed = int(np.argmax(logits))
ids = np.arange(len(logits), dtype=np.int32)
probs = np.exp(logits - logits.max())
probs /= probs.sum()
saved_logits, saved_probs = logits.copy(), probs.copy()
expected = _native_draft_candidate(logits, (suppressed,))
for engine_class in (LlamaMTPDecoding, LlamaDFlashDecoding):
engine = _draft_test_candidate_engine(
engine_class, suppressed=(suppressed,), backend=True, ids=ids, logits=logits, probs=probs,
)
token, probability = engine._candidate(0)
assert token == expected[0], engine_class.__name__
assert probability == pytest.approx(expected[1], rel=2e-6, abs=1e-8), engine_class.__name__
if len(logits) == 4:
assert probability > 0.66 # old probability renormalization rejected this draft
np.testing.assert_array_equal(logits, saved_logits)
np.testing.assert_array_equal(probs, saved_probs)
@pytest.mark.parametrize("selected", [False, True])
def test_model_draft_only_backend_selection_bypasses_cpu_suppression(selected):
ids = np.array([3, 2], dtype=np.int32)
logits = np.array([5, 2], dtype=np.float32)
probs = np.array([0.8, 0.2], dtype=np.float32)
for engine_class in (LlamaMTPDecoding, LlamaDFlashDecoding):
engine = _draft_test_candidate_engine(
engine_class, suppressed=(3,), backend=True, ids=ids, logits=logits, probs=probs,
selected=3 if selected else llama_cpp_lib.LLAMA_TOKEN_NULL,
)
token, probability = engine._candidate(0)
assert token == (3 if selected else 2), engine_class.__name__
assert probability == pytest.approx(0.8 if selected else 1.0), engine_class.__name__
@pytest.mark.parametrize("compact", ["logits", "probs"])
def test_model_draft_all_suppressed_compact_candidates_do_not_expand_to_dense_logits(compact):
ids, logits, probs = np.array([3], dtype=np.int32), np.array([5], dtype=np.float32), np.array([1], dtype=np.float32)
for engine_class in (LlamaMTPDecoding, LlamaDFlashDecoding):
engine = _draft_test_candidate_engine(
engine_class, suppressed=(3,), backend=True, ids=ids, logits=logits, probs=probs,
counts={"logits": int(compact == "logits"), "probs": int(compact == "probs")},
)
with pytest.raises(RuntimeError, match="No finite draft candidates"):
engine._candidate(0)
engine.draft_context.get_logits_ith.assert_not_called()
@pytest.mark.parametrize("p_min,expected", [(0.66, [2]), (0.67, [])])
def test_mtp_probability_cutoff_uses_suppressed_distribution_and_restores(p_min, expected):
engine = _draft_test_candidate_engine(LlamaMTPDecoding)
engine.config = SpecConfig(spec_type=SpeculativeType.DRAFT_MTP,
draft_n_max=1, draft_p_min=p_min)
engine._suppressed_tokens = (3,)
engine.n_vocab, engine.n_embd, engine.chain_heads = 4, 2, False
engine.pending_h = np.zeros(2, dtype=np.float32)
engine.batch = SimpleNamespace(reset=Mock(), add_token_embedding=Mock())
engine.checkpoint, engine.restore = Mock(return_value={"position": 5}), Mock()
logits, hidden = np.array([0, 1, 2, 5], dtype=np.float32), np.zeros(2, dtype=np.float32)
engine.draft_context = SimpleNamespace(
decode=lambda _: 0,
get_logits_ith=lambda _: logits.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
get_embeddings_nextn_ith=lambda _: hidden.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
)
assert engine.draft([], n_past=7, id_last=42, n_max=1).tolist() == expected