Skip to main content

troupekit_local/
model.rs

1use crate::error::LocalError;
2use std::sync::atomic::AtomicBool;
3use std::sync::Arc;
4
5const MAX_TOKENS_DEFAULT: usize = 512;
6const TEMPERATURE_DEFAULT: f32 = 0.7;
7const TOP_P_DEFAULT: f32 = 0.95;
8const SEED_DEFAULT: u32 = 0x5452_4B54;
9const ROOT_MAX_BYTES: usize = 64;
10
11/// One in-process model: tokenizer, chat template, generation, scoring
12/// and embeddings. Calls block; `LocalChat` runs them off the async
13/// runtime. llama.cpp implements it behind `llama`; 0.4 adds the
14/// platform models. Object safe, so `Arc<dyn LocalModel>` works.
15pub trait LocalModel: Send + Sync {
16    /// Returns the fixed facts about the loaded model.
17    /// Input: none. Output: context length, vocabulary size,
18    /// embedding size (0 when it cannot embed) and template presence.
19    fn info(&self) -> &LocalInfo;
20
21    /// Turns text into token ids, adding the model's start token when
22    /// its vocabulary asks for one. `special` lets control tokens in the
23    /// text (such as `<|im_start|>`) parse as themselves.
24    /// Output: the ids, or `Tokenize` on a refused input.
25    fn tokenize(&self, text: &str, special: bool) -> Result<Vec<u32>, LocalError>;
26
27    /// Turns token ids back into text.
28    /// Input: ids from this model's vocabulary.
29    /// Output: the text, or `Tokenize` for an id outside the vocabulary.
30    fn detokenize(&self, tokens: &[u32]) -> Result<String, LocalError>;
31
32    /// Renders messages with the model's embedded chat template.
33    /// `add_assistant` ends the text with the assistant turn opener.
34    /// Output: the prompt text, or `Unsupported("chat template")`.
35    fn render_chat(&self, msgs: &[ChatMessage], add_assistant: bool) -> Result<String, LocalError>;
36
37    /// Generates from a token prompt, calling `on_token` with each piece
38    /// of text; `Flow::Stop` ends the run. Stops at end of text, the
39    /// token limit, a stop string or the cancel flag in `params`.
40    /// Output: the `Generation`, or `ContextFull`: either the prompt is
41    /// refused before decoding, or the context fills mid-run, after
42    /// `on_token` has already seen part of the reply.
43    fn generate(
44        &self,
45        prompt: &[u32],
46        params: &GenParams,
47        on_token: &mut dyn FnMut(&str) -> Flow,
48    ) -> Result<Generation, LocalError>;
49
50    /// Scores a token sequence as the sum of each token's log-probability
51    /// given the tokens before it.
52    /// Output: the sum (at most 0), or an error from decoding.
53    fn score(&self, tokens: &[u32]) -> Result<f64, LocalError>;
54
55    /// Embeds each text into one L2-normalized vector of
56    /// `info().embedding_dims()` floats, pooled as the model was trained.
57    /// Output: one vector per text, or `Unsupported("embeddings")`.
58    fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, LocalError>;
59
60    /// Drops any cached prompt state, so the next call reuses no prefix.
61    /// Never blocks: called while a call runs (also from its `on_token`
62    /// callback), it takes effect before the next call. Input: none.
63    fn reset(&self);
64
65    /// Counts the tokens of `text` with `tokenize`, control tokens not
66    /// parsed. Input: any text.
67    /// Output: the count, or the `tokenize` error.
68    fn count_tokens(&self, text: &str) -> Result<usize, LocalError> {
69        Ok(self.tokenize(text, false)?.len())
70    }
71}
72
73/// Fixed facts about a loaded model: context length in tokens,
74/// vocabulary size, embedding size (0 when the model cannot embed) and
75/// whether it carries a chat template. Read through the getters.
76#[non_exhaustive]
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct LocalInfo {
79    context_length: usize,
80    vocab_size: usize,
81    embedding_dims: usize,
82    chat_template: bool,
83}
84
85impl LocalInfo {
86    /// Builds the facts for a `LocalModel` implementation.
87    /// Inputs: context length, vocabulary size, embedding size (0 for
88    /// none), template presence. Panics when context or vocabulary is 0.
89    pub fn new(
90        context_length: usize,
91        vocab_size: usize,
92        embedding_dims: usize,
93        chat_template: bool,
94    ) -> Self {
95        assert!(
96            context_length > 0,
97            "a model has a context of at least one token"
98        );
99        assert!(
100            vocab_size > 0,
101            "a model has at least one token in its vocabulary"
102        );
103        Self {
104            context_length,
105            vocab_size,
106            embedding_dims,
107            chat_template,
108        }
109    }
110
111    /// Returns the context length in tokens.
112    /// Prompt plus generated tokens never exceed it.
113    /// Always above 0.
114    pub fn context_length(&self) -> usize {
115        self.context_length
116    }
117
118    /// Returns the number of tokens in the vocabulary.
119    /// Every id the model returns is below it.
120    /// Always above 0.
121    pub fn vocab_size(&self) -> usize {
122        self.vocab_size
123    }
124
125    /// Returns the length of each embedding vector.
126    /// 0 means `embed` returns `Unsupported`.
127    /// `LocalEmbedder` refuses a model with 0.
128    pub fn embedding_dims(&self) -> usize {
129        self.embedding_dims
130    }
131
132    /// Returns whether the model carries a chat template.
133    /// Without one `render_chat` returns `Unsupported`.
134    /// `LocalChat` needs it.
135    pub fn chat_template(&self) -> bool {
136        self.chat_template
137    }
138}
139
140/// The speaker of one chat message. `as_str` gives the role name that
141/// chat templates expect: `system`, `user`, `assistant`, `tool`.
142/// Default `User`.
143#[non_exhaustive]
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145pub enum ChatRole {
146    System,
147    #[default]
148    User,
149    Assistant,
150    Tool,
151}
152
153impl ChatRole {
154    /// Returns the role name passed to the chat template.
155    /// Input: none. Output: a lowercase static name.
156    /// The names match the common template conventions.
157    pub fn as_str(&self) -> &'static str {
158        match self {
159            ChatRole::System => "system",
160            ChatRole::User => "user",
161            ChatRole::Assistant => "assistant",
162            ChatRole::Tool => "tool",
163        }
164    }
165}
166
167/// One message given to `render_chat`: a role and its text.
168/// Built with `new`; read through `role` and `content`.
169/// The text is passed to the template unchanged.
170#[non_exhaustive]
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct ChatMessage {
173    role: ChatRole,
174    content: String,
175}
176
177impl ChatMessage {
178    /// Builds a message.
179    /// Inputs: the speaker and the text.
180    /// Output: the message.
181    pub fn new(role: ChatRole, content: impl Into<String>) -> Self {
182        Self {
183            role,
184            content: content.into(),
185        }
186    }
187
188    /// Returns the speaker.
189    /// Input: none.
190    /// Output: the role.
191    pub fn role(&self) -> ChatRole {
192        self.role
193    }
194
195    /// Returns the text.
196    /// Input: none.
197    /// Output: the text as given to `new`.
198    pub fn content(&self) -> &str {
199        &self.content
200    }
201}
202
203/// A GBNF grammar that constrains generation, with the name of its start
204/// rule. Built by `Grammar::new`, which refuses empty text, text over
205/// `MAX_BYTES`, an interior NUL, and a root that is not a rule name.
206#[non_exhaustive]
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct Grammar {
209    gbnf: String,
210    root: String,
211}
212
213impl Grammar {
214    /// The longest grammar text accepted, in bytes.
215    /// Setting S27 of the 0.3 plan: 256 KiB.
216    /// `new` refuses longer text.
217    pub const MAX_BYTES: usize = 256 * 1024;
218
219    /// Checks and builds a grammar.
220    /// Inputs: GBNF text and the start rule name (letters, digits, `-`,
221    /// `_`, at most 64 bytes). Output: the grammar, or `LocalError::Grammar`.
222    pub fn new(gbnf: &str, root: &str) -> Result<Self, LocalError> {
223        if gbnf.trim().is_empty() {
224            return Err(LocalError::Grammar("grammar text is empty".into()));
225        }
226        if gbnf.len() > Self::MAX_BYTES {
227            return Err(LocalError::Grammar(format!(
228                "grammar is {} bytes, limit {}",
229                gbnf.len(),
230                Self::MAX_BYTES
231            )));
232        }
233        if gbnf.contains('\0') {
234            return Err(LocalError::Grammar("grammar text holds a NUL byte".into()));
235        }
236        let root_ok = !root.is_empty()
237            && root.len() <= ROOT_MAX_BYTES
238            && root
239                .bytes()
240                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
241        if !root_ok {
242            return Err(LocalError::Grammar(format!(
243                "root rule name {root:?} is not a rule name"
244            )));
245        }
246        Ok(Self {
247            gbnf: gbnf.to_string(),
248            root: root.to_string(),
249        })
250    }
251
252    /// Returns the GBNF text.
253    /// Never empty, never over `MAX_BYTES`, no NUL.
254    /// Passed to the model unchanged.
255    pub fn gbnf(&self) -> &str {
256        &self.gbnf
257    }
258
259    /// Returns the start rule name.
260    /// ASCII letters, digits, `-` and `_` only.
261    /// At most 64 bytes.
262    pub fn root(&self) -> &str {
263        &self.root
264    }
265}
266
267/// Settings for one `generate` call. Defaults: 512 tokens, temperature
268/// 0.7, top-p 0.95, seed `0x5452_4B54`, no stop strings, no grammar, no
269/// confidence, end of text allowed, no cancel flag. `with_*` setters.
270#[non_exhaustive]
271#[derive(Debug, Clone)]
272pub struct GenParams {
273    max_tokens: usize,
274    temperature: f32,
275    top_p: f32,
276    seed: u32,
277    stop: Vec<String>,
278    grammar: Option<Grammar>,
279    confidence: bool,
280    ban_eos: bool,
281    cancel: Option<Arc<AtomicBool>>,
282}
283
284impl Default for GenParams {
285    fn default() -> Self {
286        Self {
287            max_tokens: MAX_TOKENS_DEFAULT,
288            temperature: TEMPERATURE_DEFAULT,
289            top_p: TOP_P_DEFAULT,
290            seed: SEED_DEFAULT,
291            stop: Vec::new(),
292            grammar: None,
293            confidence: false,
294            ban_eos: false,
295            cancel: None,
296        }
297    }
298}
299
300impl GenParams {
301    /// Sets the most tokens generated in this call.
302    /// The model also stops at its context limit.
303    /// Default 512.
304    pub fn with_max_tokens(mut self, max_tokens: usize) -> Self {
305        self.max_tokens = max_tokens;
306        self
307    }
308
309    /// Sets the sampling temperature; 0 picks the most likely token.
310    /// A negative or non-finite value is refused by the model.
311    /// Default 0.7.
312    pub fn with_temperature(mut self, temperature: f32) -> Self {
313        self.temperature = temperature;
314        self
315    }
316
317    /// Sets the nucleus sampling share, from 0 (exclusive) to 1.
318    /// 1 keeps every token.
319    /// Default 0.95.
320    pub fn with_top_p(mut self, top_p: f32) -> Self {
321        self.top_p = top_p;
322        self
323    }
324
325    /// Sets the sampler seed.
326    /// The same seed, prompt and model give the same text.
327    /// Default `0x5452_4B54`.
328    pub fn with_seed(mut self, seed: u32) -> Self {
329        self.seed = seed;
330        self
331    }
332
333    /// Sets strings that end generation when they appear.
334    /// The stop string is not part of the returned text.
335    /// Default none.
336    pub fn with_stop(mut self, stop: Vec<String>) -> Self {
337        self.stop = stop;
338        self
339    }
340
341    /// Sets the grammar every generated token must follow.
342    /// Tool calls and structured output use it.
343    /// Default none.
344    pub fn with_grammar(mut self, grammar: Option<Grammar>) -> Self {
345        self.grammar = grammar;
346        self
347    }
348
349    /// Asks for `Generation::mean_logprob`.
350    /// Costs one softmax over the vocabulary per token.
351    /// Default false.
352    pub fn with_confidence(mut self, confidence: bool) -> Self {
353        self.confidence = confidence;
354        self
355    }
356
357    /// Bans end-of-text tokens, so the run reaches `max_tokens`.
358    /// For fixed-length runs: the bench and the kill test.
359    /// Default false.
360    pub fn with_ban_eos(mut self, ban_eos: bool) -> Self {
361        self.ban_eos = ban_eos;
362        self
363    }
364
365    /// Sets a flag that stops generation within one token once true.
366    /// `LocalChat` sets it when its future is dropped.
367    /// Default none.
368    pub fn with_cancel(mut self, cancel: Option<Arc<AtomicBool>>) -> Self {
369        self.cancel = cancel;
370        self
371    }
372
373    /// Returns the token limit of the call.
374    /// Input: none.
375    /// Default 512.
376    pub fn max_tokens(&self) -> usize {
377        self.max_tokens
378    }
379
380    /// Returns the sampling temperature.
381    /// Input: none.
382    /// Default 0.7.
383    pub fn temperature(&self) -> f32 {
384        self.temperature
385    }
386
387    /// Returns the nucleus sampling share.
388    /// Input: none.
389    /// Default 0.95.
390    pub fn top_p(&self) -> f32 {
391        self.top_p
392    }
393
394    /// Returns the sampler seed.
395    /// Input: none.
396    /// Default `0x5452_4B54`.
397    pub fn seed(&self) -> u32 {
398        self.seed
399    }
400
401    /// Returns the stop strings.
402    /// Input: none.
403    /// Default empty.
404    pub fn stop(&self) -> &[String] {
405        &self.stop
406    }
407
408    /// Returns the grammar, if any.
409    /// Input: none.
410    /// Default none.
411    pub fn grammar(&self) -> Option<&Grammar> {
412        self.grammar.as_ref()
413    }
414
415    /// Returns whether `mean_logprob` is computed.
416    /// Input: none.
417    /// Default false.
418    pub fn confidence(&self) -> bool {
419        self.confidence
420    }
421
422    /// Returns whether end-of-text tokens are banned.
423    /// Input: none.
424    /// Default false.
425    pub fn ban_eos(&self) -> bool {
426        self.ban_eos
427    }
428
429    /// Returns the cancel flag, if any.
430    /// Input: none.
431    /// Default none.
432    pub fn cancel(&self) -> Option<&Arc<AtomicBool>> {
433        self.cancel.as_ref()
434    }
435}
436
437/// Why a generation ended: the model's end of text, the token limit, a
438/// stop string or `Flow::Stop`, or the cancel flag. A full context is an
439/// error (`LocalError::ContextFull`), not a stop.
440#[non_exhaustive]
441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442pub enum GenStop {
443    EndOfText,
444    MaxTokens,
445    Stop,
446    Cancelled,
447}
448
449/// Speed and memory of one call: prefill and decode tokens per second,
450/// time to first token, peak resident memory when the platform reports
451/// it, and prompt tokens reused from the cache. All zero by default.
452#[non_exhaustive]
453#[derive(Debug, Clone, PartialEq, Default)]
454pub struct LocalMetrics {
455    prefill_tokens_per_second: f64,
456    decode_tokens_per_second: f64,
457    time_to_first_token_ms: f64,
458    peak_ram_bytes: Option<u64>,
459    reused_prefix_tokens: usize,
460}
461
462impl LocalMetrics {
463    /// Sets the prompt processing speed in tokens per second.
464    /// Input: a finite value at least 0.
465    /// Default 0.
466    pub fn with_prefill_tokens_per_second(mut self, value: f64) -> Self {
467        self.prefill_tokens_per_second = value;
468        self
469    }
470
471    /// Sets the generation speed in tokens per second.
472    /// Input: a finite value at least 0.
473    /// Default 0.
474    pub fn with_decode_tokens_per_second(mut self, value: f64) -> Self {
475        self.decode_tokens_per_second = value;
476        self
477    }
478
479    /// Sets the time from the call to the first token, in milliseconds.
480    /// Input: a finite value at least 0.
481    /// Default 0.
482    pub fn with_time_to_first_token_ms(mut self, value: f64) -> Self {
483        self.time_to_first_token_ms = value;
484        self
485    }
486
487    /// Sets the peak resident memory of the process in bytes.
488    /// None where the platform has no query.
489    /// Default none.
490    pub fn with_peak_ram_bytes(mut self, value: Option<u64>) -> Self {
491        self.peak_ram_bytes = value;
492        self
493    }
494
495    /// Sets how many prompt tokens came from the cache, not decoding.
496    /// Input: at most the prompt length.
497    /// Default 0.
498    pub fn with_reused_prefix_tokens(mut self, value: usize) -> Self {
499        self.reused_prefix_tokens = value;
500        self
501    }
502
503    /// Returns the prompt processing speed in tokens per second.
504    /// Input: none.
505    /// Default 0.
506    pub fn prefill_tokens_per_second(&self) -> f64 {
507        self.prefill_tokens_per_second
508    }
509
510    /// Returns the generation speed in tokens per second.
511    /// Input: none.
512    /// Default 0.
513    pub fn decode_tokens_per_second(&self) -> f64 {
514        self.decode_tokens_per_second
515    }
516
517    /// Returns the time to the first token in milliseconds.
518    /// Input: none.
519    /// Default 0.
520    pub fn time_to_first_token_ms(&self) -> f64 {
521        self.time_to_first_token_ms
522    }
523
524    /// Returns the peak resident memory in bytes, when known.
525    /// Input: none.
526    /// Default none.
527    pub fn peak_ram_bytes(&self) -> Option<u64> {
528        self.peak_ram_bytes
529    }
530
531    /// Returns how many prompt tokens were reused from the cache.
532    /// Input: none.
533    /// Default 0.
534    pub fn reused_prefix_tokens(&self) -> usize {
535        self.reused_prefix_tokens
536    }
537}
538
539/// The result of one `generate` call: text, generated token count, why
540/// it stopped, the mean token log-probability when asked for, and the
541/// call's metrics. Built by `LocalModel` implementations with `new`.
542#[non_exhaustive]
543#[derive(Debug, Clone, PartialEq)]
544pub struct Generation {
545    text: String,
546    tokens: usize,
547    stop: GenStop,
548    mean_logprob: Option<f64>,
549    metrics: LocalMetrics,
550}
551
552impl Generation {
553    /// Builds a result from text, token count, stop reason, mean
554    /// log-prob (`None` unless asked for) and metrics.
555    /// Panics when the mean log-prob is above 0 or NaN.
556    pub fn new(
557        text: String,
558        tokens: usize,
559        stop: GenStop,
560        mean_logprob: Option<f64>,
561        metrics: LocalMetrics,
562    ) -> Self {
563        if let Some(lp) = mean_logprob {
564            assert!(lp <= 0.0, "a mean log-probability is at most 0");
565        }
566        Self {
567            text,
568            tokens,
569            stop,
570            mean_logprob,
571            metrics,
572        }
573    }
574
575    /// Returns the generated text, stop string excluded.
576    /// Input: none.
577    /// Output: the text.
578    pub fn text(&self) -> &str {
579        &self.text
580    }
581
582    /// Returns how many tokens were generated.
583    /// Input: none.
584    /// Output: the count.
585    pub fn tokens(&self) -> usize {
586        self.tokens
587    }
588
589    /// Returns why generation ended.
590    /// Input: none.
591    /// Output: the stop reason.
592    pub fn stop(&self) -> GenStop {
593        self.stop
594    }
595
596    /// Returns the mean token log-probability.
597    /// Only set when `GenParams::confidence` was true.
598    /// Output: at most 0.
599    pub fn mean_logprob(&self) -> Option<f64> {
600        self.mean_logprob
601    }
602
603    /// Returns the call's speed and memory figures.
604    /// Input: none.
605    /// Output: the metrics.
606    pub fn metrics(&self) -> &LocalMetrics {
607        &self.metrics
608    }
609}
610
611/// What a token callback tells `generate`: keep going or stop now.
612/// `Stop` ends the run with `GenStop::Stop`.
613/// Used by streaming and by stop checks in the caller.
614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
615pub enum Flow {
616    Continue,
617    Stop,
618}