Repository navigation
Expand file tree
/
Copy path_internals.py
More file actions
3850 lines (3166 loc) · 144 KB
/
Copy path_internals.py
File metadata and controls
3850 lines (3166 loc) · 144 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
from __future__ import annotations
import ctypes
import enum
import os
import sys
import weakref
from typing import (
Callable,
Dict,
List,
Set,
Tuple,
Optional,
Sequence,
Union,
TYPE_CHECKING
)
from dataclasses import dataclass, field
from collections import deque
from contextlib import ExitStack
import numpy as np
import numpy.typing as npt
from .llama_types import *
from .llama_grammar import LlamaGrammar
from ._utils import suppress_stdout_stderr
import llama_cpp.llama_cpp as llama_cpp
if TYPE_CHECKING:
from llama_cpp._ctypes_extensions import (
CtypesArray,
CtypesPointer,
)
# Python wrappers over llama.h structs
class LlamaDecodeAbort(RuntimeError):
"""Raised when llama.cpp aborts an in-flight decoder graph."""
class LlamaModel:
"""Intermediate Python wrapper for a llama.cpp llama_model.
NOTE: For stability it's recommended you use the Llama class instead."""
def __init__(
self,
*,
path_model: str,
params: llama_cpp.llama_model_params,
verbose: bool = True,
):
self.path_model = path_model
self.params = params
self.verbose = verbose
self._exit_stack = ExitStack()
self.model = None
self.vocab = None
self._lora_registry: Dict[str, LlamaLoraAdapter] = {}
model = None
if not os.path.exists(path_model):
raise ValueError(f"LlamaModel[__init__]: Model path does not exist: {path_model}")
with suppress_stdout_stderr(disable=verbose):
model = llama_cpp.llama_model_load_from_file(
self.path_model.encode("utf-8"), self.params
)
if model is None:
raise ValueError(f"Failed to load model from file: {path_model}")
# Record ownership immediately so every later failure can release the
# native model. In particular, a failed vocab lookup must not leak the
# successfully loaded model.
self.model = model
try:
vocab = llama_cpp.llama_model_get_vocab(model)
if vocab is None:
raise ValueError(f"LlamaModel[__init__]: Failed to get vocab from model: {path_model}")
except BaseException:
llama_cpp.llama_model_free(model)
self.model = None
raise
self.vocab = vocab
def close(self):
"""Manually free LlamaModel and Vocab/Lora resources."""
if getattr(self, "model", None) is not None:
try:
llama_cpp.llama_model_free(self.model)
except Exception:
pass
self.model = None
self.vocab = None
if hasattr(self, "_lora_registry") and self._lora_registry:
self.unload_all_loras()
self._lora_registry = None
if getattr(self, "_exit_stack", None) is not None and hasattr(self._exit_stack, "close"):
self._exit_stack.close()
self._exit_stack = None
def __del__(self):
self.close()
def vocab_type(self) -> int:
if self.vocab is None:
raise RuntimeError("LlamaModel.vocab_type: vocab is None")
return llama_cpp.llama_vocab_type(self.vocab)
def n_vocab(self) -> int:
if self.vocab is None:
raise RuntimeError("LlamaModel.n_vocab: vocab is None")
return llama_cpp.llama_vocab_n_tokens(self.vocab)
def n_ctx_train(self) -> int:
return llama_cpp.llama_model_n_ctx_train(self.model)
def n_cls_out(self) -> int:
return llama_cpp.llama_model_n_cls_out(self.model)
def n_embd(self) -> int:
return llama_cpp.llama_model_n_embd(self.model)
def n_embd_inp(self) -> int:
return llama_cpp.llama_model_n_embd_inp(self.model)
def n_embd_out(self) -> int:
return llama_cpp.llama_model_n_embd_out(self.model)
def n_layer(self) -> int:
return llama_cpp.llama_model_n_layer(self.model)
def n_layer_nextn(self) -> int:
return llama_cpp.llama_model_n_layer_nextn(self.model)
def n_head(self) -> int:
return llama_cpp.llama_model_n_head(self.model)
def n_head_kv(self) -> int:
return llama_cpp.llama_model_n_head_kv(self.model)
def n_swa(self) -> int:
return llama_cpp.llama_model_n_swa(self.model)
def rope_type(self) -> int:
return llama_cpp.llama_model_rope_type(self.model)
def dflash_selector_top_k(self) -> int:
"""Return the DFlash2 selector width, or zero for DFlash v1/DSpark."""
return llama_cpp.llama_model_dflash_selector_top_k(self.model)
def target_layer_ids_n(self) -> int:
"""Return the number of target-model layers extracted by this model."""
return llama_cpp.llama_model_target_layer_ids_n(self.model)
def target_layer_ids(self) -> List[int]:
"""Return the target-model layer indices extracted by this model."""
count = self.target_layer_ids_n()
if count == 0:
return []
layer_ids = llama_cpp.llama_model_target_layer_ids(self.model)
if not layer_ids:
raise RuntimeError(
"LlamaModel.target_layer_ids: native API returned a null pointer "
f"for {count} layer IDs"
)
return [int(layer_ids[i]) for i in range(count)]
def get_tok_embd(self) -> npt.NDArray[np.float32]:
"""Return a copy of the token embedding matrix as ``[n_vocab, n_embd]``."""
element_count = llama_cpp.llama_model_get_tok_embd(self.model, None)
if element_count == 0:
raise RuntimeError(
"LlamaModel.get_tok_embd: token embedding matrix is unavailable"
)
n_vocab = self.n_vocab()
n_embd = self.n_embd()
expected_count = n_vocab * n_embd
if element_count != expected_count:
raise RuntimeError(
"LlamaModel.get_tok_embd: unexpected token embedding size: "
f"native API returned {element_count} elements, expected "
f"{expected_count} ({n_vocab} x {n_embd})"
)
out = np.empty(element_count, dtype=np.float32)
written = llama_cpp.llama_model_get_tok_embd(
self.model,
out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
)
if written != element_count:
raise RuntimeError(
"LlamaModel.get_tok_embd: failed to copy the complete token "
f"embedding matrix ({written}/{element_count} elements)"
)
return out.reshape(n_vocab, n_embd)
def rope_freq_scale_train(self) -> float:
"""
Get the model's RoPE frequency scaling factor
"""
return llama_cpp.llama_model_rope_freq_scale_train(self.model)
def model_desc(self) -> str:
"""
Get a string describing the model type
"""
buf = ctypes.create_string_buffer(256)
llama_cpp.llama_model_desc(self.model, buf, 256)
return buf.value.decode("utf-8")
def model_ftype(self) -> int:
"""
Get the model file type (quantization), e.g. LLAMA_FTYPE_MOSTLY_Q8_0
"""
return llama_cpp.llama_model_ftype(self.model)
def model_size(self) -> int:
"""
Returns the total size of all the tensors in the model in bytes
"""
return llama_cpp.llama_model_size(self.model)
def model_chat_template(self, name: Optional[bytes] = None) -> Optional[str]:
"""
Get a chat template from the model.
If name is None, returns the default chat template.
Returns None if no chat template is available.
"""
template = llama_cpp.llama_model_chat_template(self.model, name)
if template is None:
return None
return template.decode("utf-8")
def n_params(self) -> int:
"""
Returns the total number of parameters in the model
"""
return llama_cpp.llama_model_n_params(self.model)
def has_encoder(self) -> bool:
"""
Returns true if the model contains an encoder that requires llama_encode() call
"""
return llama_cpp.llama_model_has_encoder(self.model)
def has_decoder(self) -> bool:
"""
Returns true if the model contains a decoder that requires llama_decode() call
"""
return llama_cpp.llama_model_has_decoder(self.model)
def decoder_start_token(self) -> int:
"""
For encoder-decoder models, this function returns id of the token that must be provided
to the decoder to start generating output sequence. For other models, it returns -1.
"""
return llama_cpp.llama_model_decoder_start_token(self.model)
def is_recurrent(self) -> bool:
"""
Returns true if the model is recurrent (like Mamba, RWKV, etc.)
"""
return llama_cpp.llama_model_is_recurrent(self.model)
def is_hybrid(self) -> bool:
"""
Returns true if the model is hybrid (like Jamba, Granite, etc.)
"""
return llama_cpp.llama_model_is_hybrid(self.model)
def is_diffusion(self) -> bool:
"""
Returns true if the model is diffusion-based (like LLaDA, Dream, etc.)
"""
return llama_cpp.llama_model_is_diffusion(self.model)
# Vocab
def token_get_text(self, token: int) -> str:
return llama_cpp.llama_vocab_get_text(self.vocab, token).decode("utf-8")
def token_get_score(self, token: int) -> float:
return llama_cpp.llama_vocab_get_score(self.vocab, token)
def token_get_attr(self, token: int) -> int:
return llama_cpp.llama_vocab_get_attr(self.vocab, token)
def token_is_eog(self, token: int) -> bool:
return llama_cpp.llama_vocab_is_eog(self.vocab, token)
def token_is_control(self, token: int) -> bool:
return llama_cpp.llama_vocab_is_control(self.vocab, token)
# Special tokens
def token_bos(self) -> int:
return llama_cpp.llama_vocab_bos(self.vocab)
def token_eos(self) -> int:
return llama_cpp.llama_vocab_eos(self.vocab)
def token_eot(self) -> int:
return llama_cpp.llama_vocab_eot(self.vocab)
def token_sep(self) -> int:
return llama_cpp.llama_vocab_sep(self.vocab)
def token_nl(self) -> int:
return llama_cpp.llama_vocab_nl(self.vocab)
def token_pad(self) -> int:
return llama_cpp.llama_vocab_pad(self.vocab)
def token_mask(self) -> int:
return llama_cpp.llama_vocab_mask(self.vocab)
def token_cls(self) -> int:
return llama_cpp.llama_vocab_cls(self.vocab)
def token_fim_pre(self) -> int:
return llama_cpp.llama_vocab_fim_pre(self.vocab)
def token_fim_suf(self) -> int:
return llama_cpp.llama_vocab_fim_suf(self.vocab)
def token_fim_mid(self) -> int:
return llama_cpp.llama_vocab_fim_mid(self.vocab)
def token_fim_pad(self) -> int:
return llama_cpp.llama_vocab_fim_pad(self.vocab)
def token_fim_rep(self) -> int:
return llama_cpp.llama_vocab_fim_rep(self.vocab)
def token_fim_sep(self) -> int:
return llama_cpp.llama_vocab_fim_sep(self.vocab)
def get_add_bos(self) -> bool:
return llama_cpp.llama_vocab_get_add_bos(self.vocab)
def get_add_eos(self) -> bool:
return llama_cpp.llama_vocab_get_add_eos(self.vocab)
def get_add_sep(self) -> bool:
return llama_cpp.llama_vocab_get_add_sep(self.vocab)
# Tokenization
def tokenize(self, text: bytes, add_bos: bool, special: bool):
"""
Tokenize a string.
Optimized to use dynamic buffer allocation.
"""
n_tokens_alloc = len(text) + 2
tokens = (llama_cpp.llama_token * n_tokens_alloc)()
n_tokens = llama_cpp.llama_tokenize(
self.vocab, text, len(text), tokens, n_tokens_alloc, add_bos, special
)
# If the buffer is insufficient (returns a negative number), reallocate the buffer.
if n_tokens < 0:
n_tokens_alloc = -n_tokens
tokens = (llama_cpp.llama_token * n_tokens_alloc)()
n_tokens = llama_cpp.llama_tokenize(
self.vocab, text, len(text), tokens, n_tokens_alloc, add_bos, special
)
if n_tokens < 0:
raise RuntimeError(
f'Failed to tokenize: text="{text}" n_tokens={n_tokens}'
)
# return a buffer of n_tokens size.
return list(tokens[:n_tokens])
def token_to_piece(self, token: int, special: bool = False) -> bytes:
"""
Convert a single token to bytes.
Optimized to handle dynamic resizing for ultra-long tokens.
"""
size = 32
buf = (ctypes.c_char * size)()
n = llama_cpp.llama_token_to_piece(self.vocab, token, buf, size, 0, special)
# If the token is very long (returns a negative number), redistribute it according to the returned size.
if n < 0:
size = -n
buf = (ctypes.c_char * size)()
n = llama_cpp.llama_token_to_piece(self.vocab, token, buf, size, 0, special)
if n < 0:
raise RuntimeError(f"Failed to get piece for token {token}")
# return a buffer of n size.
return bytes(buf[:n])
def detokenize(self, tokens: List[int], special: bool = False) -> bytes:
"""
Convert a list of tokens to bytes.
Optimized to handle dynamic resizing for ultra-long tokens.
"""
if not tokens:
return b""
n_tokens = len(tokens)
# Convert a Python list to a C int array
tokens_array = (llama_cpp.llama_token * n_tokens)(*tokens)
# Initial buffer size estimation
# Note(JamePeng):
# Observed CJK heavy outputs are about 4.0x - 5.04x,
# with extreme values even reaching 6.0x, so this avoids most retry cases.
# In CJK use cases, the call overhead will be reduced by 50% compared to the previous detokenize method.
buffer_size = max(64, n_tokens * 5 + 32)
buffer = (ctypes.c_char * buffer_size)()
n_chars = llama_cpp.llama_detokenize(
self.vocab, tokens_array, n_tokens, buffer, buffer_size, False, special
)
# If the buffer is insufficient, expand it and retry.
if n_chars < 0:
buffer_size = -n_chars
buffer = (ctypes.c_char * buffer_size)()
n_chars = llama_cpp.llama_detokenize(
self.vocab, tokens_array, n_tokens, buffer, buffer_size, False, special
)
if n_chars < 0:
raise RuntimeError("Failed to detokenize")
return bytes(buffer[:n_chars])
# Lora
def load_lora(self, name: str, path: str):
"""Loads a LoRA adapter into VRAM without applying it yet."""
# Skip if it's already loaded
if name in self._lora_registry:
return
adapter = LlamaLoraAdapter(self.model, path)
self._lora_registry[name] = adapter
self._exit_stack.callback(adapter.free)
if self.verbose:
print(f"Loaded LoRA '{name}' into memory.")
def unload_lora(self, name: str):
"""Actively unloads a specific LoRA to free up VRAM."""
if name in self._lora_registry:
adapter = self._lora_registry.pop(name)
adapter.free()
if self.verbose:
print(f"Unloaded LoRA '{name}' and freed memory.")
@property
def loaded_lora_count(self) -> int:
"""
Returns the total number of LoRA adapters currently loaded in VRAM.
"""
return len(self._lora_registry)
def list_loras(self) -> List[str]:
"""
Returns a list of all registered LoRA names.
"""
return list(self._lora_registry.keys())
def unload_all_loras(self):
"""
Iterates through the registry and forces VRAM release for all loaded LoRAs.
"""
if not self._lora_registry:
return
# Cast keys to a list first to avoid RuntimeError:
# 'dictionary changed size during iteration' when pop() is called inside unload_lora.
loaded_names = list(self._lora_registry.keys())
for name in loaded_names:
self.unload_lora(name)
if self.verbose:
print(f"Successfully unloaded all {len(loaded_names)} LoRA adapters and cleared the registry.")
# Extra
def metadata(self) -> Dict[str, str]:
metadata: Dict[str, str] = {}
# Pre-allocate a 16KB buffer. This is large enough to handle almost all
# metadata values (including gpt-oss large chat templates ~15KB) in a single pass,
# eliminating the need for resize-and-retry in most cases.
buffer_size = 16384
buffer = ctypes.create_string_buffer(buffer_size)
# Caching function references reduces the overhead of property lookups within loops.
get_key_by_index = llama_cpp.llama_model_meta_key_by_index
get_val_by_index = llama_cpp.llama_model_meta_val_str_by_index
metadata_count = llama_cpp.llama_model_meta_count(self.model)
# iterate over model keys
for i in range(metadata_count):
# 1. Get Key
nbytes = get_key_by_index(self.model, i, buffer, buffer_size)
# Handle buffer resize if the key exceeds current size
if nbytes > buffer_size:
buffer_size = nbytes + 1024
buffer = ctypes.create_string_buffer(buffer_size)
# Retry with the larger buffer
nbytes = get_key_by_index(self.model, i, buffer, buffer_size)
key = buffer.value.decode("utf-8")
# 2. Get Value
nbytes = get_val_by_index(self.model, i, buffer, buffer_size)
# Handle buffer resize if the value exceeds current size
if nbytes > buffer_size:
buffer_size = nbytes + 1024
buffer = ctypes.create_string_buffer(buffer_size)
# Retry with the larger buffer
nbytes = get_val_by_index(self.model, i, buffer, buffer_size)
value = buffer.value.decode("utf-8")
metadata[key] = value
return metadata
@staticmethod
def default_params():
"""Get the default llama_model_params."""
return llama_cpp.llama_model_default_params()
class LlamaLoraAdapter:
"""Wrapper for llama_adapter_lora_p to safely manage C++ memory lifecycle."""
def __init__(self, model: llama_cpp.llama_model_p, path: str):
"""
Initializes and loads the LoRA adapter into memory.
Args:
model: The pointer to the base Llama model.
path: The file path to the LoRA adapter (.gguf).
"""
self.path = path
# Load the LoRA adapter from file into memory via llama.cpp API
# Note: The path string must be encoded to UTF-8 bytes for ctypes compatibility.
self.adapter = llama_cpp.llama_adapter_lora_init(
model,
path.encode("utf-8")
)
if not self.adapter:
raise RuntimeError(f"Failed to load LoRA from {path}")
def free(self):
"""
Explicitly frees the underlying C++ memory allocated for the LoRA adapter.
Should be called when the adapter is actively unloaded to instantly release VRAM.
"""
# Check if the adapter exists and hasn't been freed yet
if getattr(self, "adapter", None) is not None:
llama_cpp.llama_adapter_lora_free(self.adapter)
self.adapter = None
self.path = None
def __del__(self):
self.free()
@property
def alora_invocation_tokens(self) -> List[int]:
"""
Retrieves the list of invocation (trigger) tokens if this adapter is an ALoRA (Activation LoRA).
Returns an empty list for standard LoRA adapters.
"""
if getattr(self, "adapter", None) is None:
return []
# 1. Query the C++ backend for the exact number of trigger tokens
n_tokens = llama_cpp.llama_adapter_get_alora_n_invocation_tokens(self.adapter)
if n_tokens == 0:
return []
# 2. Retrieve the underlying C pointer to the contiguous array of tokens
tokens_ptr = llama_cpp.llama_adapter_get_alora_invocation_tokens(self.adapter)
# 3. Safely iterate through the C memory block and convert it into a native Python list
return [tokens_ptr[i] for i in range(n_tokens)]
class LlamaContext:
"""Own a native ``llama_context`` and expose its low-level operations.
The context stores runtime state such as the KV/recurrent memory, pending
backend work, output buffers, samplers, and applied adapters. Most callers
should use :class:`Llama`; this wrapper is intended for internal and
advanced low-level use. Pointers returned by output accessors are owned by
llama.cpp and remain valid only until the context reuses those buffers.
Output and state-transfer accessors synchronize pending backend work;
operations performed through the native memory handle do not generally add
an implicit synchronization boundary.
"""
def __init__(
self,
*,
model: LlamaModel,
params: llama_cpp.llama_context_params,
verbose: bool = True,
):
"""Create a context for ``model`` using native context ``params``."""
self.model = model
self.params = params
self.verbose = verbose
self._exit_stack = ExitStack()
ctx = llama_cpp.llama_init_from_model(self.model.model, self.params)
if not ctx:
raise RuntimeError(
"Failed to create llama context with model. "
"This may indicate that llama_context_params is out of sync with "
"the bundled llama.cpp version, or that required context parameters "
"were not initialized correctly."
)
self.ctx = ctx
self._loras_applied: bool = False
self._cvec_applied: bool = False
self._threadpool_refs = None
# llama.cpp borrows callbacks and their user data. Keep callbacks from
# the initial params alive just as set_abort_callback() does.
self._abort_callback_ref = (
self.params.abort_callback if bool(self.params.abort_callback) else None
)
self._abort_callback_data_ref = self.params.abort_callback_data
# The native context borrows attached sampler pointers. Keep the Python
# wrappers alive until they are detached or the context is closed.
self._sampler_refs: Dict[int, "LlamaSampler"] = {}
def close(self):
"""Manually free LlamaContext resources."""
for cache in list(getattr(self, "_checkpoint_caches", ())):
cache.close()
if hasattr(self, "_checkpoint_caches"):
self._checkpoint_caches.clear()
if getattr(self, "ctx", None) is not None:
try:
llama_cpp.llama_free(self.ctx)
except Exception:
pass
self.ctx = None
self.params = None
if getattr(self, "_exit_stack", None) is not None and hasattr(self._exit_stack, "close"):
self._exit_stack.close()
self._exit_stack = None
# The context no longer needs to keep its parent model alive once the
# native context and its callbacks have been released.
self.model = None
self._sampler_refs = {}
self._threadpool_refs = None
self._abort_callback_ref = None
self._abort_callback_data_ref = None
def __del__(self):
"""Release native resources when the wrapper is garbage-collected."""
self.close()
def _assert_ctx(self):
"""Raise when an operation is attempted on a closed context."""
if not getattr(self, "ctx", None):
raise RuntimeError(
"LlamaContext is not initialized or has already been closed. "
"Context-dependent llama.cpp operations cannot continue."
)
def n_ctx(self) -> int:
"""Return the total configured context capacity in tokens."""
return llama_cpp.llama_n_ctx(self.ctx)
def n_ctx_seq(self) -> int:
"""Return the effective context capacity available to each sequence."""
return llama_cpp.llama_n_ctx_seq(self.ctx)
def n_batch(self) -> int:
"""Return the maximum logical batch size accepted by the context."""
return llama_cpp.llama_n_batch(self.ctx)
def n_ubatch(self) -> int:
"""Return the maximum physical micro-batch size used for graph execution."""
return llama_cpp.llama_n_ubatch(self.ctx)
def n_seq_max(self) -> int:
"""Return the maximum number of sequences supported by one batch."""
return llama_cpp.llama_n_seq_max(self.ctx)
def n_rs_seq(self) -> int:
"""Return the configured recurrent-state snapshot capacity per sequence."""
return llama_cpp.llama_n_rs_seq(self.ctx)
def pooling_type(self) -> int:
"""Return the active ``llama_pooling_type`` value."""
return llama_cpp.llama_pooling_type(self.ctx)
# // Memory API
def _register_checkpoint_cache(self, cache):
"""Track a borrower without extending its lifetime."""
self._assert_ctx()
if not hasattr(self, "_checkpoint_caches"):
self._checkpoint_caches = weakref.WeakSet()
self._checkpoint_caches.add(cache)
cache._context_ref = weakref.ref(self)
def _invalidate_checkpoints(
self, seq_id: int = -1, *, suffix_start: Optional[int] = None,
keep_seq_id: Optional[int] = None, device_only: bool = False,
) -> None:
"""Invalidate registered partial snapshots, not draft engine state.
Raw C API calls and automatic SWA eviction bypass this bookkeeping.
Callers still own token/output synchronization and shared-KV dependencies.
"""
for cache in list(getattr(self, "_checkpoint_caches", ())):
if device_only and not cache.on_device:
continue
cache._invalidate_memory(seq_id, suffix_start, keep_seq_id)
def get_memory(self):
"""Return the context-owned native memory/KV-cache handle.
The handle is non-owning and must not be freed by Python. Operations on
it do not implicitly wait for pending graph execution.
"""
self._assert_ctx()
return llama_cpp.llama_get_memory(self.ctx)
def memory_clear(self, data: bool):
"""Clear memory metadata and optionally zero the backing data buffers.
This method does not synchronize pending backend work. Callers use it
at reset or other established context boundaries.
"""
memory = self.get_memory()
self._invalidate_checkpoints()
llama_cpp.llama_memory_clear(memory, data)
def memory_seq_rm(self, seq_id: int, p0: int, p1: int) -> bool:
"""Remove sequence cells in ``[p0, p1)``.
Negative bounds follow llama.cpp conventions: ``p0 < 0`` starts at
zero and ``p1 < 0`` extends through the sequence end. Returns ``False``
when the selected memory implementation cannot remove only that range.
The operation does not synchronize pending backend work.
"""
memory = self.get_memory()
try:
removed = llama_cpp.llama_memory_seq_rm(memory, seq_id, p0, p1)
except BaseException:
self._invalidate_checkpoints(seq_id)
raise
if removed and (p1 < 0 or p1 > max(0, p0)):
self._invalidate_checkpoints(
seq_id, suffix_start=max(0, p0) if p1 < 0 else None
)
return removed
def memory_seq_cp(self, seq_id_src: int, seq_id_dst: int, p0: int, p1: int):
"""Copy source-sequence memory cells in ``[p0, p1)`` to a destination.
Negative bounds follow the same convention as ``memory_seq_rm()``.
This operation does not synchronize pending backend work.
"""
memory = self.get_memory()
if seq_id_src != seq_id_dst and (p1 < 0 or p1 > max(0, p0)):
self._invalidate_checkpoints(seq_id_dst)
llama_cpp.llama_memory_seq_cp(memory, seq_id_src, seq_id_dst, p0, p1)
def memory_seq_keep(self, seq_id: int):
"""Keep only memory cells assigned to ``seq_id`` without synchronizing."""
memory = self.get_memory()
self._invalidate_checkpoints(keep_seq_id=seq_id)
llama_cpp.llama_memory_seq_keep(memory, seq_id)
def memory_seq_add(self, seq_id: int, p0: int, p1: int, delta: int):
"""Add ``delta`` to positions in ``[p0, p1)`` without synchronizing."""
memory = self.get_memory()
if delta != 0 and (p1 < 0 or p1 > max(0, p0)):
self._invalidate_checkpoints(seq_id)
llama_cpp.llama_memory_seq_add(memory, seq_id, p0, p1, delta)
def memory_seq_div(self, seq_id: int, p0: int, p1: int, d: int):
"""Integer-divide positions in ``[p0, p1)`` without synchronizing."""
memory = self.get_memory()
if d != 1 and (p1 < 0 or p1 > max(0, p0)):
self._invalidate_checkpoints(seq_id)
llama_cpp.llama_memory_seq_div(memory, seq_id, p0, p1, d)
def memory_seq_pos_max(self, seq_id: int) -> int:
"""Return the greatest cached position for ``seq_id``, or native sentinel."""
return llama_cpp.llama_memory_seq_pos_max(self.get_memory(), seq_id)
def memory_seq_pos_min(self, seq_id: int) -> int:
"""Return the smallest cached position for ``seq_id``, or native sentinel."""
return llama_cpp.llama_memory_seq_pos_min(self.get_memory(), seq_id)
def memory_can_shift(self) -> bool:
"""Return whether the active memory implementation supports position shifts."""
return llama_cpp.llama_memory_can_shift(self.get_memory())
# // State / sessions API
def get_state_size(self) -> int:
"""Return the current full-state size in bytes for serialization.
This is the actual save size, not a guaranteed upper bound for loading
an arbitrary state produced by another context.
"""
self._assert_ctx()
return llama_cpp.llama_state_get_size(self.ctx)
def get_state_data(self, dst:ctypes.Array[ctypes.c_uint8], size: int) -> int:
"""Synchronize and copy the complete context state into ``dst``.
Returns the number of bytes written. ``dst`` must provide at least
``size`` writable bytes.
"""
self._assert_ctx()
return llama_cpp.llama_state_get_data(self.ctx, dst, size)
def set_state_data(self, src:ctypes.Array[ctypes.c_uint8], size: int) -> int:
"""Synchronize, restore complete state from ``src``, and return bytes read."""
self._assert_ctx()
self._invalidate_checkpoints()
return llama_cpp.llama_state_set_data(self.ctx, src, size)
def load_state_file(
self,
path_session: bytes,
tokens_out: ctypes.Array[llama_cpp.llama_token],
n_token_capacity: ctypes.c_size_t,
n_token_count_out: CtypesPointer[ctypes.c_size_t]
) -> bool:
"""Synchronize, then load complete state and token history from a file."""
self._assert_ctx()
self._invalidate_checkpoints()
return llama_cpp.llama_state_load_file(self.ctx, path_session, tokens_out, n_token_capacity, n_token_count_out)
def save_state_file(
self,
path_session: bytes,
tokens: ctypes.Array[llama_cpp.llama_token],
n_token_count: ctypes.c_size_t
) -> bool:
"""Synchronize, then save complete state and token history to a file."""
self._assert_ctx()
return llama_cpp.llama_state_save_file(self.ctx, path_session, tokens, n_token_count)
def get_state_seq_size(self, seq_id: int) -> int:
"""Return the exact host-serialized state size for one sequence."""
self._assert_ctx()
return llama_cpp.llama_state_seq_get_size(self.ctx, seq_id)
def get_state_seq_data(self, dst: ctypes.Array[ctypes.c_uint8], size: int, seq_id: int) -> int:
"""Synchronize and copy one sequence state into ``dst``."""
self._assert_ctx()
return llama_cpp.llama_state_seq_get_data(self.ctx, dst, size, seq_id)
def set_state_seq_data(self, src: ctypes.Array[ctypes.c_uint8], size: int, dest_seq_id: int) -> int:
"""Synchronize and restore serialized state into ``dest_seq_id``."""
self._assert_ctx()
self._invalidate_checkpoints(dest_seq_id)
return llama_cpp.llama_state_seq_set_data(self.ctx, src, size, dest_seq_id)
def load_state_seq_file(
self,
filepath: bytes,
dest_seq_id: int,
tokens_out: ctypes.Array[llama_cpp.llama_token],
n_token_capacity: ctypes.c_size_t,
n_token_count_out: CtypesPointer[ctypes.c_size_t]
) -> int:
"""Synchronize, then load sequence state and tokens into ``dest_seq_id``."""
self._assert_ctx()
self._invalidate_checkpoints(dest_seq_id)
return llama_cpp.llama_state_seq_load_file(self.ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out)
def save_state_seq_file(
self,
filepath: bytes,
seq_id: int,
tokens: ctypes.Array[llama_cpp.llama_token],
n_token_count: ctypes.c_size_t
) -> int:
"""Synchronize, then save one sequence state and tokens to a file."""
self._assert_ctx()
return llama_cpp.llama_state_seq_save_file(self.ctx, filepath, seq_id, tokens, n_token_count)
def get_state_seq_size_ext(self, seq_id: int, flags: llama_cpp.llama_state_seq_flags) -> int:
"""Return the sequence-state size for an extended serialization mode.
``flags`` can restrict the snapshot to partial/recurrent state and can
request device-resident snapshots. Device snapshots are opaque and a
subsequent capture for the same sequence invalidates the prior one.
"""
self._assert_ctx()
return llama_cpp.llama_state_seq_get_size_ext(self.ctx, seq_id, flags)
def get_state_seq_data_ext(
self,
dst:ctypes.Array[ctypes.c_uint8],
size: int,
seq_id: int,
flags: llama_cpp.llama_state_seq_flags
) -> int:
"""Synchronize and capture one sequence according to ``flags``.
Returns the number of bytes or opaque handle bytes written to ``dst``.
"""
self._assert_ctx()
if flags & llama_cpp.LLAMA_STATE_SEQ_FLAGS_ON_DEVICE:
self._invalidate_checkpoints(seq_id, device_only=True)
return llama_cpp.llama_state_seq_get_data_ext(self.ctx, dst, size, seq_id, flags)
def set_state_seq_data_ext(
self,
src:ctypes.Array[ctypes.c_uint8],
size: int,
dest_seq_id: int,
flags: llama_cpp.llama_state_seq_flags
) -> int:
"""Synchronize and restore an extended snapshot into ``dest_seq_id``."""
self._assert_ctx()
self._invalidate_checkpoints(dest_seq_id)
return llama_cpp.llama_state_seq_set_data_ext(self.ctx, src, size, dest_seq_id, flags)
# // Decoding API
def encode(self, batch: LlamaBatch):
"""Run an encoder batch without using the decoder KV cache.
Raises ``RuntimeError`` for every nonzero native return code. On a
native error, llama.cpp restores memory to its pre-call state.
"""
self._assert_ctx()
return_code = llama_cpp.llama_encode(
self.ctx,
batch.batch,
)
if return_code != 0:
raise RuntimeError(f"llama_encode returned {return_code}")
def decode(self, batch: 'LlamaBatch') -> int:
"""
Evaluate the batch of tokens using the transformer model.
This method submits the decoder forward pass and updates context memory.
A successful return does not establish a host-visible completion
boundary; call ``synchronize()`` or an output accessor before consuming
results or measuring completed device time. If memory is fragmented or
out of space, it may return 1, indicating that the caller should reduce
the batch size or evict idle sequences.
Returns:
0: Success.
1: No KV slot available (Recoverable). The caller should implement a
fallback strategy, such as reducing the batch size and retrying.
Raises:
LlamaDecodeAbort: If the native abort callback interrupts decoding.
Already processed micro-batches may remain in context memory.
RuntimeError: If a fatal, non-recoverable error occurs during decoding.
"""
self._assert_ctx()
try:
return_code = llama_cpp.llama_decode(self.ctx, batch.batch)
except Exception as e:
self._invalidate_checkpoints()
raise RuntimeError(
"llama_decode raised a native exception before returning a status code. "
"This may indicate an invalid batch, invalid token id, corrupted context, "
"backend memory issue, or native access violation."
) from e
if return_code not in (0, 1):
self._invalidate_checkpoints()