Skip to main content

llama_cpp_4/
lib.rs

1//! Bindings to the llama.cpp library.
2//!
3//! As llama.cpp is a very fast moving target, this crate does not attempt to create a stable API
4//! with all the rust idioms. Instead it provides safe wrappers around nearly direct bindings to
5//! llama.cpp. This makes it easier to keep up with the changes in llama.cpp, but does mean that
6//! the API is not as nice as it could be.
7//!
8//! # Quick start
9//!
10//! ```no_run
11//! use llama_cpp_4::prelude::*;
12//! use std::num::NonZeroU32;
13//!
14//! fn main() {
15//!     let backend = LlamaBackend::init().unwrap();
16//!     let model = LlamaModel::load_from_file(
17//!         &backend,
18//!         "model.gguf",
19//!         &LlamaModelParams::default(),
20//!     )
21//!     .unwrap();
22//!     let mut ctx = model
23//!         .new_context(
24//!             &backend,
25//!             LlamaContextParams::default().with_n_ctx(NonZeroU32::new(2048)),
26//!         )
27//!         .unwrap();
28//!
29//!     let tokens = model.str_to_token("Hello, world!", AddBos::Always).unwrap();
30//!     let mut batch = LlamaBatch::new(512, 1);
31//!     for (i, &tok) in tokens.iter().enumerate() {
32//!         batch
33//!             .add(tok, i as i32, &[0], i == tokens.len() - 1)
34//!             .unwrap();
35//!     }
36//!     ctx.decode(&mut batch).unwrap();
37//!
38//!     let token = LlamaSampler::greedy().sample(&ctx, 0);
39//!     let _piece = model.token_to_bytes(token, Special::Plaintext).unwrap();
40//! }
41//! ```
42//!
43//! # Examples in this repository
44//!
45//! - [simple](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/simple)
46//! - [chat](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/chat)
47//! - [embeddings](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/embeddings)
48//! - [server](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/server)
49//! - [mtp](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/mtp) — MTP speculative decoding via [`crate::mtp::MtpSession`]
50//! - [eagle](https://github.com/eugenehp/llama-cpp-rs/tree/main/examples/eagle) — EAGLE-3 speculative decoding via [`crate::eagle::Eagle3Session`]
51//!
52//! # Advanced: tensor capture
53//!
54//! Use [`TensorCapture`] with [`LlamaContextParams::with_tensor_capture`] to read
55//! per-layer hidden states (or other named graph nodes) during
56//! [`LlamaContext::decode`]. See [`context::tensor_capture`] for a full example.
57//!
58//! # Prelude
59//!
60//! For the types used in most inference programs, import [`prelude`]:
61//!
62//! ```
63//! use llama_cpp_4::prelude::*;
64//! ```
65//!
66//! The same core types are also re-exported at the crate root (e.g.
67//! [`LlamaModel`], [`LlamaBackend`]) so you can pick whichever import style
68//! you prefer. See [`prelude`] for a full list and additional examples (chat,
69//! embeddings, memory estimation).
70//!
71//! # Feature Flags
72//!
73//! - `cuda` enables CUDA GPU support.
74//! - `metal` enables Apple Metal GPU support.
75//! - `vulkan` enables Vulkan GPU support (AMD / Intel / cross-platform).
76//! - `native` enables host-CPU optimisations (`-march=native`).
77//! - `openmp` enables OpenMP multi-core CPU parallelism (on by default).
78//! - `rpc` enables RPC backend support for distributed inference across multiple machines.
79//! - `mtmd` enables multimodal (image + audio) support via `libmtmd`.
80use std::ffi::NulError;
81use std::fmt::Debug;
82use std::num::NonZeroI32;
83
84use crate::llama_batch::BatchAddError;
85use std::os::raw::c_int;
86use std::path::PathBuf;
87use std::string::FromUtf8Error;
88
89pub mod common;
90pub mod context;
91pub mod eagle;
92pub mod fit;
93#[cfg(feature = "ggml")]
94pub mod ggml;
95pub mod llama_backend;
96pub mod llama_batch;
97pub mod model;
98pub mod mtp;
99pub mod prelude;
100pub mod quantize;
101pub mod sampling;
102pub mod speculative;
103pub mod token;
104pub mod token_type;
105
106#[cfg(feature = "rpc")]
107pub mod rpc;
108
109#[cfg(feature = "mtmd")]
110pub mod mtmd;
111
112/// A failable result from a llama.cpp function.
113pub type Result<T> = std::result::Result<T, LLamaCppError>;
114
115/// All errors that can occur in the llama-cpp crate.
116#[derive(Debug, Eq, PartialEq, thiserror::Error)]
117pub enum LLamaCppError {
118    /// The backend was already initialized. This can generally be ignored as initializing the backend
119    /// is idempotent.
120    #[error("BackendAlreadyInitialized")]
121    BackendAlreadyInitialized,
122    /// There was an error while get the chat template from model.
123    #[error("{0}")]
124    ChatTemplateError(#[from] ChatTemplateError),
125    /// There was an error while decoding a batch.
126    #[error("{0}")]
127    DecodeError(#[from] DecodeError),
128    /// There was an error while encoding a batch.
129    #[error("{0}")]
130    EncodeError(#[from] EncodeError),
131    /// There was an error loading a model.
132    #[error("{0}")]
133    LlamaModelLoadError(#[from] LlamaModelLoadError),
134    /// There was an error creating a new model context.
135    #[error("{0}")]
136    LlamaContextLoadError(#[from] LlamaContextLoadError),
137    /// There was an error adding a token to a batch.
138    #[error["{0}"]]
139    BatchAddError(#[from] BatchAddError),
140    /// see [`EmbeddingsError`]
141    #[error(transparent)]
142    EmbeddingError(#[from] EmbeddingsError),
143}
144
145/// There was an error while getting the chat template from a model.
146#[derive(Debug, Eq, PartialEq, thiserror::Error)]
147pub enum ChatTemplateError {
148    /// the buffer was too small.
149    #[error("The buffer was too small. However, a buffer size of {0} would be just large enough.")]
150    BuffSizeError(usize),
151    /// gguf has no chat template
152    #[error("the model has no meta val - returned code {0}")]
153    MissingTemplate(i32),
154    /// The chat template was not valid utf8.
155    #[error(transparent)]
156    Utf8Error(#[from] std::str::Utf8Error),
157}
158
159/// Error retrieving a string from the model (e.g. description, metadata key/value).
160#[derive(Debug, Eq, PartialEq, thiserror::Error)]
161pub enum StringFromModelError {
162    /// The C function returned a negative error code.
163    #[error("llama.cpp returned error code {0}")]
164    ReturnedError(i32),
165    /// The returned bytes were not valid UTF-8.
166    #[error(transparent)]
167    Utf8Error(#[from] std::str::Utf8Error),
168}
169
170/// Failed to Load context
171#[derive(Debug, Eq, PartialEq, thiserror::Error)]
172pub enum LlamaContextLoadError {
173    /// llama.cpp returned null
174    #[error("null reference from llama.cpp")]
175    NullReturn,
176}
177
178/// Failed to decode a batch.
179#[derive(Debug, Eq, PartialEq, thiserror::Error)]
180pub enum DecodeError {
181    /// A Rust tensor callback failed or unwound after native execution began.
182    #[error(transparent)]
183    TensorCallback(#[from] context::TensorCallbackFailure),
184    /// No kv cache slot was available.
185    #[error("Decode Error 1: NoKvCacheSlot")]
186    NoKvCacheSlot,
187    /// The number of tokens in the batch was 0.
188    #[error("Decode Error -1: n_tokens == 0")]
189    NTokensZero,
190    /// A decode lifecycle hook vetoed the decode (native returned `-4`). The
191    /// specific cause is normally surfaced via [`DecodeError::TensorCallback`];
192    /// this is the fallback when no Rust-side failure was recorded.
193    #[error("Decode Error -4: vetoed by a decode lifecycle hook")]
194    VetoedByDecodeHook,
195    /// An unknown error occurred.
196    #[error("Decode Error {0}: unknown")]
197    Unknown(c_int),
198}
199
200/// Failed to decode a batch.
201#[derive(Debug, Eq, PartialEq, thiserror::Error)]
202pub enum EncodeError {
203    /// No kv cache slot was available.
204    #[error("Encode Error 1: NoKvCacheSlot")]
205    NoKvCacheSlot,
206    /// The number of tokens in the batch was 0.
207    #[error("Encode Error -1: n_tokens == 0")]
208    NTokensZero,
209    /// An unknown error occurred.
210    #[error("Encode Error {0}: unknown")]
211    Unknown(c_int),
212}
213
214/// When embedding related functions fail
215#[derive(Debug, Eq, PartialEq, thiserror::Error)]
216pub enum EmbeddingsError {
217    /// Embeddings weren't enabled in the context options
218    #[error("Embeddings weren't enabled in the context options")]
219    NotEnabled,
220    /// Logits weren't enabled for the given token
221    #[error("Logits were not enabled for the given token")]
222    LogitsNotEnabled,
223    /// The given sequence index exceeds the max sequence id
224    #[error("Can't use sequence embeddings with a model supporting only LLAMA_POOLING_TYPE_NONE")]
225    NonePoolType,
226}
227
228/// Decode a error from llama.cpp into a [`DecodeError`].
229impl From<NonZeroI32> for DecodeError {
230    fn from(value: NonZeroI32) -> Self {
231        match value.get() {
232            1 => DecodeError::NoKvCacheSlot,
233            -1 => DecodeError::NTokensZero,
234            -4 => DecodeError::VetoedByDecodeHook,
235            i => DecodeError::Unknown(i),
236        }
237    }
238}
239
240/// Encode a error from llama.cpp into a [`EncodeError`].
241impl From<NonZeroI32> for EncodeError {
242    fn from(value: NonZeroI32) -> Self {
243        match value.get() {
244            1 => EncodeError::NoKvCacheSlot,
245            -1 => EncodeError::NTokensZero,
246            i => EncodeError::Unknown(i),
247        }
248    }
249}
250
251/// An error that can occur when loading a model.
252#[derive(Debug, Eq, PartialEq, thiserror::Error)]
253pub enum LlamaModelLoadError {
254    /// There was a null byte in a provided string and thus it could not be converted to a C string.
255    #[error("null byte in string {0}")]
256    NullError(#[from] NulError),
257    /// llama.cpp returned a nullptr - this could be many different causes.
258    #[error("null result from llama cpp")]
259    NullResult,
260    /// Failed to convert the path to a rust str. This means the path was not valid unicode
261    #[error("failed to convert path {0} to str")]
262    PathToStrError(PathBuf),
263}
264
265/// An error that can occur when loading a model.
266#[derive(Debug, Eq, PartialEq, thiserror::Error)]
267pub enum LlamaLoraAdapterInitError {
268    /// There was a null byte in a provided string and thus it could not be converted to a C string.
269    #[error("null byte in string {0}")]
270    NullError(#[from] NulError),
271    /// llama.cpp returned a nullptr - this could be many different causes.
272    #[error("null result from llama cpp")]
273    NullResult,
274    /// Failed to convert the path to a rust str. This means the path was not valid unicode
275    #[error("failed to convert path {0} to str")]
276    PathToStrError(PathBuf),
277}
278
279/// An error that can occur when loading a model.
280#[derive(Debug, Eq, PartialEq, thiserror::Error)]
281pub enum LlamaLoraAdapterSetError {
282    /// llama.cpp returned a non-zero error code.
283    #[error("error code from llama cpp")]
284    ErrorResult(i32),
285}
286
287/// An error that can occur when loading a model.
288#[derive(Debug, Eq, PartialEq, thiserror::Error)]
289pub enum LlamaLoraAdapterRemoveError {
290    /// llama.cpp returned a non-zero error code.
291    #[error("error code from llama cpp")]
292    ErrorResult(i32),
293}
294
295/// get the time (in microseconds) according to llama.cpp
296/// ```
297/// # use llama_cpp_4::llama_time_us;
298/// let time = llama_time_us();
299/// assert!(time > 0);
300/// ```
301#[must_use]
302pub fn llama_time_us() -> i64 {
303    unsafe { llama_cpp_sys_4::llama_time_us() }
304}
305
306/// get the max number of devices according to llama.cpp (this is generally cuda devices)
307/// ```
308/// # use llama_cpp_4::max_devices;
309/// let max_devices = max_devices();
310/// assert!(max_devices >= 0);
311/// ```
312#[must_use]
313pub fn max_devices() -> usize {
314    unsafe { llama_cpp_sys_4::llama_max_devices() }
315}
316
317/// is memory mapping supported according to llama.cpp
318/// ```
319/// # use llama_cpp_4::mmap_supported;
320/// let mmap_supported = mmap_supported();
321/// if mmap_supported {
322///   println!("mmap_supported!");
323/// }
324/// ```
325#[must_use]
326pub fn mmap_supported() -> bool {
327    unsafe { llama_cpp_sys_4::llama_supports_mmap() }
328}
329
330/// is memory locking supported according to llama.cpp
331/// ```
332/// # use llama_cpp_4::mlock_supported;
333/// let mlock_supported = mlock_supported();
334/// if mlock_supported {
335///    println!("mlock_supported!");
336/// }
337/// ```
338#[must_use]
339pub fn mlock_supported() -> bool {
340    unsafe { llama_cpp_sys_4::llama_supports_mlock() }
341}
342
343/// An error that can occur when converting a token to a string.
344#[derive(Debug, thiserror::Error, Clone)]
345#[non_exhaustive]
346pub enum TokenToStringError {
347    /// the token type was unknown
348    #[error("Unknown Token Type")]
349    UnknownTokenType,
350    /// There was insufficient buffer space to convert the token to a string.
351    #[error("Insufficient Buffer Space {0}")]
352    InsufficientBufferSpace(c_int),
353    /// Caller-owned storage exceeds llama.cpp's signed buffer-length type.
354    #[error("piece buffer capacity {0} exceeds the native c_int bound")]
355    BufferCapacityExceeded(usize),
356    /// llama.cpp reported a positive piece length outside the supplied buffer.
357    #[error("native piece length {returned} exceeds buffer capacity {capacity}")]
358    NativePieceLength {
359        /// Positive length returned by llama.cpp.
360        returned: c_int,
361        /// Supplied caller-owned capacity.
362        capacity: usize,
363    },
364    /// The token was not valid utf8.
365    #[error("FromUtf8Error {0}")]
366    FromUtf8Error(#[from] FromUtf8Error),
367}
368
369/// Failed to convert a string to a token sequence.
370#[derive(Debug, thiserror::Error)]
371pub enum StringToTokenError {
372    /// the string contained a null byte and thus could not be converted to a c string.
373    #[error("{0}")]
374    NulError(#[from] NulError),
375    /// The string contained an interior NUL at the reported byte.
376    #[error("input contains an interior NUL at byte {0}")]
377    InteriorNul(usize),
378    #[error("{0}")]
379    /// Failed to convert a provided integer to a [`c_int`].
380    CIntConversionError(#[from] std::num::TryFromIntError),
381    /// llama.cpp reported a positive token count outside the supplied buffer.
382    #[error("native token count {returned} exceeds buffer capacity {capacity}")]
383    NativeTokenCount {
384        /// Positive count returned by llama.cpp.
385        returned: c_int,
386        /// Supplied caller-owned capacity.
387        capacity: usize,
388    },
389}
390
391/// Failed to apply model chat template.
392#[derive(Debug, thiserror::Error)]
393pub enum NewLlamaChatMessageError {
394    /// the string contained a null byte and thus could not be converted to a c string.
395    #[error("{0}")]
396    NulError(#[from] NulError),
397}
398
399/// Failed to apply model chat template.
400#[derive(Debug, thiserror::Error)]
401pub enum ApplyChatTemplateError {
402    /// the buffer was too small.
403    #[error("The buffer was too small. Please contact a maintainer and we will update it.")]
404    BuffSizeError,
405    /// the string contained a null byte and thus could not be converted to a c string.
406    #[error("{0}")]
407    NulError(#[from] NulError),
408    /// the string could not be converted to utf8.
409    #[error("{0}")]
410    FromUtf8Error(#[from] FromUtf8Error),
411}
412
413/// Get the time in microseconds according to ggml
414///
415/// ```
416/// # use std::time::Duration;
417/// use llama_cpp_4::ggml_time_us;
418///
419/// let start = ggml_time_us();
420///
421/// std::thread::sleep(Duration::from_micros(10));
422///
423/// let end = ggml_time_us();
424///
425/// let elapsed = end - start;
426///
427/// assert!(elapsed >= 10)
428#[must_use]
429pub fn ggml_time_us() -> i64 {
430    unsafe { llama_cpp_sys_4::ggml_time_us() }
431}
432
433/// Checks if mlock is supported.
434///
435/// ```
436/// # use llama_cpp_4::llama_supports_mlock;
437///
438/// if llama_supports_mlock() {
439///   println!("mlock is supported!");
440/// } else {
441///   println!("mlock is not supported!");
442/// }
443/// ```
444#[must_use]
445pub fn llama_supports_mlock() -> bool {
446    unsafe { llama_cpp_sys_4::llama_supports_mlock() }
447}
448
449/// Checks if GPU offload is supported.
450///
451/// Returns `true` if the library was compiled with GPU support (CUDA, Metal, Vulkan, etc.).
452#[must_use]
453pub fn supports_gpu_offload() -> bool {
454    unsafe { llama_cpp_sys_4::llama_supports_gpu_offload() }
455}
456
457/// Checks if RPC backend is supported.
458///
459/// Returns `true` if the library was compiled with RPC support.
460#[must_use]
461pub fn supports_rpc() -> bool {
462    unsafe { llama_cpp_sys_4::llama_supports_rpc() }
463}
464
465/// Version of the vendored llama.cpp this crate is linked against.
466///
467/// llama.cpp adopted semantic versioning in `b10470` / `v0.1.1`, so this is a
468/// `MAJOR.MINOR.PATCH` string (with a `-dev` suffix for builds off a
469/// non-release commit) rather than a `bNNNNN` build number. Useful for
470/// reporting the exact upstream a binary carries, since the crate version and
471/// the llama.cpp version move independently.
472///
473/// ```
474/// # use llama_cpp_4::llama_version;
475/// let version = llama_version();
476/// assert!(!version.is_empty());
477/// // e.g. "0.1.1"
478/// assert!(version.starts_with(char::is_numeric));
479/// ```
480///
481/// # Panics
482///
483/// Panics if the returned string is not valid UTF-8.
484#[must_use]
485pub fn llama_version() -> &'static str {
486    // SAFETY: llama.cpp returns a pointer to a string literal baked in at
487    // compile time, so it is non-null and lives for the life of the process.
488    let c_str = unsafe { std::ffi::CStr::from_ptr(llama_cpp_sys_4::llama_version()) };
489    c_str.to_str().expect("llama version is not valid UTF-8")
490}
491
492/// Get system information string.
493///
494/// Returns a string containing CPU features, build info, and other system details.
495///
496/// # Panics
497///
498/// Panics if the returned string is not valid UTF-8.
499#[must_use]
500pub fn print_system_info() -> String {
501    let c_str = unsafe { llama_cpp_sys_4::llama_print_system_info() };
502    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
503    c_str
504        .to_str()
505        .expect("system info is not valid UTF-8")
506        .to_owned()
507}
508
509/// Get the maximum number of parallel sequences supported.
510#[must_use]
511pub fn max_parallel_sequences() -> usize {
512    unsafe { llama_cpp_sys_4::llama_max_parallel_sequences() }
513}
514
515/// Get the maximum number of tensor buffer type overrides.
516#[must_use]
517pub fn max_tensor_buft_overrides() -> usize {
518    unsafe { llama_cpp_sys_4::llama_max_tensor_buft_overrides() }
519}
520
521/// Get the name of a flash attention type.
522///
523/// # Panics
524///
525/// Panics if the returned string is not valid UTF-8.
526#[must_use]
527pub fn flash_attn_type_name(flash_attn_type: i32) -> String {
528    let c_str = unsafe { llama_cpp_sys_4::llama_flash_attn_type_name(flash_attn_type) };
529    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
530    c_str
531        .to_str()
532        .expect("flash_attn_type_name is not valid UTF-8")
533        .to_owned()
534}
535
536/// Get the string representation of a model metadata key.
537///
538/// # Panics
539///
540/// Panics if the returned string is not valid UTF-8.
541#[must_use]
542pub fn model_meta_key_str(key: u32) -> String {
543    let c_str = unsafe { llama_cpp_sys_4::llama_model_meta_key_str(key as _) };
544    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
545    c_str
546        .to_str()
547        .expect("meta_key_str is not valid UTF-8")
548        .to_owned()
549}
550
551/// Quantize a model file using typed [`crate::quantize::QuantizeParams`].
552///
553/// Returns `Ok(())` on success, or `Err(code)` with the non-zero error code
554/// returned by `llama_model_quantize`.
555///
556/// # Panics
557///
558/// Panics if either path contains an interior null byte.
559///
560/// # Errors
561///
562/// Returns `Err(code)` with the non-zero status code from `llama_model_quantize`
563/// when quantization fails.
564///
565/// # Example
566///
567/// ```no_run
568/// use llama_cpp_4::quantize::{LlamaFtype, QuantizeParams};
569///
570/// let params = QuantizeParams::new(LlamaFtype::MostlyQ4KM)
571///     .with_nthread(8)
572///     .with_quantize_output_tensor(true);
573///
574/// llama_cpp_4::model_quantize("model-f16.gguf", "model-q4km.gguf", &params).unwrap();
575/// ```
576pub fn model_quantize(
577    fname_inp: &str,
578    fname_out: &str,
579    params: &quantize::QuantizeParams,
580) -> std::result::Result<(), u32> {
581    let c_inp = std::ffi::CString::new(fname_inp).expect("input path contains null bytes");
582    let c_out = std::ffi::CString::new(fname_out).expect("output path contains null bytes");
583    let guard = params.to_raw();
584    let rc = unsafe {
585        llama_cpp_sys_4::llama_model_quantize(c_inp.as_ptr(), c_out.as_ptr(), &raw const guard.raw)
586    };
587    if rc == 0 {
588        Ok(())
589    } else {
590        Err(rc)
591    }
592}
593
594/// Set the log callback.
595///
596/// # Safety
597///
598/// The callback and user data must remain valid for the lifetime of the application
599/// or until the callback is replaced.
600pub unsafe fn log_set(
601    callback: llama_cpp_sys_4::ggml_log_callback,
602    user_data: *mut std::ffi::c_void,
603) {
604    llama_cpp_sys_4::llama_log_set(callback, user_data);
605}
606
607/// Get the current log callback and user data.
608///
609/// # Safety
610///
611/// The caller must ensure the pointers are valid.
612pub unsafe fn log_get(
613    log_callback: *mut llama_cpp_sys_4::ggml_log_callback,
614    user_data: *mut *mut std::ffi::c_void,
615) {
616    llama_cpp_sys_4::llama_log_get(log_callback, user_data);
617}
618
619/// Initialize optimizer state for fine-tuning.
620///
621/// # Safety
622///
623/// The context and model must be valid and compatible.
624pub unsafe fn opt_init(
625    ctx: *mut llama_cpp_sys_4::llama_context,
626    model: *mut llama_cpp_sys_4::llama_model,
627    params: llama_cpp_sys_4::llama_opt_params,
628) {
629    llama_cpp_sys_4::llama_opt_init(ctx, model, params);
630}
631
632/// Run one training epoch.
633///
634/// # Safety
635///
636/// All pointers and handles must be valid.
637#[allow(clippy::too_many_arguments)]
638pub unsafe fn opt_epoch(
639    ctx: *mut llama_cpp_sys_4::llama_context,
640    dataset: llama_cpp_sys_4::ggml_opt_dataset_t,
641    result_train: llama_cpp_sys_4::ggml_opt_result_t,
642    result_eval: llama_cpp_sys_4::ggml_opt_result_t,
643    idata_split: i64,
644    callback_train: llama_cpp_sys_4::ggml_opt_epoch_callback,
645    callback_eval: llama_cpp_sys_4::ggml_opt_epoch_callback,
646) {
647    llama_cpp_sys_4::llama_opt_epoch(
648        ctx,
649        dataset,
650        result_train,
651        result_eval,
652        idata_split,
653        callback_train,
654        callback_eval,
655    );
656}
657
658/// Parameter filter that accepts all tensors (for use with [`opt_init`]).
659///
660/// # Safety
661///
662/// The tensor pointer must be valid.
663pub unsafe fn opt_param_filter_all(
664    tensor: *const llama_cpp_sys_4::ggml_tensor,
665    userdata: *mut std::ffi::c_void,
666) -> bool {
667    llama_cpp_sys_4::llama_opt_param_filter_all(tensor, userdata)
668}
669
670// ── Crate-root re-exports (see also [`prelude`]) ────────────────────────────
671//
672// These mirror the most common [`prelude`] exports so callers can write
673// `llama_cpp_4::LlamaModel` without a glob import.
674
675/// Parameters used when creating a context.
676pub use context::params::LlamaContextParams;
677/// One captured intermediate tensor from [`TensorCapture`].
678pub use context::CapturedTensor;
679/// Typed retained storage from an owned tensor transaction.
680pub use context::CapturedTensorData;
681/// An inference context tied to a model.
682pub use context::LlamaContext;
683/// Per-buffer memory usage entry from [`LlamaContext::memory_breakdown`].
684pub use context::MemoryBreakdownEntry;
685/// Access granted to an exact tensor selector.
686pub use context::TensorAccess;
687/// Exact sequence and causal-position metadata for one tensor row.
688pub use context::TensorBatchRow;
689/// A contained tensor callback failure.
690pub use context::TensorCallbackFailure;
691/// Hook `cb_eval` during decode to copy named graph tensors (layer hidden states, …).
692pub use context::TensorCapture;
693/// Typed Rust-owned tensor storage supplied to a transaction handler.
694pub use context::TensorDataMut;
695/// Element representation required by an exact tensor selector.
696pub use context::TensorElementType;
697pub use context::TensorFiniteValidation;
698/// Mapping between selected tensor rows and the decode batch.
699pub use context::TensorRowMapping;
700/// Exact bounded graph-node contract.
701pub use context::TensorSelector;
702/// Validated tensor dimensions.
703pub use context::TensorShape;
704/// One synchronous owned tensor transaction.
705pub use context::TensorTransaction;
706/// Error returned by a transaction handler or selector validator.
707pub use context::TensorTransactionError;
708/// Safe synchronous tensor transaction handler.
709pub use context::TensorTransactionHandler;
710/// Owned pinned tensor callback program.
711pub use context::TensorTransactions;
712/// Native write-back decision returned by a transaction handler.
713pub use context::TensorWriteback;
714/// Complete retained tensor from one transaction.
715pub use context::TransactionalTensorCapture;
716/// Initialise the llama.cpp backend and hardware drivers.
717pub use llama_backend::LlamaBackend;
718/// Micro-batch submitted to [`LlamaContext::decode`].
719pub use llama_batch::LlamaBatch;
720/// Parameters used when loading a model.
721pub use model::params::LlamaModelParams;
722/// Controls whether tokenisation prepends a BOS token.
723pub use model::AddBos;
724/// A loaded GGUF model.
725pub use model::LlamaModel;
726/// Controls how special tokens are rendered as text.
727pub use model::Special;
728/// Sampler chain for token selection.
729pub use sampling::LlamaSampler;
730/// Failure while capturing or restoring versioned speculative state.
731pub use speculative::SpeculativeStateError;
732/// A single vocabulary token id.
733pub use token::LlamaToken;