Skip to main content

kute_types/
config.rs

1use crate::{KuteError, PayloadKind, Result, Version, VocabularyId};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4
5/// The GPT-4 style split pattern, the same default rustbpe and tiktoken use.
6pub const GPT4_PATTERN: &str = r"'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]++[\r\n]*|\s*[\r\n]|\s+(?!\S)|\s+";
7
8/// How byte input is split into chunks before merges are learned or applied.
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
10#[serde(rename_all = "snake_case")]
11pub enum Pretokenizer {
12    /// No splitting. Right for binary data.
13    #[default]
14    None,
15    /// The GPT-4 split pattern.
16    Gpt4,
17    /// A caller-supplied regular expression.
18    Regex(String),
19}
20
21impl Pretokenizer {
22    pub fn pattern(&self) -> Option<&str> {
23        match self {
24            Pretokenizer::None => None,
25            Pretokenizer::Gpt4 => Some(GPT4_PATTERN),
26            Pretokenizer::Regex(p) => Some(p.as_str()),
27        }
28    }
29}
30
31/// Everything a training run needs. Identical configuration and corpus must
32/// produce an identical vocabulary (FR-003 deterministic mode is the only mode
33/// in v0.1).
34#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
35pub struct TrainingConfig {
36    pub vocabulary_id: VocabularyId,
37    pub vocabulary_version: Version,
38    /// Target total number of tokens, including base and reserved tokens.
39    pub vocab_size: u32,
40    /// A candidate must occur at least this often to become a token.
41    #[serde(default = "one")]
42    pub min_frequency: u64,
43    #[serde(default)]
44    pub pretokenizer: Pretokenizer,
45    /// Special tokens appended after learned tokens. Never produced by encode.
46    #[serde(default)]
47    pub reserved_tokens: Vec<String>,
48    /// Upper bound on a learned token's length in units (bytes or symbols).
49    #[serde(default)]
50    pub max_token_length: Option<usize>,
51    /// Window length used to split unsegmented input while counting.
52    #[serde(default = "default_window")]
53    pub train_window: usize,
54    /// Fixed entries for the dictionary algorithm.
55    #[serde(default)]
56    pub dictionary: Vec<String>,
57    /// Job limit: refuse a corpus larger than this many units.
58    #[serde(default)]
59    pub max_corpus_units: Option<u64>,
60    /// Recorded for provenance. No v0.1 algorithm consumes randomness.
61    #[serde(default)]
62    pub seed: u64,
63    #[serde(default)]
64    pub description: Option<String>,
65    #[serde(default)]
66    pub license: Option<String>,
67    /// Store short samples of the training corpus in the vocabulary as
68    /// self-test vectors. Off unless asked for: the vectors are verbatim
69    /// excerpts of the corpus, and a vocabulary file is what gets published.
70    /// Absent means off, for a configuration someone writes by hand as much
71    /// as for one built in code. Vocabularies trained before v0.4.0 recorded
72    /// nothing here when vectors were on; whether a vocabulary has vectors
73    /// is read from the vocabulary, not from this field.
74    #[serde(default)]
75    pub embed_test_vectors: bool,
76    /// When training from files, read them in pieces of about this many
77    /// bytes, cut at a line break, instead of whole. Each piece is one
78    /// record, so memory no longer grows with file size. The value is part
79    /// of the configuration because it decides where records end.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub stream_bytes: Option<usize>,
82    /// Continue an earlier run instead of starting over. The vocabulary
83    /// given here must have been trained on the same corpus with the same
84    /// settings and a smaller `vocab_size`; its merges are kept and learning
85    /// goes on from where it stopped. The result is the vocabulary a single
86    /// run to the new size would have produced. Not part of the recorded
87    /// configuration: it changes how the result is reached, not the result.
88    /// Its merges are taken as given, so resume only from a vocabulary you
89    /// trained or trust.
90    #[serde(skip)]
91    pub resume_from: Option<Box<crate::Vocabulary>>,
92}
93
94fn one() -> u64 {
95    1
96}
97
98fn default_window() -> usize {
99    256
100}
101
102impl TrainingConfig {
103    pub fn new(vocabulary_id: VocabularyId, vocab_size: u32) -> Self {
104        Self {
105            vocabulary_id,
106            vocabulary_version: Version::new(0, 1, 0),
107            vocab_size,
108            min_frequency: 1,
109            pretokenizer: Pretokenizer::None,
110            reserved_tokens: Vec::new(),
111            max_token_length: None,
112            train_window: default_window(),
113            dictionary: Vec::new(),
114            max_corpus_units: None,
115            seed: 0,
116            description: None,
117            license: None,
118            embed_test_vectors: false,
119            stream_bytes: None,
120            resume_from: None,
121        }
122    }
123
124    pub fn validate(&self) -> Result<()> {
125        const MAX_VOCAB: u32 = 4_000_000;
126        if self.vocab_size == 0 || self.vocab_size > MAX_VOCAB {
127            return Err(KuteError::InvalidConfig(format!("vocab_size must be between 1 and {MAX_VOCAB}")));
128        }
129        if self.min_frequency == 0 {
130            return Err(KuteError::InvalidConfig("min_frequency must be at least 1".into()));
131        }
132        if self.train_window < 2 || self.train_window > 1 << 20 {
133            return Err(KuteError::InvalidConfig("train_window must be between 2 and 1048576".into()));
134        }
135        if self.stream_bytes.is_some_and(|n| !(4096..=1 << 30).contains(&n)) {
136            return Err(KuteError::InvalidConfig("stream_bytes must be between 4096 and 1073741824".into()));
137        }
138        if self.max_token_length == Some(0) {
139            return Err(KuteError::InvalidConfig("max_token_length must be at least 1".into()));
140        }
141        let mut seen = std::collections::BTreeSet::new();
142        for t in &self.reserved_tokens {
143            if t.is_empty() || t.len() > 256 {
144                return Err(KuteError::InvalidConfig("reserved tokens must be 1 to 256 bytes".into()));
145            }
146            if !seen.insert(t) {
147                return Err(KuteError::InvalidConfig(format!("reserved token {t:?} is listed twice")));
148            }
149        }
150        if let Pretokenizer::Regex(p) = &self.pretokenizer {
151            if p.is_empty() || p.len() > 4096 {
152                return Err(KuteError::InvalidConfig("pretokenizer regex must be 1 to 4096 bytes".into()));
153            }
154        }
155        Ok(())
156    }
157}
158
159/// Free-form adapter options, e.g. `{"field": "event"}`.
160#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
161pub struct AdapterConfig {
162    #[serde(flatten)]
163    pub options: BTreeMap<String, String>,
164}
165
166impl AdapterConfig {
167    pub fn with(mut self, key: &str, value: &str) -> Self {
168        self.options.insert(key.to_string(), value.to_string());
169        self
170    }
171
172    pub fn get(&self, key: &str) -> Option<&str> {
173        self.options.get(key).map(String::as_str)
174    }
175}
176
177/// What a tokenizer declares about itself (FR-002, ADR-0007).
178#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
179pub struct TokenizerCapabilities {
180    pub algorithm: String,
181    /// `decode(encode(x)) == x` for every input the tokenizer accepts.
182    pub lossless: bool,
183    pub trainable: bool,
184    pub deterministic: bool,
185    pub accepts: Vec<PayloadKind>,
186    /// Inputs outside the vocabulary are refused instead of approximated.
187    pub rejects_unknown: bool,
188    pub notes: String,
189}