oxide-rs 0.1.1

AI Inference library and CLI in Rust - llama.cpp style
Documentation
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
//! Oxide-rs
//!
//! Fast AI Inference Library & CLI in Rust - A lightweight, CPU-based LLM inference engine inspired by llama.cpp.
//!
//! # Features
//!
//! - GGUF model support (LLaMA, LFM2 architectures)
//! - Full tokenizer compatibility (SPM, BPE, WPM, UGM, RWKV)
//! - Automatic chat templates from GGUF files
//! - Streaming token generation
//! - Multiple sampling strategies (temperature, top-k, top-p)
//! - Interactive REPL and one-shot modes
//! - Memory-mapped loading for instant startup
//!
//! # Quick Start
//!
//! ## CLI Usage
//!
//! ```bash
//! # Install via cargo
//! cargo install oxide-rs
//!
//! # Run interactively
//! oxide-rs -m model.gguf
//!
//! # One-shot generation
//! oxide-rs -m model.gguf --once --prompt "Hello!"
//! ```
//!
//! ## Library Usage
//!
//! ```rust,ignore
//! use oxide_rs::{generate, GenerateOptions};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let result = generate(
//!         "model.gguf",
//!         GenerateOptions::default(),
//!         "Hello, how are you?",
//!     )?;
//!     println!("{}", result);
//!     Ok(())
//! }
//! ```
//!
//! ## Builder API
//!
//! For more control, use the `Model` builder:
//!
//! ```rust,ignore
//! use oxide_rs::Model;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let mut model = Model::new("model.gguf")
//!         .with_options(oxide_rs::GenerateOptions {
//!             max_tokens: 256,
//!             temperature: 0.7,
//!             ..Default::default()
//!         })
//!         .load()?;
//!
//!     let response = model.generate("What is Rust?")?;
//!     println!("{}", response);
//!     Ok(())
//! }
//! ```
//!
//! # Requirements
//!
//! - Rust 1.70+ (2021 edition)
//! - A GGUF quantized model file with embedded chat template
//!
//! # Links
//!
//! - [GitHub Repository](https://github.com/theawakener0/oxide-rs)
//! - [crates.io](https://crates.io/crates/oxide-rs)
//! - [Documentation](https://docs.rs/oxide-rs)

pub mod cli;
pub mod inference;
pub mod model;

use std::path::Path;
use std::path::PathBuf;

pub use inference::{Generator, StreamEvent};
pub use model::{GgufMetadata, Model as ModelWrapper, TokenizerWrapper};

/// Configuration options for text generation.
///
/// # Example
///
/// ```rust,ignore,ignore
/// use oxide_rs::GenerateOptions;
///
/// let options = GenerateOptions {
///     max_tokens: 512,
///     temperature: 0.3,
///     top_p: None,
///     top_k: None,
///     repeat_penalty: 1.1,
///     repeat_last_n: 64,
///     seed: 299792458,
///     system_prompt: None,
/// };
/// ```
#[derive(Clone, Debug)]
pub struct GenerateOptions {
    /// Maximum number of tokens to generate.
    ///
    /// Default: `512`
    pub max_tokens: usize,

    /// Sampling temperature. Higher values produce more diverse output,
    /// lower values produce more focused output.
    ///
    /// Set to `0.0` for greedy/argmax sampling.
    ///
    /// Default: `0.3`
    pub temperature: f64,

    /// Nucleus sampling (top-p) threshold. Limits sampling to the smallest
    /// set of tokens whose cumulative probability exceeds this threshold.
    ///
    /// Default: `None`
    pub top_p: Option<f64>,

    /// Top-k sampling. Limits sampling to the k most likely tokens.
    ///
    /// Default: `None`
    pub top_k: Option<usize>,

    /// Penalty applied to repeated tokens. Values > 1.0 reduce repetition.
    ///
    /// Default: `1.1`
    pub repeat_penalty: f32,

    /// Number of previous tokens to consider for repeat penalty.
    ///
    /// Default: `64`
    pub repeat_last_n: usize,

    /// Random seed for reproducibility. Same seed + same input = same output.
    ///
    /// Default: `299792458`
    pub seed: u64,

    /// System prompt to prepend to the conversation.
    ///
    /// Default: `None`
    pub system_prompt: Option<String>,
}

impl Default for GenerateOptions {
    fn default() -> Self {
        Self {
            max_tokens: 512,
            temperature: 0.3,
            top_p: None,
            top_k: None,
            repeat_penalty: 1.1,
            repeat_last_n: 64,
            seed: 299792458,
            system_prompt: None,
        }
    }
}

/// High-level model wrapper with builder pattern for text generation.
///
/// Use this when you need to:
/// - Generate multiple times with the same model
/// - Use streaming callbacks
/// - Maintain conversation history
/// - Access model metadata
///
/// # Example
///
/// ```rust,ignore,ignore
/// use oxide_rs::Model;
///
/// let mut model = Model::new("model.gguf")?
///     .with_options(oxide_rs::GenerateOptions {
///         max_tokens: 256,
///         temperature: 0.7,
///         ..Default::default()
///     })
///     .load()?;
///
/// let response = model.generate("Hello!")?;
/// println!("{}", response);
/// ```
pub struct Model {
    generator: Option<Generator>,
    model_path: PathBuf,
    tokenizer_path: Option<PathBuf>,
    options: GenerateOptions,
}

