-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathparams.rs
More file actions
467 lines (418 loc) · 16.1 KB
/
params.rs
File metadata and controls
467 lines (418 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! A safe wrapper around `llama_model_params`.
use crate::model::params::kv_overrides::KvOverrides;
use crate::LlamaCppError;
use std::ffi::{c_char, CStr};
use std::fmt::{Debug, Formatter};
use std::pin::Pin;
use std::ptr::null;
pub mod kv_overrides;
#[allow(clippy::cast_possible_wrap)]
#[allow(clippy::cast_possible_truncation)]
const LLAMA_SPLIT_MODE_NONE: i8 = llama_cpp_sys_2::LLAMA_SPLIT_MODE_NONE as i8;
#[allow(clippy::cast_possible_wrap)]
#[allow(clippy::cast_possible_truncation)]
const LLAMA_SPLIT_MODE_LAYER: i8 = llama_cpp_sys_2::LLAMA_SPLIT_MODE_LAYER as i8;
#[allow(clippy::cast_possible_wrap)]
#[allow(clippy::cast_possible_truncation)]
const LLAMA_SPLIT_MODE_ROW: i8 = llama_cpp_sys_2::LLAMA_SPLIT_MODE_ROW as i8;
/// A rusty wrapper around `llama_split_mode`.
#[repr(i8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LlamaSplitMode {
/// Single GPU
None = LLAMA_SPLIT_MODE_NONE,
/// Split layers and KV across GPUs
Layer = LLAMA_SPLIT_MODE_LAYER,
/// Split layers and KV across GPUs, use tensor parallelism if supported
Row = LLAMA_SPLIT_MODE_ROW,
}
/// An error that occurs when unknown split mode is encountered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LlamaSplitModeParseError(pub i32);
/// Create a `LlamaSplitMode` from a `i32`.
///
/// # Errors
/// Returns `LlamaSplitModeParseError` if the value does not correspond to a valid `LlamaSplitMode`.
impl TryFrom<i32> for LlamaSplitMode {
type Error = LlamaSplitModeParseError;
fn try_from(value: i32) -> Result<Self, Self::Error> {
let i8_value = value
.try_into()
.map_err(|_| LlamaSplitModeParseError(value))?;
match i8_value {
LLAMA_SPLIT_MODE_NONE => Ok(Self::None),
LLAMA_SPLIT_MODE_LAYER => Ok(Self::Layer),
LLAMA_SPLIT_MODE_ROW => Ok(Self::Row),
_ => Err(LlamaSplitModeParseError(value)),
}
}
}
/// Create a `LlamaSplitMode` from a `u32`.
///
/// # Errors
/// Returns `LlamaSplitModeParseError` if the value does not correspond to a valid `LlamaSplitMode`.
impl TryFrom<u32> for LlamaSplitMode {
type Error = LlamaSplitModeParseError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
let i8_value = value
.try_into()
.map_err(|_| LlamaSplitModeParseError(value.try_into().unwrap_or(i32::MAX)))?;
match i8_value {
LLAMA_SPLIT_MODE_NONE => Ok(Self::None),
LLAMA_SPLIT_MODE_LAYER => Ok(Self::Layer),
LLAMA_SPLIT_MODE_ROW => Ok(Self::Row),
_ => Err(LlamaSplitModeParseError(
value.try_into().unwrap_or(i32::MAX),
)),
}
}
}
/// Create a `i32` from a `LlamaSplitMode`.
impl From<LlamaSplitMode> for i32 {
fn from(value: LlamaSplitMode) -> Self {
match value {
LlamaSplitMode::None => LLAMA_SPLIT_MODE_NONE.into(),
LlamaSplitMode::Layer => LLAMA_SPLIT_MODE_LAYER.into(),
LlamaSplitMode::Row => LLAMA_SPLIT_MODE_ROW.into(),
}
}
}
/// Create a `u32` from a `LlamaSplitMode`.
impl From<LlamaSplitMode> for u32 {
fn from(value: LlamaSplitMode) -> Self {
match value {
LlamaSplitMode::None => LLAMA_SPLIT_MODE_NONE as u32,
LlamaSplitMode::Layer => LLAMA_SPLIT_MODE_LAYER as u32,
LlamaSplitMode::Row => LLAMA_SPLIT_MODE_ROW as u32,
}
}
}
/// The default split mode is `Layer` in llama.cpp.
impl Default for LlamaSplitMode {
fn default() -> Self {
LlamaSplitMode::Layer
}
}
/// The maximum number of devices supported.
///
/// The real maximum number of devices is the lesser one of this value and the value returned by
/// `llama_cpp_2::max_devices()`.
pub const LLAMA_CPP_MAX_DEVICES: usize = 16;
/// A safe wrapper around `llama_model_params`.
#[allow(clippy::module_name_repetitions)]
pub struct LlamaModelParams {
pub(crate) params: llama_cpp_sys_2::llama_model_params,
kv_overrides: Vec<llama_cpp_sys_2::llama_model_kv_override>,
buft_overrides: Vec<llama_cpp_sys_2::llama_model_tensor_buft_override>,
devices: Pin<Box<[llama_cpp_sys_2::ggml_backend_dev_t; LLAMA_CPP_MAX_DEVICES]>>,
}
impl Debug for LlamaModelParams {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LlamaModelParams")
.field("n_gpu_layers", &self.params.n_gpu_layers)
.field("main_gpu", &self.params.main_gpu)
.field("vocab_only", &self.params.vocab_only)
.field("use_mmap", &self.params.use_mmap)
.field("use_mlock", &self.params.use_mlock)
.field("split_mode", &self.split_mode())
.field("devices", &self.devices)
.field("kv_overrides", &"vec of kv_overrides")
.finish()
}
}
impl LlamaModelParams {
/// See [`KvOverrides`]
///
/// # Examples
///
/// ```rust
/// # use llama_cpp_2::model::params::LlamaModelParams;
/// let params = Box::pin(LlamaModelParams::default());
/// let kv_overrides = params.kv_overrides();
/// let count = kv_overrides.into_iter().count();
/// assert_eq!(count, 0);
/// ```
#[must_use]
pub fn kv_overrides<'a>(&'a self) -> KvOverrides<'a> {
KvOverrides::new(self)
}
/// Appends a key-value override to the model parameters. It must be pinned as this creates a self-referential struct.
///
/// # Examples
///
/// ```rust
/// # use std::ffi::{CStr, CString};
/// use std::pin::pin;
/// # use llama_cpp_2::model::params::LlamaModelParams;
/// # use llama_cpp_2::model::params::kv_overrides::ParamOverrideValue;
/// let mut params = pin!(LlamaModelParams::default());
/// let key = CString::new("key").expect("CString::new failed");
/// params.as_mut().append_kv_override(&key, ParamOverrideValue::Int(50));
///
/// let kv_overrides = params.kv_overrides().into_iter().collect::<Vec<_>>();
/// assert_eq!(kv_overrides.len(), 1);
///
/// let (k, v) = &kv_overrides[0];
/// assert_eq!(v, &ParamOverrideValue::Int(50));
///
/// assert_eq!(k.to_bytes(), b"key", "expected key to be 'key', was {:?}", k);
/// ```
#[allow(clippy::missing_panics_doc)] // panics are just to enforce internal invariants, not user errors
pub fn append_kv_override(
mut self: Pin<&mut Self>,
key: &CStr,
value: kv_overrides::ParamOverrideValue,
) {
let kv_override = self
.kv_overrides
.get_mut(0)
.expect("kv_overrides did not have a next allocated");
assert_eq!(kv_override.key[0], 0, "last kv_override was not empty");
// There should be some way to do this without iterating over everything.
for (i, &c) in key.to_bytes_with_nul().iter().enumerate() {
kv_override.key[i] = c_char::try_from(c).expect("invalid character in key");
}
kv_override.tag = value.tag();
kv_override.__bindgen_anon_1 = value.value();
// set to null pointer for panic safety (as push may move the vector, invalidating the pointer)
self.params.kv_overrides = null();
// push the next one to ensure we maintain the iterator invariant of ending with a 0
self.kv_overrides
.push(llama_cpp_sys_2::llama_model_kv_override {
key: [0; 128],
tag: 0,
__bindgen_anon_1: llama_cpp_sys_2::llama_model_kv_override__bindgen_ty_1 {
val_i64: 0,
},
});
// set the pointer to the (potentially) new vector
self.params.kv_overrides = self.kv_overrides.as_ptr();
eprintln!("saved ptr: {:?}", self.params.kv_overrides);
}
}
impl LlamaModelParams {
/// Adds buffer type overides to move all mixture-of-experts layers to CPU.
pub fn add_cpu_moe_override(self: Pin<&mut Self>) {
self.add_cpu_buft_override(c"\\.ffn_(up|down|gate)_(ch|)exps");
}
/// Appends a buffer type override to the model parameters, to move layers matching pattern to CPU.
/// It must be pinned as this creates a self-referential struct.
pub fn add_cpu_buft_override(mut self: Pin<&mut Self>, key: &CStr) {
let buft_override = self
.buft_overrides
.get_mut(0)
.expect("buft_overrides did not have a next allocated");
assert!(
buft_override.pattern.is_null(),
"last buft_override was not empty"
);
// There should be some way to do this without iterating over everything.
for &c in key.to_bytes_with_nul().iter() {
c_char::try_from(c).expect("invalid character in key");
}
buft_override.pattern = key.as_ptr();
buft_override.buft = unsafe { llama_cpp_sys_2::ggml_backend_cpu_buffer_type() };
// set to null pointer for panic safety (as push may move the vector, invalidating the pointer)
self.params.tensor_buft_overrides = null();
// push the next one to ensure we maintain the iterator invariant of ending with a 0
self.buft_overrides
.push(llama_cpp_sys_2::llama_model_tensor_buft_override {
pattern: std::ptr::null(),
buft: std::ptr::null_mut(),
});
// set the pointer to the (potentially) new vector
self.params.tensor_buft_overrides = self.buft_overrides.as_ptr();
}
}
impl LlamaModelParams {
/// Get the number of layers to offload to the GPU.
#[must_use]
pub fn n_gpu_layers(&self) -> i32 {
self.params.n_gpu_layers
}
/// The GPU that is used for scratch and small tensors
#[must_use]
pub fn main_gpu(&self) -> i32 {
self.params.main_gpu
}
/// only load the vocabulary, no weights
#[must_use]
pub fn vocab_only(&self) -> bool {
self.params.vocab_only
}
/// use mmap if possible
#[must_use]
pub fn use_mmap(&self) -> bool {
self.params.use_mmap
}
/// force system to keep model in RAM
#[must_use]
pub fn use_mlock(&self) -> bool {
self.params.use_mlock
}
/// get the split mode
///
/// # Errors
/// Returns `LlamaSplitModeParseError` if the unknown split mode is encountered.
pub fn split_mode(&self) -> Result<LlamaSplitMode, LlamaSplitModeParseError> {
LlamaSplitMode::try_from(self.params.split_mode)
}
/// get the devices
#[must_use]
pub fn devices(&self) -> Vec<usize> {
let mut backend_devices = Vec::new();
for i in 0..unsafe { llama_cpp_sys_2::ggml_backend_dev_count() } {
let dev = unsafe { llama_cpp_sys_2::ggml_backend_dev_get(i) };
backend_devices.push(dev);
}
let mut devices = Vec::new();
for &dev in self.devices.iter() {
if dev.is_null() {
break;
}
if let Some((index, _)) = backend_devices
.iter()
.enumerate()
.find(|&(_i, &d)| d == dev)
{
devices.push(index);
}
}
devices
}
/// sets the number of gpu layers to offload to the GPU.
/// ```
/// # use llama_cpp_2::model::params::LlamaModelParams;
/// let params = LlamaModelParams::default();
/// let params = params.with_n_gpu_layers(1);
/// assert_eq!(params.n_gpu_layers(), 1);
/// ```
#[must_use]
pub fn with_n_gpu_layers(mut self, n_gpu_layers: u32) -> Self {
// The only way this conversion can fail is if u32 overflows the i32 - in which case we set
// to MAX
let n_gpu_layers = i32::try_from(n_gpu_layers).unwrap_or(i32::MAX);
self.params.n_gpu_layers = n_gpu_layers;
self
}
/// sets the main GPU
///
/// To enable this option, you must set `split_mode` to `LlamaSplitMode::None` to enable single GPU mode.
#[must_use]
pub fn with_main_gpu(mut self, main_gpu: i32) -> Self {
self.params.main_gpu = main_gpu;
self
}
/// sets `vocab_only`
#[must_use]
pub fn with_vocab_only(mut self, vocab_only: bool) -> Self {
self.params.vocab_only = vocab_only;
self
}
/// sets `use_mmap`
#[must_use]
pub fn with_use_mmap(mut self, use_mmap: bool) -> Self {
self.params.use_mmap = use_mmap;
self
}
/// sets `use_mlock`
#[must_use]
pub fn with_use_mlock(mut self, use_mlock: bool) -> Self {
self.params.use_mlock = use_mlock;
self
}
/// sets `split_mode`
#[must_use]
pub fn with_split_mode(mut self, split_mode: LlamaSplitMode) -> Self {
self.params.split_mode = split_mode.into();
self
}
/// sets `devices`
///
/// The devices are specified as indices that correspond to the ggml backend device indices.
///
/// The maximum number of devices is 16.
///
/// You don't need to specify CPU or ACCEL devices.
///
/// # Errors
/// Returns `LlamaCppError::BackendDeviceNotFound` if any device index is invalid.
pub fn with_devices(mut self, devices: &[usize]) -> Result<Self, LlamaCppError> {
for dev in self.devices.iter_mut() {
*dev = std::ptr::null_mut();
}
// Check device count
let max_devices = crate::max_devices().min(LLAMA_CPP_MAX_DEVICES);
if devices.len() > max_devices {
return Err(LlamaCppError::MaxDevicesExceeded(max_devices));
}
for (i, &dev) in devices.iter().enumerate() {
if dev >= unsafe { llama_cpp_sys_2::ggml_backend_dev_count() } {
return Err(LlamaCppError::BackendDeviceNotFound(dev));
}
let backend_dev = unsafe { llama_cpp_sys_2::ggml_backend_dev_get(dev) };
self.devices[i] = backend_dev;
}
if self.devices.is_empty() {
self.params.devices = std::ptr::null_mut();
} else {
self.params.devices = self.devices.as_mut_ptr();
}
Ok(self)
}
/// Set `no_alloc`
///
/// If this parameter is true, don't allocate memory for the tensor data
///
/// You can't use `no_alloc` with `use_mmap`, so this also sets `use_mmap` to false.
#[must_use]
pub fn with_no_alloc(mut self, no_alloc: bool) -> Self {
self.params.no_alloc = no_alloc;
if no_alloc {
self = self.with_use_mmap(false);
}
self
}
/// Get `no_alloc`
///
/// If this parameter is true, don't allocate memory for the tensor data
#[must_use]
pub fn no_alloc(&self) -> bool {
self.params.no_alloc
}
}
/// Default parameters for `LlamaModel`. (as defined in llama.cpp by `llama_model_default_params`)
/// ```
/// # use llama_cpp_2::model::params::LlamaModelParams;
/// use llama_cpp_2::model::params::LlamaSplitMode;
/// let params = LlamaModelParams::default();
/// assert_eq!(params.n_gpu_layers(), -1, "n_gpu_layers should be -1");
/// assert_eq!(params.main_gpu(), 0, "main_gpu should be 0");
/// assert_eq!(params.vocab_only(), false, "vocab_only should be false");
/// assert_eq!(params.use_mmap(), true, "use_mmap should be true");
/// assert_eq!(params.use_mlock(), false, "use_mlock should be false");
/// assert_eq!(params.split_mode(), Ok(LlamaSplitMode::Layer), "split_mode should be LAYER");
/// assert_eq!(params.devices().len(), 0, "devices should be empty");
/// assert_eq!(params.no_alloc(), false, "no_alloc should be false");
/// ```
impl Default for LlamaModelParams {
fn default() -> Self {
let default_params = unsafe { llama_cpp_sys_2::llama_model_default_params() };
LlamaModelParams {
params: default_params,
// push the next one to ensure we maintain the iterator invariant of ending with a 0
kv_overrides: vec![llama_cpp_sys_2::llama_model_kv_override {
key: [0; 128],
tag: 0,
__bindgen_anon_1: llama_cpp_sys_2::llama_model_kv_override__bindgen_ty_1 {
val_i64: 0,
},
}],
buft_overrides: vec![llama_cpp_sys_2::llama_model_tensor_buft_override {
pattern: std::ptr::null(),
buft: std::ptr::null_mut(),
}],
devices: Box::pin([std::ptr::null_mut(); 16]),
}
}
}