Skip to main content

rig_llama_cpp/
types.rs

1use rig_core::error::ProviderError;
2use serde::{Deserialize, Serialize};
3use tokio::sync::{mpsc, oneshot};
4
5/// The provider document of a reply: what [`CompletionResponse::raw`]
6/// holds for every completion this crate produces, unary or streamed.
7///
8/// Read it back with `serde_json::from_value::<RawResponse>(response.raw)`.
9/// Marked `#[non_exhaustive]` because new fields may be added in future
10/// minor releases.
11///
12/// [`CompletionResponse::raw`]: rig_core::completion::CompletionResponse::raw
13#[derive(Clone, Debug, Serialize, Deserialize)]
14#[non_exhaustive]
15pub struct RawResponse {
16    /// The full generated text, exactly as the model produced it.
17    pub text: String,
18}
19
20/// One block of a turn as the worker parsed it, before rig assembles it into
21/// the response.
22#[derive(Clone, Debug, PartialEq)]
23pub(crate) enum OutputPart {
24    /// Answer text. Consecutive text parts extend one text block.
25    Text(String),
26    /// A whole reasoning block.
27    Reasoning(String),
28    /// A whole tool call.
29    ToolCall {
30        name: String,
31        arguments: serde_json::Value,
32    },
33}
34
35/// How a reply ended: token counts and the raw generated text.
36#[derive(Clone, Debug)]
37pub(crate) struct Done {
38    pub text: String,
39    pub prompt_tokens: u64,
40    pub completion_tokens: u64,
41    /// Tokens of the prompt that were already present in the persistent KV cache
42    /// (i.e. the longest common prefix shared with the previous request).
43    pub cached_input_tokens: u64,
44}
45
46/// One step of a reply, as the inference worker delivers it to the
47/// [`CompletionWire`](crate::CompletionWire) decoder.
48///
49/// Opaque: frames only travel between this crate's runtime and its wire.
50#[derive(Clone, Debug)]
51pub struct Frame(pub(crate) FrameKind);
52
53#[derive(Clone, Debug)]
54pub(crate) enum FrameKind {
55    Part(OutputPart),
56    End(Done),
57}
58
59pub(crate) type StreamSender = mpsc::UnboundedSender<Result<Frame, ProviderError>>;
60
61impl Frame {
62    pub(crate) fn part(part: OutputPart) -> Self {
63        Self(FrameKind::Part(part))
64    }
65
66    pub(crate) fn end(done: Done) -> Self {
67        Self(FrameKind::End(done))
68    }
69}
70
71pub(crate) enum ResponseChannel {
72    Completion(oneshot::Sender<Result<InferenceResult, String>>),
73    Streaming(StreamSender),
74}
75
76pub(crate) enum InferenceCommand {
77    Request(InferenceRequest),
78    Reload(ReloadRequest),
79    Shutdown,
80}
81
82pub(crate) struct ReloadRequest {
83    pub model_path: String,
84    pub mmproj_path: Option<String>,
85    pub n_ctx: u32,
86    pub fit_params: FitParams,
87    pub kv_cache_params: KvCacheParams,
88    pub checkpoint_params: CheckpointParams,
89    pub result_tx: std::sync::mpsc::Sender<Result<(), crate::error::LoadError>>,
90}
91
92pub(crate) struct InferenceRequest {
93    pub params: InferenceParams,
94    pub response_channel: ResponseChannel,
95}
96
97pub(crate) struct InferenceParams {
98    pub prepared_request: PreparedRequest,
99    pub max_tokens: u32,
100    pub temperature: f32,
101    pub top_p: f32,
102    pub top_k: i32,
103    pub min_p: f32,
104    pub presence_penalty: f32,
105    pub repetition_penalty: f32,
106    /// Seed of the final `dist` sampler.
107    pub seed: u32,
108}
109
110pub(crate) struct InferenceResult {
111    /// The parsed blocks of a unary turn. Empty for a streamed turn, whose
112    /// blocks already went out as frames.
113    pub parts: Vec<OutputPart>,
114    pub done: Done,
115}
116
117pub(crate) struct PreparedRequest {
118    pub messages_json: String,
119    pub tools_json: Option<String>,
120    pub tool_choice: Option<String>,
121    pub json_schema: Option<String>,
122    /// Parsed from the request's `additional_params` (`{ "thinking": bool }`).
123    ///
124    /// `None` means the caller expressed no preference, and is distinct from
125    /// `Some(false)`: templates commonly gate reasoning on
126    /// `enable_thinking is defined` or `| default(true)`, so passing an
127    /// explicit `false` for an unasked question turns thinking *off* for a
128    /// model that reasons by default. `None` reaches the template as undefined,
129    /// leaving its own default in charge.
130    ///
131    /// Forwarded as the `enable_thinking` variable, but only on the minijinja
132    /// paths (`src/jinja.rs`). llama.cpp's own applier takes just
133    /// `(role, content)` pairs — `llama-cpp-2` 0.1.147 dropped the
134    /// `chat_template_kwargs` plumbing the old oaicompat path used — so for a
135    /// model llama.cpp can template natively this flag stays advisory and the
136    /// template's own default decides.
137    pub enable_thinking: Option<bool>,
138    #[cfg(feature = "mtmd")]
139    pub images: Vec<PreparedImage>,
140}
141
142/// One image extracted from the chat history with its FNV-1a hash precomputed.
143/// The hash is propagated into the underlying `MtmdBitmap` via `set_id` so
144/// that `MtmdInputChunk::id()` round-trips it for the prefix-cache diff.
145#[cfg(feature = "mtmd")]
146#[derive(Clone, Debug)]
147pub(crate) struct PreparedImage {
148    pub bytes: Vec<u8>,
149    pub hash: u64,
150}
151
152pub(crate) struct PromptBuildResult {
153    pub prompt: String,
154}
155
156/// Sampling parameters that control token generation.
157///
158/// Marked `#[non_exhaustive]` so future sampling knobs can be added without
159/// a breaking release. Start from [`SamplingParams::default`] and chain
160/// `with_*` setters:
161///
162/// ```
163/// let params = rig_llama_cpp::SamplingParams::default()
164///     .with_top_k(40)
165///     .with_presence_penalty(1.5);
166/// ```
167#[derive(Clone, Copy, Debug)]
168#[non_exhaustive]
169pub struct SamplingParams {
170    /// Nucleus sampling threshold (default: `0.95`).
171    pub top_p: f32,
172    /// Top-k sampling parameter (default: `40`).
173    pub top_k: i32,
174    /// Minimum probability threshold (default: `0.0`).
175    pub min_p: f32,
176    /// Penalty for token presence (default: `0.0`).
177    pub presence_penalty: f32,
178    /// Penalty for token repetition (default: `1.0`).
179    pub repetition_penalty: f32,
180}
181
182impl Default for SamplingParams {
183    fn default() -> Self {
184        Self {
185            top_p: 0.95,
186            top_k: 40,
187            min_p: 0.0,
188            presence_penalty: 0.0,
189            repetition_penalty: 1.0,
190        }
191    }
192}
193
194impl SamplingParams {
195    /// Set the nucleus sampling threshold.
196    #[must_use]
197    pub fn with_top_p(mut self, top_p: f32) -> Self {
198        self.top_p = top_p;
199        self
200    }
201
202    /// Set the top-k sampling parameter.
203    #[must_use]
204    pub fn with_top_k(mut self, top_k: i32) -> Self {
205        self.top_k = top_k;
206        self
207    }
208
209    /// Set the minimum probability threshold.
210    #[must_use]
211    pub fn with_min_p(mut self, min_p: f32) -> Self {
212        self.min_p = min_p;
213        self
214    }
215
216    /// Set the presence penalty.
217    #[must_use]
218    pub fn with_presence_penalty(mut self, presence_penalty: f32) -> Self {
219        self.presence_penalty = presence_penalty;
220        self
221    }
222
223    /// Set the repetition penalty.
224    #[must_use]
225    pub fn with_repetition_penalty(mut self, repetition_penalty: f32) -> Self {
226        self.repetition_penalty = repetition_penalty;
227        self
228    }
229}
230
231/// Configuration for automatic GPU/CPU layer fitting.
232///
233/// Passed to [`crate::Client::builder`] (or [`crate::Client::from_gguf`]) so
234/// llama.cpp can probe available device memory and pick the optimal number
235/// of layers to offload to GPU automatically, instead of requiring a manual
236/// `n_gpu_layers` value.
237///
238/// Marked `#[non_exhaustive]`; build via `Default::default()` and chain the
239/// `with_*` setters.
240#[derive(Clone, Debug)]
241#[non_exhaustive]
242pub struct FitParams {
243    /// Memory margin per device in bytes. If `None`, defaults to 1 GiB per device.
244    pub margins: Option<Vec<usize>>,
245    /// Minimum context size to preserve during fitting (default: `4096`).
246    pub n_ctx_min: u32,
247}
248
249impl Default for FitParams {
250    fn default() -> Self {
251        Self {
252            margins: None,
253            n_ctx_min: 4096,
254        }
255    }
256}
257
258impl FitParams {
259    /// Override the per-device memory margin in bytes.
260    #[must_use]
261    pub fn with_margins(mut self, margins: Option<Vec<usize>>) -> Self {
262        self.margins = margins;
263        self
264    }
265
266    /// Override the minimum context size to preserve during fitting.
267    #[must_use]
268    pub fn with_n_ctx_min(mut self, n_ctx_min: u32) -> Self {
269        self.n_ctx_min = n_ctx_min;
270        self
271    }
272}
273
274/// Tunable parameters for the in-memory state-checkpoint cache used to
275/// preserve KV/recurrent state across chat turns for hybrid models.
276///
277/// Hybrid architectures (Qwen 3.5, Jamba, etc.) interleave Mamba-style
278/// recurrent layers with transformer layers. The recurrent state can't be
279/// rolled back to an arbitrary earlier position, so a partial KV trim
280/// fails whenever the next prompt diverges deep into the conversation.
281/// To work around this, we periodically snapshot the partial seq state
282/// (recurrent + SWA, via `LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY`) during
283/// prompt prefill and restore the closest snapshot when the next prompt
284/// arrives. Mirrors the mechanism used by upstream `llama-server`.
285///
286/// For non-hybrid models (Qwen 2.5, Llama 3, Gemma, ...) checkpoints are
287/// created but never used because the cheaper partial-trim path
288/// succeeds.
289///
290/// Marked `#[non_exhaustive]`; build via `Default::default()` and chain the
291/// `with_*` setters.
292#[derive(Clone, Copy, Debug)]
293#[non_exhaustive]
294pub struct CheckpointParams {
295    /// Maximum number of checkpoints retained per persistent context.
296    /// `0` disables checkpointing entirely. Each checkpoint is a few MB
297    /// for typical hybrid models.
298    pub max_checkpoints: u32,
299    /// Approximate spacing between checkpoints during prompt prefill, in
300    /// tokens. The last `4..=4 + n_ubatch` tokens always get a
301    /// checkpoint regardless. `<= 0` means "only checkpoint near the end
302    /// of the prompt".
303    pub every_n_tokens: i32,
304    /// Don't checkpoint the very start of a prompt — saves space for
305    /// no benefit because we'd have to re-decode that prefix anyway if
306    /// it's the entire reuse window.
307    pub min_tokens: u32,
308    /// Don't take two checkpoints closer than this many tokens apart.
309    pub min_gap: u32,
310}
311
312impl Default for CheckpointParams {
313    fn default() -> Self {
314        Self {
315            // llama-server uses 32; cap lower because each checkpoint is
316            // a few MB and we'd rather not balloon RSS.
317            max_checkpoints: 8,
318            every_n_tokens: 8192,
319            min_tokens: 64,
320            min_gap: 64,
321        }
322    }
323}
324
325impl CheckpointParams {
326    /// Override the maximum number of checkpoints retained per context.
327    #[must_use]
328    pub fn with_max_checkpoints(mut self, max_checkpoints: u32) -> Self {
329        self.max_checkpoints = max_checkpoints;
330        self
331    }
332
333    /// Override the approximate spacing between checkpoints (in tokens).
334    #[must_use]
335    pub fn with_every_n_tokens(mut self, every_n_tokens: i32) -> Self {
336        self.every_n_tokens = every_n_tokens;
337        self
338    }
339
340    /// Override the minimum prompt length before checkpoints are taken.
341    #[must_use]
342    pub fn with_min_tokens(mut self, min_tokens: u32) -> Self {
343        self.min_tokens = min_tokens;
344        self
345    }
346
347    /// Override the minimum spacing between two consecutive checkpoints.
348    #[must_use]
349    pub fn with_min_gap(mut self, min_gap: u32) -> Self {
350        self.min_gap = min_gap;
351        self
352    }
353}
354
355/// Data type used for an entry in the attention KV cache.
356///
357/// Mirrors the subset of `ggml_type` values that `llama.cpp` accepts as KV
358/// cache element types. The `F16` default preserves full attention quality;
359/// quantizing (e.g. `Q8_0` ≈ ½ size, `Q4_0` ≈ ¼ size) trades a small amount
360/// of accuracy for a large VRAM reduction at long `n_ctx`.
361///
362/// This is a local shim around `llama_cpp_2::context::params::KvCacheType`
363/// so a future `llama-cpp-2` update doesn't force a breaking release of
364/// `rig-llama-cpp`. Marked `#[non_exhaustive]`: when llama.cpp adds a new
365/// `ggml_type`, we add a corresponding variant in a minor (`0.1.x`) release.
366#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
367#[allow(non_camel_case_types)]
368#[non_exhaustive]
369pub enum KvCacheType {
370    /// IEEE 754 single precision.
371    F32,
372    /// IEEE 754 half precision (llama.cpp's default for both K and V).
373    F16,
374    /// Brain floating-point 16, common on newer NVIDIA / AMD GPUs.
375    BF16,
376    /// IEEE 754 double precision.
377    F64,
378    /// 4-bit block quantization, type 0.
379    Q4_0,
380    /// 4-bit block quantization, type 1.
381    Q4_1,
382    /// 5-bit block quantization, type 0.
383    Q5_0,
384    /// 5-bit block quantization, type 1.
385    Q5_1,
386    /// 8-bit block quantization, type 0.
387    Q8_0,
388    /// 8-bit block quantization, type 1.
389    Q8_1,
390    /// 2-bit K-quant.
391    Q2_K,
392    /// 3-bit K-quant.
393    Q3_K,
394    /// 4-bit K-quant.
395    Q4_K,
396    /// 5-bit K-quant.
397    Q5_K,
398    /// 6-bit K-quant.
399    Q6_K,
400    /// 8-bit K-quant.
401    Q8_K,
402    /// Importance-weighted 2-bit, extra-extra-small.
403    IQ2_XXS,
404    /// Importance-weighted 2-bit, extra-small.
405    IQ2_XS,
406    /// Importance-weighted 2-bit, small.
407    IQ2_S,
408    /// Importance-weighted 3-bit, extra-extra-small.
409    IQ3_XXS,
410    /// Importance-weighted 3-bit, small.
411    IQ3_S,
412    /// Importance-weighted 1-bit, small.
413    IQ1_S,
414    /// Importance-weighted 1-bit, medium.
415    IQ1_M,
416    /// Importance-weighted 4-bit, extra-small.
417    IQ4_XS,
418    /// Importance-weighted 4-bit, non-linear.
419    IQ4_NL,
420    /// Signed 8-bit integer.
421    I8,
422    /// Signed 16-bit integer.
423    I16,
424    /// Signed 32-bit integer.
425    I32,
426    /// Signed 64-bit integer.
427    I64,
428    /// Ternary 1-bit, type 0.
429    TQ1_0,
430    /// Ternary 2-bit, type 0.
431    TQ2_0,
432    /// Microscaling FP4.
433    MXFP4,
434}
435
436impl From<KvCacheType> for llama_cpp_2::context::params::KvCacheType {
437    fn from(value: KvCacheType) -> Self {
438        use llama_cpp_2::context::params::KvCacheType as Upstream;
439        match value {
440            KvCacheType::F32 => Upstream::F32,
441            KvCacheType::F16 => Upstream::F16,
442            KvCacheType::BF16 => Upstream::BF16,
443            KvCacheType::F64 => Upstream::F64,
444            KvCacheType::Q4_0 => Upstream::Q4_0,
445            KvCacheType::Q4_1 => Upstream::Q4_1,
446            KvCacheType::Q5_0 => Upstream::Q5_0,
447            KvCacheType::Q5_1 => Upstream::Q5_1,
448            KvCacheType::Q8_0 => Upstream::Q8_0,
449            KvCacheType::Q8_1 => Upstream::Q8_1,
450            KvCacheType::Q2_K => Upstream::Q2_K,
451            KvCacheType::Q3_K => Upstream::Q3_K,
452            KvCacheType::Q4_K => Upstream::Q4_K,
453            KvCacheType::Q5_K => Upstream::Q5_K,
454            KvCacheType::Q6_K => Upstream::Q6_K,
455            KvCacheType::Q8_K => Upstream::Q8_K,
456            KvCacheType::IQ2_XXS => Upstream::IQ2_XXS,
457            KvCacheType::IQ2_XS => Upstream::IQ2_XS,
458            KvCacheType::IQ2_S => Upstream::IQ2_S,
459            KvCacheType::IQ3_XXS => Upstream::IQ3_XXS,
460            KvCacheType::IQ3_S => Upstream::IQ3_S,
461            KvCacheType::IQ1_S => Upstream::IQ1_S,
462            KvCacheType::IQ1_M => Upstream::IQ1_M,
463            KvCacheType::IQ4_XS => Upstream::IQ4_XS,
464            KvCacheType::IQ4_NL => Upstream::IQ4_NL,
465            KvCacheType::I8 => Upstream::I8,
466            KvCacheType::I16 => Upstream::I16,
467            KvCacheType::I32 => Upstream::I32,
468            KvCacheType::I64 => Upstream::I64,
469            KvCacheType::TQ1_0 => Upstream::TQ1_0,
470            KvCacheType::TQ2_0 => Upstream::TQ2_0,
471            KvCacheType::MXFP4 => Upstream::MXFP4,
472        }
473    }
474}
475
476/// KV cache quantization configuration.
477///
478/// Controls the data type used for the attention K and V caches. llama.cpp defaults
479/// both to `F16` (`GGML_TYPE_F16`), which is what `KvCacheParams::default()` preserves.
480/// Quantizing the KV cache (e.g. `Q8_0` → ~½ size, `Q4_0` → ~¼ size) trades a small
481/// amount of accuracy for a large reduction in VRAM usage, which is often the dominant
482/// cost at long `n_ctx`.
483///
484/// Marked `#[non_exhaustive]`; build via `Default::default()` and chain the
485/// `with_*` setters:
486///
487/// ```
488/// use rig_llama_cpp::{KvCacheParams, KvCacheType};
489///
490/// let kv = KvCacheParams::default()
491///     .with_type_k(KvCacheType::Q8_0)
492///     .with_type_v(KvCacheType::Q8_0);
493/// ```
494#[derive(Clone, Copy, Debug)]
495#[non_exhaustive]
496pub struct KvCacheParams {
497    /// Data type for the K cache (default: [`KvCacheType::F16`]).
498    pub type_k: KvCacheType,
499    /// Data type for the V cache (default: [`KvCacheType::F16`]).
500    pub type_v: KvCacheType,
501}
502
503impl Default for KvCacheParams {
504    fn default() -> Self {
505        Self {
506            type_k: KvCacheType::F16,
507            type_v: KvCacheType::F16,
508        }
509    }
510}
511
512impl KvCacheParams {
513    /// Override the K cache data type.
514    #[must_use]
515    pub fn with_type_k(mut self, type_k: KvCacheType) -> Self {
516        self.type_k = type_k;
517        self
518    }
519
520    /// Override the V cache data type.
521    #[must_use]
522    pub fn with_type_v(mut self, type_v: KvCacheType) -> Self {
523        self.type_v = type_v;
524        self
525    }
526}