mullama 0.3.0

Comprehensive Rust bindings for llama.cpp with memory-safe API and advanced features
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
use crate::{context::KvCacheType, Context, ContextParams, Model, MullamaError};
use std::sync::Arc;

/// Builder for creating contexts with fluent API
#[derive(Debug, Clone)]
pub struct ContextBuilder {
    model: Arc<Model>,
    n_ctx: u32,
    n_batch: u32,
    n_ubatch: u32,
    n_seq_max: u32,
    n_threads: i32,
    n_threads_batch: i32,
    embeddings: bool,
    flash_attn_type: crate::sys::llama_flash_attn_type,
    offload_kqv: bool,
    type_k: KvCacheType,
    type_v: KvCacheType,
}

impl ContextBuilder {
    /// Create a new context builder
    ///
    /// # Arguments
    ///
    /// * `model` - The model to create a context for
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use mullama::builder::{ModelBuilder, ContextBuilder};
    ///
    /// # async fn example() -> Result<(), mullama::MullamaError> {
    /// let model = ModelBuilder::new().path("model.gguf").build()?;
    /// let builder = ContextBuilder::new(model);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(model: Arc<Model>) -> Self {
        Self {
            model,
            n_ctx: 2048,
            n_batch: 512,
            n_ubatch: 512,
            n_seq_max: 1,
            n_threads: num_cpus::get() as i32,
            n_threads_batch: num_cpus::get() as i32,
            embeddings: false,
            flash_attn_type: crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_AUTO,
            offload_kqv: false,
            type_k: KvCacheType::default(),
            type_v: KvCacheType::default(),
        }
    }

    /// Set the context size
    ///
    /// # Arguments
    ///
    /// * `size` - Context size in tokens
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .context_size(4096);
    /// ```
    pub fn context_size(mut self, size: u32) -> Self {
        self.n_ctx = size;
        self
    }

    /// Set the batch size
    ///
    /// # Arguments
    ///
    /// * `size` - Batch size for prompt processing
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .batch_size(1024);
    /// ```
    pub fn batch_size(mut self, size: u32) -> Self {
        self.n_batch = size;
        self
    }

    /// Set the physical batch size
    ///
    /// # Arguments
    ///
    /// * `size` - Physical batch size
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .physical_batch_size(256);
    /// ```
    pub fn physical_batch_size(mut self, size: u32) -> Self {
        self.n_ubatch = size;
        self
    }

    /// Set maximum number of sequences
    ///
    /// # Arguments
    ///
    /// * `max_seq` - Maximum number of parallel sequences
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .max_sequences(4);
    /// ```
    pub fn max_sequences(mut self, max_seq: u32) -> Self {
        self.n_seq_max = max_seq;
        self
    }

    /// Set number of threads for generation
    ///
    /// # Arguments
    ///
    /// * `threads` - Number of threads
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .threads(8);
    /// ```
    pub fn threads(mut self, threads: i32) -> Self {
        self.n_threads = threads;
        self
    }

    /// Set number of threads for batch processing
    ///
    /// # Arguments
    ///
    /// * `threads` - Number of threads for batch processing
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .batch_threads(4);
    /// ```
    pub fn batch_threads(mut self, threads: i32) -> Self {
        self.n_threads_batch = threads;
        self
    }

    /// Enable or disable embeddings
    ///
    /// # Arguments
    ///
    /// * `enable` - Whether to enable embeddings
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .embeddings(true);
    /// ```
    pub fn embeddings(mut self, enable: bool) -> Self {
        self.embeddings = enable;
        self
    }

    /// Enable or disable flash attention
    ///
    /// # Arguments
    ///
    /// * `enable` - Whether to enable flash attention
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .flash_attention(true);
    /// ```
    pub fn flash_attention(mut self, enable: bool) -> Self {
        self.flash_attn_type = if enable {
            crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_ENABLED
        } else {
            crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_DISABLED
        };
        self
    }

    /// Enable or disable KQV offloading
    ///
    /// # Arguments
    ///
    /// * `enable` - Whether to offload KQV operations to GPU
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .kqv_offload(true);
    /// ```
    pub fn kqv_offload(mut self, enable: bool) -> Self {
        self.offload_kqv = enable;
        self
    }

    /// Set KV-cache quantization type for both K and V caches
    ///
    /// Lower precision types reduce memory usage but may slightly affect quality:
    /// - F16 (default): Best quality, baseline memory
    /// - Q8_0: ~50% memory savings
    /// - Q4_0: ~75% memory savings
    ///
    /// # Arguments
    ///
    /// * `cache_type` - The quantization type for both K and V caches
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use mullama::context::KvCacheType;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .kv_cache_type(KvCacheType::Q8_0); // 50% memory savings
    /// ```
    pub fn kv_cache_type(mut self, cache_type: KvCacheType) -> Self {
        self.type_k = cache_type;
        self.type_v = cache_type;
        self
    }

    /// Set Key cache quantization type separately
    ///
    /// # Arguments
    ///
    /// * `cache_type` - The quantization type for the K cache
    pub fn key_cache_type(mut self, cache_type: KvCacheType) -> Self {
        self.type_k = cache_type;
        self
    }

    /// Set Value cache quantization type separately
    ///
    /// # Arguments
    ///
    /// * `cache_type` - The quantization type for the V cache
    pub fn value_cache_type(mut self, cache_type: KvCacheType) -> Self {
        self.type_v = cache_type;
        self
    }

    /// Apply performance optimizations
    ///
    /// This enables flash attention, optimizes thread counts,
    /// and sets efficient batch sizes.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .optimize_for_performance();
    /// ```
    pub fn optimize_for_performance(mut self) -> Self {
        self.flash_attn_type = crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_ENABLED;
        self.n_batch = 1024;
        self.n_ubatch = 512;
        self.offload_kqv = true;
        self
    }

    /// Optimize for memory usage
    ///
    /// This reduces batch sizes, uses Q4 quantized KV cache (~75% memory savings),
    /// and disables memory-intensive features.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .optimize_for_memory();
    /// ```
    pub fn optimize_for_memory(mut self) -> Self {
        self.n_ctx = 2048;
        self.n_batch = 256;
        self.n_ubatch = 256;
        self.type_k = KvCacheType::Q4_0;
        self.type_v = KvCacheType::Q4_0;
        self.flash_attn_type = crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_ENABLED;
        self
    }

    /// Balanced optimization (Q8 KV cache)
    ///
    /// Uses Q8 quantized KV cache for ~50% memory savings with minimal quality loss.
    /// Good balance between memory usage and output quality.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .optimize_balanced();
    /// ```
    pub fn optimize_balanced(mut self) -> Self {
        self.type_k = KvCacheType::Q8_0;
        self.type_v = KvCacheType::Q8_0;
        self.flash_attn_type = crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_ENABLED;
        self.offload_kqv = true;
        self
    }

    /// Optimize for quality (F16 KV cache)
    ///
    /// Uses full F16 precision KV cache for best output quality.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::ContextBuilder;
    /// # use std::sync::Arc;
    /// # let model = Arc::new(mullama::Model::load("").unwrap());
    /// let builder = ContextBuilder::new(model)
    ///     .optimize_for_quality();
    /// ```
    pub fn optimize_for_quality(mut self) -> Self {
        self.type_k = KvCacheType::F16;
        self.type_v = KvCacheType::F16;
        self.flash_attn_type = crate::sys::llama_flash_attn_type::LLAMA_FLASH_ATTN_TYPE_AUTO;
        self
    }

    /// Build the context
    ///
    /// # Returns
    ///
    /// A `Context` ready for use
    ///
    /// # Errors
    ///
    /// Returns `MullamaError` if context creation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use mullama::builder::{ModelBuilder, ContextBuilder};
    /// # fn example() -> Result<(), mullama::MullamaError> {
    /// let model = ModelBuilder::new().path("model.gguf").build()?;
    /// let context = ContextBuilder::new(model)
    ///     .context_size(2048)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self) -> Result<Context, MullamaError> {
        let params = ContextParams {
            n_ctx: self.n_ctx,
            n_batch: self.n_batch,
            n_ubatch: self.n_ubatch,
            n_seq_max: self.n_seq_max,
            n_threads: self.n_threads,
            n_threads_batch: self.n_threads_batch,
            embeddings: self.embeddings,
            flash_attn_type: self.flash_attn_type,
            offload_kqv: self.offload_kqv,
            type_k: self.type_k,
            type_v: self.type_v,
            ..Default::default()
        };

        Context::new(self.model, params)
    }

    /// Build the context asynchronously
    ///
    /// # Returns
    ///
    /// An `AsyncContext` ready for use
    ///
    /// # Errors
    ///
    /// Returns `MullamaError` if context creation fails
    #[cfg(feature = "async")]
    pub async fn build_async(self) -> Result<crate::async_support::AsyncContext, MullamaError> {
        use tokio::task;

        let params = ContextParams {
            n_ctx: self.n_ctx,
            n_batch: self.n_batch,
            n_ubatch: self.n_ubatch,
            n_seq_max: self.n_seq_max,
            n_threads: self.n_threads,
            n_threads_batch: self.n_threads_batch,
            embeddings: self.embeddings,
            flash_attn_type: self.flash_attn_type,
            offload_kqv: self.offload_kqv,
            type_k: self.type_k,
            type_v: self.type_v,
            ..Default::default()
        };

        let model = self.model.clone();
        let context = task::spawn_blocking(move || Context::new(model.clone(), params))
            .await
            .map_err(|e| MullamaError::ContextError(format!("Async task failed: {}", e)))?;

        match context {
            Ok(ctx) => Ok(crate::async_support::AsyncContext::new(ctx, self.model)),
            Err(e) => Err(e),
        }
    }
}