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    /// Reserved. KVF 0.1 defines the field but no signature scheme.
194    #[serde(default, skip_serializing_if = "Vec::is_empty")]
195    pub signatures: Vec<Signature>,
196}
197
198#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
199pub struct Vocabulary {
200    pub manifest: Manifest,
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub pretokenizer: Option<String>,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub adapter: Option<AdapterSpec>,
205    pub tokens: Vec<TokenEntry>,
206    #[serde(default)]
207    pub merges: Vec<MergeRule>,
208    #[serde(default)]
209    pub statistics: BTreeMap<String, u64>,
210    #[serde(default)]
211    pub provenance: Provenance,
212    #[serde(default)]
213    pub test_vectors: Vec<TestVector>,
214    #[serde(default, skip_serializing_if = "Vec::is_empty")]
215    pub representations: Vec<RepresentationRef>,
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub integrity: Option<Integrity>,
218}
219
220/// The token envelope from FR-005: one token with everything needed to
221/// interpret it outside its vocabulary file.
222#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
223pub struct TokenRecord {
224    pub token_id: u32,
225    pub vocabulary_id: VocabularyId,
226    pub vocabulary_version: Version,
227    pub content_hash: String,
228    pub symbol_type: TokenKind,
229    pub modality: Modality,
230    pub payload_encoding: String,
231    pub payload: serde_json::Value,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub frequency: Option<u64>,
234    pub metadata: BTreeMap<String, serde_json::Value>,
235}
236
237impl Vocabulary {
238    pub fn id(&self) -> &VocabularyId {
239        &self.manifest.id
240    }
241
242    pub fn version(&self) -> &Version {
243        &self.manifest.version
244    }
245
246    pub fn len(&self) -> usize {
247        self.tokens.len()
248    }
249
250    pub fn is_empty(&self) -> bool {
251        self.tokens.is_empty()
252    }
253
254    pub fn token(&self, id: u32) -> Result<&TokenEntry> {
255        self.tokens.get(id as usize).ok_or(KuteError::UnknownToken(id))
256    }
257
258    /// SHA-256 over the canonical JSON of everything except `integrity`.
259    pub fn compute_digest(&self) -> Result<String> {
260        let mut body = self.clone();
261        body.integrity = None;
262        Ok(sha256_tagged(&serde_json::to_vec(&body)?))
263    }
264
265    /// The digest recorded in the file, or a freshly computed one.
266    pub fn digest(&self) -> Result<String> {
267        match &self.integrity {
268            Some(i) => Ok(i.digest.clone()),
269            None => self.compute_digest(),
270        }
271    }
272
273    /// Record the content digest. Call after the last modification.
274    pub fn seal(&mut self) -> Result<()> {
275        let digest = self.compute_digest()?;
276        self.integrity = Some(Integrity { algorithm: "sha256".into(), digest, signatures: Vec::new() });
277        Ok(())
278    }
279
280    /// The FR-005 envelope for one token.
281    pub fn record(&self, id: u32) -> Result<TokenRecord> {
282        let t = self.token(id)?;
283        let (encoding, payload) = match &t.payload {
284            TokenPayload::Bytes(b) => match std::str::from_utf8(b) {
285                Ok(s) => ("utf8", serde_json::Value::String(s.to_string())),
286                Err(_) => ("base64", serde_json::Value::String(crate::b64::encode(b))),
287            },
288            TokenPayload::Symbols(s) => ("json", serde_json::json!(s)),
289        };
290        let mut metadata = BTreeMap::new();
291        metadata.insert("reversible".to_string(), serde_json::json!(self.manifest.lossless));
292        metadata.insert("algorithm".to_string(), serde_json::json!(self.manifest.algorithm));
293        metadata.insert("length".to_string(), serde_json::json!(t.payload.len()));
294        if let Some(rule) = self.merges.iter().find(|m| m.id == id) {
295            metadata.insert("merge".to_string(), serde_json::json!([rule.left, rule.right]));
296        }
297        Ok(TokenRecord {
298            token_id: id,
299            vocabulary_id: self.manifest.id.clone(),
300            vocabulary_version: self.manifest.version.clone(),
301            content_hash: t.payload.content_hash(),
302            symbol_type: t.kind,
303            modality: self.manifest.modality,
304            payload_encoding: encoding.to_string(),
305            payload,
306            frequency: t.frequency,
307            metadata,
308        })
309    }
310
311    /// Structural validation. Everything that loads a vocabulary from outside
312    /// the process must call this before using it.
313    pub fn validate(&self) -> Result<()> {
314        let bad = |why: String| Err(KuteError::InvalidVocabulary(why));
315        if self.manifest.kvf_version != KVF_VERSION {
316            return Err(KuteError::Unsupported(format!(
317                "KVF version {:?}; this build reads {KVF_VERSION:?}",
318                self.manifest.kvf_version
319            )));
320        }
321        if self.manifest.algorithm.is_empty() || self.manifest.algorithm.len() > 64 {
322            return bad("algorithm name must be 1 to 64 bytes".into());
323        }
324        if self.tokens.is_empty() {
325            return bad("no tokens".into());
326        }
327        if self.tokens.len() > MAX_TOKENS {
328            return bad(format!("more than {MAX_TOKENS} tokens"));
329        }
330        if let Some(p) = &self.pretokenizer {
331            if p.is_empty() || p.len() > 4096 {
332                return bad("pretokenizer pattern must be 1 to 4096 bytes".into());
333            }
334        }
335        for (i, t) in self.tokens.iter().enumerate() {
336            if t.id as usize != i {
337                return bad(format!("token at position {i} has id {}; ids must be dense and ordered", t.id));
338            }
339            if t.payload.kind() != self.manifest.payload_kind && t.kind != TokenKind::Special {
340                return bad(format!("token {i} payload kind differs from the manifest"));
341            }
342            match &t.payload {
343                TokenPayload::Bytes(b) => {
344                    if b.is_empty() || b.len() > MAX_TOKEN_BYTES {
345                        return bad(format!("token {i} payload must be 1 to {MAX_TOKEN_BYTES} bytes"));
346                    }
347                }
348                TokenPayload::Symbols(s) => {
349                    if s.is_empty() || s.len() > MAX_TOKEN_SYMBOLS {
350                        return bad(format!("token {i} must hold 1 to {MAX_TOKEN_SYMBOLS} symbols"));
351                    }
352                    if s.iter().any(|x| x.is_empty() || x.len() > MAX_SYMBOL_BYTES) {
353                        return bad(format!("token {i} has an empty or oversized symbol"));
354                    }
355                }
356            }
357        }
358        let mut has_rule = vec![false; self.tokens.len()];
359        for m in &self.merges {
360            let n = self.tokens.len() as u32;
361            if m.id >= n || m.left >= m.id || m.right >= m.id {
362                return bad(format!("merge rule ({}, {}) -> {} refers to a token that is not earlier in the table", m.left, m.right, m.id));
363            }
364            let target = &self.tokens[m.id as usize];
365            if target.kind != TokenKind::Merge {
366                return bad(format!("merge rule targets token {} which is not a merge token", m.id));
367            }
368            if has_rule[m.id as usize] {
369                return bad(format!("token {} has more than one merge rule", m.id));
370            }
371            has_rule[m.id as usize] = true;
372            let expected = self.tokens[m.left as usize].payload.concat(&self.tokens[m.right as usize].payload);
373            if expected.as_ref() != Some(&target.payload) {
374                return bad(format!("token {} payload is not the concatenation of tokens {} and {}", m.id, m.left, m.right));
375            }
376        }
377        for (i, t) in self.tokens.iter().enumerate() {
378            if t.kind == TokenKind::Merge && !has_rule[i] {
379                return bad(format!("merge token {i} has no merge rule"));
380            }
381        }
382        if self.test_vectors.len() > MAX_TEST_VECTORS {
383            return bad(format!("more than {MAX_TEST_VECTORS} test vectors"));
384        }
385        for (i, v) in self.test_vectors.iter().enumerate() {
386            if v.ids.iter().any(|&id| id as usize >= self.tokens.len()) {
387                return bad(format!("test vector {i} uses a token id outside the table"));
388            }
389        }
390        if let Some(integrity) = &self.integrity {
391            if integrity.algorithm != "sha256" {
392                return Err(KuteError::Unsupported(format!("integrity algorithm {:?}", integrity.algorithm)));
393            }
394            let actual = self.compute_digest()?;
395            if actual != integrity.digest {
396                return Err(KuteError::Integrity(format!(
397                    "recorded digest {} does not match content digest {actual}",
398                    integrity.digest
399                )));
400            }
401        }
402        Ok(())
403    }
404}