llama_cpp_4/model.rs
1//! A safe wrapper around `llama_model`.
2use std::ffi::CStr;
3use std::ffi::CString;
4use std::fmt;
5use std::num::NonZeroU16;
6use std::os::raw::{c_char, c_int};
7use std::path::Path;
8use std::ptr::NonNull;
9use std::slice;
10
11use llama_cpp_sys_4::{
12 llama_adapter_lora, llama_adapter_lora_init, llama_chat_apply_template,
13 llama_chat_builtin_templates, llama_chat_message, llama_detokenize, llama_init_from_model,
14 llama_model, llama_model_chat_template, llama_model_cls_label, llama_model_decoder_start_token,
15 llama_model_desc, llama_model_free, llama_model_ftype, llama_model_get_device,
16 llama_model_get_tok_embd, llama_model_get_vocab, llama_model_has_decoder,
17 llama_model_has_encoder, llama_model_is_diffusion, llama_model_is_hybrid,
18 llama_model_is_recurrent, llama_model_load_from_file, llama_model_load_from_splits,
19 llama_model_meta_count, llama_model_meta_key_by_index, llama_model_meta_val_str,
20 llama_model_meta_val_str_by_index, llama_model_n_cls_out, llama_model_n_ctx_train,
21 llama_model_n_devices, llama_model_n_embd, llama_model_n_embd_inp, llama_model_n_embd_out,
22 llama_model_n_expert, llama_model_n_head, llama_model_n_head_kv, llama_model_n_layer,
23 llama_model_n_layer_nextn, llama_model_n_params, llama_model_n_swa,
24 llama_model_rope_freq_scale_train, llama_model_rope_type, llama_model_save_to_file,
25 llama_model_size, llama_model_target_layer_ids, llama_model_target_layer_ids_n,
26 llama_split_path, llama_split_prefix, llama_token_to_piece, llama_tokenize, llama_vocab,
27 llama_vocab_type, LLAMA_VOCAB_TYPE_BPE, LLAMA_VOCAB_TYPE_SPM,
28};
29
30use crate::context::params::LlamaContextParams;
31use crate::context::LlamaContext;
32use crate::llama_backend::LlamaBackend;
33use crate::model::params::LlamaModelParams;
34use crate::quantize::LlamaFtype;
35use crate::token::LlamaToken;
36use crate::token_type::{LlamaTokenAttr, LlamaTokenAttrs};
37use crate::{
38 ApplyChatTemplateError, ChatTemplateError, LlamaContextLoadError, LlamaLoraAdapterInitError,
39 LlamaModelLoadError, NewLlamaChatMessageError, StringFromModelError, StringToTokenError,
40 TokenToStringError,
41};
42
43pub mod params;
44
45/// Opaque ggml backend device handle returned by [`LlamaModel::get_device`].
46///
47/// Use [`Self::name`], [`Self::description`], [`Self::device_type`], and
48/// [`Self::memory`] to inspect the device. The handle is valid for the lifetime
49/// of the parent [`LlamaModel`].
50#[derive(Debug, Copy, Clone, PartialEq, Eq)]
51pub struct LlamaBackendDevice {
52 pub(crate) dev: llama_cpp_sys_4::ggml_backend_dev_t,
53}
54
55/// Backend device class (CPU, discrete GPU, integrated GPU, …).
56//
57// `GGML_BACKEND_DEVICE_TYPE_*` are `c_uint` under clang/gcc and `c_int` under
58// MSVC. `as i32` compiles on both; the `cast_possible_wrap` allow covers the
59// clang/gcc case (the device-type values are small and never wrap).
60#[allow(clippy::cast_possible_wrap)]
61#[repr(i32)]
62#[derive(Copy, Clone, Debug, PartialEq, Eq)]
63pub enum LlamaBackendDeviceType {
64 /// Host CPU backend.
65 Cpu = llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_CPU as i32,
66 /// Discrete GPU.
67 Gpu = llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_GPU as i32,
68 /// Integrated GPU.
69 IntegratedGpu = llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_IGPU as i32,
70 /// Accelerator device (e.g. BLAS / Hexagon).
71 Accel = llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_ACCEL as i32,
72 /// Meta / placeholder device entry.
73 Meta = llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_META as i32,
74}
75
76impl From<llama_cpp_sys_4::ggml_backend_dev_type> for LlamaBackendDeviceType {
77 fn from(value: llama_cpp_sys_4::ggml_backend_dev_type) -> Self {
78 match value {
79 llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_CPU => Self::Cpu,
80 llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_GPU => Self::Gpu,
81 llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_IGPU => Self::IntegratedGpu,
82 llama_cpp_sys_4::GGML_BACKEND_DEVICE_TYPE_ACCEL => Self::Accel,
83 _ => Self::Meta,
84 }
85 }
86}
87
88impl LlamaBackendDevice {
89 /// Human-readable device name (e.g. `CUDA0`, `Metal`).
90 ///
91 /// # Errors
92 ///
93 /// Returns an error when the name pointer is null or not valid UTF-8.
94 pub fn name(&self) -> Result<&str, StringFromModelError> {
95 // SAFETY: a read through a live handle — the device, vocab or model
96 // this borrows from — returning a pointer llama.cpp owns and keeps
97 // valid; it is only checked and converted below, never freed here.
98 let ptr = unsafe { llama_cpp_sys_4::ggml_backend_dev_name(self.dev) };
99 if ptr.is_null() {
100 return Err(StringFromModelError::ReturnedError(-1));
101 }
102 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
103 // it owns, which outlives the borrow taken here.
104 let cstr = unsafe { CStr::from_ptr(ptr) };
105 cstr.to_str().map_err(StringFromModelError::Utf8Error)
106 }
107
108 /// Longer device description (often includes hardware name).
109 ///
110 /// # Errors
111 ///
112 /// Returns an error when the description pointer is null or not valid UTF-8.
113 pub fn description(&self) -> Result<&str, StringFromModelError> {
114 // SAFETY: a read through a live handle — the device, vocab or model
115 // this borrows from — returning a pointer llama.cpp owns and keeps
116 // valid; it is only checked and converted below, never freed here.
117 let ptr = unsafe { llama_cpp_sys_4::ggml_backend_dev_description(self.dev) };
118 if ptr.is_null() {
119 return Err(StringFromModelError::ReturnedError(-1));
120 }
121 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
122 // it owns, which outlives the borrow taken here.
123 let cstr = unsafe { CStr::from_ptr(ptr) };
124 cstr.to_str().map_err(StringFromModelError::Utf8Error)
125 }
126
127 /// Device class (CPU, GPU, integrated GPU, …).
128 #[must_use]
129 pub fn device_type(&self) -> LlamaBackendDeviceType {
130 // SAFETY: `self.dev` is a device handle owned by ggml's static registry, which
131 // outlives this borrow; the call only reads its class.
132 unsafe { llama_cpp_sys_4::ggml_backend_dev_type(self.dev).into() }
133 }
134
135 /// Device memory `(free_bytes, total_bytes)`.
136 #[must_use]
137 pub fn memory(&self) -> (usize, usize) {
138 let mut free = 0usize;
139 let mut total = 0usize;
140 // SAFETY: `self.dev` is a device handle owned by ggml's static
141 // registry, and `free`/`total` are stack locals ggml writes through.
142 unsafe {
143 llama_cpp_sys_4::ggml_backend_dev_memory(self.dev, &raw mut free, &raw mut total);
144 }
145 (free, total)
146 }
147}
148
149/// Iterator over [`LlamaBackendDevice`] handles for a loaded model.
150///
151/// # Examples
152///
153/// ```no_run
154/// use llama_cpp_4::prelude::*;
155///
156/// fn main() {
157/// let backend = LlamaBackend::init().unwrap();
158/// let model = LlamaModel::load_from_file(&backend, "model.gguf", &LlamaModelParams::default()).unwrap();
159/// for dev in model.devices() {
160/// let (free, total) = dev.memory();
161/// println!("{}: {} / {} bytes free", dev.name().unwrap(), free, total);
162/// }
163/// }
164/// ```
165#[derive(Debug, Clone, Copy)]
166pub struct LlamaBackendDevices<'a> {
167 model: &'a LlamaModel,
168 next: i32,
169}
170
171#[allow(clippy::copy_iterator)]
172impl Iterator for LlamaBackendDevices<'_> {
173 type Item = LlamaBackendDevice;
174
175 fn next(&mut self) -> Option<Self::Item> {
176 let dev = self.model.get_device(self.next)?;
177 self.next += 1;
178 Some(dev)
179 }
180
181 fn size_hint(&self) -> (usize, Option<usize>) {
182 let remaining = usize::try_from((self.model.n_devices() - self.next).max(0)).unwrap_or(0);
183 (remaining, Some(remaining))
184 }
185}
186
187impl ExactSizeIterator for LlamaBackendDevices<'_> {}
188
189/// A safe wrapper around `llama_model`.
190#[derive(Debug)]
191#[repr(transparent)]
192#[allow(clippy::module_name_repetitions)]
193pub struct LlamaModel {
194 pub(crate) model: NonNull<llama_model>,
195}
196
197/// A safe wrapper around `llama_vocab`.
198#[derive(Debug)]
199#[repr(transparent)]
200#[allow(clippy::module_name_repetitions)]
201pub struct LlamaVocab {
202 pub(crate) vocab: NonNull<llama_vocab>,
203}
204
205impl LlamaVocab {
206 /// Get the number of tokens in the vocabulary.
207 #[must_use]
208 pub fn n_tokens(&self) -> i32 {
209 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
210 // token and index arguments are scalars llama.cpp range-checks.
211 unsafe { llama_cpp_sys_4::llama_vocab_n_tokens(self.vocab.as_ref()) }
212 }
213
214 /// Get the vocabulary type.
215 ///
216 /// # Panics
217 ///
218 /// Panics if the C API returns a vocabulary type that does not fit in `u32`.
219 #[must_use]
220 pub fn vocab_type(&self) -> u32 {
221 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
222 // token and index arguments are scalars llama.cpp range-checks.
223 unsafe { llama_cpp_sys_4::llama_vocab_type(self.vocab.as_ref()) as u32 }
224 }
225
226 /// Get the BOS token.
227 #[must_use]
228 pub fn bos(&self) -> LlamaToken {
229 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
230 // token and index arguments are scalars llama.cpp range-checks.
231 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_bos(self.vocab.as_ref()) })
232 }
233
234 /// Get the EOS token.
235 #[must_use]
236 pub fn eos(&self) -> LlamaToken {
237 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
238 // token and index arguments are scalars llama.cpp range-checks.
239 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_eos(self.vocab.as_ref()) })
240 }
241
242 /// Get the EOT (end of turn) token.
243 #[must_use]
244 pub fn eot(&self) -> LlamaToken {
245 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
246 // token and index arguments are scalars llama.cpp range-checks.
247 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_eot(self.vocab.as_ref()) })
248 }
249
250 /// Get the CLS (classification) token.
251 ///
252 /// Upstream removed `llama_vocab_cls` in `b12388` — its own deprecation
253 /// note said "use `llama_vocab_bos` instead", because the two were the
254 /// same token for every vocabulary that defined either. This resolves to
255 /// [`bos`](Self::bos) accordingly.
256 #[must_use]
257 #[deprecated(
258 since = "0.12.0",
259 note = "upstream removed `llama_vocab_cls`; this is now an alias for `bos`"
260 )]
261 pub fn cls(&self) -> LlamaToken {
262 self.bos()
263 }
264
265 /// Get the SEP (separator) token.
266 #[must_use]
267 pub fn sep(&self) -> LlamaToken {
268 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
269 // token and index arguments are scalars llama.cpp range-checks.
270 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_sep(self.vocab.as_ref()) })
271 }
272
273 /// Get the NL (newline) token.
274 #[must_use]
275 pub fn nl(&self) -> LlamaToken {
276 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
277 // token and index arguments are scalars llama.cpp range-checks.
278 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_nl(self.vocab.as_ref()) })
279 }
280
281 /// Get the PAD (padding) token.
282 #[must_use]
283 pub fn pad(&self) -> LlamaToken {
284 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
285 // token and index arguments are scalars llama.cpp range-checks.
286 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_pad(self.vocab.as_ref()) })
287 }
288
289 /// Get the FIM prefix token.
290 #[must_use]
291 pub fn fim_pre(&self) -> LlamaToken {
292 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
293 // token and index arguments are scalars llama.cpp range-checks.
294 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_pre(self.vocab.as_ref()) })
295 }
296
297 /// Get the FIM suffix token.
298 #[must_use]
299 pub fn fim_suf(&self) -> LlamaToken {
300 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
301 // token and index arguments are scalars llama.cpp range-checks.
302 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_suf(self.vocab.as_ref()) })
303 }
304
305 /// Get the FIM middle token.
306 #[must_use]
307 pub fn fim_mid(&self) -> LlamaToken {
308 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
309 // token and index arguments are scalars llama.cpp range-checks.
310 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_mid(self.vocab.as_ref()) })
311 }
312
313 /// Get the FIM padding token.
314 #[must_use]
315 pub fn fim_pad(&self) -> LlamaToken {
316 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
317 // token and index arguments are scalars llama.cpp range-checks.
318 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_pad(self.vocab.as_ref()) })
319 }
320
321 /// Get the FIM repository token.
322 #[must_use]
323 pub fn fim_rep(&self) -> LlamaToken {
324 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
325 // token and index arguments are scalars llama.cpp range-checks.
326 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_rep(self.vocab.as_ref()) })
327 }
328
329 /// Get the FIM separator token.
330 #[must_use]
331 pub fn fim_sep(&self) -> LlamaToken {
332 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
333 // token and index arguments are scalars llama.cpp range-checks.
334 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_fim_sep(self.vocab.as_ref()) })
335 }
336
337 /// Check whether BOS should be added.
338 #[must_use]
339 pub fn get_add_bos(&self) -> bool {
340 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
341 // token and index arguments are scalars llama.cpp range-checks.
342 unsafe { llama_cpp_sys_4::llama_vocab_get_add_bos(self.vocab.as_ref()) }
343 }
344
345 /// Check whether EOS should be added.
346 #[must_use]
347 pub fn get_add_eos(&self) -> bool {
348 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
349 // token and index arguments are scalars llama.cpp range-checks.
350 unsafe { llama_cpp_sys_4::llama_vocab_get_add_eos(self.vocab.as_ref()) }
351 }
352
353 /// Check whether SEP should be added.
354 #[must_use]
355 pub fn get_add_sep(&self) -> bool {
356 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
357 // token and index arguments are scalars llama.cpp range-checks.
358 unsafe { llama_cpp_sys_4::llama_vocab_get_add_sep(self.vocab.as_ref()) }
359 }
360
361 /// Tokens the model itself declares should never be sampled.
362 ///
363 /// Read from the GGUF key `tokenizer.ggml.suppress_tokens`. Whisper-style
364 /// models use this to bar non-speech tokens; most models declare none and
365 /// this returns an empty slice. Feed the result to
366 /// [`LlamaSampler::logit_bias`](crate::sampling::LlamaSampler::logit_bias)
367 /// with `f32::NEG_INFINITY` to enforce it.
368 ///
369 /// The slice borrows the vocab's own array; it is valid for as long as the
370 /// model is.
371 #[must_use]
372 pub fn suppress_tokens(&self) -> &[LlamaToken] {
373 let mut n: i32 = 0;
374 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
375 // token and index arguments are scalars llama.cpp range-checks.
376 let ptr = unsafe {
377 llama_cpp_sys_4::llama_vocab_get_suppress_tokens(self.vocab.as_ref(), &raw mut n)
378 };
379 let Ok(n) = usize::try_from(n) else {
380 return &[];
381 };
382 if ptr.is_null() || n == 0 {
383 return &[];
384 }
385 // SAFETY: `LlamaToken` is `#[repr(transparent)]` over `llama_token`, so
386 // the arrays have identical layout. The pointer is owned by the vocab
387 // and outlives `&self`.
388 unsafe { std::slice::from_raw_parts(ptr.cast::<LlamaToken>(), n) }
389 }
390
391 /// Get the text representation of a token.
392 ///
393 /// # Errors
394 ///
395 /// Returns an error if the text pointer is null or not valid UTF-8.
396 pub fn get_text(&self, token: LlamaToken) -> Result<&str, StringFromModelError> {
397 let bytes = self.get_text_bytes(token)?;
398 std::str::from_utf8(bytes).map_err(StringFromModelError::Utf8Error)
399 }
400
401 /// Get the exact byte representation stored for a vocabulary token.
402 ///
403 /// Unlike [`Self::get_text`], this method does not require the token text
404 /// to be valid UTF-8.
405 ///
406 /// # Errors
407 ///
408 /// Returns an error if llama.cpp reports a null text pointer.
409 pub fn get_text_bytes(&self, token: LlamaToken) -> Result<&[u8], StringFromModelError> {
410 // SAFETY: a read through a live handle — the device, vocab or model
411 // this borrows from — returning a pointer llama.cpp owns and keeps
412 // valid; it is only checked and converted below, never freed here.
413 let ptr = unsafe { llama_cpp_sys_4::llama_vocab_get_text(self.vocab.as_ref(), token.0) };
414 if ptr.is_null() {
415 return Err(StringFromModelError::ReturnedError(-1));
416 }
417 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
418 // it owns, which outlives the borrow taken here.
419 let cstr = unsafe { CStr::from_ptr(ptr) };
420 Ok(cstr.to_bytes())
421 }
422
423 /// Get the score of a token.
424 #[must_use]
425 pub fn get_score(&self, token: LlamaToken) -> f32 {
426 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
427 // token and index arguments are scalars llama.cpp range-checks.
428 unsafe { llama_cpp_sys_4::llama_vocab_get_score(self.vocab.as_ref(), token.0) }
429 }
430
431 /// Get the attributes of a token.
432 ///
433 /// # Panics
434 ///
435 /// Panics if the C API returns attributes that do not fit in `u32`.
436 #[must_use]
437 pub fn get_attr(&self, token: LlamaToken) -> u32 {
438 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
439 // token and index arguments are scalars llama.cpp range-checks.
440 unsafe { llama_cpp_sys_4::llama_vocab_get_attr(self.vocab.as_ref(), token.0) as u32 }
441 }
442
443 /// Check if a token is a control token.
444 #[must_use]
445 pub fn is_control(&self, token: LlamaToken) -> bool {
446 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
447 // token and index arguments are scalars llama.cpp range-checks.
448 unsafe { llama_cpp_sys_4::llama_vocab_is_control(self.vocab.as_ref(), token.0) }
449 }
450
451 /// Check if a token is an end-of-generation token.
452 #[must_use]
453 pub fn is_eog(&self, token: LlamaToken) -> bool {
454 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
455 // token and index arguments are scalars llama.cpp range-checks.
456 unsafe { llama_cpp_sys_4::llama_vocab_is_eog(self.vocab.as_ref(), token.0) }
457 }
458
459 /// Get the token mask value for the vocabulary.
460 #[must_use]
461 pub fn mask(&self) -> LlamaToken {
462 // SAFETY: the adapter handle and the model it came from are both alive for the
463 // call; any path argument is a `CString` that outlives it.
464 LlamaToken(unsafe { llama_cpp_sys_4::llama_vocab_mask(self.vocab.as_ref()) })
465 }
466}
467
468/// A safe wrapper around `llama_adapter_lora`.
469#[derive(Debug)]
470#[repr(transparent)]
471#[allow(clippy::module_name_repetitions)]
472pub struct LlamaLoraAdapter {
473 pub(crate) lora_adapter: NonNull<llama_adapter_lora>,
474}
475
476impl LlamaLoraAdapter {
477 /// Get the number of metadata key-value pairs in the adapter.
478 #[must_use]
479 pub fn meta_count(&self) -> i32 {
480 // SAFETY: the adapter handle and the model it came from are both alive for the
481 // call; any path argument is a `CString` that outlives it.
482 unsafe { llama_cpp_sys_4::llama_adapter_meta_count(self.lora_adapter.as_ptr()) }
483 }
484
485 /// Get a metadata key by index.
486 ///
487 /// # Errors
488 ///
489 /// Returns an error if the index is out of range or the key is not valid UTF-8.
490 #[allow(clippy::cast_sign_loss)]
491 pub fn meta_key_by_index(
492 &self,
493 index: i32,
494 buf_size: usize,
495 ) -> Result<String, StringFromModelError> {
496 let mut buf = vec![0u8; buf_size];
497 // SAFETY: the adapter handle and the model it came from are both alive for the
498 // call; any path argument is a `CString` that outlives it.
499 let ret = unsafe {
500 llama_cpp_sys_4::llama_adapter_meta_key_by_index(
501 self.lora_adapter.as_ptr(),
502 index,
503 buf.as_mut_ptr().cast::<c_char>(),
504 buf_size,
505 )
506 };
507 if ret < 0 {
508 return Err(StringFromModelError::ReturnedError(ret));
509 }
510 let len = ret as usize;
511 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
512 Ok(s.to_owned())
513 }
514
515 /// Get a metadata value by key name.
516 ///
517 /// # Errors
518 ///
519 /// Returns an error if the key is not found or the value is not valid UTF-8.
520 #[allow(clippy::cast_sign_loss)]
521 pub fn meta_val_str(&self, key: &str, buf_size: usize) -> Result<String, StringFromModelError> {
522 let c_key = CString::new(key).map_err(|_| StringFromModelError::ReturnedError(-1))?;
523 let mut buf = vec![0u8; buf_size];
524 // SAFETY: the adapter handle and the model it came from are both alive for the
525 // call; any path argument is a `CString` that outlives it.
526 let ret = unsafe {
527 llama_cpp_sys_4::llama_adapter_meta_val_str(
528 self.lora_adapter.as_ptr(),
529 c_key.as_ptr(),
530 buf.as_mut_ptr().cast::<c_char>(),
531 buf_size,
532 )
533 };
534 if ret < 0 {
535 return Err(StringFromModelError::ReturnedError(ret));
536 }
537 let len = ret as usize;
538 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
539 Ok(s.to_owned())
540 }
541
542 /// Get a metadata value by index.
543 ///
544 /// # Errors
545 ///
546 /// Returns an error if the index is out of range or the value is not valid UTF-8.
547 #[allow(clippy::cast_sign_loss)]
548 pub fn meta_val_str_by_index(
549 &self,
550 index: i32,
551 buf_size: usize,
552 ) -> Result<String, StringFromModelError> {
553 let mut buf = vec![0u8; buf_size];
554 // SAFETY: the adapter handle and the model it came from are both alive for the
555 // call; any path argument is a `CString` that outlives it.
556 let ret = unsafe {
557 llama_cpp_sys_4::llama_adapter_meta_val_str_by_index(
558 self.lora_adapter.as_ptr(),
559 index,
560 buf.as_mut_ptr().cast::<c_char>(),
561 buf_size,
562 )
563 };
564 if ret < 0 {
565 return Err(StringFromModelError::ReturnedError(ret));
566 }
567 let len = ret as usize;
568 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
569 Ok(s.to_owned())
570 }
571
572 /// Get all metadata as a list of `(key, value)` pairs.
573 ///
574 /// # Errors
575 ///
576 /// Returns an error if any key or value cannot be read or is not valid UTF-8.
577 #[allow(clippy::cast_sign_loss)]
578 pub fn metadata(&self) -> Result<Vec<(String, String)>, StringFromModelError> {
579 let count = self.meta_count();
580 let mut result = Vec::with_capacity(count as usize);
581 for i in 0..count {
582 let key = self.meta_key_by_index(i, 256)?;
583 let val = self.meta_val_str_by_index(i, 4096)?;
584 result.push((key, val));
585 }
586 Ok(result)
587 }
588
589 /// Get the number of invocation tokens for this adapter.
590 #[must_use]
591 pub fn n_invocation_tokens(&self) -> u64 {
592 // SAFETY: the adapter handle and the model it came from are both alive for the
593 // call; any path argument is a `CString` that outlives it.
594 unsafe {
595 llama_cpp_sys_4::llama_adapter_get_alora_n_invocation_tokens(self.lora_adapter.as_ptr())
596 }
597 }
598
599 /// Get the invocation tokens for this adapter.
600 ///
601 /// Returns an empty slice if there are no invocation tokens.
602 #[must_use]
603 #[allow(clippy::cast_possible_truncation)]
604 pub fn invocation_tokens(&self) -> &[LlamaToken] {
605 let n = self.n_invocation_tokens() as usize;
606 if n == 0 {
607 return &[];
608 }
609 // SAFETY: the adapter handle and the model it came from are both alive for the
610 // call; any path argument is a `CString` that outlives it.
611 let ptr = unsafe {
612 llama_cpp_sys_4::llama_adapter_get_alora_invocation_tokens(self.lora_adapter.as_ptr())
613 };
614 if ptr.is_null() {
615 return &[];
616 }
617 // LlamaToken is repr(transparent) over llama_token (i32), so this cast is safe
618 // SAFETY: the pointer is non-null and the length is the count llama.cpp reported
619 // for that same buffer, so the slice stays inside it.
620 unsafe { std::slice::from_raw_parts(ptr.cast::<LlamaToken>(), n) }
621 }
622}
623
624impl Drop for LlamaLoraAdapter {
625 fn drop(&mut self) {
626 // SAFETY: this runs once from `Drop` on a non-null handle, and nothing reads it
627 // afterwards.
628 unsafe {
629 llama_cpp_sys_4::llama_adapter_lora_free(self.lora_adapter.as_ptr());
630 }
631 }
632}
633
634/// A Safe wrapper around `llama_chat_message`
635#[derive(Debug, Eq, PartialEq, Clone)]
636pub struct LlamaChatMessage {
637 role: CString,
638 content: CString,
639}
640
641impl LlamaChatMessage {
642 /// Create a new `LlamaChatMessage`.
643 ///
644 /// # Errors
645 ///
646 /// Returns [`NewLlamaChatMessageError`] if the role or content contains a null byte.
647 pub fn new(role: String, content: String) -> Result<Self, NewLlamaChatMessageError> {
648 Ok(Self {
649 role: CString::new(role)?,
650 content: CString::new(content)?,
651 })
652 }
653}
654
655/// How to determine if we should prepend a bos token to tokens
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub enum AddBos {
658 /// Add the beginning of stream token to the start of the string.
659 Always,
660 /// Do not add the beginning of stream token to the start of the string.
661 Never,
662}
663
664/// How to determine if we should tokenize special tokens
665#[derive(Debug, Clone, Copy, PartialEq, Eq)]
666pub enum Special {
667 /// Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext. Does not insert a leading space.
668 Tokenize,
669 /// Treat special and/or control tokens as plaintext.
670 Plaintext,
671}
672
673/// Which `DFlash` draft family a checkpoint belongs to.
674///
675/// Mirrors `llama_dflash_variant`. [`None`](Self::None) is upstream's `-1` and
676/// means the model is not a `DFlash` draft, which is the case for every
677/// ordinary checkpoint.
678#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
679#[non_exhaustive]
680pub enum LlamaDflashVariant {
681 /// Not a `DFlash` draft model.
682 None,
683 /// `DFlash`.
684 Dflash,
685 /// `DFlash2`.
686 Dflash2,
687 /// `DSpark`.
688 Dspark,
689 /// `LiliCorr`.
690 Lilicorr,
691}
692
693impl LlamaDflashVariant {
694 /// Map the raw `llama_dflash_variant` value.
695 ///
696 /// An unrecognised value reads as [`None`](Self::None): a variant this
697 /// build does not know is not one it can drive.
698 fn from_raw(raw: llama_cpp_sys_4::llama_dflash_variant) -> Self {
699 match raw {
700 llama_cpp_sys_4::LLAMA_DFLASH_VARIANT_DFLASH => Self::Dflash,
701 llama_cpp_sys_4::LLAMA_DFLASH_VARIANT_DFLASH2 => Self::Dflash2,
702 llama_cpp_sys_4::LLAMA_DFLASH_VARIANT_DSPARK => Self::Dspark,
703 llama_cpp_sys_4::LLAMA_DFLASH_VARIANT_LILICORR => Self::Lilicorr,
704 _ => Self::None,
705 }
706 }
707}
708
709// SAFETY: a `llama_model` is not tied to the thread that loaded it; llama.cpp
710// stores no thread-local state in it.
711unsafe impl Send for LlamaModel {}
712
713// SAFETY: every method on `LlamaModel` that mutates the underlying model takes
714// `&mut self` (`set_attn_rot`), so a shared reference reaches only reads,
715// which llama.cpp allows concurrently.
716unsafe impl Sync for LlamaModel {}
717
718impl LlamaModel {
719 /// Retrieves the vocabulary associated with the current Llama model.
720 ///
721 /// This method fetches the vocabulary from the underlying model using an unsafe
722 /// FFI call. The returned `LlamaVocab` struct contains a non-null pointer to
723 /// the vocabulary data, which is wrapped in a `NonNull` for safety.
724 ///
725 /// # Safety
726 /// This method uses an unsafe block to call a C function (`llama_model_get_vocab`),
727 /// which is assumed to return a valid pointer to the vocabulary. The caller should
728 /// ensure that the model object is properly initialized and valid before calling
729 /// this method, as dereferencing invalid pointers can lead to undefined behavior.
730 ///
731 /// # Returns
732 /// A `LlamaVocab` struct containing the vocabulary of the model.
733 ///
734 /// # Panics
735 ///
736 /// Panics if the underlying C function returns a null pointer.
737 ///
738 /// # Example
739 /// ```rust,ignore
740 /// let vocab = model.get_vocab();
741 /// ```
742 #[must_use]
743 pub fn get_vocab(&self) -> LlamaVocab {
744 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
745 // scalars llama.cpp validates itself.
746 let llama_vocab = unsafe { llama_model_get_vocab(self.model.as_ptr()) }.cast_mut();
747
748 LlamaVocab {
749 vocab: NonNull::new(llama_vocab).unwrap(),
750 }
751 }
752 /// Get the number of tokens the model was trained on.
753 ///
754 /// This function returns the number of tokens that the model was trained on, represented as a `u32`.
755 ///
756 /// # Panics
757 ///
758 /// This function will panic if the number of tokens the model was trained on does not fit into a `u32`.
759 /// This should be impossible on most platforms since llama.cpp returns a `c_int` (i32 on most platforms),
760 /// which is almost certainly positive.
761 #[must_use]
762 pub fn n_ctx_train(&self) -> u32 {
763 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
764 // scalars llama.cpp validates itself.
765 let n_ctx_train = unsafe { llama_model_n_ctx_train(self.model.as_ptr()) };
766 u32::try_from(n_ctx_train).expect("n_ctx_train fits into an u32")
767 }
768
769 /// Get all tokens in the model.
770 ///
771 /// This function returns an iterator over all the tokens in the model. Each item in the iterator is a tuple
772 /// containing a `LlamaToken` and its corresponding string representation (or an error if the conversion fails).
773 ///
774 /// # Parameters
775 ///
776 /// - `special`: The `Special` value that determines how special tokens (like BOS, EOS, etc.) are handled.
777 pub fn tokens(
778 &self,
779 special: Special,
780 ) -> impl Iterator<Item = (LlamaToken, Result<String, TokenToStringError>)> + '_ {
781 (0..self.n_vocab())
782 .map(LlamaToken::new)
783 .map(move |llama_token| (llama_token, self.token_to_str(llama_token, special)))
784 }
785
786 /// Get the beginning of stream token.
787 ///
788 /// This function returns the token that represents the beginning of a stream (BOS token).
789 #[must_use]
790 pub fn token_bos(&self) -> LlamaToken {
791 self.get_vocab().bos()
792 }
793
794 /// Get the end of stream token.
795 ///
796 /// This function returns the token that represents the end of a stream (EOS token).
797 #[must_use]
798 pub fn token_eos(&self) -> LlamaToken {
799 self.get_vocab().eos()
800 }
801
802 /// Get the newline token.
803 ///
804 /// This function returns the token that represents a newline character.
805 #[must_use]
806 pub fn token_nl(&self) -> LlamaToken {
807 self.get_vocab().nl()
808 }
809
810 /// Check if a token represents the end of generation (end of turn, end of sequence, etc.).
811 ///
812 /// This function returns `true` if the provided token signifies the end of generation or end of sequence,
813 /// such as EOS or other special tokens.
814 ///
815 /// # Parameters
816 ///
817 /// - `token`: The `LlamaToken` to check.
818 ///
819 /// # Returns
820 ///
821 /// - `true` if the token is an end-of-generation token, otherwise `false`.
822 #[must_use]
823 pub fn is_eog_token(&self, token: LlamaToken) -> bool {
824 self.get_vocab().is_eog(token)
825 }
826
827 /// Get the classification token.
828 ///
829 /// # Deprecated
830 ///
831 /// Mirrors [`LlamaVocab::cls`]: upstream dropped `llama_vocab_cls`, so this
832 /// resolves to [`token_bos`](Self::token_bos).
833 #[must_use]
834 #[deprecated(
835 since = "0.12.0",
836 note = "upstream removed `llama_vocab_cls`; this is now an alias for `token_bos`"
837 )]
838 pub fn token_cls(&self) -> LlamaToken {
839 self.get_vocab().bos()
840 }
841
842 /// Get the end-of-turn token.
843 #[must_use]
844 pub fn token_eot(&self) -> LlamaToken {
845 self.get_vocab().eot()
846 }
847
848 /// Get the padding token.
849 #[must_use]
850 pub fn token_pad(&self) -> LlamaToken {
851 self.get_vocab().pad()
852 }
853
854 /// Get the separator token.
855 #[must_use]
856 pub fn token_sep(&self) -> LlamaToken {
857 self.get_vocab().sep()
858 }
859
860 /// Get the fill-in-the-middle prefix token.
861 #[must_use]
862 pub fn token_fim_pre(&self) -> LlamaToken {
863 self.get_vocab().fim_pre()
864 }
865
866 /// Get the fill-in-the-middle suffix token.
867 #[must_use]
868 pub fn token_fim_suf(&self) -> LlamaToken {
869 self.get_vocab().fim_suf()
870 }
871
872 /// Get the fill-in-the-middle middle token.
873 #[must_use]
874 pub fn token_fim_mid(&self) -> LlamaToken {
875 self.get_vocab().fim_mid()
876 }
877
878 /// Get the fill-in-the-middle padding token.
879 #[must_use]
880 pub fn token_fim_pad(&self) -> LlamaToken {
881 self.get_vocab().fim_pad()
882 }
883
884 /// Get the fill-in-the-middle repository token.
885 #[must_use]
886 pub fn token_fim_rep(&self) -> LlamaToken {
887 self.get_vocab().fim_rep()
888 }
889
890 /// Get the fill-in-the-middle separator token.
891 #[must_use]
892 pub fn token_fim_sep(&self) -> LlamaToken {
893 self.get_vocab().fim_sep()
894 }
895
896 /// Check if a token is a control token.
897 #[must_use]
898 pub fn token_is_control(&self, token: LlamaToken) -> bool {
899 self.get_vocab().is_control(token)
900 }
901
902 /// Get the score of a token.
903 #[must_use]
904 pub fn token_get_score(&self, token: LlamaToken) -> f32 {
905 self.get_vocab().get_score(token)
906 }
907
908 /// Get the raw text of a token.
909 ///
910 /// # Errors
911 ///
912 /// Returns an error if the token text is null or not valid UTF-8.
913 pub fn token_get_text(&self, token: LlamaToken) -> Result<&str, StringFromModelError> {
914 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
915 // token and index arguments are scalars llama.cpp range-checks.
916 let ptr = unsafe {
917 llama_cpp_sys_4::llama_vocab_get_text(self.get_vocab().vocab.as_ref(), token.0)
918 };
919 if ptr.is_null() {
920 return Err(StringFromModelError::ReturnedError(-1));
921 }
922 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
923 // it owns, which outlives the borrow taken here.
924 let cstr = unsafe { CStr::from_ptr(ptr) };
925 cstr.to_str().map_err(StringFromModelError::Utf8Error)
926 }
927
928 /// Check if a BOS token should be added when tokenizing.
929 #[must_use]
930 pub fn add_bos_token(&self) -> bool {
931 self.get_vocab().get_add_bos()
932 }
933
934 /// Check if an EOS token should be added when tokenizing.
935 #[must_use]
936 pub fn add_eos_token(&self) -> bool {
937 self.get_vocab().get_add_eos()
938 }
939
940 /// Get the decoder start token.
941 ///
942 /// This function returns the token used to signal the start of decoding (i.e., the token used at the start
943 /// of a sequence generation).
944 #[must_use]
945 pub fn decode_start_token(&self) -> LlamaToken {
946 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
947 // scalars llama.cpp validates itself.
948 let token = unsafe { llama_model_decoder_start_token(self.model.as_ptr()) };
949 LlamaToken(token)
950 }
951
952 /// Convert a single token to a string.
953 ///
954 /// This function converts a `LlamaToken` into its string representation.
955 ///
956 /// # Errors
957 ///
958 /// This function returns an error if the token cannot be converted to a string. For more details, refer to
959 /// [`TokenToStringError`].
960 ///
961 /// # Parameters
962 ///
963 /// - `token`: The `LlamaToken` to convert.
964 /// - `special`: The `Special` value used to handle special tokens.
965 pub fn token_to_str(
966 &self,
967 token: LlamaToken,
968 special: Special,
969 ) -> Result<String, TokenToStringError> {
970 self.token_to_str_with_size(token, 32, special)
971 }
972
973 /// Convert a single token to bytes.
974 ///
975 /// This function converts a `LlamaToken` into a byte representation.
976 ///
977 /// # Errors
978 ///
979 /// This function returns an error if the token cannot be converted to bytes. For more details, refer to
980 /// [`TokenToStringError`].
981 ///
982 /// # Parameters
983 ///
984 /// - `token`: The `LlamaToken` to convert.
985 /// - `special`: The `Special` value used to handle special tokens.
986 pub fn token_to_bytes(
987 &self,
988 token: LlamaToken,
989 special: Special,
990 ) -> Result<Vec<u8>, TokenToStringError> {
991 self.token_to_bytes_with_size(token, 32, special, None)
992 }
993
994 /// Convert a single token to its raw llama.cpp piece bytes.
995 ///
996 /// Unlike [`LlamaModel::token_to_bytes`], this does not discard tokens based
997 /// on token attributes before calling llama.cpp. This is useful for runtimes
998 /// that must preserve control, byte, or other model-specific pieces exactly.
999 ///
1000 /// This convenience form sizes the buffer automatically: it attempts a small
1001 /// default buffer and, if llama.cpp reports it is too small, retries once
1002 /// with the exact size llama.cpp requires. Use
1003 /// [`LlamaModel::token_to_raw_bytes_with_size`] when you want explicit
1004 /// control over the buffer (for example to reuse an allocation).
1005 ///
1006 /// # Errors
1007 ///
1008 /// This function returns an error if llama.cpp cannot convert the token.
1009 pub fn token_to_raw_bytes(
1010 &self,
1011 token: LlamaToken,
1012 special: Special,
1013 ) -> Result<Vec<u8>, TokenToStringError> {
1014 let mut buffer = Vec::with_capacity(32);
1015 self.token_to_raw_bytes_into(token, special, &mut buffer)?;
1016 Ok(buffer)
1017 }
1018
1019 /// Converts one token to raw piece bytes in caller-owned reusable storage.
1020 ///
1021 /// # Errors
1022 ///
1023 /// Returns an error if llama.cpp reports an unknown token or an excessive
1024 /// required buffer length.
1025 pub fn token_to_raw_bytes_into(
1026 &self,
1027 token: LlamaToken,
1028 special: Special,
1029 buffer: &mut Vec<u8>,
1030 ) -> Result<(), TokenToStringError> {
1031 let special = matches!(special, Special::Tokenize);
1032 buffer.clear();
1033 if buffer.capacity() < 32 {
1034 buffer.reserve(32);
1035 }
1036 loop {
1037 let capacity = buffer.capacity();
1038 buffer.resize(capacity, 0);
1039 let native_capacity = c_int::try_from(capacity)
1040 .map_err(|_| TokenToStringError::BufferCapacityExceeded(capacity))?;
1041 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1042 // cannot write past it; a negative return means the buffer was too small
1043 // and nothing was written. Any string arguments are `CString`s alive for
1044 // the call.
1045 let size = unsafe {
1046 llama_token_to_piece(
1047 self.get_vocab().vocab.as_ref(),
1048 token.0,
1049 buffer.as_mut_ptr().cast::<c_char>(),
1050 native_capacity,
1051 0,
1052 special,
1053 )
1054 };
1055 match size {
1056 0 => {
1057 buffer.clear();
1058 return Err(TokenToStringError::UnknownTokenType);
1059 }
1060 needed if needed.is_negative() => {
1061 let required = usize::try_from(-needed)
1062 .map_err(|_| TokenToStringError::InsufficientBufferSpace(needed))?;
1063 buffer.clear();
1064 if required <= capacity {
1065 return Err(TokenToStringError::InsufficientBufferSpace(needed));
1066 }
1067 buffer.reserve_exact(required);
1068 }
1069 written => {
1070 let written = usize::try_from(written).map_err(|_| {
1071 TokenToStringError::NativePieceLength {
1072 returned: written,
1073 capacity,
1074 }
1075 })?;
1076 if written > capacity {
1077 buffer.clear();
1078 return Err(TokenToStringError::NativePieceLength {
1079 returned: size,
1080 capacity,
1081 });
1082 }
1083 buffer.truncate(written);
1084 return Ok(());
1085 }
1086 }
1087 }
1088 }
1089
1090 /// Convert a slice of tokens to their concatenated raw llama.cpp piece bytes.
1091 ///
1092 /// This is the batch counterpart to [`LlamaModel::token_to_raw_bytes`]: it
1093 /// forwards each token directly to `llama_token_to_piece` without the
1094 /// token-attribute filtering applied by [`LlamaModel::tokens_to_str`] /
1095 /// [`LlamaModel::detokenize`], preserving control, byte, and other
1096 /// model-specific pieces exactly. The bytes are not guaranteed to be valid
1097 /// UTF-8 on their own, since a single codepoint may be split across several
1098 /// byte-fallback tokens; see [`crate::token::detokenizer`] for incremental,
1099 /// UTF-8-aware decoding.
1100 ///
1101 /// # Errors
1102 ///
1103 /// Returns an error if any token cannot be converted (see
1104 /// [`LlamaModel::token_to_raw_bytes`]).
1105 pub fn tokens_to_raw_bytes(
1106 &self,
1107 tokens: &[LlamaToken],
1108 special: Special,
1109 ) -> Result<Vec<u8>, TokenToStringError> {
1110 let mut bytes = Vec::new();
1111 for &token in tokens {
1112 bytes.extend_from_slice(&self.token_to_raw_bytes(token, special)?);
1113 }
1114 Ok(bytes)
1115 }
1116
1117 /// Convert a vector of tokens to a single string.
1118 ///
1119 /// This function takes a slice of `LlamaToken`s and converts them into a single string, concatenating their
1120 /// string representations.
1121 ///
1122 /// # Errors
1123 ///
1124 /// This function returns an error if any token cannot be converted to a string. For more details, refer to
1125 /// [`TokenToStringError`].
1126 ///
1127 /// # Parameters
1128 ///
1129 /// - `tokens`: A slice of `LlamaToken`s to convert.
1130 /// - `special`: The `Special` value used to handle special tokens.
1131 pub fn tokens_to_str(
1132 &self,
1133 tokens: &[LlamaToken],
1134 special: Special,
1135 ) -> Result<String, TokenToStringError> {
1136 let mut builder = String::with_capacity(tokens.len() * 4);
1137 for str in tokens
1138 .iter()
1139 .copied()
1140 .map(|t| self.token_to_str(t, special))
1141 {
1142 builder += &str?;
1143 }
1144 Ok(builder)
1145 }
1146
1147 /// Convert a string to a vector of tokens.
1148 ///
1149 /// This function converts a string into a vector of `LlamaToken`s. The function will tokenize the string
1150 /// and return the corresponding tokens.
1151 ///
1152 /// # Errors
1153 ///
1154 /// - This function will return an error if the input string contains a null byte.
1155 ///
1156 /// # Panics
1157 ///
1158 /// - This function will panic if the number of tokens exceeds `usize::MAX`.
1159 ///
1160 /// # Example
1161 ///
1162 /// ```no_run
1163 /// use llama_cpp_4::model::LlamaModel;
1164 ///
1165 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1166 /// use std::path::Path;
1167 /// use llama_cpp_4::model::AddBos;
1168 /// let backend = llama_cpp_4::llama_backend::LlamaBackend::init()?;
1169 /// let model = LlamaModel::load_from_file(&backend, Path::new("path/to/model"), &Default::default())?;
1170 /// let tokens = model.str_to_token("Hello, World!", AddBos::Always)?;
1171 /// # Ok(())
1172 /// # }
1173 /// ```
1174 pub fn str_to_token(
1175 &self,
1176 str: &str,
1177 add_bos: AddBos,
1178 ) -> Result<Vec<LlamaToken>, StringToTokenError> {
1179 let mut buffer = Vec::new();
1180 self.str_to_token_into(str, add_bos, &mut buffer)?;
1181 Ok(buffer)
1182 }
1183
1184 /// Tokenizes into caller-owned storage so repeated operations can reuse
1185 /// their allocation.
1186 ///
1187 /// # Errors
1188 ///
1189 /// Returns an error when the text contains NUL or its length exceeds the
1190 /// native integer representation.
1191 pub fn str_to_token_into(
1192 &self,
1193 str: &str,
1194 add_bos: AddBos,
1195 buffer: &mut Vec<LlamaToken>,
1196 ) -> Result<(), StringToTokenError> {
1197 self.str_to_token_into_with_special(str, add_bos, Special::Tokenize, buffer)
1198 }
1199
1200 /// Tokenize, choosing whether markup like `<|im_start|>` becomes the
1201 /// special token or literal text.
1202 ///
1203 /// [`Self::str_to_token`] always parses special tokens, which is right for
1204 /// text your own template produced and wrong for text a *user* supplied: if
1205 /// a user types `<|im_start|>assistant` and it tokenizes as the real
1206 /// control token, they have forged a turn. Pass [`Special::Plaintext`] for
1207 /// anything that came from outside.
1208 ///
1209 /// [`ChatParams::tokenize_prompt`](crate::chat::ChatParams::tokenize_prompt)
1210 /// does this for you across a rendered prompt, using llama.cpp's own
1211 /// per-span `is_input` flags.
1212 ///
1213 /// # Errors
1214 ///
1215 /// Returns an error when the text contains NUL or its length exceeds the
1216 /// native integer representation.
1217 pub fn str_to_token_with_special(
1218 &self,
1219 str: &str,
1220 add_bos: AddBos,
1221 special: Special,
1222 ) -> Result<Vec<LlamaToken>, StringToTokenError> {
1223 let mut buffer = Vec::new();
1224 self.str_to_token_into_with_special(str, add_bos, special, &mut buffer)?;
1225 Ok(buffer)
1226 }
1227
1228 /// [`Self::str_to_token_with_special`] into caller-owned storage.
1229 ///
1230 /// # Errors
1231 ///
1232 /// Returns an error when the text contains NUL or its length exceeds the
1233 /// native integer representation.
1234 pub fn str_to_token_into_with_special(
1235 &self,
1236 str: &str,
1237 add_bos: AddBos,
1238 special: Special,
1239 buffer: &mut Vec<LlamaToken>,
1240 ) -> Result<(), StringToTokenError> {
1241 let parse_special = matches!(special, Special::Tokenize);
1242 let add_bos = match add_bos {
1243 AddBos::Always => true,
1244 AddBos::Never => false,
1245 };
1246 if let Some(position) = str.as_bytes().iter().position(|byte| *byte == 0) {
1247 return Err(StringToTokenError::InteriorNul(position));
1248 }
1249 let tokens_estimation = std::cmp::max(8, (str.len() / 2) + usize::from(add_bos));
1250 buffer.clear();
1251 if buffer.capacity() < tokens_estimation {
1252 buffer.reserve(tokens_estimation);
1253 }
1254 let buffer_capacity = c_int::try_from(buffer.capacity())?;
1255 let text_length = c_int::try_from(str.len())?;
1256 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1257 // cannot write past it; a negative return means the buffer was too small
1258 // and nothing was written. Any string arguments are `CString`s alive for
1259 // the call.
1260 let size = unsafe {
1261 llama_tokenize(
1262 self.get_vocab().vocab.as_ref(),
1263 str.as_ptr().cast(),
1264 text_length,
1265 buffer.as_mut_ptr().cast(),
1266 buffer_capacity,
1267 add_bos,
1268 parse_special,
1269 )
1270 };
1271
1272 // if we fail the first time we can resize the vector to the correct size and try again. This should never fail.
1273 // as a result - size is guaranteed to be positive here.
1274 let size = if size.is_negative() {
1275 let required = usize::try_from(size.unsigned_abs())?;
1276 if buffer.capacity() < required {
1277 buffer.reserve_exact(required);
1278 }
1279 let retry_capacity = c_int::try_from(buffer.capacity())?;
1280 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1281 // cannot write past it; a negative return means the buffer was too small
1282 // and nothing was written. Any string arguments are `CString`s alive for
1283 // the call.
1284 unsafe {
1285 llama_tokenize(
1286 self.get_vocab().vocab.as_ref(),
1287 str.as_ptr().cast(),
1288 text_length,
1289 buffer.as_mut_ptr().cast(),
1290 retry_capacity,
1291 add_bos,
1292 parse_special,
1293 )
1294 }
1295 } else {
1296 size
1297 };
1298
1299 let native_size = size;
1300 let size = usize::try_from(native_size)?;
1301 if size > buffer.capacity() {
1302 return Err(StringToTokenError::NativeTokenCount {
1303 returned: native_size,
1304 capacity: buffer.capacity(),
1305 });
1306 }
1307
1308 // Safety: `size <= capacity` and llama.cpp initialized elements up to `size`.
1309 unsafe { buffer.set_len(size) }
1310 Ok(())
1311 }
1312
1313 /// Counts tokens without materializing token identifiers.
1314 ///
1315 /// # Errors
1316 ///
1317 /// Returns an error when the text contains NUL or its length/count cannot
1318 /// be represented by the native API.
1319 pub fn str_token_count(&self, str: &str, add_bos: AddBos) -> Result<usize, StringToTokenError> {
1320 let add_bos = matches!(add_bos, AddBos::Always);
1321 if let Some(position) = str.as_bytes().iter().position(|byte| *byte == 0) {
1322 return Err(StringToTokenError::InteriorNul(position));
1323 }
1324 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1325 // cannot write past it; a negative return means the buffer was too small
1326 // and nothing was written. Any string arguments are `CString`s alive for
1327 // the call.
1328 let size = unsafe {
1329 llama_tokenize(
1330 self.get_vocab().vocab.as_ref(),
1331 str.as_ptr().cast(),
1332 c_int::try_from(str.len())?,
1333 std::ptr::null_mut(),
1334 0,
1335 add_bos,
1336 true,
1337 )
1338 };
1339 Ok(usize::try_from(i64::from(size).unsigned_abs())?)
1340 }
1341
1342 /// Get the type of a token.
1343 ///
1344 /// This function retrieves the attributes associated with a given token. The attributes are typically used to
1345 /// understand whether the token represents a special type of token (e.g., beginning-of-sequence (BOS), end-of-sequence (EOS),
1346 /// control tokens, etc.).
1347 ///
1348 /// # Panics
1349 ///
1350 /// - This function will panic if the token type is unknown or cannot be converted to a valid `LlamaTokenAttrs`.
1351 ///
1352 /// # Example
1353 ///
1354 /// ```no_run
1355 /// use llama_cpp_4::model::LlamaModel;
1356 /// use llama_cpp_4::model::params::LlamaModelParams;
1357 /// use llama_cpp_4::llama_backend::LlamaBackend;
1358 /// use llama_cpp_4::token::LlamaToken;
1359 ///
1360 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1361 /// let backend = LlamaBackend::init()?;
1362 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1363 /// let token = LlamaToken::new(42);
1364 /// let token_attrs = model.token_attr(token);
1365 /// # Ok(())
1366 /// # }
1367 /// ```
1368 #[must_use]
1369 pub fn token_attr(&self, LlamaToken(id): LlamaToken) -> LlamaTokenAttrs {
1370 let token_type =
1371 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
1372 // token and index arguments are scalars llama.cpp range-checks.
1373 unsafe { llama_cpp_sys_4::llama_vocab_get_attr(self.get_vocab().vocab.as_ref(), id) };
1374 LlamaTokenAttrs::try_from(token_type).expect("token type is valid")
1375 }
1376
1377 /// Detokenize a slice of tokens into a string.
1378 ///
1379 /// This is the inverse of [`str_to_token`](Self::str_to_token).
1380 ///
1381 /// # Parameters
1382 ///
1383 /// - `tokens`: The tokens to detokenize.
1384 /// - `remove_special`: If `true`, special tokens are removed from the output.
1385 /// - `unparse_special`: If `true`, special tokens are rendered as their text representation.
1386 ///
1387 /// # Errors
1388 ///
1389 /// Returns an error if the detokenized text is not valid UTF-8.
1390 #[allow(
1391 clippy::cast_possible_truncation,
1392 clippy::cast_possible_wrap,
1393 clippy::cast_sign_loss
1394 )]
1395 pub fn detokenize(
1396 &self,
1397 tokens: &[LlamaToken],
1398 remove_special: bool,
1399 unparse_special: bool,
1400 ) -> Result<String, StringFromModelError> {
1401 // First call with empty buffer to get required size
1402 let n_tokens = tokens.len() as i32;
1403 let token_ptr = tokens.as_ptr().cast::<llama_cpp_sys_4::llama_token>();
1404 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1405 // cannot write past it; a negative return means the buffer was too small
1406 // and nothing was written. Any string arguments are `CString`s alive for
1407 // the call.
1408 let needed = unsafe {
1409 llama_detokenize(
1410 self.get_vocab().vocab.as_ref(),
1411 token_ptr,
1412 n_tokens,
1413 std::ptr::null_mut(),
1414 0,
1415 remove_special,
1416 unparse_special,
1417 )
1418 };
1419 // llama_detokenize returns negative required size when buffer is too small
1420 let buf_size = if needed < 0 {
1421 (-needed) as usize
1422 } else {
1423 needed as usize
1424 };
1425 let mut buf = vec![0u8; buf_size];
1426 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1427 // cannot write past it; a negative return means the buffer was too small
1428 // and nothing was written. Any string arguments are `CString`s alive for
1429 // the call.
1430 let ret = unsafe {
1431 llama_detokenize(
1432 self.get_vocab().vocab.as_ref(),
1433 token_ptr,
1434 n_tokens,
1435 buf.as_mut_ptr().cast::<c_char>(),
1436 buf_size as i32,
1437 remove_special,
1438 unparse_special,
1439 )
1440 };
1441 if ret < 0 {
1442 return Err(StringFromModelError::ReturnedError(ret));
1443 }
1444 let len = ret as usize;
1445 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
1446 Ok(s.to_owned())
1447 }
1448
1449 /// Convert a token to a string with a specified buffer size.
1450 ///
1451 /// This function allows you to convert a token into a string, with the ability to specify a buffer size for the operation.
1452 /// It is generally recommended to use `LlamaModel::token_to_str` instead, as 8 bytes is typically sufficient for most tokens,
1453 /// and the extra buffer size doesn't usually matter.
1454 ///
1455 /// # Errors
1456 ///
1457 /// - If the token type is unknown, an error will be returned.
1458 /// - If the resultant token exceeds the provided `buffer_size`, an error will occur.
1459 /// - If the token string returned by `llama-cpp` is not valid UTF-8, it will return an error.
1460 ///
1461 /// # Panics
1462 ///
1463 /// - This function will panic if the `buffer_size` does not fit into a `c_int`.
1464 /// - It will also panic if the size returned from `llama-cpp` does not fit into a `usize`, which should typically never happen.
1465 ///
1466 /// # Example
1467 ///
1468 /// ```no_run
1469 /// use llama_cpp_4::model::{LlamaModel, Special};
1470 /// use llama_cpp_4::model::params::LlamaModelParams;
1471 /// use llama_cpp_4::llama_backend::LlamaBackend;
1472 /// use llama_cpp_4::token::LlamaToken;
1473 ///
1474 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1475 /// let backend = LlamaBackend::init()?;
1476 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1477 /// let token = LlamaToken::new(42);
1478 /// let token_string = model.token_to_str_with_size(token, 32, Special::Plaintext)?;
1479 /// # Ok(())
1480 /// # }
1481 /// ```
1482 pub fn token_to_str_with_size(
1483 &self,
1484 token: LlamaToken,
1485 buffer_size: usize,
1486 special: Special,
1487 ) -> Result<String, TokenToStringError> {
1488 let bytes = self.token_to_bytes_with_size(token, buffer_size, special, None)?;
1489 Ok(String::from_utf8(bytes)?)
1490 }
1491
1492 /// Convert a token to bytes with a specified buffer size.
1493 ///
1494 /// Generally you should use [`LlamaModel::token_to_bytes`] instead as 8 bytes is enough for most words and
1495 /// the extra bytes do not really matter.
1496 ///
1497 /// # Errors
1498 ///
1499 /// - if the token type is unknown
1500 /// - the resultant token is larger than `buffer_size`.
1501 ///
1502 /// # Panics
1503 ///
1504 /// - This function will panic if `buffer_size` cannot fit into a `c_int`.
1505 /// - It will also panic if the size returned from `llama-cpp` cannot be converted to `usize` (which should not happen).
1506 ///
1507 /// # Example
1508 ///
1509 /// ```no_run
1510 /// use llama_cpp_4::model::{LlamaModel, Special};
1511 /// use llama_cpp_4::model::params::LlamaModelParams;
1512 /// use llama_cpp_4::llama_backend::LlamaBackend;
1513 /// use llama_cpp_4::token::LlamaToken;
1514 ///
1515 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1516 /// let backend = LlamaBackend::init()?;
1517 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1518 /// let token = LlamaToken::new(42);
1519 /// let token_bytes = model.token_to_bytes_with_size(token, 32, Special::Plaintext, None)?;
1520 /// # Ok(())
1521 /// # }
1522 /// ```
1523 pub fn token_to_bytes_with_size(
1524 &self,
1525 token: LlamaToken,
1526 buffer_size: usize,
1527 special: Special,
1528 lstrip: Option<NonZeroU16>,
1529 ) -> Result<Vec<u8>, TokenToStringError> {
1530 if token == self.token_nl() {
1531 return Ok(String::from("\n").into_bytes());
1532 }
1533
1534 // unsure what to do with this in the face of the 'special' arg + attr changes
1535 let attrs = self.token_attr(token);
1536 if (attrs.contains(LlamaTokenAttr::Control)
1537 && (token == self.token_bos() || token == self.token_eos()))
1538 || attrs.is_empty()
1539 || attrs
1540 .intersects(LlamaTokenAttr::Unknown | LlamaTokenAttr::Byte | LlamaTokenAttr::Unused)
1541 {
1542 return Ok(Vec::new());
1543 }
1544
1545 let special = match special {
1546 Special::Tokenize => true,
1547 Special::Plaintext => false,
1548 };
1549
1550 let string = CString::new(vec![b'*'; buffer_size]).expect("no null");
1551 let len = string.as_bytes().len();
1552 let len = c_int::try_from(len).expect("length fits into c_int");
1553 let buf = string.into_raw();
1554 let lstrip = lstrip.map_or(0, |it| i32::from(it.get()));
1555 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1556 // cannot write past it; a negative return means the buffer was too small
1557 // and nothing was written. Any string arguments are `CString`s alive for
1558 // the call.
1559 let size = unsafe {
1560 llama_token_to_piece(
1561 self.get_vocab().vocab.as_ref(),
1562 token.0,
1563 buf,
1564 len,
1565 lstrip,
1566 special,
1567 )
1568 };
1569
1570 match size {
1571 0 => Err(TokenToStringError::UnknownTokenType),
1572 i if i.is_negative() => Err(TokenToStringError::InsufficientBufferSpace(i)),
1573 size => {
1574 // SAFETY: the bytes come from llama.cpp's own output and contain no interior NUL,
1575 // which is what the unchecked constructor requires.
1576 let string = unsafe { CString::from_raw(buf) };
1577 let mut bytes = string.into_bytes();
1578 let len = usize::try_from(size).expect("size is positive and fits into usize");
1579 bytes.truncate(len);
1580 Ok(bytes)
1581 }
1582 }
1583 }
1584
1585 /// Convert a token to raw llama.cpp piece bytes with a specified buffer size.
1586 ///
1587 /// This intentionally bypasses the token-attribute filtering in
1588 /// [`LlamaModel::token_to_bytes_with_size`] and forwards directly to
1589 /// `llama_token_to_piece`.
1590 ///
1591 /// # Errors
1592 ///
1593 /// - if llama.cpp reports an unknown token type.
1594 /// - if the resultant token is larger than `buffer_size`.
1595 ///
1596 /// # Panics
1597 ///
1598 /// This function will panic if `buffer_size` cannot fit into a `c_int`.
1599 pub fn token_to_raw_bytes_with_size(
1600 &self,
1601 token: LlamaToken,
1602 buffer_size: usize,
1603 special: Special,
1604 lstrip: Option<NonZeroU16>,
1605 ) -> Result<Vec<u8>, TokenToStringError> {
1606 let special = match special {
1607 Special::Tokenize => true,
1608 Special::Plaintext => false,
1609 };
1610 let mut buffer = vec![0_u8; buffer_size];
1611 let len = c_int::try_from(buffer.len()).expect("length fits into c_int");
1612 let lstrip = lstrip.map_or(0, |it| i32::from(it.get()));
1613 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
1614 // cannot write past it; a negative return means the buffer was too small
1615 // and nothing was written. Any string arguments are `CString`s alive for
1616 // the call.
1617 let size = unsafe {
1618 llama_token_to_piece(
1619 self.get_vocab().vocab.as_ref(),
1620 token.0,
1621 buffer.as_mut_ptr().cast::<c_char>(),
1622 len,
1623 lstrip,
1624 special,
1625 )
1626 };
1627
1628 match size {
1629 0 => Err(TokenToStringError::UnknownTokenType),
1630 i if i.is_negative() => Err(TokenToStringError::InsufficientBufferSpace(i)),
1631 size => {
1632 let len = usize::try_from(size).expect("size is positive and fits into usize");
1633 buffer.truncate(len);
1634 Ok(buffer)
1635 }
1636 }
1637 }
1638 /// The number of tokens the model was trained on.
1639 ///
1640 /// This function returns the number of tokens the model was trained on. It is returned as a `c_int` for maximum
1641 /// compatibility with the underlying llama-cpp library, though it can typically be cast to an `i32` without issue.
1642 ///
1643 /// # Example
1644 ///
1645 /// ```no_run
1646 /// use llama_cpp_4::model::LlamaModel;
1647 /// use llama_cpp_4::model::params::LlamaModelParams;
1648 /// use llama_cpp_4::llama_backend::LlamaBackend;
1649 ///
1650 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1651 /// let backend = LlamaBackend::init()?;
1652 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1653 /// let n_vocab = model.n_vocab();
1654 /// # Ok(())
1655 /// # }
1656 /// ```
1657 #[must_use]
1658 pub fn n_vocab(&self) -> i32 {
1659 self.get_vocab().n_tokens()
1660 }
1661
1662 /// The type of vocab the model was trained on.
1663 ///
1664 /// This function returns the type of vocabulary used by the model, such as whether it is based on byte-pair encoding (BPE),
1665 /// word-level tokens, or another tokenization scheme.
1666 ///
1667 /// # Panics
1668 ///
1669 /// - This function will panic if `llama-cpp` emits a vocab type that is not recognized or is invalid for this library.
1670 ///
1671 /// # Example
1672 ///
1673 /// ```no_run
1674 /// use llama_cpp_4::model::LlamaModel;
1675 /// use llama_cpp_4::model::params::LlamaModelParams;
1676 /// use llama_cpp_4::llama_backend::LlamaBackend;
1677 ///
1678 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1679 /// let backend = LlamaBackend::init()?;
1680 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1681 /// let vocab_type = model.vocab_type();
1682 /// # Ok(())
1683 /// # }
1684 /// ```
1685 #[must_use]
1686 pub fn vocab_type(&self) -> VocabType {
1687 // SAFETY: the vocab is borrowed from a live model and outlives the call; the
1688 // token and index arguments are scalars llama.cpp range-checks.
1689 let vocab_type = unsafe { llama_vocab_type(self.get_vocab().vocab.as_ref()) };
1690 VocabType::try_from(vocab_type).expect("invalid vocab type")
1691 }
1692
1693 /// Returns the number of embedding dimensions for the model.
1694 ///
1695 /// This function retrieves the number of embeddings (or embedding dimensions) used by the model. It is typically
1696 /// used for analyzing model architecture and setting up context parameters or other model configuration aspects.
1697 ///
1698 /// # Panics
1699 ///
1700 /// - This function may panic if the underlying `llama-cpp` library returns an invalid embedding dimension value.
1701 ///
1702 /// # Example
1703 ///
1704 /// ```no_run
1705 /// use llama_cpp_4::model::LlamaModel;
1706 /// use llama_cpp_4::model::params::LlamaModelParams;
1707 /// use llama_cpp_4::llama_backend::LlamaBackend;
1708 ///
1709 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1710 /// let backend = LlamaBackend::init()?;
1711 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
1712 /// let n_embd = model.n_embd();
1713 /// # Ok(())
1714 /// # }
1715 /// ```
1716 #[must_use]
1717 pub fn n_embd(&self) -> c_int {
1718 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1719 // scalars llama.cpp validates itself.
1720 unsafe { llama_model_n_embd(self.model.as_ptr()) }
1721 }
1722
1723 /// Get the number of transformer layers in the model.
1724 #[must_use]
1725 pub fn n_layer(&self) -> c_int {
1726 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1727 // scalars llama.cpp validates itself.
1728 unsafe { llama_model_n_layer(self.model.as_ptr()) }
1729 }
1730
1731 /// Get the number of `NextN` / MTP prediction heads bundled with the model.
1732 ///
1733 /// Returns `0` when the checkpoint has no `NextN` blocks. Multi-head models
1734 /// (e.g. Step3.5) return values greater than `1`; pair with
1735 /// [`crate::context::LlamaContext::set_nextn_layer_offset`] on the draft
1736 /// context. See [`crate::mtp`] for the speculative-decoding workflow.
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```no_run
1741 /// # use llama_cpp_4::llama_backend::LlamaBackend;
1742 /// # use llama_cpp_4::model::{LlamaModel, params::LlamaModelParams};
1743 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1744 /// # let backend = LlamaBackend::init()?;
1745 /// # let model = LlamaModel::load_from_file(&backend, "model.gguf", &LlamaModelParams::default())?;
1746 /// if model.n_layer_nextn() > 0 {
1747 /// println!("MTP model with {} NextN heads", model.n_layer_nextn());
1748 /// }
1749 /// # Ok(())
1750 /// # }
1751 /// ```
1752 #[must_use]
1753 pub fn n_layer_nextn(&self) -> c_int {
1754 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1755 // scalars llama.cpp validates itself.
1756 unsafe { llama_model_n_layer_nextn(self.model.as_ptr()) }
1757 }
1758
1759 /// Which `DFlash` draft family this checkpoint belongs to, if any.
1760 ///
1761 /// Speculative decoding picks a different driver per variant, so this is
1762 /// how a caller knows which one a draft model will use — or that it is not
1763 /// a `DFlash` draft at all. Wraps `llama_model_dflash_variant`, new in
1764 /// `b12388`.
1765 #[must_use]
1766 pub fn dflash_variant(&self) -> LlamaDflashVariant {
1767 // SAFETY: `self.model` is non-null and kept alive by this borrow; the
1768 // call only reads a field of the loaded model.
1769 let raw = unsafe { llama_cpp_sys_4::llama_model_dflash_variant(self.model.as_ptr()) };
1770 LlamaDflashVariant::from_raw(raw)
1771 }
1772
1773 /// Candidate tokens a `DFlash2` selector keeps per block position.
1774 ///
1775 /// `0` when the model has no selector head. The packed lattice also holds
1776 /// `top_k x top_k` pairwise transition scores, so this squares into the
1777 /// lattice size. Wraps `llama_model_dflash_selector_top_k`.
1778 #[must_use]
1779 pub fn dflash_selector_top_k(&self) -> i32 {
1780 // SAFETY: a plain read through a live, non-null model.
1781 unsafe { llama_cpp_sys_4::llama_model_dflash_selector_top_k(self.model.as_ptr()) }
1782 }
1783
1784 /// Get the number of mixture-of-experts (`MoE`) layers in the model.
1785 ///
1786 /// Returns `0` for dense (non-MoE) checkpoints.
1787 #[must_use]
1788 pub fn n_expert(&self) -> c_int {
1789 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1790 // scalars llama.cpp validates itself.
1791 unsafe { llama_model_n_expert(self.model.as_ptr()) }
1792 }
1793
1794 /// Number of backend devices the model tensors are spread across.
1795 ///
1796 /// Use with [`Self::get_device`] to inspect each device. Returns `0` when
1797 /// the model is not yet loaded onto any device.
1798 #[must_use]
1799 pub fn n_devices(&self) -> c_int {
1800 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1801 // scalars llama.cpp validates itself.
1802 unsafe { llama_model_n_devices(self.model.as_ptr()) }
1803 }
1804
1805 /// Get the backend device at `index`.
1806 ///
1807 /// Valid indices satisfy `0 <= index < n_devices()`. Returns `None` for
1808 /// out-of-range indices or when the device pointer is null.
1809 #[must_use]
1810 pub fn get_device(&self, index: i32) -> Option<LlamaBackendDevice> {
1811 if index < 0 || index >= self.n_devices() {
1812 return None;
1813 }
1814 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1815 // scalars llama.cpp validates itself.
1816 let dev = unsafe { llama_model_get_device(self.model.as_ptr(), index) };
1817 if dev.is_null() {
1818 None
1819 } else {
1820 Some(LlamaBackendDevice { dev })
1821 }
1822 }
1823
1824 /// Iterate backend devices the model tensors are spread across.
1825 ///
1826 /// Equivalent to calling [`Self::get_device`] for `0..self.n_devices()`.
1827 /// Use [`LlamaBackendDevice::memory`] to inspect free/total bytes per device.
1828 #[must_use]
1829 pub fn devices(&self) -> LlamaBackendDevices<'_> {
1830 LlamaBackendDevices {
1831 model: self,
1832 next: 0,
1833 }
1834 }
1835
1836 /// Target-model layer indices stored in this checkpoint.
1837 ///
1838 /// Populated for EAGLE / distillation draft models that record which target
1839 /// layers they were trained against. Returns an empty slice when the
1840 /// metadata is absent.
1841 #[must_use]
1842 pub fn target_layer_ids(&self) -> &[i32] {
1843 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1844 // scalars llama.cpp validates itself.
1845 let n = unsafe { llama_model_target_layer_ids_n(self.model.as_ptr()) };
1846 if n == 0 {
1847 return &[];
1848 }
1849 // SAFETY: the pointer is non-null and the length is the count llama.cpp reported
1850 // for that same buffer, so the slice stays inside it.
1851 let ptr = unsafe { llama_model_target_layer_ids(self.model.as_ptr()) };
1852 if ptr.is_null() {
1853 &[]
1854 } else {
1855 // SAFETY: the pointer is non-null and the length is the count llama.cpp reported
1856 // for that same buffer, so the slice stays inside it.
1857 unsafe { slice::from_raw_parts(ptr, n as usize) }
1858 }
1859 }
1860
1861 /// Get the number of attention heads in the model.
1862 #[must_use]
1863 pub fn n_head(&self) -> c_int {
1864 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1865 // scalars llama.cpp validates itself.
1866 unsafe { llama_model_n_head(self.model.as_ptr()) }
1867 }
1868
1869 /// Get the number of key-value attention heads in the model.
1870 #[must_use]
1871 pub fn n_head_kv(&self) -> c_int {
1872 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1873 // scalars llama.cpp validates itself.
1874 unsafe { llama_model_n_head_kv(self.model.as_ptr()) }
1875 }
1876
1877 /// Get the input embedding size of the model.
1878 #[must_use]
1879 pub fn n_embd_inp(&self) -> c_int {
1880 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1881 // scalars llama.cpp validates itself.
1882 unsafe { llama_model_n_embd_inp(self.model.as_ptr()) }
1883 }
1884
1885 /// Get the output embedding size of the model.
1886 #[must_use]
1887 pub fn n_embd_out(&self) -> c_int {
1888 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1889 // scalars llama.cpp validates itself.
1890 unsafe { llama_model_n_embd_out(self.model.as_ptr()) }
1891 }
1892
1893 /// Get the sliding window attention size of the model.
1894 /// Returns 0 if the model does not use sliding window attention.
1895 #[must_use]
1896 pub fn n_swa(&self) -> c_int {
1897 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1898 // scalars llama.cpp validates itself.
1899 unsafe { llama_model_n_swa(self.model.as_ptr()) }
1900 }
1901
1902 /// Get the `RoPE` type used by the model.
1903 #[must_use]
1904 pub fn rope_type(&self) -> i32 {
1905 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1906 // scalars llama.cpp validates itself.
1907 unsafe { llama_model_rope_type(self.model.as_ptr()) }
1908 }
1909
1910 /// Get the `RoPE` frequency scale used during training.
1911 #[must_use]
1912 pub fn rope_freq_scale_train(&self) -> f32 {
1913 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1914 // scalars llama.cpp validates itself.
1915 unsafe { llama_model_rope_freq_scale_train(self.model.as_ptr()) }
1916 }
1917
1918 /// Get the model size in bytes.
1919 #[must_use]
1920 pub fn model_size(&self) -> u64 {
1921 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1922 // scalars llama.cpp validates itself.
1923 unsafe { llama_model_size(self.model.as_ptr()) }
1924 }
1925
1926 /// Get the number of parameters in the model.
1927 #[must_use]
1928 pub fn n_params(&self) -> u64 {
1929 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1930 // scalars llama.cpp validates itself.
1931 unsafe { llama_model_n_params(self.model.as_ptr()) }
1932 }
1933
1934 /// Get the number of classification outputs.
1935 #[must_use]
1936 pub fn n_cls_out(&self) -> u32 {
1937 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1938 // scalars llama.cpp validates itself.
1939 unsafe { llama_model_n_cls_out(self.model.as_ptr()) }
1940 }
1941
1942 /// Get the classification label for the given index.
1943 ///
1944 /// # Errors
1945 ///
1946 /// Returns an error if the label is null or not valid UTF-8.
1947 pub fn cls_label(&self, index: u32) -> Result<&str, StringFromModelError> {
1948 // SAFETY: a read through a live handle — the device, vocab or model
1949 // this borrows from — returning a pointer llama.cpp owns and keeps
1950 // valid; it is only checked and converted below, never freed here.
1951 let ptr = unsafe { llama_model_cls_label(self.model.as_ptr(), index) };
1952 if ptr.is_null() {
1953 return Err(StringFromModelError::ReturnedError(-1));
1954 }
1955 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
1956 // it owns, which outlives the borrow taken here.
1957 let cstr = unsafe { CStr::from_ptr(ptr) };
1958 cstr.to_str().map_err(StringFromModelError::Utf8Error)
1959 }
1960
1961 /// Adopt a raw `llama_model *`, taking ownership.
1962 ///
1963 /// # Safety
1964 ///
1965 /// `raw` must come from a llama.cpp entry point documented as returning a
1966 /// model the caller must release with `llama_model_free`, and must not be
1967 /// owned by anything else — [`Drop`] frees it.
1968 pub(crate) unsafe fn from_raw(raw: NonNull<llama_model>) -> Self {
1969 Self { model: raw }
1970 }
1971
1972 /// Get the number of metadata key-value pairs.
1973 #[must_use]
1974 pub fn meta_count(&self) -> c_int {
1975 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
1976 // scalars llama.cpp validates itself.
1977 unsafe { llama_model_meta_count(self.model.as_ptr()) }
1978 }
1979
1980 /// Get a chat template baked into the model, by name.
1981 ///
1982 /// Pass `None` for the default template (GGUF key `tokenizer.chat_template`),
1983 /// or a name to reach a variant — `Some("tool_use")` resolves
1984 /// `tokenizer.chat_template.tool_use`, which several models ship alongside
1985 /// their default and which is the one you want when the request carries
1986 /// tools.
1987 ///
1988 /// Supersedes the deprecated `get_chat_template`, which reads the default
1989 /// key straight out of GGUF metadata into a buffer the caller has to size —
1990 /// too small and it fails, too large and it wastes the allocation. This
1991 /// borrows a pointer llama.cpp already owns, so neither applies, and it can
1992 /// reach the named variants the other cannot.
1993 ///
1994 /// # Errors
1995 ///
1996 /// Returns [`StringFromModelError::ReturnedError`] if the model has no such
1997 /// template, or [`StringFromModelError::Utf8Error`] if it is not UTF-8.
1998 pub fn chat_template(&self, name: Option<&str>) -> Result<&str, StringFromModelError> {
1999 let c_name = match name {
2000 Some(n) => Some(CString::new(n).map_err(|_| StringFromModelError::ReturnedError(-1))?),
2001 None => None,
2002 };
2003 let name_ptr = c_name.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
2004 // SAFETY: a read through a live handle — the device, vocab or model
2005 // this borrows from — returning a pointer llama.cpp owns and keeps
2006 // valid; it is only checked and converted below, never freed here.
2007 let ptr = unsafe { llama_model_chat_template(self.model.as_ptr(), name_ptr) };
2008 if ptr.is_null() {
2009 return Err(StringFromModelError::ReturnedError(-1));
2010 }
2011 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
2012 // it owns, which outlives the borrow taken here.
2013 let cstr = unsafe { CStr::from_ptr(ptr) };
2014 cstr.to_str().map_err(StringFromModelError::Utf8Error)
2015 }
2016
2017 /// Get the model's file type — the quantization it was stored with.
2018 ///
2019 /// Returns `None` for a type this crate's [`LlamaFtype`] does not know,
2020 /// which is what you get for `LLAMA_FTYPE_GUESSED` (the file did not
2021 /// specify one) or a type added upstream since this release.
2022 #[must_use]
2023 pub fn ftype(&self) -> Option<LlamaFtype> {
2024 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2025 // scalars llama.cpp validates itself.
2026 let raw = unsafe { llama_model_ftype(self.model.as_ptr()) };
2027 LlamaFtype::try_from(raw).ok()
2028 }
2029
2030 /// Copy just the embedding rows for `tokens`, in order — `tokens.len() *
2031 /// n_embd` values, row-major.
2032 ///
2033 /// Prefer this over [`Self::token_embeddings`] whenever you know which
2034 /// tokens you want: that one materialises the entire matrix, which is
2035 /// `4 * n_vocab * n_embd` bytes — around 500 MB for a 128k-vocab 1024-dim
2036 /// model. Wraps `llama_model_get_tok_embd_rows`.
2037 ///
2038 /// # Errors
2039 ///
2040 /// Returns [`StringFromModelError::ReturnedError`] if the model exposes no
2041 /// token-embedding tensor, or if any token is out of range — llama.cpp
2042 /// reports both as a zero write without distinguishing them.
2043 ///
2044 /// # Examples
2045 ///
2046 /// ```no_run
2047 /// # use llama_cpp_4::model::LlamaModel;
2048 /// # use llama_cpp_4::token::LlamaToken;
2049 /// # fn f(model: &LlamaModel) -> Result<(), Box<dyn std::error::Error>> {
2050 /// let rows = model.token_embedding_rows(&[LlamaToken(0), LlamaToken(1)])?;
2051 /// assert_eq!(rows.len(), 2 * model.n_embd() as usize);
2052 /// # Ok(())
2053 /// # }
2054 /// ```
2055 pub fn token_embedding_rows(
2056 &self,
2057 tokens: &[LlamaToken],
2058 ) -> Result<Vec<f32>, StringFromModelError> {
2059 if tokens.is_empty() {
2060 return Ok(Vec::new());
2061 }
2062 let n_tokens =
2063 u32::try_from(tokens.len()).map_err(|_| StringFromModelError::ReturnedError(-1))?;
2064 let n_embd =
2065 usize::try_from(self.n_embd()).map_err(|_| StringFromModelError::ReturnedError(-1))?;
2066 let mut out = vec![0.0_f32; tokens.len() * n_embd];
2067
2068 // SAFETY: `tokens` is `#[repr(transparent)]` over `llama_token`, so the
2069 // cast is a layout no-op, and `n_tokens` is its real length. `out` is
2070 // sized `n_tokens * n_embd`, which is what upstream documents it writes.
2071 let written = unsafe {
2072 llama_cpp_sys_4::llama_model_get_tok_embd_rows(
2073 self.model.as_ptr(),
2074 tokens.as_ptr().cast(),
2075 n_tokens,
2076 out.as_mut_ptr(),
2077 )
2078 };
2079 if written == 0 {
2080 return Err(StringFromModelError::ReturnedError(-1));
2081 }
2082 out.truncate(written as usize);
2083 Ok(out)
2084 }
2085
2086 /// Labels a decision model attaches to its options, in order.
2087 ///
2088 /// Decision models (`clef`, `nimble`, `pplx-decider`, the `d1` family)
2089 /// score a list of options rather than generating text: you mark each
2090 /// option's span with
2091 /// [`LlamaBatchExt::set_decision_order`](crate::llama_batch_ext::LlamaBatchExt::set_decision_order),
2092 /// decode, and read one score per option out of the embeddings. These are
2093 /// the names those scores belong to — without them you have a vector of
2094 /// numbers and no way to say which option each is for.
2095 ///
2096 /// Empty for a model that is not a decision model. Wraps
2097 /// `llama_model_decision_label`, which reports
2098 /// `"<arch>.decision.labels"`.
2099 #[must_use]
2100 pub fn decision_labels(&self) -> Vec<String> {
2101 let mut out = Vec::new();
2102 for i in 0.. {
2103 // SAFETY: upstream returns null past the last label, which is the
2104 // loop's terminator; the pointer is a static C string owned by the
2105 // model, valid for as long as `&self`.
2106 let raw =
2107 unsafe { llama_cpp_sys_4::llama_model_decision_label(self.model.as_ptr(), i) };
2108 if raw.is_null() {
2109 break;
2110 }
2111 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
2112 // it owns, which outlives the borrow taken here.
2113 let label = unsafe { std::ffi::CStr::from_ptr(raw) };
2114 match label.to_str() {
2115 Ok(label) => out.push(label.to_owned()),
2116 // A non-UTF-8 label would be a broken GGUF; skipping it keeps
2117 // the indices of the rest aligned with the option order.
2118 Err(_) => out.push(String::new()),
2119 }
2120 }
2121 out
2122 }
2123
2124 /// How many tokens a realtime model's output lags behind its audio input.
2125 ///
2126 /// `0` when the model is not a realtime one. Used by mtmd to line generated
2127 /// audio up against the input stream; wraps `llama_model_n_tokens_delay`.
2128 #[must_use]
2129 pub fn n_tokens_delay(&self) -> u32 {
2130 // SAFETY: a plain read of model hparams through a live `&self`.
2131 unsafe { llama_cpp_sys_4::llama_model_n_tokens_delay(self.model.as_ptr()) }
2132 }
2133
2134 /// Turn the KV-cache attention rotation on or off for every context created
2135 /// from this model from now on.
2136 ///
2137 /// This is `TurboQuant`'s rotation, and upstream marks the setter as being
2138 /// for testing. Prefer
2139 /// [`LlamaContextParams::with_attn_rot_disabled`](crate::context::params::LlamaContextParams)
2140 /// for ordinary use — it scopes the choice to one context, where this
2141 /// mutates the model every later context inherits from. Wraps
2142 /// `llama_model_set_attn_rot`.
2143 pub fn set_attn_rot(&mut self, enabled: bool) {
2144 // SAFETY: `&mut self` is what rules out another context being created
2145 // from this model concurrently; the call only flips a model flag.
2146 unsafe { llama_cpp_sys_4::llama_model_set_attn_rot(self.model.as_ptr(), enabled) }
2147 }
2148
2149 /// Copy the whole token-embedding matrix out as `f32`, row-major and
2150 /// `n_vocab * n_embd` long.
2151 ///
2152 /// llama.cpp converts from whatever the tensor is stored as, so this
2153 /// allocates `4 * n_vocab * n_embd` bytes — 500 MB for a 128k-vocab 1024-dim
2154 /// model. Wraps `llama_model_get_tok_embd`.
2155 ///
2156 /// # Errors
2157 ///
2158 /// Returns [`StringFromModelError::ReturnedError`] if the model exposes no
2159 /// token-embedding tensor.
2160 pub fn token_embeddings(&self) -> Result<Vec<f32>, StringFromModelError> {
2161 // A null `out` asks for the element count without writing anything.
2162 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2163 // scalars llama.cpp validates itself.
2164 let n = unsafe { llama_model_get_tok_embd(self.model.as_ptr(), std::ptr::null_mut()) };
2165 if n == 0 {
2166 return Err(StringFromModelError::ReturnedError(-1));
2167 }
2168 let mut out = vec![0.0_f32; n as usize];
2169 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2170 // scalars llama.cpp validates itself.
2171 let written = unsafe { llama_model_get_tok_embd(self.model.as_ptr(), out.as_mut_ptr()) };
2172 if written == 0 {
2173 return Err(StringFromModelError::ReturnedError(-1));
2174 }
2175 // Trust the second call's count over the first: a shrink would otherwise
2176 // leave uninitialised-looking zeros on the tail.
2177 out.truncate(written as usize);
2178 Ok(out)
2179 }
2180
2181 /// Get a model description string.
2182 ///
2183 /// The `buf_size` parameter specifies the maximum buffer size for the description.
2184 /// A default of 256 bytes is usually sufficient.
2185 ///
2186 /// # Errors
2187 ///
2188 /// Returns an error if the description could not be retrieved or is not valid UTF-8.
2189 #[allow(clippy::cast_sign_loss)]
2190 pub fn desc(&self, buf_size: usize) -> Result<String, StringFromModelError> {
2191 let mut buf = vec![0u8; buf_size];
2192 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2193 // cannot write past it; a negative return means the buffer was too small
2194 // and nothing was written. Any string arguments are `CString`s alive for
2195 // the call.
2196 let ret = unsafe {
2197 llama_model_desc(
2198 self.model.as_ptr(),
2199 buf.as_mut_ptr().cast::<c_char>(),
2200 buf_size,
2201 )
2202 };
2203 if ret < 0 {
2204 return Err(StringFromModelError::ReturnedError(ret));
2205 }
2206 let len = ret as usize;
2207 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
2208 Ok(s.to_owned())
2209 }
2210
2211 /// Get a metadata key by index.
2212 ///
2213 /// The `buf_size` parameter specifies the maximum buffer size for the key.
2214 /// A default of 256 bytes is usually sufficient.
2215 ///
2216 /// # Errors
2217 ///
2218 /// Returns an error if the index is out of range or the key is not valid UTF-8.
2219 #[allow(clippy::cast_sign_loss)]
2220 pub fn meta_key_by_index(
2221 &self,
2222 index: i32,
2223 buf_size: usize,
2224 ) -> Result<String, StringFromModelError> {
2225 let mut buf = vec![0u8; buf_size];
2226 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2227 // cannot write past it; a negative return means the buffer was too small
2228 // and nothing was written. Any string arguments are `CString`s alive for
2229 // the call.
2230 let ret = unsafe {
2231 llama_model_meta_key_by_index(
2232 self.model.as_ptr(),
2233 index,
2234 buf.as_mut_ptr().cast::<c_char>(),
2235 buf_size,
2236 )
2237 };
2238 if ret < 0 {
2239 return Err(StringFromModelError::ReturnedError(ret));
2240 }
2241 let len = ret as usize;
2242 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
2243 Ok(s.to_owned())
2244 }
2245
2246 /// Get a metadata value string by index.
2247 ///
2248 /// The `buf_size` parameter specifies the maximum buffer size for the value.
2249 /// Values can be large (e.g. chat templates, token lists), so 4096+ may be needed.
2250 ///
2251 /// # Errors
2252 ///
2253 /// Returns an error if the index is out of range or the value is not valid UTF-8.
2254 #[allow(clippy::cast_sign_loss)]
2255 pub fn meta_val_str_by_index(
2256 &self,
2257 index: i32,
2258 buf_size: usize,
2259 ) -> Result<String, StringFromModelError> {
2260 let mut buf = vec![0u8; buf_size];
2261 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2262 // scalars llama.cpp validates itself.
2263 let ret = unsafe {
2264 llama_model_meta_val_str_by_index(
2265 self.model.as_ptr(),
2266 index,
2267 buf.as_mut_ptr().cast::<c_char>(),
2268 buf_size,
2269 )
2270 };
2271 if ret < 0 {
2272 return Err(StringFromModelError::ReturnedError(ret));
2273 }
2274 let len = ret as usize;
2275 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
2276 Ok(s.to_owned())
2277 }
2278
2279 /// Get a metadata value by key name.
2280 ///
2281 /// This is more convenient than iterating metadata by index when you know the key.
2282 /// The `buf_size` parameter specifies the maximum buffer size for the value.
2283 ///
2284 /// # Errors
2285 ///
2286 /// Returns an error if the key is not found, contains a null byte, or the value is not valid UTF-8.
2287 #[allow(clippy::cast_sign_loss)]
2288 pub fn meta_val_str(&self, key: &str, buf_size: usize) -> Result<String, StringFromModelError> {
2289 let c_key = CString::new(key).map_err(|_| StringFromModelError::ReturnedError(-1))?;
2290 let mut buf = vec![0u8; buf_size];
2291 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2292 // cannot write past it; a negative return means the buffer was too small
2293 // and nothing was written. Any string arguments are `CString`s alive for
2294 // the call.
2295 let ret = unsafe {
2296 llama_model_meta_val_str(
2297 self.model.as_ptr(),
2298 c_key.as_ptr(),
2299 buf.as_mut_ptr().cast::<c_char>(),
2300 buf_size,
2301 )
2302 };
2303 if ret < 0 {
2304 return Err(StringFromModelError::ReturnedError(ret));
2305 }
2306 let len = ret as usize;
2307 let s = std::str::from_utf8(&buf[..len]).map_err(StringFromModelError::Utf8Error)?;
2308 Ok(s.to_owned())
2309 }
2310
2311 /// Get all metadata as a list of `(key, value)` pairs.
2312 ///
2313 /// This is a convenience method that iterates over all metadata entries.
2314 /// Keys use a buffer of 256 bytes and values use 4096 bytes.
2315 /// For values that may be larger (e.g. token lists), use
2316 /// [`meta_val_str_by_index`](Self::meta_val_str_by_index) directly with a larger buffer.
2317 ///
2318 /// # Errors
2319 ///
2320 /// Returns an error if any key or value cannot be read or is not valid UTF-8.
2321 #[allow(clippy::cast_sign_loss)]
2322 pub fn metadata(&self) -> Result<Vec<(String, String)>, StringFromModelError> {
2323 let count = self.meta_count();
2324 let mut result = Vec::with_capacity(count as usize);
2325 for i in 0..count {
2326 let key = self.meta_key_by_index(i, 256)?;
2327 let val = self.meta_val_str_by_index(i, 4096)?;
2328 result.push((key, val));
2329 }
2330 Ok(result)
2331 }
2332
2333 /// Check if the model has an encoder.
2334 #[must_use]
2335 pub fn has_encoder(&self) -> bool {
2336 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2337 // scalars llama.cpp validates itself.
2338 unsafe { llama_model_has_encoder(self.model.as_ptr()) }
2339 }
2340
2341 /// Check if the model has a decoder.
2342 #[must_use]
2343 pub fn has_decoder(&self) -> bool {
2344 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2345 // scalars llama.cpp validates itself.
2346 unsafe { llama_model_has_decoder(self.model.as_ptr()) }
2347 }
2348
2349 /// Check if the model is recurrent (e.g. Mamba, RWKV).
2350 #[must_use]
2351 pub fn is_recurrent(&self) -> bool {
2352 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2353 // scalars llama.cpp validates itself.
2354 unsafe { llama_model_is_recurrent(self.model.as_ptr()) }
2355 }
2356
2357 /// Check if the model is a hybrid model.
2358 #[must_use]
2359 pub fn is_hybrid(&self) -> bool {
2360 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2361 // scalars llama.cpp validates itself.
2362 unsafe { llama_model_is_hybrid(self.model.as_ptr()) }
2363 }
2364
2365 /// Check if the model is a diffusion model.
2366 #[must_use]
2367 pub fn is_diffusion(&self) -> bool {
2368 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2369 // scalars llama.cpp validates itself.
2370 unsafe { llama_model_is_diffusion(self.model.as_ptr()) }
2371 }
2372
2373 /// Get chat template from model.
2374 ///
2375 /// # Errors
2376 ///
2377 /// - If the model does not have a chat template, it will return an error.
2378 /// - If the chat template is not a valid `CString`, it will return an error.
2379 ///
2380 /// # Example
2381 ///
2382 /// ```no_run
2383 /// use llama_cpp_4::model::LlamaModel;
2384 /// use llama_cpp_4::model::params::LlamaModelParams;
2385 /// use llama_cpp_4::llama_backend::LlamaBackend;
2386 ///
2387 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2388 /// let backend = LlamaBackend::init()?;
2389 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
2390 /// let chat_template = model.get_chat_template(1024)?;
2391 /// # Ok(())
2392 /// # }
2393 /// ```
2394 #[deprecated(
2395 since = "0.7.0",
2396 note = "use `chat_template(None)`, which borrows llama.cpp's own pointer \
2397 instead of copying into a caller-sized buffer, and can reach named \
2398 variants such as `chat_template(Some(\"tool_use\"))`"
2399 )]
2400 #[allow(clippy::missing_panics_doc)] // We statically know this will not panic as long as the buffer size is sufficient
2401 pub fn get_chat_template(&self, buf_size: usize) -> Result<String, ChatTemplateError> {
2402 // longest known template is about 1200 bytes from llama.cpp
2403 let chat_temp = CString::new(vec![b'*'; buf_size]).expect("no null");
2404 let chat_ptr = chat_temp.into_raw();
2405 let chat_name = CString::new("tokenizer.chat_template").expect("no null bytes");
2406
2407 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2408 // cannot write past it; a negative return means the buffer was too small
2409 // and nothing was written. Any string arguments are `CString`s alive for
2410 // the call.
2411 let ret = unsafe {
2412 llama_model_meta_val_str(self.model.as_ptr(), chat_name.as_ptr(), chat_ptr, buf_size)
2413 };
2414
2415 if ret < 0 {
2416 return Err(ChatTemplateError::MissingTemplate(ret));
2417 }
2418
2419 // SAFETY: the bytes come from llama.cpp's own output and contain no interior NUL,
2420 // which is what the unchecked constructor requires.
2421 let template_c = unsafe { CString::from_raw(chat_ptr) };
2422 let template = template_c.to_str()?;
2423
2424 let ret: usize = ret.try_into().unwrap();
2425 if template.len() < ret {
2426 return Err(ChatTemplateError::BuffSizeError(ret + 1));
2427 }
2428
2429 Ok(template.to_owned())
2430 }
2431
2432 /// Loads a model from a file.
2433 ///
2434 /// This function loads a model from a specified file path and returns the corresponding `LlamaModel` instance.
2435 ///
2436 /// # Errors
2437 ///
2438 /// - If the path cannot be converted to a string or if the model file does not exist, it will return an error.
2439 /// - If the model cannot be loaded (e.g., due to an invalid or corrupted model file), it will return a `LlamaModelLoadError`.
2440 ///
2441 /// # Example
2442 ///
2443 /// ```no_run
2444 /// use llama_cpp_4::model::LlamaModel;
2445 /// use llama_cpp_4::model::params::LlamaModelParams;
2446 /// use llama_cpp_4::llama_backend::LlamaBackend;
2447 ///
2448 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2449 /// let backend = LlamaBackend::init()?;
2450 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
2451 /// # Ok(())
2452 /// # }
2453 /// ```
2454 #[tracing::instrument(skip_all, fields(params))]
2455 pub fn load_from_file(
2456 _: &LlamaBackend,
2457 path: impl AsRef<Path>,
2458 params: &LlamaModelParams,
2459 ) -> Result<Self, LlamaModelLoadError> {
2460 let path = path.as_ref();
2461 debug_assert!(
2462 Path::new(path).exists(),
2463 "{} does not exist",
2464 path.display()
2465 );
2466 let path = path
2467 .to_str()
2468 .ok_or(LlamaModelLoadError::PathToStrError(path.to_path_buf()))?;
2469
2470 let cstr = CString::new(path)?;
2471 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2472 // scalars llama.cpp validates itself.
2473 let llama_model = unsafe { llama_model_load_from_file(cstr.as_ptr(), params.params) };
2474
2475 let model = NonNull::new(llama_model).ok_or(LlamaModelLoadError::NullResult)?;
2476
2477 tracing::debug!(?path, "Loaded model");
2478 Ok(LlamaModel { model })
2479 }
2480
2481 /// Load a model from multiple split files.
2482 ///
2483 /// This function loads a model that has been split across multiple files. This is useful for
2484 /// very large models that exceed filesystem limitations or need to be distributed across
2485 /// multiple storage devices.
2486 ///
2487 /// # Arguments
2488 ///
2489 /// * `paths` - A slice of paths to the split model files
2490 /// * `params` - The model parameters
2491 ///
2492 /// # Errors
2493 ///
2494 /// Returns an error if:
2495 /// - Any of the paths cannot be converted to a C string
2496 /// - The model fails to load from the splits
2497 /// - Any path doesn't exist or isn't accessible
2498 ///
2499 /// # Example
2500 ///
2501 /// ```no_run
2502 /// use llama_cpp_4::model::{LlamaModel, params::LlamaModelParams};
2503 /// use llama_cpp_4::llama_backend::LlamaBackend;
2504 ///
2505 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2506 /// let backend = LlamaBackend::init()?;
2507 /// let params = LlamaModelParams::default();
2508 ///
2509 /// let paths = vec![
2510 /// "model-00001-of-00003.gguf",
2511 /// "model-00002-of-00003.gguf",
2512 /// "model-00003-of-00003.gguf",
2513 /// ];
2514 ///
2515 /// let model = LlamaModel::load_from_splits(&backend, &paths, ¶ms)?;
2516 /// # Ok(())
2517 /// # }
2518 /// ```
2519 #[tracing::instrument(skip_all)]
2520 pub fn load_from_splits(
2521 _: &LlamaBackend,
2522 paths: &[impl AsRef<Path>],
2523 params: &LlamaModelParams,
2524 ) -> Result<Self, LlamaModelLoadError> {
2525 // Convert paths to C strings
2526 let c_strings: Vec<CString> = paths
2527 .iter()
2528 .map(|p| {
2529 let path = p.as_ref();
2530 debug_assert!(path.exists(), "{} does not exist", path.display());
2531 let path_str = path
2532 .to_str()
2533 .ok_or(LlamaModelLoadError::PathToStrError(path.to_path_buf()))?;
2534 CString::new(path_str).map_err(LlamaModelLoadError::from)
2535 })
2536 .collect::<Result<Vec<_>, _>>()?;
2537
2538 // Create array of pointers to C strings
2539 let c_ptrs: Vec<*const c_char> = c_strings.iter().map(|s| s.as_ptr()).collect();
2540
2541 // Load the model from splits
2542 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2543 // scalars llama.cpp validates itself.
2544 let llama_model = unsafe {
2545 llama_model_load_from_splits(c_ptrs.as_ptr().cast_mut(), c_ptrs.len(), params.params)
2546 };
2547
2548 let model = NonNull::new(llama_model).ok_or(LlamaModelLoadError::NullResult)?;
2549
2550 tracing::debug!("Loaded model from {} splits", paths.len());
2551 Ok(LlamaModel { model })
2552 }
2553
2554 /// Load a model from a `FILE` pointer.
2555 ///
2556 /// # Safety
2557 ///
2558 /// The `file` pointer must be a valid, open `FILE*`.
2559 ///
2560 /// # Errors
2561 ///
2562 /// Returns an error if the model cannot be loaded.
2563 pub unsafe fn load_from_file_ptr(
2564 file: *mut llama_cpp_sys_4::FILE,
2565 params: &LlamaModelParams,
2566 ) -> Result<Self, LlamaModelLoadError> {
2567 let model = llama_cpp_sys_4::llama_model_load_from_file_ptr(file, params.params);
2568 let model = NonNull::new(model).ok_or(LlamaModelLoadError::NullResult)?;
2569 Ok(LlamaModel { model })
2570 }
2571
2572 /// Initialize a model from user-provided data.
2573 ///
2574 /// # Safety
2575 ///
2576 /// The metadata, callback, and user data must be valid.
2577 ///
2578 /// # Errors
2579 ///
2580 /// Returns an error if the model cannot be initialized.
2581 pub unsafe fn init_from_user(
2582 metadata: *mut llama_cpp_sys_4::gguf_context,
2583 set_tensor_data: llama_cpp_sys_4::llama_model_set_tensor_data_t,
2584 set_tensor_data_ud: *mut std::ffi::c_void,
2585 params: &LlamaModelParams,
2586 ) -> Result<Self, LlamaModelLoadError> {
2587 let model = llama_cpp_sys_4::llama_model_init_from_user(
2588 metadata,
2589 set_tensor_data,
2590 set_tensor_data_ud,
2591 params.params,
2592 );
2593 let model = NonNull::new(model).ok_or(LlamaModelLoadError::NullResult)?;
2594 Ok(LlamaModel { model })
2595 }
2596
2597 /// Save the model to a file.
2598 ///
2599 /// # Panics
2600 ///
2601 /// Panics if the path contains null bytes.
2602 pub fn save_to_file(&self, path: impl AsRef<Path>) {
2603 let path = path.as_ref();
2604 let path_str = path.to_str().expect("path is not valid UTF-8");
2605 let c_path = CString::new(path_str).expect("path contains null bytes");
2606 // SAFETY: `self.model` is non-null and kept alive by this borrow, and the remaining arguments are
2607 // scalars llama.cpp validates itself.
2608 unsafe {
2609 llama_model_save_to_file(self.model.as_ptr(), c_path.as_ptr());
2610 }
2611 }
2612
2613 /// Get the list of built-in chat templates.
2614 ///
2615 /// Returns the names of all chat templates that are built into llama.cpp.
2616 ///
2617 /// # Panics
2618 ///
2619 /// Panics if any template name is not valid UTF-8.
2620 #[allow(clippy::cast_sign_loss)]
2621 #[must_use]
2622 pub fn chat_builtin_templates() -> Vec<String> {
2623 // First call to get count
2624 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2625 // cannot write past it; a negative return means the buffer was too small
2626 // and nothing was written. Any string arguments are `CString`s alive for
2627 // the call.
2628 let count = unsafe { llama_chat_builtin_templates(std::ptr::null_mut(), 0) };
2629 if count <= 0 {
2630 return Vec::new();
2631 }
2632 let count = count as usize;
2633 let mut ptrs: Vec<*const c_char> = vec![std::ptr::null(); count];
2634 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
2635 // cannot write past it; a negative return means the buffer was too small
2636 // and nothing was written. Any string arguments are `CString`s alive for
2637 // the call.
2638 unsafe {
2639 llama_chat_builtin_templates(ptrs.as_mut_ptr(), count);
2640 }
2641 ptrs.iter()
2642 .map(|&p| {
2643 // SAFETY: the pointer comes from llama.cpp and points at a NUL-terminated string
2644 // it owns, which outlives the borrow taken here.
2645 let cstr = unsafe { CStr::from_ptr(p) };
2646 cstr.to_str()
2647 .expect("template name is not valid UTF-8")
2648 .to_owned()
2649 })
2650 .collect()
2651 }
2652
2653 /// Initializes a lora adapter from a file.
2654 ///
2655 /// This function initializes a Lora adapter, which is a model extension used to adapt or fine-tune the existing model
2656 /// to a specific domain or task. The adapter file is typically in the form of a binary or serialized file that can be applied
2657 /// to the model for improved performance on specialized tasks.
2658 ///
2659 /// # Errors
2660 ///
2661 /// - If the adapter file path cannot be converted to a string or if the adapter cannot be initialized, it will return an error.
2662 ///
2663 /// # Example
2664 ///
2665 /// ```no_run
2666 /// use llama_cpp_4::model::LlamaModel;
2667 /// use llama_cpp_4::model::params::LlamaModelParams;
2668 /// use llama_cpp_4::llama_backend::LlamaBackend;
2669 ///
2670 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2671 /// let backend = LlamaBackend::init()?;
2672 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
2673 /// let adapter = model.lora_adapter_init("path/to/lora/adapter")?;
2674 /// # Ok(())
2675 /// # }
2676 /// ```
2677 pub fn lora_adapter_init(
2678 &self,
2679 path: impl AsRef<Path>,
2680 ) -> Result<LlamaLoraAdapter, LlamaLoraAdapterInitError> {
2681 let path = path.as_ref();
2682 debug_assert!(
2683 Path::new(path).exists(),
2684 "{} does not exist",
2685 path.display()
2686 );
2687
2688 let path = path
2689 .to_str()
2690 .ok_or(LlamaLoraAdapterInitError::PathToStrError(
2691 path.to_path_buf(),
2692 ))?;
2693
2694 let cstr = CString::new(path)?;
2695 // SAFETY: the adapter handle and the model it came from are both alive for the
2696 // call; any path argument is a `CString` that outlives it.
2697 let adapter = unsafe { llama_adapter_lora_init(self.model.as_ptr(), cstr.as_ptr()) };
2698
2699 let adapter = NonNull::new(adapter).ok_or(LlamaLoraAdapterInitError::NullResult)?;
2700
2701 tracing::debug!(?path, "Initialized lora adapter");
2702 Ok(LlamaLoraAdapter {
2703 lora_adapter: adapter,
2704 })
2705 }
2706
2707 /// Initialize a `LoRA` adapter from an open `FILE` pointer, reading from its
2708 /// current position.
2709 ///
2710 /// Wraps `llama_adapter_lora_init_from_file_ptr`
2711 /// ([llama.cpp #28993](https://github.com/ggml-org/llama.cpp/pull/28993)),
2712 /// the counterpart to
2713 /// [`LlamaModel::load_from_file_ptr`]. Use it when the adapter GGUF is
2714 /// *embedded* in a larger file — appended to an executable, or packed into
2715 /// an archive — which is the one thing
2716 /// [`Self::lora_adapter_init`] cannot do, since it opens the path itself
2717 /// and reads from byte zero. For an adapter that is its own file, use that
2718 /// instead.
2719 ///
2720 /// The adapter does not keep the `FILE`: llama.cpp reads what it needs
2721 /// before returning, exactly as `llama_adapter_lora_init` does before it
2722 /// `fclose`s its own handle. So the caller still owns the handle and should
2723 /// close it, and the returned [`LlamaLoraAdapter`] stays valid afterwards.
2724 ///
2725 /// # Safety
2726 ///
2727 /// `file` must be a valid, open `FILE*` positioned at the start of the
2728 /// adapter GGUF. Reading advances the position and llama.cpp does not
2729 /// restore it.
2730 ///
2731 /// # Errors
2732 ///
2733 /// Returns [`LlamaLoraAdapterInitError::NullResult`] if `file` is null or
2734 /// llama.cpp could not read an adapter from it; the reason is in the
2735 /// llama.cpp log.
2736 pub unsafe fn lora_adapter_init_from_file_ptr(
2737 &self,
2738 file: *mut llama_cpp_sys_4::FILE,
2739 ) -> Result<LlamaLoraAdapter, LlamaLoraAdapterInitError> {
2740 let adapter =
2741 llama_cpp_sys_4::llama_adapter_lora_init_from_file_ptr(self.model.as_ptr(), file);
2742 let adapter = NonNull::new(adapter).ok_or(LlamaLoraAdapterInitError::NullResult)?;
2743
2744 tracing::debug!("Initialized lora adapter from a FILE pointer");
2745 Ok(LlamaLoraAdapter {
2746 lora_adapter: adapter,
2747 })
2748 }
2749
2750 /// Initialize a `LoRA` adapter from an adapter GGUF embedded at `offset`
2751 /// inside a larger file.
2752 ///
2753 /// [`Self::lora_adapter_init`] opens the path itself and reads from byte
2754 /// zero, so it only works for an adapter that is its own file. This is the
2755 /// safe way to reach llama.cpp's `FILE *`-based loader for the other case:
2756 /// an adapter appended to an executable, packed into an archive, or stored
2757 /// alongside other blobs. Pass `0` and it behaves like
2758 /// [`Self::lora_adapter_init`].
2759 ///
2760 /// The handle is opened, positioned, read and closed inside this call;
2761 /// llama.cpp does not keep it.
2762 ///
2763 /// # Examples
2764 ///
2765 /// ```no_run
2766 /// # use llama_cpp_4::model::LlamaModel;
2767 /// # fn f(model: &LlamaModel) -> Result<(), Box<dyn std::error::Error>> {
2768 /// // The adapter starts 4 KiB into a bundle of several.
2769 /// let adapter = model.lora_adapter_init_at_offset("bundle.bin", 4096)?;
2770 /// # drop(adapter);
2771 /// # Ok(())
2772 /// # }
2773 /// ```
2774 ///
2775 /// # Errors
2776 ///
2777 /// - [`LlamaLoraAdapterInitError::FileOpen`] if the file cannot be opened.
2778 /// - [`LlamaLoraAdapterInitError::FileSeek`] if it cannot be positioned at
2779 /// `offset` — including an `offset` too large for a 32-bit target's file
2780 /// offsets.
2781 /// - [`LlamaLoraAdapterInitError::NullResult`] if llama.cpp could not read
2782 /// an adapter from that position; the reason is in the llama.cpp log.
2783 pub fn lora_adapter_init_at_offset(
2784 &self,
2785 path: impl AsRef<Path>,
2786 offset: u64,
2787 ) -> Result<LlamaLoraAdapter, LlamaLoraAdapterInitError> {
2788 let path = path.as_ref();
2789
2790 let mut file = crate::cfile::CFile::open_read(path).map_err(|e| {
2791 LlamaLoraAdapterInitError::FileOpen {
2792 path: path.to_path_buf(),
2793 reason: e.to_string(),
2794 }
2795 })?;
2796 file.seek_to(offset)
2797 .map_err(|e| LlamaLoraAdapterInitError::FileSeek {
2798 path: path.to_path_buf(),
2799 offset,
2800 reason: e.to_string(),
2801 })?;
2802
2803 // SAFETY: `file` is open for the duration of the call, and llama.cpp
2804 // does not retain it — it reads what it needs before returning, just as
2805 // `llama_adapter_lora_init` does before closing its own handle.
2806 let adapter = unsafe { self.lora_adapter_init_from_file_ptr(file.as_ptr()) }?;
2807
2808 tracing::debug!(?path, offset, "Initialized lora adapter at offset");
2809 Ok(adapter)
2810 }
2811
2812 /// Create a new context from this model.
2813 ///
2814 /// This function creates a new context for the model, which is used to manage and perform computations for inference,
2815 /// including token generation, embeddings, and other tasks that the model can perform. The context allows fine-grained
2816 /// control over model parameters for a specific task.
2817 ///
2818 /// # Errors
2819 ///
2820 /// - There are various potential failures such as invalid parameters or a failure to allocate the context. See [`LlamaContextLoadError`]
2821 /// for more detailed error descriptions.
2822 ///
2823 /// # Example
2824 ///
2825 /// ```no_run
2826 /// use llama_cpp_4::model::LlamaModel;
2827 /// use llama_cpp_4::model::params::LlamaModelParams;
2828 /// use llama_cpp_4::context::params::LlamaContextParams;
2829 /// use llama_cpp_4::llama_backend::LlamaBackend;
2830 ///
2831 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2832 /// let backend = LlamaBackend::init()?;
2833 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
2834 /// let context = model.new_context(&backend, LlamaContextParams::default())?;
2835 /// # Ok(())
2836 /// # }
2837 /// ```
2838 #[allow(clippy::needless_pass_by_value)]
2839 pub fn new_context(
2840 &self,
2841 _: &LlamaBackend,
2842 mut params: LlamaContextParams,
2843 ) -> Result<LlamaContext<'_>, LlamaContextLoadError> {
2844 // Apply TurboQuant attn-rotation preference before the KV cache is
2845 // initialised inside llama_init_from_model.
2846 let prev_rot_var = std::env::var("LLAMA_ATTN_ROT_DISABLE").ok();
2847 if params.attn_rot_disabled {
2848 // SAFETY: we restore the value right after the call.
2849 #[allow(unused_unsafe)]
2850 unsafe {
2851 std::env::set_var("LLAMA_ATTN_ROT_DISABLE", "1");
2852 }
2853 } else if std::env::var("LLAMA_ATTN_ROT_DISABLE").is_ok() {
2854 // params say "enabled" – only clear if it was previously unset
2855 // (respect explicit user env var).
2856 }
2857
2858 let context_type = params.ctx_type();
2859 let context_params = params.context_params;
2860 let embeddings_enabled = params.embeddings();
2861 // SAFETY: the model outlives the context by the lifetime on the return type, and
2862 // the params are a plain struct passed by value. The result is checked
2863 // for null before being wrapped.
2864 let context = unsafe { llama_init_from_model(self.model.as_ptr(), context_params) };
2865
2866 // Restore the env-var to its previous state.
2867 #[allow(unused_unsafe)]
2868 match prev_rot_var {
2869 // SAFETY: setting an environment variable races with any concurrent `getenv` in
2870 // the process. This runs during model setup, before any thread that
2871 // could read it is started, which is the only point it is safe to do.
2872 Some(v) => unsafe { std::env::set_var("LLAMA_ATTN_ROT_DISABLE", v) },
2873 // SAFETY: setting an environment variable races with any concurrent `getenv` in
2874 // the process. This runs during model setup, before any thread that
2875 // could read it is started, which is the only point it is safe to do.
2876 None if params.attn_rot_disabled => unsafe {
2877 std::env::remove_var("LLAMA_ATTN_ROT_DISABLE");
2878 },
2879 None => {}
2880 }
2881
2882 let context = NonNull::new(context).ok_or(LlamaContextLoadError::NullReturn)?;
2883 let tensor_transactions = params.tensor_transactions.take();
2884 Ok(LlamaContext::new(
2885 self,
2886 context,
2887 embeddings_enabled,
2888 context_type,
2889 tensor_transactions,
2890 ))
2891 }
2892
2893 /// Apply the model's chat template to a sequence of messages.
2894 ///
2895 /// This function applies the model's chat template to the provided chat messages, formatting them accordingly. The chat
2896 /// template determines the structure or style of conversation between the system and user, such as token formatting,
2897 /// role separation, and more. The template can be customized by providing an optional template string, or if `None`
2898 /// is provided, the default template used by `llama.cpp` will be applied.
2899 ///
2900 /// For more information on supported templates, visit:
2901 /// <https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template>
2902 ///
2903 /// # Arguments
2904 ///
2905 /// - `tmpl`: An optional custom template string. If `None`, the default template will be used.
2906 /// - `chat`: A vector of `LlamaChatMessage` instances, which represent the conversation between the system and user.
2907 /// - `add_ass`: A boolean flag indicating whether additional system-specific instructions (like "assistant") should be included.
2908 ///
2909 /// # Errors
2910 ///
2911 /// There are several possible points of failure when applying the chat template:
2912 /// - Insufficient buffer size to hold the formatted chat (this will return `ApplyChatTemplateError::BuffSizeError`).
2913 /// - If the template or messages cannot be processed properly, various errors from `ApplyChatTemplateError` may occur.
2914 ///
2915 /// # Example
2916 ///
2917 /// ```no_run
2918 /// use llama_cpp_4::model::{LlamaModel, LlamaChatMessage};
2919 /// use llama_cpp_4::model::params::LlamaModelParams;
2920 /// use llama_cpp_4::llama_backend::LlamaBackend;
2921 ///
2922 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2923 /// let backend = LlamaBackend::init()?;
2924 /// let model = LlamaModel::load_from_file(&backend, "path/to/model", &LlamaModelParams::default())?;
2925 /// let chat = vec![
2926 /// LlamaChatMessage::new("user".to_string(), "Hello!".to_string())?,
2927 /// LlamaChatMessage::new("assistant".to_string(), "Hi! How can I assist you today?".to_string())?,
2928 /// ];
2929 /// let formatted_chat = model.apply_chat_template(None, &chat, true)?;
2930 /// # Ok(())
2931 /// # }
2932 /// ```
2933 ///
2934 /// # Notes
2935 ///
2936 /// The provided buffer is twice the length of the messages by default, which is recommended by the `llama.cpp` documentation.
2937 /// # Panics
2938 ///
2939 /// Panics if the buffer length exceeds `i32::MAX`.
2940 #[tracing::instrument(skip_all)]
2941 pub fn apply_chat_template(
2942 &self,
2943 tmpl: Option<&str>,
2944 chat: &[LlamaChatMessage],
2945 add_ass: bool,
2946 ) -> Result<String, ApplyChatTemplateError> {
2947 // Compute raw message byte total from the original LlamaChatMessage vec
2948 // *before* we shadow `chat` with the sys-type vec below.
2949 let message_length = chat.iter().fold(0usize, |acc, c| {
2950 acc + c.role.to_bytes().len() + c.content.to_bytes().len()
2951 });
2952
2953 // Build our llama_cpp_sys chat messages (raw pointers into CStrings).
2954 let chat_sys: Vec<llama_chat_message> = chat
2955 .iter()
2956 .map(|c| llama_chat_message {
2957 role: c.role.as_ptr(),
2958 content: c.content.as_ptr(),
2959 })
2960 .collect();
2961
2962 // Set the tmpl pointer.
2963 let tmpl_cstring = tmpl.map(CString::new).transpose()?;
2964 let tmpl_ptr = tmpl_cstring
2965 .as_ref()
2966 .map_or(std::ptr::null(), |s| s.as_ptr());
2967
2968 // `message_length * 4` is far too small for models whose built-in chat
2969 // template adds a long default system prompt (e.g. Qwen3.5 prepends
2970 // ~80+ chars of markup even for a one-word user message). Start with
2971 // at least 4 KiB so short inputs like "hi" always have room.
2972 //
2973 // `llama_chat_apply_template` returns the number of bytes it *actually*
2974 // needed when the buffer was too small, so we retry exactly once with
2975 // that precise size rather than giving up immediately.
2976 let mut buf_size = message_length.saturating_mul(4).max(4096);
2977
2978 for _ in 0..2 {
2979 // Use u8 so that as_mut_ptr()/as_ptr() match the binding (*mut u8 / *const u8).
2980 let mut buff = vec![0u8; buf_size];
2981 // SAFETY: the template and message pointers are alive for the
2982 // call, and `buff`'s pointer and length are passed together so
2983 // llama.cpp cannot write past it. A return larger than the
2984 // buffer means nothing was written and the loop retries with
2985 // exactly the size it reported.
2986 let res = unsafe {
2987 llama_chat_apply_template(
2988 tmpl_ptr,
2989 chat_sys.as_ptr(),
2990 chat_sys.len(),
2991 add_ass,
2992 buff.as_mut_ptr().cast(),
2993 i32::try_from(buff.len()).expect("buffer length fits in i32"),
2994 )
2995 };
2996
2997 if res < 0 {
2998 return Err(ApplyChatTemplateError::BuffSizeError);
2999 }
3000
3001 #[allow(clippy::cast_sign_loss)]
3002 let needed = res as usize;
3003 if needed > buf_size {
3004 // Buffer was too small — retry with the exact size llama.cpp reported.
3005 buf_size = needed + 1; // +1 for null terminator
3006 continue;
3007 }
3008
3009 // SAFETY: llama_chat_apply_template wrote a NUL-terminated string
3010 // into `buff`; `needed` bytes were used.
3011 let formatted = unsafe {
3012 CStr::from_ptr(buff.as_ptr().cast())
3013 .to_string_lossy()
3014 .into_owned()
3015 };
3016 return Ok(formatted);
3017 }
3018
3019 Err(ApplyChatTemplateError::BuffSizeError)
3020 }
3021
3022 /// Build a split GGUF file path for a specific chunk.
3023 ///
3024 /// This utility function creates the standardized filename for a split model chunk
3025 /// following the pattern: `{prefix}-{split_no:05d}-of-{split_count:05d}.gguf`
3026 ///
3027 /// # Arguments
3028 ///
3029 /// * `path_prefix` - The base path and filename prefix
3030 /// * `split_no` - The split number (1-indexed)
3031 /// * `split_count` - The total number of splits
3032 ///
3033 /// # Returns
3034 ///
3035 /// Returns the formatted split path as a String
3036 ///
3037 /// # Example
3038 ///
3039 /// ```
3040 /// use llama_cpp_4::model::LlamaModel;
3041 ///
3042 /// let path = LlamaModel::split_path("/models/llama", 1, 4);
3043 /// assert_eq!(path, "/models/llama-00002-of-00004.gguf");
3044 /// ```
3045 ///
3046 /// # Panics
3047 ///
3048 /// Panics if the path prefix contains a null byte.
3049 #[must_use]
3050 pub fn split_path(path_prefix: &str, split_no: i32, split_count: i32) -> String {
3051 let mut buffer = vec![0u8; 1024];
3052 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
3053 // cannot write past it; a negative return means the buffer was too small
3054 // and nothing was written. Any string arguments are `CString`s alive for
3055 // the call.
3056 let len = unsafe {
3057 llama_split_path(
3058 buffer.as_mut_ptr().cast::<c_char>(),
3059 buffer.len(),
3060 CString::new(path_prefix).unwrap().as_ptr(),
3061 split_no,
3062 split_count,
3063 )
3064 };
3065
3066 let len = usize::try_from(len).expect("split_path length fits in usize");
3067 buffer.truncate(len);
3068 String::from_utf8(buffer).unwrap_or_default()
3069 }
3070
3071 /// Extract the path prefix from a split filename.
3072 ///
3073 /// This function extracts the base path prefix from a split model filename,
3074 /// but only if the `split_no` and `split_count` match the pattern in the filename.
3075 ///
3076 /// # Arguments
3077 ///
3078 /// * `split_path` - The full path to the split file
3079 /// * `split_no` - The expected split number
3080 /// * `split_count` - The expected total number of splits
3081 ///
3082 /// # Returns
3083 ///
3084 /// Returns the path prefix if the pattern matches, or None if it doesn't
3085 ///
3086 /// # Example
3087 ///
3088 /// ```
3089 /// use llama_cpp_4::model::LlamaModel;
3090 ///
3091 /// let prefix = LlamaModel::split_prefix("/models/llama-00002-of-00004.gguf", 1, 4);
3092 /// assert_eq!(prefix, Some("/models/llama".to_string()));
3093 /// ```
3094 ///
3095 /// # Panics
3096 ///
3097 /// Panics if the split path contains a null byte.
3098 #[must_use]
3099 pub fn split_prefix(split_path: &str, split_no: i32, split_count: i32) -> Option<String> {
3100 let mut buffer = vec![0u8; 1024];
3101 // SAFETY: the buffer's pointer and capacity are passed together, so llama.cpp
3102 // cannot write past it; a negative return means the buffer was too small
3103 // and nothing was written. Any string arguments are `CString`s alive for
3104 // the call.
3105 let len = unsafe {
3106 llama_split_prefix(
3107 buffer.as_mut_ptr().cast::<c_char>(),
3108 buffer.len(),
3109 CString::new(split_path).unwrap().as_ptr(),
3110 split_no,
3111 split_count,
3112 )
3113 };
3114
3115 if len > 0 {
3116 let len = usize::try_from(len).expect("split_prefix length fits in usize");
3117 buffer.truncate(len);
3118 String::from_utf8(buffer).ok()
3119 } else {
3120 None
3121 }
3122 }
3123}
3124
3125#[allow(clippy::cast_precision_loss)]
3126impl fmt::Display for LlamaModel {
3127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3128 let desc = self.desc(256).unwrap_or_else(|_| "unknown".to_string());
3129 write!(
3130 f,
3131 "{desc} | {layers}L {heads}H {embd}E | {params} params | {size:.1} MiB",
3132 layers = self.n_layer(),
3133 heads = self.n_head(),
3134 embd = self.n_embd(),
3135 params = self.n_params(),
3136 size = self.model_size() as f64 / (1024.0 * 1024.0),
3137 )
3138 }
3139}
3140
3141impl Drop for LlamaModel {
3142 fn drop(&mut self) {
3143 // SAFETY: this runs once from `Drop` on a non-null handle, and nothing reads it
3144 // afterwards.
3145 unsafe { llama_model_free(self.model.as_ptr()) }
3146 }
3147}
3148
3149/// Defines the possible types of vocabulary used by the model.
3150///
3151/// The model may use different types of vocabulary depending on the tokenization method chosen during training.
3152/// This enum represents these types, specifically `BPE` (Byte Pair Encoding) and `SPM` (`SentencePiece`).
3153///
3154/// # Variants
3155///
3156/// - `BPE`: Byte Pair Encoding, a common tokenization method used in NLP tasks.
3157/// - `SPM`: `SentencePiece`, another popular tokenization method for NLP models.
3158///
3159/// # Example
3160///
3161/// ```no_run
3162/// use llama_cpp_4::model::VocabType;
3163///
3164/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
3165/// let vocab_type = VocabType::BPE;
3166/// match vocab_type {
3167/// VocabType::BPE => println!("The model uses Byte Pair Encoding (BPE)"),
3168/// VocabType::SPM => println!("The model uses SentencePiece (SPM)"),
3169/// }
3170/// # Ok(())
3171/// # }
3172/// ```
3173#[repr(u32)]
3174#[derive(Debug, Eq, Copy, Clone, PartialEq)]
3175pub enum VocabType {
3176 /// Byte Pair Encoding
3177 BPE = LLAMA_VOCAB_TYPE_BPE as _,
3178 /// Sentence Piece Tokenizer
3179 SPM = LLAMA_VOCAB_TYPE_SPM as _,
3180}
3181
3182/// Error that occurs when trying to convert a `llama_vocab_type` to a `VocabType`.
3183///
3184/// This error is raised when the integer value returned by the system does not correspond to a known vocabulary type.
3185///
3186/// # Variants
3187///
3188/// - `UnknownValue`: The error is raised when the value is not a valid `llama_vocab_type`. The invalid value is returned with the error.
3189///
3190/// # Example
3191///
3192/// ```no_run
3193/// use llama_cpp_4::model::LlamaTokenTypeFromIntError;
3194///
3195/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
3196/// let invalid_value = 999; // Not a valid vocabulary type
3197/// let error = LlamaTokenTypeFromIntError::UnknownValue(invalid_value);
3198/// println!("Error: {}", error);
3199/// # Ok(())
3200/// # }
3201/// ```
3202#[derive(thiserror::Error, Debug, Eq, PartialEq)]
3203pub enum LlamaTokenTypeFromIntError {
3204 /// The value is not a valid `llama_token_type`. Contains the int value that was invalid.
3205 #[error("Unknown Value {0}")]
3206 UnknownValue(llama_vocab_type),
3207}
3208
3209impl TryFrom<llama_vocab_type> for VocabType {
3210 type Error = LlamaTokenTypeFromIntError;
3211
3212 fn try_from(value: llama_vocab_type) -> Result<Self, Self::Error> {
3213 match value {
3214 LLAMA_VOCAB_TYPE_BPE => Ok(VocabType::BPE),
3215 LLAMA_VOCAB_TYPE_SPM => Ok(VocabType::SPM),
3216 unknown => Err(LlamaTokenTypeFromIntError::UnknownValue(unknown)),
3217 }
3218 }
3219}