Skip to main content

llama_cpp_4/
fit.rs

1//! Memory estimation and parameter fitting from llama.cpp `common/fit`.
2//!
3//! - [`get_device_memory_data`] — project per-device memory for a parameter set
4//!   without keeping a context alive.
5//! - [`fit_params`] — adjust [`LlamaModelParams`] / [`LlamaContextParams`] to fit
6//!   available device memory (upstream `common_fit_params`).
7//!
8//! # Example — memory estimate
9//!
10//! ```no_run
11//! use llama_cpp_4::prelude::*;
12//! use std::path::Path;
13//!
14//! fn main() {
15//!     let _backend = LlamaBackend::init().unwrap();
16//!     let report = get_device_memory_data(
17//!         Path::new("model.gguf"),
18//!         &LlamaModelParams::default().with_n_gpu_layers(99),
19//!         &LlamaContextParams::default(),
20//!         llama_cpp_sys_4::GGML_LOG_LEVEL_ERROR,
21//!     )
22//!     .unwrap();
23//!
24//!     println!("training ctx: {}", report.hyperparams.n_ctx_train);
25//!     for (i, entry) in report.entries.iter().enumerate() {
26//!         println!(
27//!             "device {i}: {} bytes free / {} total (projected {})",
28//!             entry.free,
29//!             entry.total,
30//!             entry.used(),
31//!         );
32//!     }
33//! }
34//! ```
35//!
36//! # Example — auto-fit parameters
37//!
38//! ```no_run
39//! use llama_cpp_4::fit::{fit_params, FitParams};
40//! use llama_cpp_4::prelude::*;
41//! use std::path::Path;
42//!
43//! fn main() {
44//!     let backend = LlamaBackend::init().unwrap();
45//!     let result = fit_params(
46//!         &backend,
47//!         Path::new("model.gguf"),
48//!         FitParams::default().with_n_ctx_min(512),
49//!     )
50//!     .unwrap();
51//!
52//!     use std::num::NonZeroU32;
53//!
54//!     println!("n_ctx: {}", result.context_params.n_ctx().map_or(0, NonZeroU32::get));
55//!     println!("n_gpu_layers: {}", result.model_params.n_gpu_layers());
56//! }
57//! ```
58
59use std::ffi::CString;
60use std::path::Path;
61use std::ptr::{null, null_mut};
62
63use thiserror::Error;
64
65use crate::context::params::LlamaContextParams;
66use crate::llama_backend::LlamaBackend;
67use crate::model::params::LlamaModelParams;
68use crate::{max_devices, max_tensor_buft_overrides};
69
70/// Per-device memory projection from [`get_device_memory_data`].
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct DeviceMemoryEntry {
73    /// Total device memory in bytes.
74    pub total: i64,
75    /// Free device memory in bytes at query time.
76    pub free: i64,
77    /// Projected model weight bytes on this device.
78    pub model: usize,
79    /// Projected KV / recurrent cache bytes.
80    pub context: usize,
81    /// Projected temporary compute buffer bytes.
82    pub compute: usize,
83}
84
85impl DeviceMemoryEntry {
86    /// Sum of model, context, and compute bytes.
87    #[must_use]
88    pub fn used(&self) -> usize {
89        self.model + self.context + self.compute
90    }
91}
92
93/// Hyper-parameters discovered while estimating device memory.
94///
95/// This crate builds it; callers read it. `#[non_exhaustive]` because upstream
96/// reports more of these over time — `n_gpu_layers_skipped` arrived in
97/// `b12388` — and each addition would otherwise break every struct literal
98/// downstream.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct DeviceMemoryHyperParams {
102    /// Model `n_gpu_layers` hyper-parameter used for the estimate.
103    pub n_gpu_layers: u32,
104    /// `NextN` layers excluded from `n_gpu_layers`.
105    ///
106    /// `0` when the MTP head is being loaded; otherwise the model's
107    /// `n_layer_nextn`, since those layers are not offloaded. New in
108    /// `b12388`, where upstream began reporting it alongside the rest.
109    pub n_gpu_layers_skipped: u32,
110    /// Model training context length.
111    pub n_ctx_train: u32,
112    /// Number of `MoE` experts (`0` when dense).
113    pub n_expert: u32,
114}
115
116/// Result of [`get_device_memory_data`].
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct DeviceMemoryReport {
119    /// Per-device memory breakdown (one entry per backend device).
120    pub entries: Vec<DeviceMemoryEntry>,
121    /// Hyper-parameters read from the checkpoint during estimation.
122    pub hyperparams: DeviceMemoryHyperParams,
123}
124
125/// Errors from [`get_device_memory_data`].
126#[derive(Debug, Error, PartialEq, Eq)]
127pub enum DeviceMemoryError {
128    /// The model path could not be encoded as a C string.
129    #[error("invalid model path")]
130    InvalidPath,
131    /// The underlying C++ helper failed (model missing, incompatible params, …).
132    #[error("device memory query failed")]
133    QueryFailed,
134    /// More devices were reported than the internal buffer allows.
135    #[error("device memory entry buffer overflow")]
136    BufferOverflow,
137}
138
139/// Estimate per-device memory for a model path and parameter set.
140///
141/// This wraps `common_get_device_memory_data` through `ext_shim`. The model is
142/// loaded with `no_alloc` and freed before returning; no context is kept alive.
143///
144/// # Errors
145///
146/// Returns [`DeviceMemoryError`] when the path is invalid or llama.cpp cannot
147/// produce an estimate.
148pub fn get_device_memory_data(
149    path_model: &Path,
150    mparams: &LlamaModelParams,
151    cparams: &LlamaContextParams,
152    log_level: llama_cpp_sys_4::ggml_log_level,
153) -> Result<DeviceMemoryReport, DeviceMemoryError> {
154    let path = CString::new(path_model.to_string_lossy().as_ref())
155        .map_err(|_| DeviceMemoryError::InvalidPath)?;
156
157    let mparams = mparams.params;
158    let cparams = cparams.context_params;
159
160    let mut capacity = 8usize;
161    loop {
162        let mut raw = vec![
163            llama_cpp_sys_4::common_device_memory_flat_entry {
164                total: 0,
165                free: 0,
166                model: 0,
167                context: 0,
168                compute: 0,
169            };
170            capacity
171        ];
172        let mut hp_ngl = 0u32;
173        let mut hp_ngl_skip = 0u32;
174        let mut hp_nct = 0u32;
175        let mut hp_nex = 0u32;
176
177        // SAFETY: the arguments are either scalars or pointers that outlive the call, and
178        // the library owns whatever it returns.
179        let n = unsafe {
180            llama_cpp_sys_4::common_device_memory_collect(
181                path.as_ptr(),
182                &raw const mparams,
183                &raw const cparams,
184                log_level,
185                raw.as_mut_ptr(),
186                capacity,
187                &raw mut hp_ngl,
188                &raw mut hp_ngl_skip,
189                &raw mut hp_nct,
190                &raw mut hp_nex,
191            )
192        };
193
194        if n == usize::MAX {
195            return Err(DeviceMemoryError::QueryFailed);
196        }
197
198        if n < capacity {
199            let entries = raw
200                .into_iter()
201                .take(n)
202                .map(|e| DeviceMemoryEntry {
203                    total: e.total,
204                    free: e.free,
205                    model: e.model,
206                    context: e.context,
207                    compute: e.compute,
208                })
209                .collect();
210            return Ok(DeviceMemoryReport {
211                entries,
212                hyperparams: DeviceMemoryHyperParams {
213                    n_gpu_layers: hp_ngl,
214                    n_gpu_layers_skipped: hp_ngl_skip,
215                    n_ctx_train: hp_nct,
216                    n_expert: hp_nex,
217                },
218            });
219        }
220
221        capacity = capacity.saturating_mul(2);
222        if capacity > 256 {
223            return Err(DeviceMemoryError::BufferOverflow);
224        }
225    }
226}
227
228const DEFAULT_MARGIN_BYTES: usize = 1024 * 1024 * 1024;
229
230/// Input to [`fit_params`].
231///
232/// Defaults mirror upstream `common_params`: unset `n_ctx` (`0`) so context size
233/// can be reduced, default model params so `n_gpu_layers` may be adjusted, and
234/// 1 GiB per-device memory margins.
235#[derive(Debug)]
236pub struct FitParams {
237    /// Starting model parameters. Only fields still at their defaults are modified.
238    pub model_params: LlamaModelParams,
239    /// Starting context parameters. Set `n_ctx` to `0` via
240    /// [`LlamaContextParams::with_n_ctx`]`(None)` to let fitting pick a context size.
241    pub context_params: LlamaContextParams,
242    /// Minimum free memory to leave on each device, in bytes (one entry per device).
243    pub margins: Vec<usize>,
244    /// Minimum context size when fitting must reduce `n_ctx`.
245    pub n_ctx_min: u32,
246    /// Minimum log level printed during fitting.
247    pub log_level: llama_cpp_sys_4::ggml_log_level,
248}
249
250impl Default for FitParams {
251    fn default() -> Self {
252        let nd = max_devices();
253        Self {
254            model_params: LlamaModelParams::default(),
255            context_params: LlamaContextParams::default().with_n_ctx(None),
256            margins: vec![DEFAULT_MARGIN_BYTES; nd],
257            n_ctx_min: 4096,
258            log_level: llama_cpp_sys_4::GGML_LOG_LEVEL_ERROR,
259        }
260    }
261}
262
263impl FitParams {
264    /// Override starting model parameters.
265    #[must_use]
266    pub fn with_model_params(mut self, model_params: LlamaModelParams) -> Self {
267        self.model_params = model_params;
268        self
269    }
270
271    /// Override starting context parameters.
272    #[must_use]
273    pub fn with_context_params(mut self, context_params: LlamaContextParams) -> Self {
274        self.context_params = context_params;
275        self
276    }
277
278    /// Per-device memory margins in bytes (length must be at least [`max_devices`]`()`).
279    #[must_use]
280    pub fn with_margins(mut self, margins: Vec<usize>) -> Self {
281        self.margins = margins;
282        self
283    }
284
285    /// Minimum context size when fitting reduces memory by shrinking `n_ctx`.
286    #[must_use]
287    pub fn with_n_ctx_min(mut self, n_ctx_min: u32) -> Self {
288        self.n_ctx_min = n_ctx_min;
289        self
290    }
291
292    /// Minimum log level emitted while fitting.
293    #[must_use]
294    pub fn with_log_level(mut self, log_level: llama_cpp_sys_4::ggml_log_level) -> Self {
295        self.log_level = log_level;
296        self
297    }
298}
299
300/// Fitted model/context parameters plus auxiliary buffers.
301///
302/// [`LlamaModelParams`] inside this struct may point at [`Self::tensor_split`] and
303/// its internal tensor buffer-type override storage; keep the whole `FitParamsResult` alive while
304/// loading a model with these parameters.
305#[derive(Debug)]
306pub struct FitParamsResult {
307    /// Model parameters after fitting (`n_gpu_layers`, tensor split, …).
308    pub model_params: LlamaModelParams,
309    /// Context parameters after fitting (`n_ctx`, …).
310    pub context_params: LlamaContextParams,
311    /// Layer split ratios per device (writable buffer passed to llama.cpp).
312    pub tensor_split: Vec<f32>,
313    /// Tensor buffer-type overrides written by fitting (keeps pointers valid).
314    #[allow(dead_code)]
315    pub(crate) tensor_buft_overrides: Vec<llama_cpp_sys_4::llama_model_tensor_buft_override>,
316    /// Per-device memory margins used during fitting (bytes).
317    pub margins: Vec<usize>,
318}
319
320impl FitParamsResult {
321    /// Tensor split values for active devices, trimming trailing zeros.
322    #[must_use]
323    pub fn active_tensor_split(&self) -> &[f32] {
324        let mut nd = self.tensor_split.len();
325        while nd > 1 && self.tensor_split[nd - 1] == 0.0 {
326            nd -= 1;
327        }
328        &self.tensor_split[..nd]
329    }
330}
331
332/// Errors from [`fit_params`].
333#[derive(Debug, Error, PartialEq, Eq)]
334pub enum FitParamsError {
335    /// The model path could not be encoded as a C string.
336    #[error("invalid model path")]
337    InvalidPath,
338    /// Fitting could not find allocations that fit device memory.
339    #[error("could not fit parameters to available device memory")]
340    CouldNotFit,
341    /// A hard error occurred (e.g. model file missing).
342    #[error("parameter fitting failed")]
343    Failed,
344}
345
346/// Adjust model and context parameters to fit available device memory.
347///
348/// Wraps `common_fit_params`. Requires an initialized [`LlamaBackend`]. The model
349/// is probed with `no_alloc` internally; nothing is kept loaded on return.
350///
351/// Only model fields still equal to [`LlamaModelParams::default`] are modified
352/// (except `n_gpu_layers` on macOS where the default is `-1`). Context `n_ctx`
353/// is adjusted only when it is `0` — use [`LlamaContextParams::with_n_ctx`] with `None`.
354///
355/// # Errors
356///
357/// Returns [`FitParamsError::InvalidPath`] for bad paths,
358/// [`FitParamsError::CouldNotFit`] when no allocation fits, and
359/// [`FitParamsError::Failed`] on hard errors (missing model, incompatible params, …).
360pub fn fit_params(
361    _backend: &LlamaBackend,
362    path_model: &Path,
363    options: FitParams,
364) -> Result<FitParamsResult, FitParamsError> {
365    let path = CString::new(path_model.to_string_lossy().as_ref())
366        .map_err(|_| FitParamsError::InvalidPath)?;
367
368    let nd = max_devices();
369    let mut tensor_split = vec![0.0_f32; nd];
370
371    let ntbo = max_tensor_buft_overrides();
372    let mut tensor_buft_overrides = vec![
373        llama_cpp_sys_4::llama_model_tensor_buft_override {
374            pattern: null(),
375            buft: null_mut(),
376        };
377        ntbo + 1
378    ];
379
380    let mut margins = options.margins;
381    if margins.len() < nd {
382        margins.resize(nd, DEFAULT_MARGIN_BYTES);
383    }
384
385    let mut model_params = options.model_params;
386    model_params.params.tensor_split = tensor_split.as_mut_ptr();
387    model_params.params.tensor_buft_overrides = tensor_buft_overrides.as_mut_ptr();
388
389    let mut context_params = options.context_params;
390
391    // SAFETY: the `CString` arguments are alive for the duration of the call, and any
392    // out-param is a stack local the shim writes through.
393    let status = unsafe {
394        llama_cpp_sys_4::common_fit_params_one(
395            path.as_ptr(),
396            &raw mut model_params.params,
397            &raw mut context_params.context_params,
398            tensor_split.as_mut_ptr(),
399            tensor_buft_overrides.as_mut_ptr(),
400            margins.as_mut_ptr(),
401            options.n_ctx_min,
402            options.log_level,
403        )
404    };
405
406    // `common_fit_params_one` widens `common_params_fit_status` to `int32_t`,
407    // because the enum lives in a header `ext_shim.h` does not include, while
408    // bindgen renders the enumerators as `u32`. Narrowing the status back is
409    // what lets the bindings' own constants be matched against, rather than
410    // values copied out of the header.
411    match u32::try_from(status) {
412        Ok(llama_cpp_sys_4::COMMON_PARAMS_FIT_STATUS_SUCCESS) => {
413            model_params.params.tensor_split = tensor_split.as_mut_ptr();
414            model_params.params.tensor_buft_overrides = tensor_buft_overrides.as_mut_ptr();
415            Ok(FitParamsResult {
416                model_params,
417                context_params,
418                tensor_split,
419                tensor_buft_overrides,
420                margins,
421            })
422        }
423        Ok(llama_cpp_sys_4::COMMON_PARAMS_FIT_STATUS_FAILURE) => Err(FitParamsError::CouldNotFit),
424        _ => Err(FitParamsError::Failed),
425    }
426}