Repository navigation
Expand file tree
/
Copy path_internals.py
More file actions
3176 lines (2570 loc) · 113 KB
/
Copy path_internals.py
File metadata and controls
3176 lines (2570 loc) · 113 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
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 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_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:
"""Intermediate Python wrapper for a llama.cpp llama_context.
NOTE: For stability it's recommended you use the Llama class instead."""
def __init__(
self,
*,
model: LlamaModel,
params: llama_cpp.llama_context_params,
verbose: bool = True,
):
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
def close(self):
"""Manually free LlamaContext resources."""
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
def __del__(self):
self.close()
def _assert_ctx(self):
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 llama_cpp.llama_n_ctx(self.ctx)
def n_ctx_seq(self) -> int:
return llama_cpp.llama_n_ctx_seq(self.ctx)
def n_batch(self) -> int:
return llama_cpp.llama_n_batch(self.ctx)
def n_ubatch(self) -> int:
return llama_cpp.llama_n_ubatch(self.ctx)
def n_seq_max(self) -> int:
return llama_cpp.llama_n_seq_max(self.ctx)
def n_rs_seq(self) -> int:
return llama_cpp.llama_n_rs_seq(self.ctx)
def pooling_type(self) -> int:
return llama_cpp.llama_pooling_type(self.ctx)
# // Memory API
def get_memory(self):
return llama_cpp.llama_get_memory(self.ctx)
def memory_clear(self, data: bool):
llama_cpp.llama_memory_clear(self.get_memory(), data)
def memory_seq_rm(self, seq_id: int, p0: int, p1: int) -> bool:
if self.ctx is not None:
return llama_cpp.llama_memory_seq_rm(self.get_memory(), seq_id, p0, p1)
else:
return False
def memory_seq_cp(self, seq_id_src: int, seq_id_dst: int, p0: int, p1: int):
llama_cpp.llama_memory_seq_cp(self.get_memory(), seq_id_src, seq_id_dst, p0, p1)
def memory_seq_keep(self, seq_id: int):
llama_cpp.llama_memory_seq_keep(self.get_memory(), seq_id)
def memory_seq_add(self, seq_id: int, p0: int, p1: int, delta: int):
llama_cpp.llama_memory_seq_add(self.get_memory(), seq_id, p0, p1, delta)
def memory_seq_div(self, seq_id: int, p0: int, p1: int, d: int):
llama_cpp.llama_memory_seq_div(self.get_memory(), seq_id, p0, p1, d)
def memory_seq_pos_max(self, seq_id: int) -> int:
return llama_cpp.llama_memory_seq_pos_max(self.get_memory(), seq_id)
def memory_seq_pos_min(self, seq_id: int) -> int:
return llama_cpp.llama_memory_seq_pos_min(self.get_memory(), seq_id)
def memory_can_shift(self) -> bool:
return llama_cpp.llama_memory_can_shift(self.get_memory())
# // State / sessions API
def get_state_size(self) -> int:
return llama_cpp.llama_state_get_size(self.ctx)
def get_state_data(self, dst:ctypes.Array[ctypes.c_uint8], size: int) -> int:
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:
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:
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:
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 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:
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:
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:
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:
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 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:
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:
return llama_cpp.llama_state_seq_set_data_ext(self.ctx, src, size, dest_seq_id, flags)
# // Decoding API
def encode(self, batch: LlamaBatch):
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 executes the forward pass. If the KV cache is heavily fragmented
or out of space, it may return 1, indicating the caller should try to 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:
RuntimeError: If a fatal, non-recoverable error occurs during decoding
(e.g., negative error codes or invalid batch structures).
"""
self._assert_ctx()
try:
return_code = llama_cpp.llama_decode(self.ctx, batch.batch)
except Exception as e:
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 == 0:
return 0
# 1 means "No KV slot available".
# We explicitly return 1 instead of raising an exception so that the caller
# can gracefully handle it via dynamic batch sizing (batch_size //= 2).
elif return_code == 1:
return 1
# Any other code indicates a fatal failure.
error_map = {
2: "Decoding aborted by user callback",
-1: "Invalid input batch (e.g. n_tokens == 0 or exceeding capacity)",
-2: "Could not allocate space for the compute graph (VRAM exhausted)",
-3: "Graph computation failed internally",
}
msg = error_map.get(return_code, "Unknown fatal internal error")
raise RuntimeError(f"llama_decode failed (code {return_code}): {msg}")
def set_n_threads(self, n_threads: int, n_threads_batch: int):
"""
Set the number of threads used for decoding
Args:
n_threads: the number of threads used for generation (single token)
n_threads_batch: the number of threads used for prompt and batch processing (multiple tokens)
"""
llama_cpp.llama_set_n_threads(self.ctx, n_threads, n_threads_batch)
def n_threads(self) -> int:
"""Get the number of threads used for generation of a single token."""
return llama_cpp.llama_n_threads(self.ctx)
def n_threads_batch(self) -> int:
"""Get the number of threads used for prompt and batch processing (multiple token)."""
return llama_cpp.llama_n_threads_batch(self.ctx)
def set_causal_attn(self, causal_attn: bool):
"""
Set whether to use causal attention or not
If set to true, the model will only attend to the past tokens
"""
llama_cpp.llama_set_causal_attn(self.ctx, causal_attn)
def synchronize(self):
"""
Wait until all computations are finished
This is automatically done when using one of the functions below to obtain the computation results
and is not necessary to call it explicitly in most cases
"""
llama_cpp.llama_synchronize(self.ctx)
def get_logits(self):
"""
Token logits obtained from the last call to llama_decode()
The logits for which llama_batch.logits[i] != 0 are stored contiguously
in the order they have appeared in the batch.
Rows: number of tokens for which llama_batch.logits[i] != 0
Cols: n_vocab
Returns:
Pointer to the logits buffer of shape (n_tokens, n_vocab)
"""
self._assert_ctx()
logits = llama_cpp.llama_get_logits(self.ctx)
if not logits:
raise RuntimeError(f"LlamaContext.get_logits: failed to get logits")
return logits
def get_logits_ith(self, i: int):
"""
Return logits for the ith output row from the last llama_decode call.
Note:
This calls llama_get_logits_ith(), which may reorder/synchronize
the output buffer internally. Avoid calling it on the hot path unless
Python-side logits are required.
"""
self._assert_ctx()
logits = llama_cpp.llama_get_logits_ith(self.ctx, i)
if not logits:
raise RuntimeError(f"LlamaContext.get_logits_ith: invalid logits index {i}")
return logits
def set_embeddings(self, embeddings: bool):
self._assert_ctx()
llama_cpp.llama_set_embeddings(self.ctx, embeddings)
def get_embeddings(self):
self._assert_ctx()
return llama_cpp.llama_get_embeddings(self.ctx)
def get_embeddings_ith(self, i: int):
self._assert_ctx()
return llama_cpp.llama_get_embeddings_ith(self.ctx, i)
def get_embeddings_seq(self, seq_id: int):
self._assert_ctx()
return llama_cpp.llama_get_embeddings_seq(self.ctx, seq_id)
def reset_timings(self):
llama_cpp.llama_perf_context_reset(self.ctx)
def print_timings(self):
llama_cpp.llama_perf_context_print(self.ctx)
# LoRA / ALoRA Dynamic Routing Methods
def clear_loras(self):
"""
Clears all currently applied LoRA weights from the context.
Restores the computational graph to the base model state.
"""
if not self._loras_applied:
return
llama_cpp.llama_set_adapters_lora(self.ctx, None, 0, None)
self._loras_applied = False
def apply_loras(self, active_loras: List[Tuple["LlamaLoraAdapter", float]]):
"""
Dynamically mounts a combination of LoRAs and their scales to the current context.
This must be called immediately before evaluating/decoding the computation graph.
Args:
active_loras: A list of tuples containing (LlamaLoraAdapter instance, scale float).
"""
# If no LoRAs are requested, ensure the context is wiped clean to prevent contamination
if not active_loras:
self.clear_loras()
return
n_adapters = len(active_loras)
# 1. Dynamically construct contiguous C-array types required by the C++ backend
AdapterArrayType = llama_cpp.llama_adapter_lora_p_ctypes * n_adapters
ScaleArrayType = ctypes.c_float * n_adapters
# 2. Instantiate the arrays in memory
c_adapters = AdapterArrayType()
c_scales = ScaleArrayType()
# 3. Populate the C-arrays with the underlying adapter pointers and float scales
for i, (adapter_obj, scale) in enumerate(active_loras):
c_adapters[i] = adapter_obj.adapter
c_scales[i] = scale
# 4. Atomically apply the requested adapters to the computation graph
ret = llama_cpp.llama_set_adapters_lora(
self.ctx,
c_adapters,
n_adapters,
c_scales
)
if ret != 0:
raise RuntimeError("LlamaContext(apply_loras): Failed to set LoRA adapters dynamically.")
self._loras_applied = True
if self.verbose:
print(f"LlamaContext(apply_loras): Successfully applied {n_adapters} LoRA adapter(s) to the compute graph.")
# Control Vector (CVec) Methods
def clear_cvec(self):
"""
Clears the currently loaded control vector from the context.
Passing NULL (None) and zeros safely resets the graph.
"""
if not self._cvec_applied:
return
llama_cpp.llama_set_adapter_cvec(self.ctx, None, 0, 0, 0, 0)
self._cvec_applied = False
def apply_cvec(self, data: List[float], n_embd: int, il_start: int, il_end: int):
"""
Dynamically applies a Control Vector (CVec) to the specified layer range.
Args:
data: Flattened 1D list of floats.
[CRITICAL_LAYOUT_RULE]: Based on llama.cpp source, the data buffer
is strictly mapped starting from Layer 1. Even if il_start > 1,
the `data` array must contain zero-padding for the skipped early layers.
Total length MUST be >= n_embd * il_end.
n_embd: The embedding dimension of the model.
il_start: The starting layer to apply the vector (inclusive, 1-indexed).
il_end: The ending layer to apply the vector (inclusive).
"""
if not data:
self.clear_cvec()
return
length = len(data)
# Strictly validate length based on C++ buffer mapping rules
# The C++ backend uses offset: off = n_embd * (il - 1).
# To successfully write up to il_end, the buffer length must be at least n_embd * il_end.
minimum_required_len = n_embd * il_end
if length < minimum_required_len:
raise ValueError(
f"LlamaContext(apply_cvec): "
f"[Memory Layout Error] Control vector data length ({length}) is too short. "
f"llama.cpp requires the buffer to map continuously from Layer 1. "
f"To apply up to layer {il_end}, length must be at least {minimum_required_len}."
)
# 1. Convert to C Array
CFloatArrayType = ctypes.c_float * length
c_data = CFloatArrayType(*data)
# 2. Inject into graph
ret = llama_cpp.llama_set_adapter_cvec(
self.ctx,
c_data,
length,
n_embd,
il_start,
il_end
)
# 3. Handle specific C++ boolean false (converted to -1)
if ret != 0:
raise RuntimeError(
f"LlamaContext(apply_cvec): "
f"C++ backend rejected the Control Vector. "
f"Usually indicates n_embd ({n_embd}) does not match the model's actual embedding dimension."
)
self._cvec_applied = True