Skip to main content

kute_types/
vocab.rs

1//! The in-memory vocabulary model. KVF (see `specifications/kvf`) is the
2//! serialization of this structure; `kute-vocab` does the file handling.
3
4use crate::{sha256_tagged, KuteError, Modality, PayloadKind, Result, Version, VocabularyId};
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7
8/// The KVF format version this build reads and writes.
9pub const KVF_VERSION: &str = "0.1";
10
11pub const MAX_TOKENS: usize = 4_000_000;
12pub const MAX_TOKEN_BYTES: usize = 64 * 1024;
13pub const MAX_TOKEN_SYMBOLS: usize = 4096;
14pub const MAX_SYMBOL_BYTES: usize = 1024;
15pub const MAX_TEST_VECTORS: usize = 1024;
16
17#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
18pub struct Manifest {
19    pub kvf_version: String,
20    pub id: VocabularyId,
21    pub version: Version,
22    /// Name of the algorithm that interprets this vocabulary, e.g. `bpe`.
23    pub algorithm: String,
24    pub modality: Modality,
25    pub payload_kind: PayloadKind,
26    /// True when every input the tokenizer accepts decodes back exactly.
27    pub lossless: bool,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub description: Option<String>,
30    /// Optional creation time. Left out by default so training is reproducible
31    /// byte for byte.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub created: Option<String>,
34    /// Software that wrote the file, e.g. `kute 0.1.0`.
35    pub generator: String,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum TokenKind {
41    /// One of the 256 byte values.
42    Byte,
43    /// A single Unicode character.
44    Char,
45    /// A single named symbol from a symbol alphabet.
46    Symbol,
47    /// A fixed dictionary entry.
48    Entry,
49    /// A learned token: the concatenation of two earlier tokens.
50    Merge,
51    /// A reserved token. Never produced by encoding content.
52    Special,
53}
54
55#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum TokenPayload {
58    /// Raw bytes, base64 in JSON.
59    Bytes(#[serde(with = "crate::b64")] Vec<u8>),
60    /// An ordered sequence of symbol names.
61    Symbols(Vec<String>),
62}
63
64impl TokenPayload {
65    pub fn kind(&self) -> PayloadKind {
66        match self {
67            TokenPayload::Bytes(_) => PayloadKind::Bytes,
68            TokenPayload::Symbols(_) => PayloadKind::Symbols,
69        }
70    }
71
72    pub fn len(&self) -> usize {
73        match self {
74            TokenPayload::Bytes(b) => b.len(),
75            TokenPayload::Symbols(s) => s.len(),
76        }
77    }
78
79    pub fn is_empty(&self) -> bool {
80        self.len() == 0
81    }
82
83    fn concat(&self, other: &TokenPayload) -> Option<TokenPayload> {
84        match (self, other) {
85            (TokenPayload::Bytes(a), TokenPayload::Bytes(b)) => {
86                let mut v = Vec::with_capacity(a.len() + b.len());
87                v.extend_from_slice(a);
88                v.extend_from_slice(b);
89                Some(TokenPayload::Bytes(v))
90            }
91            (TokenPayload::Symbols(a), TokenPayload::Symbols(b)) => {
92                let mut v = Vec::with_capacity(a.len() + b.len());
93                v.extend(a.iter().cloned());
94                v.extend(b.iter().cloned());
95                Some(TokenPayload::Symbols(v))
96            }
97            _ => None,
98        }
99    }
100
101    /// Stable content hash of the payload, independent of any token id.
102    pub fn content_hash(&self) -> String {
103        match self {
104            TokenPayload::Bytes(b) => {
105                let mut buf = Vec::with_capacity(b.len() + 1);
106                buf.push(b'b');
107                buf.extend_from_slice(b);
108                sha256_tagged(&buf)
109            }
110            TokenPayload::Symbols(s) => {
111                let mut buf = vec![b's'];
112                for sym in s {
113                    buf.extend_from_slice(&(sym.len() as u64).to_le_bytes());
114                    buf.extend_from_slice(sym.as_bytes());
115                }
116                sha256_tagged(&buf)
117            }
118        }
119    }
120}
121
122#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
123pub struct TokenEntry {
124    pub id: u32,
125    pub kind: TokenKind,
126    #[serde(flatten)]
127    pub payload: TokenPayload,
128    /// Occurrences observed during training, when known.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub frequency: Option<u64>,
131}
132
133/// A learned transformation: tokens `left` and `right`, adjacent, become `id`.
134#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
135pub struct MergeRule {
136    pub left: u32,
137    pub right: u32,
138    pub id: u32,
139}
140
141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142pub struct AdapterSpec {
143    pub name: String,
144    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
145    pub options: BTreeMap<String, String>,
146    /// Whether the adapter reconstructs the original bytes exactly.
147    pub lossless: bool,
148}
149
150#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
151pub struct Provenance {
152    /// `sha256:` fingerprints of the training corpus as the tokenizer saw it.
153    #[serde(default)]
154    pub corpus_fingerprints: Vec<String>,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub license: Option<String>,
157    /// The training configuration, kept so a run can be repeated.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub training: Option<serde_json::Value>,
160}
161
162/// A known input and the ids it must encode to. Shipped inside the vocabulary
163/// so any implementation can check itself against the file.
164#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
165pub struct TestVector {
166    #[serde(flatten)]
167    pub input: TokenPayload,
168    pub ids: Vec<u32>,
169}
170
171/// Pointer to an independently versioned mapping from token ids to another
172/// representation (FR-015). KVF only references mappings; it never embeds them.
173#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
174pub struct RepresentationRef {
175    pub mapping_id: String,
176    pub mapping_version: String,
177    pub kind: String,
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub uri: Option<String>,
180}
181
182#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
183pub struct Signature {
184    pub key_id: String,
185    pub algorithm: String,
186    pub signature: String,
187}
188
189#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
190pub struct Integrity {
191    pub algorithm: String,
192    pub digest: String,
193    /// Signatures over the digest. They are outside what the digest
194    /// covers, so adding one does not change it. The engine reads and
195    /// keeps them and checks none: `kute verify` does, against keys the
196    /// caller names.
197    #[serde(default, skip_serializing_if = "Vec::is_empty")]
198    pub signatures: Vec<Signature>,
199}
200
201#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
202pub struct Vocabulary {
203    pub manifest: Manifest,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub pretokenizer: Option<String>,
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub adapter: Option<AdapterSpec>,
208    pub tokens: Vec<TokenEntry>,
209    #[serde(default)]
210    pub merges: Vec<MergeRule>,
211    #[serde(default)]
212    pub statistics: BTreeMap<String, u64>,
213    #[serde(default)]
214    pub provenance: Provenance,
215    #[serde(default)]
216    pub test_vectors: Vec<TestVector>,
217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
218    pub representations: Vec<RepresentationRef>,
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub integrity: Option<Integrity>,
221}
222
223/// The token envelope from FR-005: one token with everything needed to
224/// interpret it outside its vocabulary file.
225#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
226pub struct TokenRecord {
227    pub token_id: u32,
228    pub vocabulary_id: VocabularyId,
229    pub vocabulary_version: Version,
230    pub content_hash: String,
231    pub symbol_type: TokenKind,
232    pub modality: Modality,
233    pub payload_encoding: String,
234    pub payload: serde_json::Value,
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub frequency: Option<u64>,
237    pub metadata: BTreeMap<String, serde_json::Value>,
238}
239
240impl Vocabulary {
241    pub fn id(&self) -> &VocabularyId {
242        &self.manifest.id
243    }
244
245    pub fn version(&self) -> &Version {
246        &self.manifest.version
247    }
248
249    pub fn len(&self) -> usize {
250        self.tokens.len()
251    }
252
253    pub fn is_empty(&self) -> bool {
254        self.tokens.is_empty()
255    }
256
257    pub fn token(&self, id: u32) -> Result<&TokenEntry> {
258        self.tokens.get(id as usize).ok_or(KuteError::UnknownToken(id))
259    }
260
261    /// SHA-256 over the canonical JSON of everything except `integrity`.
262    pub fn compute_digest(&self) -> Result<String> {
263        let mut body = self.clone();
264        body.integrity = None;
265        Ok(sha256_tagged(&serde_json::to_vec(&body)?))
266    }
267
268    /// The digest recorded in the file, or a freshly computed one.
269    pub fn digest(&self) -> Result<String> {
270        match &self.integrity {
271            Some(i) => Ok(i.digest.clone()),
272            None => self.compute_digest(),
273        }
274    }
275
276    /// Record the content digest. Call after the last modification.
277    pub fn seal(&mut self) -> Result<()> {
278        let digest = self.compute_digest()?;
279        // Signatures are of the digest: they stay while it stays, and go
280        // with the content they were made for.
281        let signatures = match self.integrity.take() {
282            Some(old) if old.digest == digest => old.signatures,
283            _ => Vec::new(),
284        };
285        self.integrity = Some(Integrity { algorithm: "sha256".into(), digest, signatures });
286        Ok(())
287    }
288
289    /// The FR-005 envelope for one token.
290    pub fn record(&self, id: u32) -> Result<TokenRecord> {
291        let t = self.token(id)?;
292        let (encoding, payload) = match &t.payload {
293            TokenPayload::Bytes(b) => match std::str::from_utf8(b) {
294                Ok(s) => ("utf8", serde_json::Value::String(s.to_string())),
295                Err(_) => ("base64", serde_json::Value::String(crate::b64::encode(b))),
296            },
297            TokenPayload::Symbols(s) => ("json", serde_json::json!(s)),
298        };
299        let mut metadata = BTreeMap::new();
300        metadata.insert("reversible".to_string(), serde_json::json!(self.manifest.lossless));
301        metadata.insert("algorithm".to_string(), serde_json::json!(self.manifest.algorithm));
302        metadata.insert("length".to_string(), serde_json::json!(t.payload.len()));
303        if let Some(rule) = self.merges.iter().find(|m| m.id == id) {
304            metadata.insert("merge".to_string(), serde_json::json!([rule.left, rule.right]));
305        }
306        Ok(TokenRecord {
307            token_id: id,
308            vocabulary_id: self.manifest.id.clone(),
309            vocabulary_version: self.manifest.version.clone(),
310            content_hash: t.payload.content_hash(),
311            symbol_type: t.kind,
312            modality: self.manifest.modality,
313            payload_encoding: encoding.to_string(),
314            payload,
315            frequency: t.frequency,
316            metadata,
317        })
318    }
319
320    /// Structural validation. Everything that loads a vocabulary from outside
321    /// the process must call this before using it.
322    pub fn validate(&self) -> Result<()> {
323        let bad = |why: String| Err(KuteError::InvalidVocabulary(why));
324        if self.manifest.kvf_version != KVF_VERSION {
325            return Err(KuteError::Unsupported(format!(
326                "KVF version {:?}; this build reads {KVF_VERSION:?}",
327                self.manifest.kvf_version
328            )));
329        }
330        if self.manifest.algorithm.is_empty() || self.manifest.algorithm.len() > 64 {
331            return bad("algorithm name must be 1 to 64 bytes".into());
332        }
333        if self.tokens.is_empty() {
334            return bad("no tokens".into());
335        }
336        if self.tokens.len() > MAX_TOKENS {
337            return bad(format!("more than {MAX_TOKENS} tokens"));
338        }
339        if let Some(p) = &self.pretokenizer {
340            if p.is_empty() || p.len() > 4096 {
341                return bad("pretokenizer pattern must be 1 to 4096 bytes".into());
342            }
343        }
344        for (i, t) in self.tokens.iter().enumerate() {
345            if t.id as usize != i {
346                return bad(format!("token at position {i} has id {}; ids must be dense and ordered", t.id));
347            }
348            if t.payload.kind() != self.manifest.payload_kind && t.kind != TokenKind::Special {
349                return bad(format!("token {i} payload kind differs from the manifest"));
350            }
351            match &t.payload {
352                TokenPayload::Bytes(b) => {
353                    if b.is_empty() || b.len() > MAX_TOKEN_BYTES {
354                        return bad(format!("token {i} payload must be 1 to {MAX_TOKEN_BYTES} bytes"));
355                    }
356                }
357                TokenPayload::Symbols(s) => {
358                    if s.is_empty() || s.len() > MAX_TOKEN_SYMBOLS {
359                        return bad(format!("token {i} must hold 1 to {MAX_TOKEN_SYMBOLS} symbols"));
360                    }
361                    if s.iter().any(|x| x.is_empty() || x.len() > MAX_SYMBOL_BYTES) {
362                        return bad(format!("token {i} has an empty or oversized symbol"));
363                    }
364                }
365            }
366        }
367        let mut has_rule = vec![false; self.tokens.len()];
368        for m in &self.merges {
369            let n = self.tokens.len() as u32;
370            if m.id >= n || m.left >= m.id || m.right >= m.id {
371                return bad(format!("merge rule ({}, {}) -> {} refers to a token that is not earlier in the table", m.left, m.right, m.id));
372            }
373            let target = &self.tokens[m.id as usize];
374            if target.kind != TokenKind::Merge {
375                return bad(format!("merge rule targets token {} which is not a merge token", m.id));
376            }
377            if has_rule[m.id as usize] {
378                return bad(format!("token {} has more than one merge rule", m.id));
379            }
380            has_rule[m.id as usize] = true;
381            let expected = self.tokens[m.left as usize].payload.concat(&self.tokens[m.right as usize].payload);
382            if expected.as_ref() != Some(&target.payload) {
383                return bad(format!("token {} payload is not the concatenation of tokens {} and {}", m.id, m.left, m.right));
384            }
385        }
386        for (i, t) in self.tokens.iter().enumerate() {
387            if t.kind == TokenKind::Merge && !has_rule[i] {
388                return bad(format!("merge token {i} has no merge rule"));
389            }
390        }
391        if self.test_vectors.len() > MAX_TEST_VECTORS {
392            return bad(format!("more than {MAX_TEST_VECTORS} test vectors"));
393        }
394        for (i, v) in self.test_vectors.iter().enumerate() {
395            if v.ids.iter().any(|&id| id as usize >= self.tokens.len()) {
396                return bad(format!("test vector {i} uses a token id outside the table"));
397            }
398        }
399        if let Some(integrity) = &self.integrity {
400            if integrity.algorithm != "sha256" {
401                return Err(KuteError::Unsupported(format!("integrity algorithm {:?}", integrity.algorithm)));
402            }
403            let actual = self.compute_digest()?;
404            if actual != integrity.digest {
405                return Err(KuteError::Integrity(format!(
406                    "recorded digest {} does not match content digest {actual}",
407                    integrity.digest
408                )));
409            }
410            if integrity.signatures.len() > 16 || integrity.signatures.iter().any(|s| s.key_id.len() > 256 || s.algorithm.len() > 64 || s.signature.len() > 1024) {
411                return bad("more than 16 signatures, or one with an overlong field".into());
412            }
413        }
414        Ok(())
415    }
416}