llama_cpp_4/context.rs
1//! Safe wrapper around `llama_context`.
2//!
3//! Submodules:
4//!
5//! - [`tensor_capture`] — hook `cb_eval` during [`LlamaContext::decode`] to copy
6//! intermediate tensors (per-layer hidden states, norms, …).
7//! - [`memory_breakdown`] — per-buffer memory usage after load/decode.
8//! - [`kv_cache`] — sequence copy, shift, and clear helpers.
9
10use std::fmt::{Debug, Formatter};
11use std::num::NonZeroI32;
12use std::pin::Pin;
13use std::ptr::NonNull;
14use std::slice;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use llama_cpp_sys_4::llama_pooling_type;
18use params::{LlamaContextType, LlamaPoolingType};
19use perf::PerfContextData;
20
21use crate::llama_batch::LlamaBatch;
22use crate::llama_batch_ext::{LlamaBatchExt, LlamaProcessType};
23use crate::model::{LlamaLoraAdapter, LlamaModel};
24use crate::token::data::LlamaTokenData;
25use crate::token::data_array::LlamaTokenDataArray;
26use crate::token::LlamaToken;
27use crate::{
28 DecodeError, EmbeddingsError, EncodeError, LlamaLoraAdapterRemoveError,
29 LlamaLoraAdapterSetError, NextnRowsError, ProcessError,
30};
31
32/// Source of [`LlamaContext::id`].
33///
34/// A [`LlamaBatchExt`] is bound to the context that built it, and comparing raw
35/// `llama_context` pointers is not enough to detect a stale binding: the
36/// allocator can hand a new context the address a dropped one had. A counter
37/// that only ever goes up cannot be reused that way.
38static NEXT_CONTEXT_ID: AtomicU64 = AtomicU64::new(0);
39
40pub mod kv_cache;
41pub mod memory_breakdown;
42pub mod params;
43pub mod perf;
44pub mod session;
45pub mod tensor_capture;
46pub mod tensor_transaction;
47
48pub use memory_breakdown::MemoryBreakdownEntry;
49pub use tensor_capture::{CapturedTensor, TensorCapture};
50pub use tensor_transaction::{
51 CapturedTensorData, TensorAccess, TensorBatchRow, TensorCallbackFailure, TensorDataMut,
52 TensorElementType, TensorFiniteValidation, TensorRowMapping, TensorSelector, TensorShape,
53 TensorTransaction, TensorTransactionError, TensorTransactionHandler, TensorTransactions,
54 TensorWriteback, TransactionalTensorCapture,
55};
56
57/// The size of a graph reserved by
58/// [`LlamaContext::reserve_graph`].
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub struct GraphReservation {
61 /// Compute nodes in the graph.
62 ///
63 /// ggml exposes no public leaf count, so this is the whole measurement —
64 /// enough to compare one batch shape against another, which is what it is
65 /// for.
66 pub n_nodes: i32,
67}
68
69/// [`LlamaContext::reserve_graph`] could not build a graph for that shape.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
71#[error("llama.cpp could not reserve a graph for n_tokens={n_tokens}, n_seqs={n_seqs}, n_outputs={n_outputs}")]
72pub struct ReserveGraphError {
73 /// Tokens requested.
74 pub n_tokens: u32,
75 /// Sequences requested.
76 pub n_seqs: u32,
77 /// Outputs requested.
78 pub n_outputs: u32,
79}
80
81/// A safe wrapper around the `llama_context` C++ context.
82///
83/// This struct provides a safe interface to interact with the `llama_context` used by the `LlamaModel`.
84/// It encapsulates the raw C++ context pointer and provides additional fields for managing the model and
85/// context-specific settings like embeddings and logits.
86///
87/// The `LlamaContext` struct ensures that the C++ context is always valid by using the `NonNull` type for
88/// the context pointer, preventing it from being null. The struct also holds a reference to the model
89/// (`LlamaModel`) that the context is tied to, along with some internal state like whether embeddings are enabled
90/// and the initialized logits for the context.
91///
92/// # Fields
93///
94/// - `context`: A non-null pointer to the raw C++ `llama_context`. This is the main context used for interacting with the model.
95/// - `model`: A reference to the `LlamaModel` associated with this context. This model provides the data and parameters
96/// that the context interacts with.
97/// - `initialized_logits`: A vector used to store the initialized logits. These are used in the model's processing and
98/// are kept separate from the context data.
99/// - `embeddings_enabled`: A boolean flag indicating whether embeddings are enabled in the context. This is useful for
100/// controlling whether embedding data is generated during the interaction with the model.
101#[allow(clippy::module_name_repetitions)]
102pub struct LlamaContext<'a> {
103 pub(crate) context: NonNull<llama_cpp_sys_4::llama_context>,
104 /// a reference to the contexts model.
105 pub model: &'a LlamaModel,
106 initialized_logits: Vec<i32>,
107 embeddings_enabled: bool,
108 context_type: LlamaContextType,
109 tensor_transactions: Option<Pin<Box<TensorTransactions>>>,
110 /// Identity of this context, unique for the life of the process. See
111 /// [`NEXT_CONTEXT_ID`].
112 id: u64,
113}
114
115impl Debug for LlamaContext<'_> {
116 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117 f.debug_struct("LlamaContext")
118 .field("context", &self.context)
119 .finish()
120 }
121}
122
123impl LlamaContext<'_> {
124 // ── raw output buffers ───────────────────────────────────────────────
125 //
126 // Every accessor below reads a buffer llama.cpp owns, through a pointer it
127 // hands back, for a number of elements this crate has to supply. The width
128 // is not a cosmetic detail: pass one too large and the slice runs off the
129 // row — off the whole allocation, on the last one. That is exactly what
130 // issue #360 was, in five separate accessors, because each picked its own
131 // width inline and nothing tied the choice to llama.cpp's allocation.
132 //
133 // So the widths are derived in one place here, and the pointer-to-slice
134 // step happens in one of two helpers rather than at each call site. There
135 // are three correct answers and they are easy to confuse:
136 //
137 // embd / embd_nextn n_embd_out() `n_embd_out*n_outputs_max`
138 // embd_seq pooling-dependent: n_cls_out for RANK, else n_embd_out
139 // embd_layer_inp n_embd layer *inputs*, a different buffer
140 // logits n_vocab
141
142 /// Read a scalar straight off the context.
143 ///
144 /// These are all the same one-line shape — call an llama.cpp getter with
145 /// the context pointer and return what it says — so they share one
146 /// justification here rather than repeating it a dozen times.
147 fn get<T>(&self, f: unsafe extern "C" fn(*const llama_cpp_sys_4::llama_context) -> T) -> T {
148 // SAFETY: `f` is an llama.cpp accessor that only reads from the
149 // context, and `self.context` is non-null and kept alive by this
150 // borrow. Nothing here escapes a pointer.
151 unsafe { f(self.context.as_ptr()) }
152 }
153
154 /// [`Self::get`] for the handful of read-only getters whose binding still
155 /// takes `*mut llama_context`.
156 ///
157 /// The mutability is upstream's signature, not a statement about what the
158 /// call does, which is why this takes `&self` like its sibling.
159 fn get_via_mut<T>(
160 &self,
161 f: unsafe extern "C" fn(*mut llama_cpp_sys_4::llama_context) -> T,
162 ) -> T {
163 // SAFETY: as `get` above — a read through a live, non-null context.
164 unsafe { f(self.context.as_ptr()) }
165 }
166
167 /// Row width of the token-embedding buffers (`embd` and `embd_nextn`).
168 ///
169 /// llama.cpp allocates both as `n_embd_out * n_outputs_max` and strides
170 /// them by `hparams.n_embd_out()`, which is `n_embd_out_impl` when the
171 /// model declares one and `n_embd` otherwise — so this is *not*
172 /// interchangeable with [`LlamaModel::n_embd`].
173 fn embd_row_width(&self) -> usize {
174 usize::try_from(self.model.n_embd_out()).expect("n_embd_out does not fit into a usize")
175 }
176
177 /// Row width of the pooled `embd_seq` buffer, which depends on pooling.
178 ///
179 /// RANK pooling stores `n_cls_out` rerank scores per sequence rather than
180 /// an embedding, so it is not an embedding width at all.
181 fn embd_seq_row_width(&self) -> usize {
182 if self.pooling_type() == LlamaPoolingType::Rank {
183 usize::try_from(self.model.n_cls_out()).expect("n_cls_out does not fit into a usize")
184 } else {
185 self.embd_row_width()
186 }
187 }
188
189 /// Row width of the logits buffer.
190 fn logits_row_width(&self) -> usize {
191 usize::try_from(self.model.n_vocab()).expect("n_vocab does not fit into a usize")
192 }
193
194 /// One row from a whole-buffer accessor, or `None` if llama.cpp has no
195 /// data for it.
196 ///
197 /// `len` must be a width from the helpers above; passing anything else is
198 /// what this exists to prevent.
199 fn buffer(
200 &self,
201 get: unsafe extern "C" fn(*mut llama_cpp_sys_4::llama_context) -> *mut f32,
202 len: usize,
203 ) -> Option<&[f32]> {
204 // SAFETY: `get` is one of llama.cpp's buffer accessors and
205 // `self.context` is a live, non-null context this borrow keeps alive,
206 // so the call is valid and returns either null or a pointer to a
207 // buffer llama.cpp owns. `len` comes from the width helpers above,
208 // which mirror llama.cpp's own allocation, so the slice stays inside
209 // it. The lifetime is tied to `&self`, and every method that can
210 // invalidate the buffer takes `&mut self`.
211 unsafe {
212 let ptr = get(self.context.as_ptr());
213 (!ptr.is_null() && len != 0).then(|| slice::from_raw_parts(ptr, len))
214 }
215 }
216
217 /// One row from an accessor indexed by token or sequence id.
218 ///
219 /// Out-of-range indices come back as `None`: llama.cpp logs and returns
220 /// null rather than trapping (in release builds).
221 fn buffer_at<I, T>(
222 &self,
223 get: unsafe extern "C" fn(*mut llama_cpp_sys_4::llama_context, I) -> *mut T,
224 i: I,
225 len: usize,
226 ) -> Option<&[T]> {
227 // SAFETY: as `buffer` above; `i` is passed through to llama.cpp, which
228 // range-checks it and returns null when it is out of range.
229 unsafe {
230 let ptr = get(self.context.as_ptr(), i);
231 (!ptr.is_null() && len != 0).then(|| slice::from_raw_parts(ptr, len))
232 }
233 }
234}
235
236impl<'model> LlamaContext<'model> {
237 /// Creates a new instance of `LlamaContext` with the provided model, context, and embeddings flag.
238 ///
239 /// This function initializes a new `LlamaContext` object, which is used to interact with the
240 /// `LlamaModel`. The context is created from a pointer to a C++ context and the embeddings flag
241 /// determines whether embeddings are enabled in the context.
242 ///
243 /// # Parameters
244 ///
245 /// - `llama_model`: A reference to an existing `LlamaModel` that will be used with the new context.
246 /// - `llama_context`: A non-null pointer to an existing `llama_cpp_sys_4::llama_context` representing
247 /// the context created in previous steps. This context is necessary for interacting with the model.
248 /// - `embeddings_enabled`: A boolean flag indicating whether embeddings are enabled in this context.
249 /// - `context_type`: The exact graph/context mode selected at allocation.
250 ///
251 /// # Returns
252 ///
253 /// This function returns a new instance of `LlamaContext` initialized with the given parameters:
254 /// - The model reference (`llama_model`) is stored in the context.
255 /// - The raw context pointer (`llama_context`) is wrapped in a `NonNull` to ensure safety.
256 /// - The `embeddings_enabled` flag is used to determine if embeddings are enabled for the context.
257 ///
258 /// # Example
259 /// ```ignore
260 /// let llama_model = LlamaModel::load_from_file(&backend, "path/to/model", ¶ms).unwrap();
261 /// let context_ptr = NonNull::new(some_llama_context_ptr).unwrap();
262 /// let context = LlamaContext::new(
263 /// &llama_model,
264 /// context_ptr,
265 /// true,
266 /// LlamaContextType::Default,
267 /// None,
268 /// );
269 /// // Now you can use the context
270 /// ```
271 pub(crate) fn new(
272 llama_model: &'model LlamaModel,
273 llama_context: NonNull<llama_cpp_sys_4::llama_context>,
274 embeddings_enabled: bool,
275 context_type: LlamaContextType,
276 tensor_transactions: Option<Pin<Box<TensorTransactions>>>,
277 ) -> Self {
278 Self {
279 context: llama_context,
280 model: llama_model,
281 initialized_logits: Vec::new(),
282 embeddings_enabled,
283 context_type,
284 tensor_transactions,
285 id: NEXT_CONTEXT_ID.fetch_add(1, Ordering::Relaxed),
286 }
287 }
288
289 /// Identity of this context, unique among every context this process has
290 /// created. Used to tie a [`LlamaBatchExt`] to the context that built it.
291 pub(crate) fn id(&self) -> u64 {
292 self.id
293 }
294
295 /// Returns the context type selected at native allocation.
296 #[must_use]
297 pub fn context_type(&self) -> LlamaContextType {
298 self.context_type
299 }
300
301 /// Gets the max number of logical tokens that can be submitted to decode. Must be greater than or equal to `n_ubatch`.
302 #[must_use]
303 pub fn n_batch(&self) -> u32 {
304 self.get(llama_cpp_sys_4::llama_n_batch)
305 }
306
307 /// Gets the max number of physical tokens (hardware level) to decode in batch. Must be less than or equal to `n_batch`.
308 #[must_use]
309 pub fn n_ubatch(&self) -> u32 {
310 self.get(llama_cpp_sys_4::llama_n_ubatch)
311 }
312
313 /// Gets the size of the context.
314 #[must_use]
315 pub fn n_ctx(&self) -> u32 {
316 self.get(llama_cpp_sys_4::llama_n_ctx)
317 }
318
319 /// Decodes the batch.
320 ///
321 /// # Errors
322 ///
323 /// - `DecodeError` if the decoding failed.
324 ///
325 /// # Panics
326 ///
327 /// - the returned [`std::ffi::c_int`] from llama-cpp does not fit into a i32 (this should never happen on most systems)
328 pub fn decode(&mut self, batch: &mut LlamaBatch) -> Result<(), DecodeError> {
329 let result =
330 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `batch` is owned by the caller and
331 // valid for the duration of the call. llama.cpp reports failure through the
332 // return code rather than by trapping.
333 unsafe { llama_cpp_sys_4::llama_decode(self.context.as_ptr(), batch.llama_batch) };
334 if let Some(failure) = self
335 .tensor_transactions
336 .as_ref()
337 .and_then(|transactions| transactions.failure())
338 .cloned()
339 {
340 return Err(DecodeError::TensorCallback(failure));
341 }
342
343 match NonZeroI32::new(result) {
344 None => {
345 self.initialized_logits
346 .clone_from(&batch.initialized_logits);
347 Ok(())
348 }
349 Some(error) => Err(DecodeError::from(error)),
350 }
351 }
352
353 /// Run an entry-wise [`LlamaBatchExt`] through this context's encoder or
354 /// decoder.
355 ///
356 /// This is `llama_process`, upstream's entry point for the
357 /// `llama_batch_ext` API. Use it when the batch needs something
358 /// [`LlamaBatch`] cannot express — per-entry embeddings, M-RoPE positions,
359 /// or an MTP state embedding. For a plain token batch,
360 /// [`Self::decode`] and [`Self::encode`] are the same work with less
361 /// ceremony.
362 ///
363 /// # Decode lifecycle hooks do not apply
364 ///
365 /// This crate's tensor transactions
366 /// ([`LlamaContextParams::with_tensor_transactions`](crate::context::params::LlamaContextParams))
367 /// are driven by hooks this repo patches into `llama_decode`.
368 /// `llama_process` reaches the graph without passing through it, and the
369 /// hook signature is built around `llama_batch`, so it cannot describe an
370 /// entry-wise batch at all. Rather than run the batch with the transactions
371 /// silently inert, this returns
372 /// [`ProcessError::TensorTransactionsUnsupported`].
373 ///
374 /// # Errors
375 ///
376 /// - [`ProcessError::ContextMismatch`] if `batch` was built for a
377 /// different context — it borrows its originating context's batch size,
378 /// sequence count and memory module, so it is not transferable.
379 /// - [`ProcessError::TensorTransactionsUnsupported`] as described above.
380 /// - [`ProcessError::IncompleteEntry`] if an entry carries no input; see
381 /// [`LlamaBatchExt::has_incomplete_entry`].
382 /// - Otherwise whatever `llama_decode` would report; the return codes are
383 /// the same.
384 pub fn process(
385 &mut self,
386 batch: &mut LlamaBatchExt,
387 kind: LlamaProcessType,
388 ) -> Result<(), ProcessError> {
389 if batch.ctx_id != self.id {
390 return Err(ProcessError::ContextMismatch);
391 }
392 if self.tensor_transactions.is_some() {
393 return Err(ProcessError::TensorTransactionsUnsupported);
394 }
395 if let Some(entry) = batch.first_incomplete_entry() {
396 return Err(ProcessError::IncompleteEntry(entry));
397 }
398
399 // SAFETY: `self.context` is non-null and kept alive by this borrow, and
400 // `batch` belongs to this context — checked against `batch.ctx_id`
401 // above — with every entry confirmed complete, so llama.cpp will not
402 // read an uninitialised one. Failure comes back as a return code.
403 let result = unsafe {
404 llama_cpp_sys_4::llama_process(self.context.as_ptr(), kind.into(), batch.as_ptr())
405 };
406
407 match NonZeroI32::new(result) {
408 None => {
409 self.initialized_logits
410 .clone_from(&batch.initialized_logits);
411 Ok(())
412 }
413 Some(error) => Err(ProcessError::from(error)),
414 }
415 }
416
417 /// Reserve a compute graph for a batch of the given shape, returning how
418 /// big it is.
419 ///
420 /// Two uses. As **warmup**, it forces the graph build and buffer
421 /// allocation that the first real decode would otherwise pay for, so
422 /// first-token latency stops being an outlier. As **measurement**, the
423 /// returned node count is the graph's size for that shape, which
424 /// is what
425 /// [`PerfContextData::n_reallocs_diff`](crate::context::perf::PerfContextData::n_reallocs_diff)
426 /// counts changes in.
427 ///
428 /// Reserve the shapes you actually decode — typically one for prefill
429 /// (`n_tokens = n_batch`) and one for single-token generation.
430 ///
431 /// # Why this does not hand back the graph
432 ///
433 /// `llama_graph_reserve` returns a `ggml_cgraph *` that upstream documents
434 /// as valid only *until the next call to `llama_graph_reserve`* — it is
435 /// owned by the context and reused. Returning it would be a borrow this
436 /// type cannot enforce, so the counts come back instead; they are the part
437 /// a caller can act on.
438 ///
439 /// # Errors
440 ///
441 /// Returns [`ReserveGraphError`] if llama.cpp could not build a graph for
442 /// that shape, which is what an over-large `n_tokens` or `n_outputs` looks
443 /// like.
444 pub fn reserve_graph(
445 &mut self,
446 n_tokens: u32,
447 n_seqs: u32,
448 n_outputs: u32,
449 ) -> Result<GraphReservation, ReserveGraphError> {
450 // SAFETY: a live `&mut self` gives an exclusive, non-null context, and
451 // the three arguments are scalars llama.cpp range-checks itself. The
452 // returned pointer is only read here and never escapes — see the note
453 // above on its lifetime.
454 let graph = unsafe {
455 llama_cpp_sys_4::llama_graph_reserve(self.context.as_ptr(), n_tokens, n_seqs, n_outputs)
456 };
457 if graph.is_null() {
458 return Err(ReserveGraphError {
459 n_tokens,
460 n_seqs,
461 n_outputs,
462 });
463 }
464 // SAFETY: non-null and valid until the next `llama_graph_reserve`,
465 // which cannot happen between here and this read.
466 let n_nodes = unsafe { llama_cpp_sys_4::ggml_graph_n_nodes(graph) };
467 Ok(GraphReservation { n_nodes })
468 }
469
470 /// Returns the owned tensor transaction program attached to this context.
471 #[must_use]
472 pub fn tensor_transactions(&self) -> Option<&TensorTransactions> {
473 self.tensor_transactions.as_deref()
474 }
475
476 /// Returns the owned tensor transaction program attached to this context.
477 ///
478 /// Retained captures can be removed with [`TensorTransactions::take_captures`].
479 pub fn tensor_transactions_mut(&mut self) -> Option<&mut TensorTransactions> {
480 self.tensor_transactions
481 .as_mut()
482 .map(|transactions| transactions.as_mut().get_mut())
483 }
484
485 /// Encodes the batch.
486 ///
487 /// # Errors
488 ///
489 /// - `EncodeError` if the decoding failed.
490 ///
491 /// # Panics
492 ///
493 /// - the returned [`std::ffi::c_int`] from llama-cpp does not fit into a i32 (this should never happen on most systems)
494 pub fn encode(&mut self, batch: &mut LlamaBatch) -> Result<(), EncodeError> {
495 let result =
496 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `batch` is owned by the caller and
497 // valid for the duration of the call.
498 unsafe { llama_cpp_sys_4::llama_encode(self.context.as_ptr(), batch.llama_batch) };
499
500 match NonZeroI32::new(result) {
501 None => {
502 self.initialized_logits
503 .clone_from(&batch.initialized_logits);
504 Ok(())
505 }
506 Some(error) => Err(EncodeError::from(error)),
507 }
508 }
509
510 /// Return Pooling type for Llama's Context
511 #[must_use]
512 pub fn pooling_type(&self) -> LlamaPoolingType {
513 // SAFETY: a plain read through a live context.
514 let pooling_type = unsafe { llama_pooling_type(self.context.as_ptr()) };
515
516 LlamaPoolingType::from(pooling_type)
517 }
518
519 /// Get the embeddings for the `i`th sequence in the current context.
520 ///
521 /// # Returns
522 ///
523 /// A slice containing the embeddings for the last decoded batch.
524 /// The size corresponds to the `n_embd` parameter of the context's model.
525 ///
526 /// # Errors
527 ///
528 /// - When the current context was constructed without enabling embeddings.
529 /// - If the current model had a pooling type of [`llama_cpp_sys_4::LLAMA_POOLING_TYPE_NONE`]
530 /// - If the given sequence index exceeds the max sequence id.
531 ///
532 /// # Panics
533 ///
534 /// * the row width does not fit into a usize
535 pub fn embeddings_seq_ith(&self, i: i32) -> Result<&[f32], EmbeddingsError> {
536 if !self.embeddings_enabled {
537 return Err(EmbeddingsError::NotEnabled);
538 }
539
540 // Technically also possible whenever `i >= max(batch.n_seq)`, but can't
541 // check that here.
542 self.buffer_at(
543 llama_cpp_sys_4::llama_get_embeddings_seq,
544 i,
545 self.embd_seq_row_width(),
546 )
547 .ok_or(EmbeddingsError::NonePoolType)
548 }
549
550 /// Get the embeddings for the `i`th token in the current context.
551 ///
552 /// # Returns
553 ///
554 /// A slice containing the embeddings for the last decoded batch of the given token.
555 /// The size corresponds to [`LlamaModel::n_embd_out`], the model's *output*
556 /// embedding width.
557 ///
558 /// # Errors
559 ///
560 /// - When the current context was constructed without enabling embeddings.
561 /// - When the given token didn't have logits enabled when it was passed.
562 /// - If the given token index exceeds the max token id.
563 ///
564 /// # Panics
565 ///
566 /// * `n_embd_out` does not fit into a usize
567 pub fn embeddings_ith(&self, i: i32) -> Result<&[f32], EmbeddingsError> {
568 if !self.embeddings_enabled {
569 return Err(EmbeddingsError::NotEnabled);
570 }
571
572 // Technically also possible whenever `i >= batch.n_tokens`, but no good
573 // way of checking `n_tokens` here.
574 self.buffer_at(
575 llama_cpp_sys_4::llama_get_embeddings_ith,
576 i,
577 self.embd_row_width(),
578 )
579 .ok_or(EmbeddingsError::LogitsNotEnabled)
580 }
581
582 /// Get the logits for the last token in the context.
583 ///
584 /// # Returns
585 /// An iterator over unsorted `LlamaTokenData` containing the
586 /// logits for the last token in the context.
587 ///
588 /// # Panics
589 ///
590 /// - underlying logits data is null
591 pub fn candidates(&self) -> impl Iterator<Item = LlamaTokenData> + '_ {
592 (0_i32..).zip(self.get_logits()).map(|(i, logit)| {
593 let token = LlamaToken::new(i);
594 LlamaTokenData::new(token, *logit, 0_f32)
595 })
596 }
597
598 /// Get the token data array for the last token in the context.
599 ///
600 /// This is a convience method that implements:
601 /// ```ignore
602 /// LlamaTokenDataArray::from_iter(ctx.candidates(), false)
603 /// ```
604 ///
605 /// # Panics
606 ///
607 /// - underlying logits data is null
608 #[must_use]
609 pub fn token_data_array(&self) -> LlamaTokenDataArray {
610 LlamaTokenDataArray::from_iter(self.candidates(), false)
611 }
612
613 /// Token logits obtained from the last call to `decode()`.
614 /// The logits for which `batch.logits[i] != 0` are stored contiguously
615 /// in the order they have appeared in the batch.
616 /// Rows: number of tokens for which `batch.logits[i] != 0`
617 /// Cols: `n_vocab`
618 ///
619 /// # Returns
620 ///
621 /// A slice containing the logits for the last decoded token.
622 /// The size corresponds to the `n_vocab` parameter of the context's model.
623 ///
624 /// # Panics
625 ///
626 /// - `n_vocab` does not fit into a usize
627 /// - token data returned is null
628 #[must_use]
629 pub fn get_logits(&self) -> &[f32] {
630 self.buffer(llama_cpp_sys_4::llama_get_logits, self.logits_row_width())
631 .expect("logits data for last token is null")
632 }
633
634 /// Get the logits for the ith token in the context.
635 ///
636 /// # Panics
637 ///
638 /// - logit `i` is not initialized.
639 pub fn candidates_ith(&self, i: i32) -> impl Iterator<Item = LlamaTokenData> + '_ {
640 (0_i32..).zip(self.get_logits_ith(i)).map(|(i, logit)| {
641 let token = LlamaToken::new(i);
642 LlamaTokenData::new(token, *logit, 0_f32)
643 })
644 }
645
646 /// Get the logits for the ith token in the context.
647 ///
648 /// # Panics
649 ///
650 /// - `i` is greater than `n_ctx`
651 /// - `n_vocab` does not fit into a usize
652 /// - logit `i` is not initialized.
653 #[must_use]
654 pub fn get_logits_ith(&self, i: i32) -> &[f32] {
655 assert!(
656 self.initialized_logits.contains(&i),
657 "logit {i} is not initialized. only {:?} is",
658 self.initialized_logits
659 );
660 assert!(
661 self.n_ctx() > u32::try_from(i).expect("i does not fit into a u32"),
662 "n_ctx ({}) must be greater than i ({})",
663 self.n_ctx(),
664 i
665 );
666
667 self.buffer_at(
668 llama_cpp_sys_4::llama_get_logits_ith,
669 i,
670 self.logits_row_width(),
671 )
672 .expect("logits data for this token is null")
673 }
674
675 /// Get the number of context tokens per sequence.
676 #[must_use]
677 pub fn n_ctx_seq(&self) -> u32 {
678 self.get(llama_cpp_sys_4::llama_n_ctx_seq)
679 }
680
681 /// Get the maximum number of sequences.
682 #[must_use]
683 pub fn n_seq_max(&self) -> u32 {
684 self.get(llama_cpp_sys_4::llama_n_seq_max)
685 }
686
687 /// Get the number of recurrent-state snapshots per sequence.
688 #[must_use]
689 pub fn n_rs_seq(&self) -> u32 {
690 self.get(llama_cpp_sys_4::llama_n_rs_seq)
691 }
692
693 /// Get the number of threads used for generation.
694 #[must_use]
695 pub fn n_threads(&self) -> i32 {
696 self.get_via_mut(llama_cpp_sys_4::llama_n_threads)
697 }
698
699 /// Get the number of threads used for batch processing.
700 #[must_use]
701 pub fn n_threads_batch(&self) -> i32 {
702 self.get_via_mut(llama_cpp_sys_4::llama_n_threads_batch)
703 }
704
705 /// Set the number of threads used for generation and batch processing.
706 pub fn set_n_threads(&mut self, n_threads: i32, n_threads_batch: i32) {
707 // SAFETY: `self.context` is non-null and kept alive by this borrow; the two counts are plain integers
708 // llama.cpp range-checks itself.
709 unsafe {
710 llama_cpp_sys_4::llama_set_n_threads(self.context.as_ptr(), n_threads, n_threads_batch);
711 }
712 }
713
714 /// Set whether to use causal attention.
715 ///
716 /// If set to `false`, the model will use non-causal attention, which is
717 /// needed for embedding models.
718 pub fn set_causal_attn(&mut self, causal_attn: bool) {
719 // SAFETY: `self.context` is non-null and kept alive by this borrow; the argument is a `bool` with no
720 // validity requirement.
721 unsafe {
722 llama_cpp_sys_4::llama_set_causal_attn(self.context.as_ptr(), causal_attn);
723 }
724 }
725
726 /// Whether the context is currently using causal attention.
727 ///
728 /// The counterpart to [`Self::set_causal_attn`]. Worth reading back rather
729 /// than tracking yourself: the initial value comes from
730 /// [`LlamaContextParams::with_attention_type`](crate::context::params::LlamaContextParams::with_attention_type)
731 /// via the model's own default, not from anything the caller set.
732 #[must_use]
733 pub fn causal_attn(&self) -> bool {
734 self.get(llama_cpp_sys_4::llama_get_causal_attn)
735 }
736
737 /// Set whether to compute embeddings.
738 ///
739 /// This allows toggling embedding mode at runtime (as opposed to only at
740 /// context creation time).
741 pub fn set_embeddings(&mut self, embeddings: bool) {
742 self.embeddings_enabled = embeddings;
743 // SAFETY: `self.context` is non-null and kept alive by this borrow; the argument is a `bool` with no
744 // validity requirement.
745 unsafe {
746 llama_cpp_sys_4::llama_set_embeddings(self.context.as_ptr(), embeddings);
747 }
748 }
749
750 /// Wait for all pending async computations to finish.
751 pub fn synchronize(&mut self) {
752 // SAFETY: `self.context` is non-null and kept alive by this borrow; this only waits for pending work.
753 unsafe {
754 llama_cpp_sys_4::llama_synchronize(self.context.as_ptr());
755 }
756 }
757
758 /// Get all embeddings for the current context.
759 ///
760 /// Returns a slice of all embeddings from the last decoded batch.
761 /// For pooled embeddings use [`embeddings_seq_ith`](Self::embeddings_seq_ith) instead.
762 ///
763 /// # Errors
764 ///
765 /// - When the current context was constructed without enabling embeddings.
766 /// - If the embeddings pointer is null.
767 ///
768 /// # Panics
769 ///
770 /// * `n_embd_out` does not fit into a usize
771 pub fn get_embeddings(&self) -> Result<&[f32], EmbeddingsError> {
772 if !self.embeddings_enabled {
773 return Err(EmbeddingsError::NotEnabled);
774 }
775
776 self.buffer(llama_cpp_sys_4::llama_get_embeddings, self.embd_row_width())
777 .ok_or(EmbeddingsError::LogitsNotEnabled)
778 }
779
780 /// Toggle extraction of next-n embeddings (Rust name: pre-norm) — hidden
781 /// states used by MTP draft heads. Upstream C API: `llama_set_embeddings_nextn`
782 /// (llama.cpp PR #23198 and later renames).
783 ///
784 /// If `masked` is `true`, pre-norm rows are extracted only for tokens
785 /// whose `batch.logits[i]` is non-zero. If `masked` is `false`, rows are
786 /// extracted for every token in the batch regardless of `batch.logits` —
787 /// callers can then leave `batch.logits[i] = false` on prompt-fill
788 /// positions and avoid copying the full logits row for each one.
789 ///
790 /// Upstream's MTP session init configures pre-norm extraction on the target
791 /// and draft contexts automatically. Call this manually only for custom
792 /// speculative setups.
793 pub fn set_embeddings_pre_norm(&mut self, value: bool, masked: bool) {
794 // SAFETY: `self.context` is non-null and kept alive by this borrow; the argument is a `bool` with no
795 // validity requirement.
796 unsafe {
797 llama_cpp_sys_4::llama_set_embeddings_nextn(self.context.as_ptr(), value, masked);
798 }
799 }
800
801 /// Get the full pre-norm embeddings buffer for the last decoded batch.
802 ///
803 /// Returns `None` when pre-norm embeddings are disabled or the buffer
804 /// hasn't been populated. The length of the returned slice is
805 /// `n_embd_out * <number of pre-norm rows>` — interpretation of the row
806 /// count depends on whether the setter was called with `masked=true`
807 /// (one row per sampled token) or `masked=false` (one row per batch
808 /// token). Use [`get_embeddings_pre_norm_ith`](Self::get_embeddings_pre_norm_ith)
809 /// when you only need a single row.
810 ///
811 /// # Panics
812 ///
813 /// Panics if `n_embd` does not fit in `usize`.
814 #[must_use]
815 pub fn get_embeddings_pre_norm(&self) -> Option<&[f32]> {
816 self.buffer(
817 llama_cpp_sys_4::llama_get_embeddings_nextn,
818 self.embd_row_width(),
819 )
820 }
821
822 /// Get the pre-norm embedding row for the `i`th output position of the
823 /// last decoded batch. Returns `None` if upstream rejects the index
824 /// (e.g. masked mode with `batch.logits[i] == 0`, or out of range).
825 ///
826 /// # Panics
827 ///
828 /// Panics if `n_embd` does not fit in `usize`.
829 #[must_use]
830 pub fn get_embeddings_pre_norm_ith(&self, i: i32) -> Option<&[f32]> {
831 self.buffer_at(
832 llama_cpp_sys_4::llama_get_embeddings_nextn_ith,
833 i,
834 self.embd_row_width(),
835 )
836 }
837
838 /// Whether `decode` accepts entries added with
839 /// [`LlamaBatchExt::add_embd_row`](crate::llama_batch_ext::LlamaBatchExt).
840 ///
841 /// Needs a DFlash/DSpark decoder context whose paired context has a layer
842 /// input device buffer. Wraps `llama_supports_embd_row`, new in `b12388`.
843 #[must_use]
844 pub fn supports_embd_row(&self) -> bool {
845 self.get(llama_cpp_sys_4::llama_supports_embd_row)
846 }
847
848 /// Keep the unmasked pre-norm rows in a device buffer instead of copying
849 /// them to host memory after every decode.
850 ///
851 /// Returns `false` when the buffer cannot be used, in which case the rows
852 /// are extracted to host memory as before — so a `false` here is a
853 /// fallback, not an error. Wraps `llama_set_embeddings_nextn_dev`, new in
854 /// `b12388`.
855 pub fn set_embeddings_pre_norm_device(&mut self, value: bool) -> bool {
856 // SAFETY: `self.context` is non-null and kept alive by this borrow; the
857 // argument is a `bool` with no validity requirement.
858 unsafe { llama_cpp_sys_4::llama_set_embeddings_nextn_dev(self.context.as_ptr(), value) }
859 }
860
861 /// Copy rows out of the pre-norm device buffer, starting at `row0`.
862 ///
863 /// How many rows are read is derived from `out`: the buffer is
864 /// `[n_embd_out, n_batch + n_seq_max]`, so `out` must be a whole number of
865 /// `n_embd_out`-wide rows. Taking the count from the slice rather than as
866 /// a separate argument is deliberate — a caller-supplied row count that
867 /// disagreed with the buffer is exactly the shape of
868 /// [#360](https://github.com/eugenehp/llama-cpp-rs/issues/360).
869 ///
870 /// Wraps `llama_get_embeddings_nextn_rows`, new in `b12388`.
871 ///
872 /// # Errors
873 ///
874 /// Returns [`NextnRowsError::Shape`] when `out` is not a whole number of
875 /// rows, and [`NextnRowsError::Unavailable`] when llama.cpp declines —
876 /// either because the device buffer was never enabled with
877 /// [`set_embeddings_pre_norm_device`](Self::set_embeddings_pre_norm_device),
878 /// or because `row0` plus the rows in `out` run past the end of it.
879 pub fn get_embeddings_pre_norm_rows(
880 &mut self,
881 row0: i64,
882 out: &mut [f32],
883 ) -> Result<usize, NextnRowsError> {
884 let n_rows = Self::rows_in(out.len(), self.embd_row_width())?;
885 // SAFETY: `self.context` is non-null and kept alive by this exclusive
886 // borrow, and `out`'s pointer is paired with a row count computed from
887 // its own length times the width llama.cpp allocates, so it cannot be
888 // written past.
889 let ok = unsafe {
890 llama_cpp_sys_4::llama_get_embeddings_nextn_rows(
891 self.context.as_ptr(),
892 row0,
893 n_rows,
894 out.as_mut_ptr(),
895 )
896 };
897 if ok {
898 Ok(usize::try_from(n_rows).unwrap_or(0))
899 } else {
900 Err(NextnRowsError::Unavailable)
901 }
902 }
903
904 /// Copy rows into the pre-norm device buffer, starting at `row0`.
905 ///
906 /// The row count comes from `data`, as in
907 /// [`get_embeddings_pre_norm_rows`](Self::get_embeddings_pre_norm_rows).
908 /// Rows at and above `n_batch` are the ones reserved for the caller.
909 ///
910 /// Wraps `llama_set_embeddings_nextn_rows`, new in `b12388`.
911 ///
912 /// # Errors
913 ///
914 /// As [`get_embeddings_pre_norm_rows`](Self::get_embeddings_pre_norm_rows).
915 pub fn set_embeddings_pre_norm_rows(
916 &mut self,
917 row0: i64,
918 data: &[f32],
919 ) -> Result<usize, NextnRowsError> {
920 let n_rows = Self::rows_in(data.len(), self.embd_row_width())?;
921 // SAFETY: as the getter above, with `data` read rather than written.
922 let ok = unsafe {
923 llama_cpp_sys_4::llama_set_embeddings_nextn_rows(
924 self.context.as_ptr(),
925 row0,
926 n_rows,
927 data.as_ptr(),
928 )
929 };
930 if ok {
931 Ok(usize::try_from(n_rows).unwrap_or(0))
932 } else {
933 Err(NextnRowsError::Unavailable)
934 }
935 }
936
937 /// Read batch state rows from `src`'s pre-norm device buffer.
938 ///
939 /// Returns whether `decode` will accept batches carrying state rows —
940 /// `false` unless this is an MTP context and `src`'s buffer has the width
941 /// the MTP graph expects. Wraps `llama_set_ctx_state_src`, new in
942 /// `b12388`.
943 ///
944 /// # Safety
945 ///
946 /// llama.cpp keeps the pointer to `src` in this context's parameters and
947 /// reads through it on every subsequent decode, so the borrow ending does
948 /// not end the aliasing: `src` must stay alive until this context is
949 /// dropped or the pairing is dropped with
950 /// [`clear_ctx_state_src`](Self::clear_ctx_state_src). Dropping `src`
951 /// first and decoding again reads freed memory.
952 ///
953 /// This mirrors
954 /// [`LlamaContextParams::with_ctx_other`](crate::context::params::LlamaContextParams::with_ctx_other),
955 /// which pairs contexts the same way at construction time.
956 pub unsafe fn set_ctx_state_src(&mut self, src: &Self) -> bool {
957 // SAFETY: both contexts are live and non-null here — this one through
958 // an exclusive borrow, `src` through a shared one. Keeping `src` alive
959 // past the call is the caller's half of the contract, documented above.
960 unsafe {
961 llama_cpp_sys_4::llama_set_ctx_state_src(self.context.as_ptr(), src.context.as_ptr())
962 }
963 }
964
965 /// Drop the pairing made by
966 /// [`set_ctx_state_src`](Self::set_ctx_state_src).
967 ///
968 /// This is what makes outliving the source context optional: clear the
969 /// pointer and the source is free to be dropped. Always returns `false`,
970 /// since a context with no state source accepts no state rows.
971 pub fn clear_ctx_state_src(&mut self) -> bool {
972 // SAFETY: `self.context` is live and non-null, and upstream reads
973 // `ctx_src` only to store it — a null source is how it spells "none".
974 unsafe {
975 llama_cpp_sys_4::llama_set_ctx_state_src(self.context.as_ptr(), std::ptr::null_mut())
976 }
977 }
978
979 /// Rows in a buffer of `len` floats, or an error if it is not a whole
980 /// number of them.
981 fn rows_in(len: usize, width: usize) -> Result<i64, NextnRowsError> {
982 if width == 0 || !len.is_multiple_of(width) {
983 return Err(NextnRowsError::Shape { len, width });
984 }
985 i64::try_from(len / width).map_err(|_| NextnRowsError::Shape { len, width })
986 }
987
988 /// Select which `NextN` block the MTP draft graph runs.
989 ///
990 /// `offset` indexes past the trunk transformer layers (`0` = first `NextN`
991 /// head). Required for multi-head MTP models such as Step3.5; restore to
992 /// `0` after drafting. See [`crate::mtp`] for the full speculative loop.
993 ///
994 /// # Examples
995 ///
996 /// ```no_run
997 /// # use llama_cpp_4::model::LlamaModel;
998 /// # use llama_cpp_4::mtp::MtpSession;
999 /// # use llama_cpp_4::token::LlamaToken;
1000 /// # fn f(model: &LlamaModel, session: &mut MtpSession<'_, '_>, n_past: i32,
1001 /// # last_token: LlamaToken) -> Result<(), Box<dyn std::error::Error>> {
1002 /// for head in 0..model.n_layer_nextn() {
1003 /// // Via the session: it borrows the draft context exclusively.
1004 /// session.draft_context_mut().set_nextn_layer_offset(head);
1005 /// let drafts = session.draft(0, n_past, last_token)?;
1006 /// }
1007 /// session.draft_context_mut().set_nextn_layer_offset(0);
1008 /// # Ok(())
1009 /// # }
1010 /// ```
1011 pub fn set_nextn_layer_offset(&mut self, offset: i32) {
1012 // SAFETY: `self.context` is non-null and kept alive by this borrow; the offset is a plain scalar
1013 // llama.cpp validates itself.
1014 unsafe {
1015 llama_cpp_sys_4::llama_set_nextn_layer_offset(self.context.as_ptr(), offset);
1016 }
1017 }
1018
1019 /// Return the paired context set via
1020 /// [`crate::context::params::LlamaContextParams::with_ctx_other`].
1021 ///
1022 /// The pointer refers to the other live context created during
1023 /// [`crate::model::LlamaModel::new_context`]; it is `None` when no pairing
1024 /// was configured.
1025 #[must_use]
1026 pub fn ctx_other(&self) -> Option<NonNull<llama_cpp_sys_4::llama_context>> {
1027 NonNull::new(self.get_via_mut(llama_cpp_sys_4::llama_get_ctx_other))
1028 }
1029
1030 /// Reset the timings for the context.
1031 pub fn reset_timings(&mut self) {
1032 // SAFETY: no pointer is involved; this initialises ggml's global timer and is
1033 // safe to call more than once.
1034 unsafe { llama_cpp_sys_4::ggml_time_init() }
1035 }
1036
1037 /// Returns the timings for the context.
1038 pub fn timings(&mut self) -> PerfContextData {
1039 let perf_context_data = self.get(llama_cpp_sys_4::llama_perf_context);
1040 PerfContextData { perf_context_data }
1041 }
1042
1043 /// Reset the performance counters for the context.
1044 pub fn perf_context_reset(&mut self) {
1045 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `&mut self` rules out a
1046 // concurrent read of the counters being reset.
1047 unsafe { llama_cpp_sys_4::llama_perf_context_reset(self.context.as_ptr()) }
1048 }
1049
1050 /// Check if the KV cache memory supports shifting.
1051 #[must_use]
1052 pub fn memory_can_shift(&self) -> bool {
1053 // SAFETY: `self.context` is non-null and kept alive by this borrow, so the memory handle it returns is
1054 // borrowed from that context and valid for the rest of this block.
1055 unsafe {
1056 let mem = llama_cpp_sys_4::llama_get_memory(self.context.as_ptr());
1057 llama_cpp_sys_4::llama_memory_can_shift(mem)
1058 }
1059 }
1060
1061 /// Get the minimum position in a sequence's KV cache.
1062 #[must_use]
1063 pub fn memory_seq_pos_min(&self, seq_id: i32) -> i32 {
1064 // SAFETY: `self.context` is non-null and kept alive by this borrow, so the memory handle it returns is
1065 // borrowed from that context and valid for the rest of this block.
1066 unsafe {
1067 let mem = llama_cpp_sys_4::llama_get_memory(self.context.as_ptr());
1068 llama_cpp_sys_4::llama_memory_seq_pos_min(mem, seq_id)
1069 }
1070 }
1071
1072 /// Print a human-readable memory breakdown to stderr via llama.cpp.
1073 ///
1074 /// For structured access use [`Self::memory_breakdown`].
1075 pub fn memory_breakdown_print(&self) {
1076 // SAFETY: `self.context` is non-null and kept alive by this borrow; the shim only reads from it and
1077 // writes to llama.cpp's own log.
1078 unsafe {
1079 llama_cpp_sys_4::common_memory_breakdown_print(self.context.as_ptr());
1080 }
1081 }
1082
1083 /// Return structured per-buffer memory usage for this context.
1084 ///
1085 /// Each [`memory_breakdown::MemoryBreakdownEntry`] reports model weights,
1086 /// KV / recurrent cache, and compute scratch bytes for one ggml buffer
1087 /// type. Returns an empty vector when no buffers are registered.
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```no_run
1092 /// use llama_cpp_4::prelude::*;
1093 ///
1094 /// fn main() {
1095 /// let backend = LlamaBackend::init().unwrap();
1096 /// let model = LlamaModel::load_from_file(&backend, "model.gguf", &LlamaModelParams::default()).unwrap();
1097 /// let ctx = model.new_context(&backend, LlamaContextParams::default()).unwrap();
1098 /// let total: usize = ctx.memory_breakdown().iter().map(|e| e.total()).sum();
1099 /// println!("context uses {total} bytes across all buffer types");
1100 /// }
1101 /// ```
1102 #[must_use]
1103 pub fn memory_breakdown(&self) -> Vec<memory_breakdown::MemoryBreakdownEntry> {
1104 memory_breakdown::collect_memory_breakdown(self.context.as_ptr())
1105 }
1106
1107 /// Enable or disable extraction of input embeddings for a transformer layer.
1108 ///
1109 /// Maps to `llama_set_embeddings_layer_inp`. After a successful
1110 /// [`Self::decode`], read the vector with [`Self::get_embeddings_layer_inp`].
1111 pub fn set_embeddings_layer_inp(&mut self, layer_id: u32, value: bool) {
1112 // SAFETY: `self.context` is non-null and kept alive by this borrow; the argument is a `bool` with no
1113 // validity requirement.
1114 unsafe {
1115 llama_cpp_sys_4::llama_set_embeddings_layer_inp(self.context.as_ptr(), layer_id, value);
1116 }
1117 }
1118
1119 /// Keep the enabled layer inputs in a device buffer instead of copying
1120 /// them to host memory after every decode.
1121 ///
1122 /// The buffer is `[n_layer_inp * n_embd, n_batch]`, row `r` holding the
1123 /// token at batch index `r` with the layers in ascending id order. It is
1124 /// not readable from Rust — the point is that it stays on the device: a
1125 /// paired `DFlash`/`DSpark` decoder reads it directly, which is what makes
1126 /// [`supports_embd_row`](Self::supports_embd_row) true and
1127 /// [`LlamaBatchExt::add_embd_row`](crate::llama_batch_ext::LlamaBatchExt::add_embd_row)
1128 /// usable on the paired context.
1129 ///
1130 /// Call [`set_embeddings_layer_inp`](Self::set_embeddings_layer_inp) first
1131 /// — the buffer is sized from the layers that are enabled when it is
1132 /// allocated. Wraps `llama_set_embeddings_layer_inp_dev`, new in `b12388`.
1133 pub fn set_embeddings_layer_inp_device(&mut self, value: bool) {
1134 // SAFETY: `self.context` is non-null and kept alive by this borrow; the
1135 // argument is a `bool` with no validity requirement.
1136 unsafe {
1137 llama_cpp_sys_4::llama_set_embeddings_layer_inp_dev(self.context.as_ptr(), value);
1138 }
1139 }
1140
1141 /// Get input embeddings for `layer_id` from the last decoded batch.
1142 ///
1143 /// Returns `None` when the layer was not enabled via
1144 /// [`Self::set_embeddings_layer_inp`] or when upstream has no data for
1145 /// `layer_id`. The slice length is [`LlamaModel::n_embd`].
1146 ///
1147 /// # Panics
1148 ///
1149 /// Panics if `n_embd` does not fit in `usize`.
1150 #[must_use]
1151 pub fn get_embeddings_layer_inp(&self, layer_id: u32) -> Option<&[f32]> {
1152 // `n_embd()` here is deliberate, unlike every other buffer on this
1153 // type, which take `n_embd_out()`. These rows are layer *inputs*:
1154 // llama.cpp allocates `embd_layer_inp[lid]` as `n_embd * n_batch` and
1155 // asserts `row_floats == hparams.n_embd` when filling it. The output
1156 // width does not apply.
1157 let n_embd =
1158 usize::try_from(self.model.n_embd()).expect("n_embd does not fit into a usize");
1159 self.buffer_at(
1160 llama_cpp_sys_4::llama_get_embeddings_layer_inp,
1161 layer_id,
1162 n_embd,
1163 )
1164 }
1165
1166 /// Get the size of the full context state in bytes.
1167 ///
1168 /// This is the size needed for [`state_get_data`](Self::state_get_data) and
1169 /// [`state_set_data`](Self::state_set_data).
1170 #[must_use]
1171 pub fn state_get_size(&mut self) -> usize {
1172 self.get_via_mut(llama_cpp_sys_4::llama_state_get_size)
1173 }
1174
1175 /// Copy the full context state into a byte buffer.
1176 ///
1177 /// The buffer must be at least [`state_get_size`](Self::state_get_size) bytes.
1178 ///
1179 /// Returns the number of bytes written.
1180 pub fn state_get_data(&mut self, dst: &mut [u8]) -> usize {
1181 // SAFETY: `self.context` is non-null and kept alive by this borrow, and the destination is a Rust buffer
1182 // whose length is passed alongside it, so llama.cpp cannot write past it.
1183 unsafe {
1184 llama_cpp_sys_4::llama_state_get_data(
1185 self.context.as_ptr(),
1186 dst.as_mut_ptr(),
1187 dst.len(),
1188 )
1189 }
1190 }
1191
1192 /// Restore the full context state from a byte buffer.
1193 ///
1194 /// Returns the number of bytes read.
1195 pub fn state_set_data(&mut self, src: &[u8]) -> usize {
1196 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `src` is a Rust slice whose
1197 // pointer and length are passed together, so the read stays in bounds.
1198 unsafe {
1199 llama_cpp_sys_4::llama_state_set_data(self.context.as_ptr(), src.as_ptr(), src.len())
1200 }
1201 }
1202
1203 /// Save the context state to a file along with the given tokens.
1204 ///
1205 /// Returns `true` on success.
1206 ///
1207 /// # Panics
1208 ///
1209 /// Panics if the path contains null bytes.
1210 pub fn state_save_file(
1211 &mut self,
1212 path: impl AsRef<std::path::Path>,
1213 tokens: &[LlamaToken],
1214 ) -> bool {
1215 let path_str = path.as_ref().to_str().expect("path is not valid UTF-8");
1216 let c_path = std::ffi::CString::new(path_str).expect("path contains null bytes");
1217 // SAFETY: `self.context` is non-null and kept alive by this borrow; the path is a `CString` alive for the
1218 // call, and the token pointer and count come from the same slice.
1219 unsafe {
1220 llama_cpp_sys_4::llama_state_save_file(
1221 self.context.as_ptr(),
1222 c_path.as_ptr(),
1223 tokens.as_ptr().cast(),
1224 tokens.len(),
1225 )
1226 }
1227 }
1228
1229 /// Load a context state from a file.
1230 ///
1231 /// Returns `true` on success and fills `tokens_out` with the saved tokens.
1232 ///
1233 /// # Panics
1234 ///
1235 /// Panics if the path contains null bytes.
1236 pub fn state_load_file(
1237 &mut self,
1238 path: impl AsRef<std::path::Path>,
1239 tokens_out: &mut Vec<LlamaToken>,
1240 n_token_capacity: usize,
1241 ) -> bool {
1242 tokens_out.resize(n_token_capacity, LlamaToken(0));
1243 let mut n_token_count: usize = 0;
1244 let path_str = path.as_ref().to_str().expect("path is not valid UTF-8");
1245 let c_path = std::ffi::CString::new(path_str).expect("path contains null bytes");
1246 // SAFETY: `self.context` is non-null and kept alive by this borrow; the path is a `CString` alive for the
1247 // call, and the output buffer's capacity is passed with it.
1248 let ok = unsafe {
1249 llama_cpp_sys_4::llama_state_load_file(
1250 self.context.as_ptr(),
1251 c_path.as_ptr(),
1252 tokens_out.as_mut_ptr().cast(),
1253 n_token_capacity,
1254 std::ptr::addr_of_mut!(n_token_count),
1255 )
1256 };
1257 if ok {
1258 tokens_out.truncate(n_token_count);
1259 }
1260 ok
1261 }
1262
1263 /// Get the size of a single sequence's state in bytes.
1264 #[must_use]
1265 pub fn state_seq_get_size(&mut self, seq_id: i32) -> usize {
1266 // SAFETY: a read through a live context; `seq_id` is validated by llama.cpp.
1267 unsafe { llama_cpp_sys_4::llama_state_seq_get_size(self.context.as_ptr(), seq_id) }
1268 }
1269
1270 /// Copy a single sequence's state into a byte buffer.
1271 ///
1272 /// Returns the number of bytes written.
1273 pub fn state_seq_get_data(&mut self, dst: &mut [u8], seq_id: i32) -> usize {
1274 // SAFETY: `self.context` is non-null and kept alive by this borrow, and the destination buffer's length
1275 // is passed with its pointer.
1276 unsafe {
1277 llama_cpp_sys_4::llama_state_seq_get_data(
1278 self.context.as_ptr(),
1279 dst.as_mut_ptr(),
1280 dst.len(),
1281 seq_id,
1282 )
1283 }
1284 }
1285
1286 /// Restore a single sequence's state from a byte buffer.
1287 ///
1288 /// Returns the number of bytes read.
1289 pub fn state_seq_set_data(&mut self, src: &[u8], dest_seq_id: i32) -> usize {
1290 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `src` is a Rust slice passed as
1291 // pointer plus length.
1292 unsafe {
1293 llama_cpp_sys_4::llama_state_seq_set_data(
1294 self.context.as_ptr(),
1295 src.as_ptr(),
1296 src.len(),
1297 dest_seq_id,
1298 )
1299 }
1300 }
1301
1302 /// Save a single sequence's state to a file.
1303 ///
1304 /// Returns the number of bytes written (0 on failure).
1305 ///
1306 /// # Panics
1307 ///
1308 /// Panics if the path contains null bytes.
1309 pub fn state_seq_save_file(
1310 &mut self,
1311 path: impl AsRef<std::path::Path>,
1312 seq_id: i32,
1313 tokens: &[LlamaToken],
1314 ) -> usize {
1315 let path_str = path.as_ref().to_str().expect("path is not valid UTF-8");
1316 let c_path = std::ffi::CString::new(path_str).expect("path contains null bytes");
1317 // SAFETY: `self.context` is non-null and kept alive by this borrow; the path is a `CString` alive for
1318 // the call, and the token pointer and count come from one slice.
1319 unsafe {
1320 llama_cpp_sys_4::llama_state_seq_save_file(
1321 self.context.as_ptr(),
1322 c_path.as_ptr(),
1323 seq_id,
1324 tokens.as_ptr().cast(),
1325 tokens.len(),
1326 )
1327 }
1328 }
1329
1330 /// Load a single sequence's state from a file.
1331 ///
1332 /// Returns the number of bytes read (0 on failure).
1333 ///
1334 /// # Panics
1335 ///
1336 /// Panics if the path contains null bytes.
1337 pub fn state_seq_load_file(
1338 &mut self,
1339 path: impl AsRef<std::path::Path>,
1340 dest_seq_id: i32,
1341 tokens_out: &mut Vec<LlamaToken>,
1342 n_token_capacity: usize,
1343 ) -> usize {
1344 tokens_out.resize(n_token_capacity, LlamaToken(0));
1345 let mut n_token_count: usize = 0;
1346 let path_str = path.as_ref().to_str().expect("path is not valid UTF-8");
1347 let c_path = std::ffi::CString::new(path_str).expect("path contains null bytes");
1348 // SAFETY: `self.context` is non-null and kept alive by this borrow; the path is a `CString` alive for
1349 // the call, and the destination capacity is passed with its pointer.
1350 let ret = unsafe {
1351 llama_cpp_sys_4::llama_state_seq_load_file(
1352 self.context.as_ptr(),
1353 c_path.as_ptr(),
1354 dest_seq_id,
1355 tokens_out.as_mut_ptr().cast(),
1356 n_token_capacity,
1357 std::ptr::addr_of_mut!(n_token_count),
1358 )
1359 };
1360 if ret > 0 {
1361 tokens_out.truncate(n_token_count);
1362 }
1363 ret
1364 }
1365
1366 /// Set a control vector on the context.
1367 ///
1368 /// # Parameters
1369 ///
1370 /// - `data`: The control vector data (embedding values). Pass an empty slice to clear.
1371 /// - `n_embd`: The embedding dimension.
1372 /// - `il_start`: The starting layer index (inclusive).
1373 /// - `il_end`: The ending layer index (exclusive).
1374 ///
1375 /// # Errors
1376 ///
1377 /// Returns `Err` with the error code if the operation fails.
1378 pub fn set_adapter_cvec(
1379 &mut self,
1380 data: &[f32],
1381 n_embd: i32,
1382 il_start: i32,
1383 il_end: i32,
1384 ) -> Result<(), i32> {
1385 // SAFETY: `self.context` is non-null and kept alive by this borrow; the control-vector data is a Rust
1386 // slice whose pointer and length are passed together.
1387 let ret = unsafe {
1388 llama_cpp_sys_4::llama_set_adapter_cvec(
1389 self.context.as_ptr(),
1390 data.as_ptr(),
1391 data.len(),
1392 n_embd,
1393 il_start,
1394 il_end,
1395 )
1396 };
1397 if ret != 0 {
1398 Err(ret)
1399 } else {
1400 Ok(())
1401 }
1402 }
1403
1404 /// Get sampled token debug info for the `i`th position.
1405 ///
1406 /// Returns the sampled token at position `i` from the last decode call.
1407 #[must_use]
1408 pub fn get_sampled_token_ith(&self, i: i32) -> LlamaToken {
1409 let token =
1410 // SAFETY: a read through a live context; llama.cpp range-checks `i`.
1411 unsafe { llama_cpp_sys_4::llama_get_sampled_token_ith(self.context.as_ptr(), i) };
1412 LlamaToken(token)
1413 }
1414
1415 /// Get sampled candidate tokens for the `i`th position.
1416 ///
1417 /// Returns a slice of candidate tokens from the last decode call.
1418 #[must_use]
1419 pub fn get_sampled_candidates_ith(&self, i: i32) -> &[LlamaToken] {
1420 // SAFETY: a read through a live context; llama.cpp range-checks `i`.
1421 let count = unsafe {
1422 llama_cpp_sys_4::llama_get_sampled_candidates_count_ith(self.context.as_ptr(), i)
1423 } as usize;
1424 if count == 0 {
1425 return &[];
1426 }
1427 let ptr =
1428 // SAFETY: a read through a live context; the returned pointer is checked
1429 // for null immediately below.
1430 unsafe { llama_cpp_sys_4::llama_get_sampled_candidates_ith(self.context.as_ptr(), i) };
1431 if ptr.is_null() {
1432 return &[];
1433 }
1434 // SAFETY: `ptr` is non-null (checked just above) and `count` came from
1435 // llama.cpp's own count accessor for this same row, so it matches the
1436 // allocation. `LlamaToken` is `#[repr(transparent)]` over `llama_token`,
1437 // so the cast is a layout no-op.
1438 unsafe { slice::from_raw_parts(ptr.cast::<LlamaToken>(), count) }
1439 }
1440
1441 /// Get the number of sampled logits for the `i`th position.
1442 #[must_use]
1443 pub fn get_sampled_logits_count_ith(&self, i: i32) -> u32 {
1444 // SAFETY: a read through a live context; llama.cpp range-checks `i`.
1445 unsafe { llama_cpp_sys_4::llama_get_sampled_logits_count_ith(self.context.as_ptr(), i) }
1446 }
1447
1448 /// Get sampled logits for the `i`th position.
1449 ///
1450 /// Returns a slice of logit values from the last decode call.
1451 #[must_use]
1452 pub fn get_sampled_logits_ith(&self, i: i32) -> &[f32] {
1453 let count = self.get_sampled_logits_count_ith(i) as usize;
1454 // `buffer_at` already returns `None` for a null pointer or a zero
1455 // length, which is what an uninitialised row looks like here.
1456 self.buffer_at(llama_cpp_sys_4::llama_get_sampled_logits_ith, i, count)
1457 .unwrap_or(&[])
1458 }
1459
1460 /// Get the number of sampled probabilities for the `i`th position.
1461 #[must_use]
1462 pub fn get_sampled_probs_count_ith(&self, i: i32) -> u32 {
1463 // SAFETY: a read through a live context; llama.cpp range-checks `i`.
1464 unsafe { llama_cpp_sys_4::llama_get_sampled_probs_count_ith(self.context.as_ptr(), i) }
1465 }
1466
1467 /// Get sampled probabilities for the `i`th position.
1468 ///
1469 /// Returns a slice of probability values from the last decode call.
1470 #[must_use]
1471 pub fn get_sampled_probs_ith(&self, i: i32) -> &[f32] {
1472 let count = self.get_sampled_probs_count_ith(i) as usize;
1473 // `buffer_at` already returns `None` for a null pointer or a zero
1474 // length, which is what an uninitialised row looks like here.
1475 self.buffer_at(llama_cpp_sys_4::llama_get_sampled_probs_ith, i, count)
1476 .unwrap_or(&[])
1477 }
1478
1479 /// Get the size of a single sequence's state with flags.
1480 #[must_use]
1481 pub fn state_seq_get_size_ext(&mut self, seq_id: i32, flags: u32) -> usize {
1482 // SAFETY: a read through a live context; `seq_id` is validated by llama.cpp.
1483 unsafe {
1484 llama_cpp_sys_4::llama_state_seq_get_size_ext(self.context.as_ptr(), seq_id, flags)
1485 }
1486 }
1487
1488 /// Copy a single sequence's state into a byte buffer with flags.
1489 ///
1490 /// Returns the number of bytes written.
1491 pub fn state_seq_get_data_ext(&mut self, dst: &mut [u8], seq_id: i32, flags: u32) -> usize {
1492 // SAFETY: `self.context` is non-null and kept alive by this borrow, and the destination buffer's length
1493 // is passed with its pointer.
1494 unsafe {
1495 llama_cpp_sys_4::llama_state_seq_get_data_ext(
1496 self.context.as_ptr(),
1497 dst.as_mut_ptr(),
1498 dst.len(),
1499 seq_id,
1500 flags,
1501 )
1502 }
1503 }
1504
1505 /// Restore a single sequence's state from a byte buffer with flags.
1506 ///
1507 /// Returns the number of bytes read.
1508 pub fn state_seq_set_data_ext(&mut self, src: &[u8], dest_seq_id: i32, flags: u32) -> usize {
1509 // SAFETY: `self.context` is non-null and kept alive by this borrow, and `src` is a Rust slice passed as
1510 // pointer plus length.
1511 unsafe {
1512 llama_cpp_sys_4::llama_state_seq_set_data_ext(
1513 self.context.as_ptr(),
1514 src.as_ptr(),
1515 src.len(),
1516 dest_seq_id,
1517 flags,
1518 )
1519 }
1520 }
1521
1522 /// Set an abort callback for the context.
1523 ///
1524 /// The callback is called periodically during computation. If it returns `true`,
1525 /// the computation is aborted.
1526 ///
1527 /// # Safety
1528 ///
1529 /// The callback data must remain valid for the lifetime of the context or until
1530 /// the callback is replaced.
1531 pub unsafe fn set_abort_callback(
1532 &mut self,
1533 callback: llama_cpp_sys_4::ggml_abort_callback,
1534 data: *mut std::ffi::c_void,
1535 ) {
1536 llama_cpp_sys_4::llama_set_abort_callback(self.context.as_ptr(), callback, data);
1537 }
1538
1539 /// Attach a thread pool to the context.
1540 ///
1541 /// # Safety
1542 ///
1543 /// The thread pools must remain valid for the lifetime of the context or until
1544 /// they are detached.
1545 pub unsafe fn attach_threadpool(
1546 &mut self,
1547 threadpool: llama_cpp_sys_4::ggml_threadpool_t,
1548 threadpool_batch: llama_cpp_sys_4::ggml_threadpool_t,
1549 ) {
1550 llama_cpp_sys_4::llama_attach_threadpool(
1551 self.context.as_ptr(),
1552 threadpool,
1553 threadpool_batch,
1554 );
1555 }
1556
1557 /// Detach the thread pool from the context.
1558 pub fn detach_threadpool(&mut self) {
1559 // SAFETY: `self.context` is non-null and kept alive by this borrow; detaching is idempotent and leaves the
1560 // pool owned by the caller.
1561 unsafe {
1562 llama_cpp_sys_4::llama_detach_threadpool(self.context.as_ptr());
1563 }
1564 }
1565
1566 /// Set a sampler for a specific sequence.
1567 ///
1568 /// Returns `true` on success.
1569 pub fn set_sampler(
1570 &mut self,
1571 seq_id: i32,
1572 sampler: &mut crate::sampling::LlamaSampler,
1573 ) -> bool {
1574 // SAFETY: `self.context` is non-null and kept alive by this borrow; the sampler outlives the call and
1575 // llama.cpp takes its own reference.
1576 unsafe {
1577 llama_cpp_sys_4::llama_set_sampler(
1578 self.context.as_ptr(),
1579 seq_id,
1580 sampler.sampler.as_ptr(),
1581 )
1582 }
1583 }
1584
1585 /// Get the raw model pointer from this context.
1586 ///
1587 /// This is mainly useful for FFI interop. In normal usage, access
1588 /// the model via the `model` field instead.
1589 #[must_use]
1590 pub fn get_model_ptr(&self) -> *const llama_cpp_sys_4::llama_model {
1591 self.get(llama_cpp_sys_4::llama_get_model)
1592 }
1593
1594 /// Sets a lora adapter.
1595 ///
1596 /// # Errors
1597 ///
1598 /// See [`LlamaLoraAdapterSetError`] for more information.
1599 pub fn lora_adapter_set(
1600 &self,
1601 adapter: &mut LlamaLoraAdapter,
1602 scale: f32,
1603 ) -> Result<(), LlamaLoraAdapterSetError> {
1604 // SAFETY: `self.context` is non-null and kept alive by this borrow; the adapter array is built here and
1605 // stays alive for the call, with its length passed alongside.
1606 let err_code = unsafe {
1607 // llama_set_adapter_lora / llama_rm_adapter_lora were replaced by llama_set_adapters_lora
1608 // which takes a full list of adapters + scales at once (b8249+)
1609 let mut adapter_ptr = adapter.lora_adapter.as_ptr();
1610 let mut scale_val = scale;
1611 llama_cpp_sys_4::llama_set_adapters_lora(
1612 self.context.as_ptr(),
1613 &raw mut adapter_ptr,
1614 1,
1615 &raw mut scale_val,
1616 )
1617 };
1618 if err_code != 0 {
1619 return Err(LlamaLoraAdapterSetError::ErrorResult(err_code));
1620 }
1621
1622 tracing::debug!("Set lora adapter");
1623 Ok(())
1624 }
1625
1626 /// Remove all lora adapters from the context.
1627 ///
1628 /// Note: as of llama.cpp b8249 the per-adapter remove API was replaced by
1629 /// `llama_set_adapters_lora` which operates on the full adapter list at once.
1630 /// Calling this function clears **all** adapters currently set on the context.
1631 ///
1632 /// # Errors
1633 ///
1634 /// See [`LlamaLoraAdapterRemoveError`] for more information.
1635 pub fn lora_adapter_remove(
1636 &self,
1637 _adapter: &mut LlamaLoraAdapter,
1638 ) -> Result<(), LlamaLoraAdapterRemoveError> {
1639 // SAFETY: `self.context` is non-null and kept alive by this borrow; the adapter array is built here and
1640 // stays alive for the call, with its length passed alongside.
1641 let err_code = unsafe {
1642 llama_cpp_sys_4::llama_set_adapters_lora(
1643 self.context.as_ptr(),
1644 std::ptr::null_mut(),
1645 0,
1646 std::ptr::null_mut(),
1647 )
1648 };
1649 if err_code != 0 {
1650 return Err(LlamaLoraAdapterRemoveError::ErrorResult(err_code));
1651 }
1652
1653 tracing::debug!("Remove lora adapter");
1654 Ok(())
1655 }
1656}
1657
1658impl Drop for LlamaContext<'_> {
1659 fn drop(&mut self) {
1660 // SAFETY: this is the only place the context is freed, `Drop` runs once, and
1661 // nothing reads `self.context` afterwards.
1662 unsafe { llama_cpp_sys_4::llama_free(self.context.as_ptr()) }
1663 }
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668 use super::{LlamaContext, NextnRowsError};
1669
1670 /// The row count handed to llama.cpp is derived from the buffer, so the
1671 /// derivation is the thing that keeps a short buffer from being written
1672 /// past — the mistake behind
1673 /// [#360](https://github.com/eugenehp/llama-cpp-rs/issues/360).
1674 #[test]
1675 fn rows_in_counts_whole_rows_only() {
1676 assert_eq!(LlamaContext::rows_in(0, 64), Ok(0));
1677 assert_eq!(LlamaContext::rows_in(64, 64), Ok(1));
1678 assert_eq!(LlamaContext::rows_in(192, 64), Ok(3));
1679 }
1680
1681 #[test]
1682 fn rows_in_rejects_a_partial_row() {
1683 assert_eq!(
1684 LlamaContext::rows_in(65, 64),
1685 Err(NextnRowsError::Shape { len: 65, width: 64 })
1686 );
1687 assert_eq!(
1688 LlamaContext::rows_in(63, 64),
1689 Err(NextnRowsError::Shape { len: 63, width: 64 })
1690 );
1691 }
1692
1693 /// A zero width would make every length a whole number of rows and then
1694 /// divide by zero working out how many.
1695 #[test]
1696 fn rows_in_rejects_a_zero_width() {
1697 assert_eq!(
1698 LlamaContext::rows_in(64, 0),
1699 Err(NextnRowsError::Shape { len: 64, width: 0 })
1700 );
1701 }
1702}