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`.
80#![deny(clippy::undocumented_unsafe_blocks)]
81
82use std::ffi::NulError;
83use std::fmt::Debug;
84use std::num::NonZeroI32;
85
86use crate::llama_batch::BatchAddError;
87use std::os::raw::c_int;
88use std::path::PathBuf;
89use std::string::FromUtf8Error;
90
91mod cfile;
92
93pub mod chat;
94pub mod common;
95pub mod common_sampler;
96pub mod context;
97pub mod eagle;
98pub mod fit;
99#[cfg(feature = "ggml")]
100pub mod ggml;
101pub mod llama_backend;
102pub mod llama_batch;
103pub mod llama_batch_ext;
104
105/// The C `FILE` type, re-exported so callers can name it without taking a
106/// direct dependency on `llama-cpp-sys-4`.
107///
108/// Needed by the `*_from_file_ptr` constructors —
109/// [`LlamaModel::load_from_file_ptr`](model::LlamaModel::load_from_file_ptr)
110/// and
111/// [`LlamaModel::lora_adapter_init_from_file_ptr`](model::LlamaModel::lora_adapter_init_from_file_ptr)
112/// — which read a GGUF from an already-open handle at its current position.
113/// For the common case of an adapter embedded at a byte offset, prefer the safe
114/// [`LlamaModel::lora_adapter_init_at_offset`](model::LlamaModel::lora_adapter_init_at_offset),
115/// which needs none of this.
116pub use llama_cpp_sys_4::FILE;
117pub mod model;
118pub mod mtp;
119pub mod ngram;
120pub mod prelude;
121pub mod quantize;
122pub mod runtime;
123pub mod sampling;
124// Plumbing shared by the shim-backed modules; not part of the public surface.
125mod shim;
126
127/// The error type every shim-backed module shares.
128///
129/// [`chat::ChatError`], [`ngram::NgramError`], [`common_sampler::CommonSamplerError`]
130/// and [`runtime::RuntimeError`] are all aliases of this one type: the C shims
131/// share a status enum and a thread-local error buffer, so they share an error.
132/// Re-exported here because those aliases are public API and their variants
133/// should be documented somewhere reachable.
134pub use crate::shim::ShimError;
135pub mod speculative;
136pub mod token;
137pub mod token_type;
138
139#[cfg(feature = "rpc")]
140pub mod rpc;
141
142#[cfg(feature = "mtmd")]
143pub mod mtmd;
144
145/// A failable result from a llama.cpp function.
146pub type Result<T> = std::result::Result<T, LLamaCppError>;
147
148/// All errors that can occur in the llama-cpp crate.
149#[derive(Debug, Eq, PartialEq, thiserror::Error)]
150pub enum LLamaCppError {
151    /// The backend was already initialized. This can generally be ignored as initializing the backend
152    /// is idempotent.
153    #[error("BackendAlreadyInitialized")]
154    BackendAlreadyInitialized,
155    /// There was an error while get the chat template from model.
156    #[error("{0}")]
157    ChatTemplateError(#[from] ChatTemplateError),
158    /// There was an error while decoding a batch.
159    #[error("{0}")]
160    DecodeError(#[from] DecodeError),
161    /// There was an error while encoding a batch.
162    #[error("{0}")]
163    EncodeError(#[from] EncodeError),
164    /// There was an error loading a model.
165    #[error("{0}")]
166    LlamaModelLoadError(#[from] LlamaModelLoadError),
167    /// There was an error creating a new model context.
168    #[error("{0}")]
169    LlamaContextLoadError(#[from] LlamaContextLoadError),
170    /// There was an error adding a token to a batch.
171    #[error["{0}"]]
172    BatchAddError(#[from] BatchAddError),
173    /// see [`EmbeddingsError`]
174    #[error(transparent)]
175    EmbeddingError(#[from] EmbeddingsError),
176}
177
178/// There was an error while getting the chat template from a model.
179#[derive(Debug, Eq, PartialEq, thiserror::Error)]
180pub enum ChatTemplateError {
181    /// the buffer was too small.
182    #[error("The buffer was too small. However, a buffer size of {0} would be just large enough.")]
183    BuffSizeError(usize),
184    /// gguf has no chat template
185    #[error("the model has no meta val - returned code {0}")]
186    MissingTemplate(i32),
187    /// The chat template was not valid utf8.
188    #[error(transparent)]
189    Utf8Error(#[from] std::str::Utf8Error),
190}
191
192/// Error retrieving a string from the model (e.g. description, metadata key/value).
193#[derive(Debug, Eq, PartialEq, thiserror::Error)]
194pub enum StringFromModelError {
195    /// The C function returned a negative error code.
196    #[error("llama.cpp returned error code {0}")]
197    ReturnedError(i32),
198    /// The returned bytes were not valid UTF-8.
199    #[error(transparent)]
200    Utf8Error(#[from] std::str::Utf8Error),
201}
202
203/// Failed to Load context
204#[derive(Debug, Eq, PartialEq, thiserror::Error)]
205pub enum LlamaContextLoadError {
206    /// llama.cpp returned null
207    #[error("null reference from llama.cpp")]
208    NullReturn,
209}
210
211/// Failed to decode a batch.
212#[derive(Debug, Eq, PartialEq, thiserror::Error)]
213pub enum DecodeError {
214    /// A Rust tensor callback failed or unwound after native execution began.
215    #[error(transparent)]
216    TensorCallback(#[from] context::TensorCallbackFailure),
217    /// No kv cache slot was available.
218    #[error("Decode Error 1: NoKvCacheSlot")]
219    NoKvCacheSlot,
220    /// The number of tokens in the batch was 0.
221    #[error("Decode Error -1: n_tokens == 0")]
222    NTokensZero,
223    /// A decode lifecycle hook vetoed the decode (native returned `-4`). The
224    /// specific cause is normally surfaced via [`DecodeError::TensorCallback`];
225    /// this is the fallback when no Rust-side failure was recorded.
226    #[error("Decode Error -4: vetoed by a decode lifecycle hook")]
227    VetoedByDecodeHook,
228    /// An unknown error occurred.
229    #[error("Decode Error {0}: unknown")]
230    Unknown(c_int),
231}
232
233/// Failed to decode a batch.
234#[derive(Debug, Eq, PartialEq, thiserror::Error)]
235pub enum EncodeError {
236    /// No kv cache slot was available.
237    #[error("Encode Error 1: NoKvCacheSlot")]
238    NoKvCacheSlot,
239    /// The number of tokens in the batch was 0.
240    #[error("Encode Error -1: n_tokens == 0")]
241    NTokensZero,
242    /// An unknown error occurred.
243    #[error("Encode Error {0}: unknown")]
244    Unknown(c_int),
245}
246
247/// Failed to run a [`LlamaBatchExt`](llama_batch_ext::LlamaBatchExt) through a
248/// context.
249///
250/// `llama_process` returns the same codes as `llama_decode`; the first two
251/// variants are checks this crate makes before calling it.
252#[derive(Debug, Eq, PartialEq, thiserror::Error)]
253pub enum ProcessError {
254    /// The batch was built for a different context. A
255    /// [`LlamaBatchExt`](llama_batch_ext::LlamaBatchExt) captures its
256    /// context's batch size, sequence count and memory module, so it cannot be
257    /// handed to another one.
258    #[error("this batch was built for a different llama context")]
259    ContextMismatch,
260    /// The context owns tensor transactions, which are driven by hooks patched
261    /// into `llama_decode`. `llama_process` does not pass through them, so
262    /// running the batch would leave the transactions silently inert — use
263    /// [`LlamaContext::decode`](context::LlamaContext::decode) with a
264    /// [`llama_batch::LlamaBatch`] instead.
265    #[error("llama_process() does not run the decode lifecycle hooks that this context's tensor transactions need; use decode() with a LlamaBatch")]
266    TensorTransactionsUnsupported,
267    /// An entry in the batch carries no input — neither a token id nor an
268    /// input embedding. See
269    /// [`LlamaBatchExt::has_incomplete_entry`](llama_batch_ext::LlamaBatchExt::has_incomplete_entry).
270    #[error("batch entry {0} carries no input; clear the batch and rebuild it")]
271    IncompleteEntry(i32),
272    /// No kv cache slot was available.
273    #[error("Process Error 1: NoKvCacheSlot")]
274    NoKvCacheSlot,
275    /// The batch held no entries.
276    #[error("Process Error -1: n_tokens == 0")]
277    NTokensZero,
278    /// An unknown error occurred.
279    #[error("Process Error {0}: unknown")]
280    Unknown(c_int),
281}
282
283/// Failure reading or writing the pre-norm (`NextN`) device buffer.
284#[derive(Debug, Clone, Copy, Eq, PartialEq, thiserror::Error)]
285pub enum NextnRowsError {
286    /// The caller's buffer is not a whole number of `n_embd_out`-wide rows.
287    #[error("buffer of {len} floats is not a whole number of {width}-wide rows")]
288    Shape {
289        /// Length of the caller's buffer, in floats.
290        len: usize,
291        /// Row width llama.cpp uses, i.e. `n_embd_out`.
292        width: usize,
293    },
294    /// llama.cpp declined the transfer — because the device buffer was never
295    /// enabled with `set_embeddings_pre_norm_device`, because this context
296    /// produces no pre-norm output, or because the requested rows run past the
297    /// end of the buffer, which holds `n_batch + n_seq_max` of them.
298    #[error("the pre-norm device buffer is not available on this context")]
299    Unavailable,
300}
301
302/// When embedding related functions fail
303#[derive(Debug, Eq, PartialEq, thiserror::Error)]
304pub enum EmbeddingsError {
305    /// Embeddings weren't enabled in the context options
306    #[error("Embeddings weren't enabled in the context options")]
307    NotEnabled,
308    /// Logits weren't enabled for the given token
309    #[error("Logits were not enabled for the given token")]
310    LogitsNotEnabled,
311    /// The given sequence index exceeds the max sequence id
312    #[error("Can't use sequence embeddings with a model supporting only LLAMA_POOLING_TYPE_NONE")]
313    NonePoolType,
314}
315
316/// Decode a error from llama.cpp into a [`DecodeError`].
317impl From<NonZeroI32> for DecodeError {
318    fn from(value: NonZeroI32) -> Self {
319        match value.get() {
320            1 => DecodeError::NoKvCacheSlot,
321            -1 => DecodeError::NTokensZero,
322            -4 => DecodeError::VetoedByDecodeHook,
323            i => DecodeError::Unknown(i),
324        }
325    }
326}
327
328/// Encode a error from llama.cpp into a [`EncodeError`].
329impl From<NonZeroI32> for EncodeError {
330    fn from(value: NonZeroI32) -> Self {
331        match value.get() {
332            1 => EncodeError::NoKvCacheSlot,
333            -1 => EncodeError::NTokensZero,
334            i => EncodeError::Unknown(i),
335        }
336    }
337}
338
339/// Decode an error from `llama_process` into a [`ProcessError`].
340impl From<NonZeroI32> for ProcessError {
341    fn from(value: NonZeroI32) -> Self {
342        match value.get() {
343            1 => ProcessError::NoKvCacheSlot,
344            -1 => ProcessError::NTokensZero,
345            i => ProcessError::Unknown(i),
346        }
347    }
348}
349
350/// An error that can occur when loading a model.
351#[derive(Debug, Eq, PartialEq, thiserror::Error)]
352pub enum LlamaModelLoadError {
353    /// There was a null byte in a provided string and thus it could not be converted to a C string.
354    #[error("null byte in string {0}")]
355    NullError(#[from] NulError),
356    /// llama.cpp returned a nullptr - this could be many different causes.
357    #[error("null result from llama cpp")]
358    NullResult,
359    /// Failed to convert the path to a rust str. This means the path was not valid unicode
360    #[error("failed to convert path {0} to str")]
361    PathToStrError(PathBuf),
362}
363
364/// An error that can occur when loading a model.
365#[derive(Debug, Eq, PartialEq, thiserror::Error)]
366pub enum LlamaLoraAdapterInitError {
367    /// There was a null byte in a provided string and thus it could not be converted to a C string.
368    #[error("null byte in string {0}")]
369    NullError(#[from] NulError),
370    /// llama.cpp returned a nullptr - this could be many different causes.
371    #[error("null result from llama cpp")]
372    NullResult,
373    /// Failed to convert the path to a rust str. This means the path was not valid unicode
374    #[error("failed to convert path {0} to str")]
375    PathToStrError(PathBuf),
376    /// The adapter file could not be opened.
377    #[error("failed to open {path}: {reason}")]
378    FileOpen {
379        /// Path that could not be opened.
380        path: PathBuf,
381        /// What the OS reported.
382        reason: String,
383    },
384    /// The adapter file could not be positioned at the requested offset.
385    #[error("failed to seek {path} to offset {offset}: {reason}")]
386    FileSeek {
387        /// Path being read.
388        path: PathBuf,
389        /// Offset that was requested.
390        offset: u64,
391        /// What the OS reported.
392        reason: String,
393    },
394}
395
396/// An error that can occur when loading a model.
397#[derive(Debug, Eq, PartialEq, thiserror::Error)]
398pub enum LlamaLoraAdapterSetError {
399    /// llama.cpp returned a non-zero error code.
400    #[error("error code from llama cpp")]
401    ErrorResult(i32),
402}
403
404/// An error that can occur when loading a model.
405#[derive(Debug, Eq, PartialEq, thiserror::Error)]
406pub enum LlamaLoraAdapterRemoveError {
407    /// llama.cpp returned a non-zero error code.
408    #[error("error code from llama cpp")]
409    ErrorResult(i32),
410}
411
412/// get the time (in microseconds) according to llama.cpp
413/// ```
414/// # use llama_cpp_4::llama_time_us;
415/// let time = llama_time_us();
416/// assert!(time > 0);
417/// ```
418#[must_use]
419pub fn llama_time_us() -> i64 {
420    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
421    // the library owns whatever it returns.
422    unsafe { llama_cpp_sys_4::llama_time_us() }
423}
424
425/// get the max number of devices according to llama.cpp (this is generally cuda devices)
426/// ```
427/// # use llama_cpp_4::max_devices;
428/// let max_devices = max_devices();
429/// assert!(max_devices >= 0);
430/// ```
431#[must_use]
432pub fn max_devices() -> usize {
433    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
434    // the library owns whatever it returns.
435    unsafe { llama_cpp_sys_4::llama_max_devices() }
436}
437
438/// is memory mapping supported according to llama.cpp
439/// ```
440/// # use llama_cpp_4::mmap_supported;
441/// let mmap_supported = mmap_supported();
442/// if mmap_supported {
443///   println!("mmap_supported!");
444/// }
445/// ```
446#[must_use]
447pub fn mmap_supported() -> bool {
448    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
449    // the library owns whatever it returns.
450    unsafe { llama_cpp_sys_4::llama_supports_mmap() }
451}
452
453/// is memory locking supported according to llama.cpp
454/// ```
455/// # use llama_cpp_4::mlock_supported;
456/// let mlock_supported = mlock_supported();
457/// if mlock_supported {
458///    println!("mlock_supported!");
459/// }
460/// ```
461#[must_use]
462pub fn mlock_supported() -> bool {
463    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
464    // the library owns whatever it returns.
465    unsafe { llama_cpp_sys_4::llama_supports_mlock() }
466}
467
468/// An error that can occur when converting a token to a string.
469#[derive(Debug, thiserror::Error, Clone)]
470#[non_exhaustive]
471pub enum TokenToStringError {
472    /// the token type was unknown
473    #[error("Unknown Token Type")]
474    UnknownTokenType,
475    /// There was insufficient buffer space to convert the token to a string.
476    #[error("Insufficient Buffer Space {0}")]
477    InsufficientBufferSpace(c_int),
478    /// Caller-owned storage exceeds llama.cpp's signed buffer-length type.
479    #[error("piece buffer capacity {0} exceeds the native c_int bound")]
480    BufferCapacityExceeded(usize),
481    /// llama.cpp reported a positive piece length outside the supplied buffer.
482    #[error("native piece length {returned} exceeds buffer capacity {capacity}")]
483    NativePieceLength {
484        /// Positive length returned by llama.cpp.
485        returned: c_int,
486        /// Supplied caller-owned capacity.
487        capacity: usize,
488    },
489    /// The token was not valid utf8.
490    #[error("FromUtf8Error {0}")]
491    FromUtf8Error(#[from] FromUtf8Error),
492}
493
494/// Failed to convert a string to a token sequence.
495#[derive(Debug, thiserror::Error)]
496pub enum StringToTokenError {
497    /// the string contained a null byte and thus could not be converted to a c string.
498    #[error("{0}")]
499    NulError(#[from] NulError),
500    /// The string contained an interior NUL at the reported byte.
501    #[error("input contains an interior NUL at byte {0}")]
502    InteriorNul(usize),
503    #[error("{0}")]
504    /// Failed to convert a provided integer to a [`c_int`].
505    CIntConversionError(#[from] std::num::TryFromIntError),
506    /// llama.cpp reported a positive token count outside the supplied buffer.
507    #[error("native token count {returned} exceeds buffer capacity {capacity}")]
508    NativeTokenCount {
509        /// Positive count returned by llama.cpp.
510        returned: c_int,
511        /// Supplied caller-owned capacity.
512        capacity: usize,
513    },
514}
515
516/// Failed to apply model chat template.
517#[derive(Debug, thiserror::Error)]
518pub enum NewLlamaChatMessageError {
519    /// the string contained a null byte and thus could not be converted to a c string.
520    #[error("{0}")]
521    NulError(#[from] NulError),
522}
523
524/// Failed to apply model chat template.
525#[derive(Debug, thiserror::Error)]
526pub enum ApplyChatTemplateError {
527    /// the buffer was too small.
528    #[error("The buffer was too small. Please contact a maintainer and we will update it.")]
529    BuffSizeError,
530    /// the string contained a null byte and thus could not be converted to a c string.
531    #[error("{0}")]
532    NulError(#[from] NulError),
533    /// the string could not be converted to utf8.
534    #[error("{0}")]
535    FromUtf8Error(#[from] FromUtf8Error),
536}
537
538/// Get the time in microseconds according to ggml
539///
540/// ```
541/// # use std::time::Duration;
542/// use llama_cpp_4::ggml_time_us;
543///
544/// let start = ggml_time_us();
545///
546/// std::thread::sleep(Duration::from_micros(10));
547///
548/// let end = ggml_time_us();
549///
550/// let elapsed = end - start;
551///
552/// assert!(elapsed >= 10)
553#[must_use]
554pub fn ggml_time_us() -> i64 {
555    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
556    // the library owns whatever it returns.
557    unsafe { llama_cpp_sys_4::ggml_time_us() }
558}
559
560/// Checks if mlock is supported.
561///
562/// ```
563/// # use llama_cpp_4::llama_supports_mlock;
564///
565/// if llama_supports_mlock() {
566///   println!("mlock is supported!");
567/// } else {
568///   println!("mlock is not supported!");
569/// }
570/// ```
571#[must_use]
572pub fn llama_supports_mlock() -> bool {
573    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
574    // the library owns whatever it returns.
575    unsafe { llama_cpp_sys_4::llama_supports_mlock() }
576}
577
578/// Checks if GPU offload is supported.
579///
580/// Returns `true` if the library was compiled with GPU support (CUDA, Metal, Vulkan, etc.).
581#[must_use]
582pub fn supports_gpu_offload() -> bool {
583    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
584    // the library owns whatever it returns.
585    unsafe { llama_cpp_sys_4::llama_supports_gpu_offload() }
586}
587
588/// Checks if RPC backend is supported.
589///
590/// Returns `true` if the library was compiled with RPC support.
591#[must_use]
592pub fn supports_rpc() -> bool {
593    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
594    // the library owns whatever it returns.
595    unsafe { llama_cpp_sys_4::llama_supports_rpc() }
596}
597
598/// Version of the vendored llama.cpp this crate is linked against.
599///
600/// llama.cpp adopted semantic versioning in `b10470` / `v0.1.1`, so this is a
601/// `MAJOR.MINOR.PATCH` string (with a `-dev` suffix for builds off a
602/// non-release commit) rather than a `bNNNNN` build number. Useful for
603/// reporting the exact upstream a binary carries, since the crate version and
604/// the llama.cpp version move independently.
605///
606/// ```
607/// # use llama_cpp_4::llama_version;
608/// let version = llama_version();
609/// assert!(!version.is_empty());
610/// // e.g. "0.1.1"
611/// assert!(version.starts_with(char::is_numeric));
612/// ```
613///
614/// # Panics
615///
616/// Panics if the returned string is not valid UTF-8.
617#[must_use]
618pub fn llama_version() -> &'static str {
619    // SAFETY: llama.cpp returns a pointer to a string literal baked in at
620    // compile time, so it is non-null and lives for the life of the process.
621    let c_str = unsafe { std::ffi::CStr::from_ptr(llama_cpp_sys_4::llama_version()) };
622    c_str.to_str().expect("llama version is not valid UTF-8")
623}
624
625/// Get system information string.
626///
627/// Returns a string containing CPU features, build info, and other system details.
628///
629/// # Panics
630///
631/// Panics if the returned string is not valid UTF-8.
632#[must_use]
633pub fn print_system_info() -> String {
634    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
635    // library owns, which outlives the borrow taken here.
636    let c_str = unsafe { llama_cpp_sys_4::llama_print_system_info() };
637    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
638    // library owns, which outlives the borrow taken here.
639    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
640    c_str
641        .to_str()
642        .expect("system info is not valid UTF-8")
643        .to_owned()
644}
645
646/// Get the maximum number of parallel sequences supported.
647#[must_use]
648pub fn max_parallel_sequences() -> usize {
649    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
650    // the library owns whatever it returns.
651    unsafe { llama_cpp_sys_4::llama_max_parallel_sequences() }
652}
653
654/// Get the maximum number of tensor buffer type overrides.
655#[must_use]
656pub fn max_tensor_buft_overrides() -> usize {
657    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
658    // the library owns whatever it returns.
659    unsafe { llama_cpp_sys_4::llama_max_tensor_buft_overrides() }
660}
661
662/// Get the name of a flash attention type.
663///
664/// # Panics
665///
666/// Panics if the returned string is not valid UTF-8.
667#[must_use]
668pub fn flash_attn_type_name(flash_attn_type: i32) -> String {
669    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
670    // library owns, which outlives the borrow taken here.
671    let c_str = unsafe { llama_cpp_sys_4::llama_flash_attn_type_name(flash_attn_type) };
672    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
673    // library owns, which outlives the borrow taken here.
674    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
675    c_str
676        .to_str()
677        .expect("flash_attn_type_name is not valid UTF-8")
678        .to_owned()
679}
680
681/// Get the string representation of a model metadata key.
682///
683/// # Panics
684///
685/// Panics if the returned string is not valid UTF-8.
686#[must_use]
687pub fn model_meta_key_str(key: u32) -> String {
688    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
689    // library owns, which outlives the borrow taken here.
690    let c_str = unsafe { llama_cpp_sys_4::llama_model_meta_key_str(key as _) };
691    // SAFETY: the pointer is non-null and points at a NUL-terminated string the
692    // library owns, which outlives the borrow taken here.
693    let c_str = unsafe { std::ffi::CStr::from_ptr(c_str) };
694    c_str
695        .to_str()
696        .expect("meta_key_str is not valid UTF-8")
697        .to_owned()
698}
699
700/// Quantize a model file using typed [`crate::quantize::QuantizeParams`].
701///
702/// Returns `Ok(())` on success, or `Err(code)` with the non-zero error code
703/// returned by `llama_model_quantize`.
704///
705/// # Panics
706///
707/// Panics if either path contains an interior null byte.
708///
709/// # Errors
710///
711/// Returns `Err(code)` with the non-zero status code from `llama_model_quantize`
712/// when quantization fails.
713///
714/// # Example
715///
716/// ```no_run
717/// use llama_cpp_4::quantize::{LlamaFtype, QuantizeParams};
718///
719/// let params = QuantizeParams::new(LlamaFtype::MostlyQ4KM)
720///     .with_nthread(8)
721///     .with_quantize_output_tensor(true);
722///
723/// llama_cpp_4::model_quantize("model-f16.gguf", "model-q4km.gguf", &params).unwrap();
724/// ```
725pub fn model_quantize(
726    fname_inp: &str,
727    fname_out: &str,
728    params: &quantize::QuantizeParams,
729) -> std::result::Result<(), u32> {
730    let c_inp = std::ffi::CString::new(fname_inp).expect("input path contains null bytes");
731    let c_out = std::ffi::CString::new(fname_out).expect("output path contains null bytes");
732    let guard = params.to_raw();
733    // SAFETY: the arguments are either scalars or pointers that outlive the call, and
734    // the library owns whatever it returns.
735    let rc = unsafe {
736        llama_cpp_sys_4::llama_model_quantize(c_inp.as_ptr(), c_out.as_ptr(), &raw const guard.raw)
737    };
738    if rc == 0 {
739        Ok(())
740    } else {
741        Err(rc)
742    }
743}
744
745/// Set the log callback.
746///
747/// # Safety
748///
749/// The callback and user data must remain valid for the lifetime of the application
750/// or until the callback is replaced.
751pub unsafe fn log_set(
752    callback: llama_cpp_sys_4::ggml_log_callback,
753    user_data: *mut std::ffi::c_void,
754) {
755    llama_cpp_sys_4::llama_log_set(callback, user_data);
756}
757
758/// Get the current log callback and user data.
759///
760/// # Safety
761///
762/// The caller must ensure the pointers are valid.
763pub unsafe fn log_get(
764    log_callback: *mut llama_cpp_sys_4::ggml_log_callback,
765    user_data: *mut *mut std::ffi::c_void,
766) {
767    llama_cpp_sys_4::llama_log_get(log_callback, user_data);
768}
769
770/// Initialize optimizer state for fine-tuning.
771///
772/// # Safety
773///
774/// The context and model must be valid and compatible.
775pub unsafe fn opt_init(
776    ctx: *mut llama_cpp_sys_4::llama_context,
777    model: *mut llama_cpp_sys_4::llama_model,
778    params: llama_cpp_sys_4::llama_opt_params,
779) {
780    llama_cpp_sys_4::llama_opt_init(ctx, model, params);
781}
782
783/// Run one training epoch.
784///
785/// # Safety
786///
787/// All pointers and handles must be valid.
788#[allow(clippy::too_many_arguments)]
789pub unsafe fn opt_epoch(
790    ctx: *mut llama_cpp_sys_4::llama_context,
791    dataset: llama_cpp_sys_4::ggml_opt_dataset_t,
792    result_train: llama_cpp_sys_4::ggml_opt_result_t,
793    result_eval: llama_cpp_sys_4::ggml_opt_result_t,
794    idata_split: i64,
795    callback_train: llama_cpp_sys_4::ggml_opt_epoch_callback,
796    callback_eval: llama_cpp_sys_4::ggml_opt_epoch_callback,
797) {
798    llama_cpp_sys_4::llama_opt_epoch(
799        ctx,
800        dataset,
801        result_train,
802        result_eval,
803        idata_split,
804        callback_train,
805        callback_eval,
806    );
807}
808
809/// Parameter filter that accepts all tensors (for use with [`opt_init`]).
810///
811/// # Safety
812///
813/// The tensor pointer must be valid.
814pub unsafe fn opt_param_filter_all(
815    tensor: *const llama_cpp_sys_4::ggml_tensor,
816    userdata: *mut std::ffi::c_void,
817) -> bool {
818    llama_cpp_sys_4::llama_opt_param_filter_all(tensor, userdata)
819}
820
821// ── Crate-root re-exports (see also [`prelude`]) ────────────────────────────
822//
823// These mirror the most common [`prelude`] exports so callers can write
824// `llama_cpp_4::LlamaModel` without a glob import.
825
826/// Parameters used when creating a context.
827pub use context::params::LlamaContextParams;
828/// One captured intermediate tensor from [`TensorCapture`].
829pub use context::CapturedTensor;
830/// Typed retained storage from an owned tensor transaction.
831pub use context::CapturedTensorData;
832/// An inference context tied to a model.
833pub use context::LlamaContext;
834/// Per-buffer memory usage entry from [`LlamaContext::memory_breakdown`].
835pub use context::MemoryBreakdownEntry;
836/// Access granted to an exact tensor selector.
837pub use context::TensorAccess;
838/// Exact sequence and causal-position metadata for one tensor row.
839pub use context::TensorBatchRow;
840/// A contained tensor callback failure.
841pub use context::TensorCallbackFailure;
842/// Hook `cb_eval` during decode to copy named graph tensors (layer hidden states, …).
843pub use context::TensorCapture;
844/// Typed Rust-owned tensor storage supplied to a transaction handler.
845pub use context::TensorDataMut;
846/// Element representation required by an exact tensor selector.
847pub use context::TensorElementType;
848pub use context::TensorFiniteValidation;
849/// Mapping between selected tensor rows and the decode batch.
850pub use context::TensorRowMapping;
851/// Exact bounded graph-node contract.
852pub use context::TensorSelector;
853/// Validated tensor dimensions.
854pub use context::TensorShape;
855/// One synchronous owned tensor transaction.
856pub use context::TensorTransaction;
857/// Error returned by a transaction handler or selector validator.
858pub use context::TensorTransactionError;
859/// Safe synchronous tensor transaction handler.
860pub use context::TensorTransactionHandler;
861/// Owned pinned tensor callback program.
862pub use context::TensorTransactions;
863/// Native write-back decision returned by a transaction handler.
864pub use context::TensorWriteback;
865/// Complete retained tensor from one transaction.
866pub use context::TransactionalTensorCapture;
867/// Initialise the llama.cpp backend and hardware drivers.
868pub use llama_backend::LlamaBackend;
869/// Micro-batch submitted to [`LlamaContext::decode`].
870pub use llama_batch::LlamaBatch;
871/// Parameters used when loading a model.
872pub use model::params::LlamaModelParams;
873/// Controls whether tokenisation prepends a BOS token.
874pub use model::AddBos;
875/// A loaded GGUF model.
876pub use model::LlamaModel;
877/// Controls how special tokens are rendered as text.
878pub use model::Special;
879/// Sampler chain for token selection.
880pub use sampling::LlamaSampler;
881/// Failure while capturing or restoring versioned speculative state.
882pub use speculative::SpeculativeStateError;
883/// A single vocabulary token id.
884pub use token::LlamaToken;