Intermediate Python wrapper for a llama.cpp llama_context. NOTE: For stability it's recommended you use the Llama class instead.
| 245 | |
| 246 | |
| 247 | class LlamaContext: |
| 248 | """Intermediate Python wrapper for a llama.cpp llama_context. |
| 249 | NOTE: For stability it's recommended you use the Llama class instead.""" |
| 250 | |
| 251 | def __init__( |
| 252 | self, |
| 253 | *, |
| 254 | model: LlamaModel, |
| 255 | params: llama_cpp.llama_context_params, |
| 256 | verbose: bool = True, |
| 257 | ): |
| 258 | self.model = model |
| 259 | self.params = params |
| 260 | self.verbose = verbose |
| 261 | self._exit_stack = ExitStack() |
| 262 | |
| 263 | ctx = llama_cpp.llama_init_from_model(self.model.model, self.params) |
| 264 | |
| 265 | if ctx is None: |
| 266 | raise ValueError("Failed to create llama_context") |
| 267 | |
| 268 | self.ctx = ctx |
| 269 | self.memory = llama_cpp.llama_get_memory(self.ctx) |
| 270 | self.sampler = None # LlamaContext doesn't manage samplers directly, but some cleanup code expects this attribute |
| 271 | |
| 272 | def free_ctx(): |
| 273 | if self.ctx is None: |
| 274 | return |
| 275 | llama_cpp.llama_free(self.ctx) |
| 276 | self.ctx = None |
| 277 | |
| 278 | self._exit_stack.callback(free_ctx) |
| 279 | |
| 280 | def close(self): |
| 281 | self._exit_stack.close() |
| 282 | |
| 283 | def __del__(self): |
| 284 | self.close() |
| 285 | |
| 286 | def n_ctx(self) -> int: |
| 287 | return llama_cpp.llama_n_ctx(self.ctx) |
| 288 | |
| 289 | def pooling_type(self) -> int: |
| 290 | return llama_cpp.llama_pooling_type(self.ctx) |
| 291 | |
| 292 | def kv_cache_clear(self): |
| 293 | # Embedding models with non-causal attention may not allocate memory. |
| 294 | if self.memory is None: |
| 295 | return |
| 296 | llama_cpp.llama_memory_clear(self.memory, True) |
| 297 | |
| 298 | def kv_cache_seq_rm(self, seq_id: int, p0: int, p1: int) -> bool: |
| 299 | assert self.memory is not None, "Memory is not initialized" |
| 300 | seq_id = seq_id if seq_id >= 0 else 0 |
| 301 | return llama_cpp.llama_memory_seq_rm(self.memory, seq_id, p0, p1) |
| 302 | |
| 303 | def kv_cache_seq_cp(self, seq_id_src: int, seq_id_dst: int, p0: int, p1: int): |
| 304 | assert self.memory is not None, "Memory is not initialized" |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…