impl Model {
    /// Create a new Model instance.
    ///
    /// This only creates the Model struct - use `load()` to actually load the model.
    ///
    /// # Arguments
    ///
    /// * `model_path` - Path to a GGUF model file
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let model = Model::new("model.gguf")?;
    /// ```
    pub fn new<P: AsRef<Path>>(model_path: P) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            generator: None,
            model_path: model_path.as_ref().to_path_buf(),
            tokenizer_path: None,
            options: GenerateOptions::default(),
        })
    }

    /// Set generation options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let model = Model::new("model.gguf")
    ///     .with_options(GenerateOptions {
    ///         max_tokens: 256,
    ///         temperature: 0.8,
    ///         ..Default::default()
    ///     });
    /// ```
    pub fn with_options(mut self, options: GenerateOptions) -> Self {
        self.options = options;
        self
    }

    /// Set a custom tokenizer path.
    ///
    /// If not provided, the tokenizer will be extracted from the GGUF file.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let model = Model::new("model.gguf")
    ///     .with_tokenizer("tokenizer.json");
    /// ```
    pub fn with_tokenizer<P: AsRef<Path>>(mut self, tokenizer_path: P) -> Self {
        self.tokenizer_path = Some(tokenizer_path.as_ref().to_path_buf());
        self
    }

    /// Load the model into memory.
    ///
    /// This must be called before `generate()`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut model = Model::new("model.gguf")?.load()?;
    /// ```
    pub fn load(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let generator = Generator::new(
            &self.model_path,
            self.tokenizer_path.as_ref(),
            self.options.temperature,
            self.options.top_p,
            self.options.top_k,
            self.options.seed,
            self.options.system_prompt.clone(),
        )?;
        self.generator = Some(generator);
        Ok(())
    }

    /// Generate text from a prompt.
    ///
    /// Requires `load()` to be called first.
    ///
    /// # Arguments
    ///
    /// * `prompt` - The input prompt
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let response = model.generate("What is Rust?")?;
    /// println!("{}", response);
    /// ```
    pub fn generate(&mut self, prompt: &str) -> Result<String, Box<dyn std::error::Error>> {
        let generator = self
            .generator
            .as_mut()
            .ok_or("Model not loaded. Call load() first.")?;

        let result = generator.generate(
            prompt,
            self.options.max_tokens,
            self.options.repeat_penalty,
            self.options.repeat_last_n,
            |_event| {},
        )?;

        Ok(result)
    }

    /// Generate text with streaming callback.
    ///
    /// Tokens are passed to the callback as they're generated, enabling
    /// real-time output display.
    ///
    /// Requires `load()` to be called first.
    ///
    /// # Arguments
    ///
    /// * `prompt` - The input prompt
    /// * `callback` - Function called for each generated token
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// model.generate_stream("Tell me a story", |token| {
    ///     print!("{}", token);
    /// })?;
    /// ```
    pub fn generate_stream<F>(
        &mut self,
        prompt: &str,
        mut callback: F,
    ) -> Result<String, Box<dyn std::error::Error>>
    where
        F: FnMut(String),
    {
        let generator = self
            .generator
            .as_mut()
            .ok_or("Model not loaded. Call load() first.")?;

        let mut output = String::new();
        generator.generate(
            prompt,
            self.options.max_tokens,
            self.options.repeat_penalty,
            self.options.repeat_last_n,
            |event| match event {
                StreamEvent::Token(t) => {
                    output.push_str(&t);
                    callback(t);
                }
                StreamEvent::Done => {}
            },
        )?;

        Ok(output)
    }

    /// Pre-compile compute kernels for faster first-token generation.
    ///
    /// Call this after `load()` to warm up the model before first use.
    ///
    /// # Arguments
    ///
    /// * `num_tokens` - Number of tokens to use for warmup (default: 128)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// model.load()?;
    /// model.warmup(128)?;
    /// // First generation will be faster
    /// ```
    pub fn warmup(&mut self, num_tokens: usize) -> Result<(), Box<dyn std::error::Error>> {
        let generator = self
            .generator
            .as_mut()
            .ok_or("Model not loaded. Call load() first.")?;
        generator.warmup(num_tokens)?;
        Ok(())
    }

    /// Clear conversation history.
    ///
    /// Removes all previous messages from the conversation context.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// model.generate("Hello")?;
    /// model.clear_history();
    /// ```
    pub fn clear_history(&mut self) {
        if let Some(ref mut generator) = self.generator {
            generator.clear_history();
        }
    }

    /// Get model metadata.
    ///
    /// Returns information about the loaded model including name,
    /// architecture, layer count, embedding size, etc.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if let Some(meta) = model.metadata() {
    ///     println!("Model: {}", meta.name);
    ///     println!("Architecture: {}", meta.architecture);
    /// }
    /// ```
    pub fn metadata(&self) -> Option<&GgufMetadata> {
        self.generator.as_ref().map(|g| g.metadata())
    }
}

/// Simple one-shot text generation function.
///
/// This is the easiest way to generate text - just provide the model path,
/// options, and prompt. The model is loaded and used in a single call.
///
/// For multiple generations, use [`Model`] instead to avoid reloading.
///
/// # Arguments
///
/// * `model_path` - Path to GGUF model file
/// * `options` - Generation configuration
/// * `prompt` - Input prompt
///
/// # Returns
///
/// Generated text string
///
/// # Example
///
/// ```rust,ignore,ignore
/// use oxide_rs::{generate, GenerateOptions};
///
/// let result = generate(
///     "model.gguf",
///     GenerateOptions::default(),
///     "Hello, how are you?",
/// )?;
/// println!("{}", result);
/// ```
pub fn generate<P: AsRef<Path>>(
    model_path: P,
    options: GenerateOptions,
    prompt: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut model = Model::new(model_path)?.with_options(options);
    model.load()?;
    model.generate(prompt)
}