Skip to main content

keyrill_core/
model.rs

1//! Embedded reference EN/RU word frequencies and order-2 character chains.
2//!
3//! Each language has two tables, and inference asks each a different question. The lexicon maps
4//! a lowercase word to its log10 corpus frequency: it says how common the candidate reading is
5//! and whether the typed string is already a word of its own language. The character chain gives
6//! the probability of each letter after the two before it, with start and end markers, so it can
7//! score any string of the alphabet, including one the lexicon has never seen; inference uses it
8//! for the chance that the typed letters were meant as typed.
9//!
10//! `assets/model.bin` is produced by `tools/pack-model.py`, which documents the layout. Values
11//! are log10 probabilities stored as integer micro-units; dividing by 10^6 reproduces the
12//! correctly rounded parse of the frozen six-decimal source text exactly. Corpus frequencies
13//! are not calibrated layout-error probabilities.
14//!
15//! ```text
16//! offset 0   "KRMODEL\0"  u32 version  [u8; 32] source SHA-256  u32 languages = 2
17//! offset 48  per language, en then ru, all little-endian:
18//!              u32 L          u16[L] alphabet, UTF-16 units
19//!              u32 n          u32[n + 1] offsets, from 0, increasing
20//!              u8[offsets[n]] each word as alphabet indices, words in UTF-16 order
21//!              i32[n]         log10 frequency of word i, micro-units
22//!              i32[S * S * S] log10 P(c | a, b) at (a * S + b) * S + c, micro-units
23//!            where S = L + 2: index L is the end marker and L + 1 the start marker
24//! ```
25//!
26//! The words are sorted so that a lookup is a binary search; ё (U+0451) sorts after я, although
27//! the alphabet lists it after е. [`Model::parse`] checks every count, offset, index and the
28//! order once; each section is then its own slice, and a lookup cannot read past it.
29
30use crate::session::Mode;
31
32static EMBEDDED: &[u8] = include_bytes!("../../../assets/model.bin");
33
34const MAGIC: &[u8; 8] = b"KRMODEL\0";
35const VERSION: u32 = 1;
36const LANGUAGES: u32 = 2;
37const SCALE: f64 = 1_000_000.0;
38const SOURCE_SHA256: [u8; 32] = [
39    0x82, 0xb2, 0x2d, 0xd4, 0x05, 0x5c, 0x4b, 0xdb, 0x70, 0x3d, 0xf8, 0xa8, 0x1b, 0x1a, 0x15, 0x47,
40    0x4b, 0x5b, 0x9b, 0xe2, 0x2a, 0x64, 0x52, 0x5d, 0x41, 0x6f, 0x53, 0x60, 0x93, 0x81, 0xac, 0x27,
41];
42/// Longest stored word in UTF-16 units. Inference treats a longer word as ineligible.
43pub const MAX_MODEL_WORD: usize = 32;
44
45/// Structural reason an asset was rejected; carries no asset content.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum ModelError {
48    /// The asset ends before a declared section.
49    Truncated,
50    /// Wrong magic bytes.
51    Magic,
52    /// Unsupported format version.
53    Version,
54    /// Source identity differs from the frozen model (consistency, not authenticity).
55    SourceHash,
56    /// Unexpected number of languages.
57    LanguageCount,
58    /// Alphabet differs from the frozen language table.
59    Alphabet,
60    /// Entry count differs from the frozen language table.
61    WordCount,
62    /// Word offsets do not start at zero, or a word is empty or longer than [`MAX_MODEL_WORD`].
63    Offsets,
64    /// A word contains an index outside its alphabet.
65    Word,
66    /// Words are not strictly increasing in UTF-16 order.
67    Order,
68    /// Bytes remain after the last section.
69    TrailingBytes,
70}
71
72impl std::fmt::Display for ModelError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.write_str(match self {
75            Self::Truncated => "model asset is truncated",
76            Self::Magic => "not a Keyrill model asset",
77            Self::Version => "unsupported model format version",
78            Self::SourceHash => "model source differs from the frozen model",
79            Self::LanguageCount => "unexpected number of model languages",
80            Self::Alphabet => "model alphabet differs from the frozen table",
81            Self::WordCount => "model word count differs from the frozen table",
82            Self::Offsets => "invalid model word offsets",
83            Self::Word => "model word uses an index outside its alphabet",
84            Self::Order => "model words are not in UTF-16 order",
85            Self::TrailingBytes => "model asset has trailing bytes",
86        })
87    }
88}
89
90impl std::error::Error for ModelError {}
91
92/// One language's frequency table and character chain, borrowed from a validated asset.
93#[derive(Clone, Copy)]
94pub struct LanguageModel<'a> {
95    alphabet: &'a [u8],
96    offsets: &'a [u8],
97    words: &'a [u8],
98    frequencies: &'a [u8],
99    chain: &'a [u8],
100}
101
102/// Validated EN and RU models.
103#[derive(Clone, Copy)]
104pub struct Model<'a> {
105    en: LanguageModel<'a>,
106    ru: LanguageModel<'a>,
107}
108
109/// Cursor over the asset; a read past the end is [`ModelError::Truncated`].
110struct Reader<'a> {
111    bytes: &'a [u8],
112}
113
114impl<'a> Reader<'a> {
115    fn take(&mut self, length: usize) -> Result<&'a [u8], ModelError> {
116        if length > self.bytes.len() {
117            return Err(ModelError::Truncated);
118        }
119        let (head, tail) = self.bytes.split_at(length);
120        self.bytes = tail;
121        Ok(head)
122    }
123
124    fn take_array(&mut self, count: usize, width: usize) -> Result<&'a [u8], ModelError> {
125        self.take(count.checked_mul(width).ok_or(ModelError::Truncated)?)
126    }
127
128    fn u32(&mut self) -> Result<u32, ModelError> {
129        u32_at(self.take(4)?, 0).ok_or(ModelError::Truncated)
130    }
131}
132
133fn u16_at(bytes: &[u8], index: usize) -> Option<u16> {
134    let at = index.checked_mul(2)?;
135    Some(u16::from_le_bytes(
136        bytes.get(at..at.checked_add(2)?)?.try_into().ok()?,
137    ))
138}
139
140fn u32_at(bytes: &[u8], index: usize) -> Option<u32> {
141    let at = index.checked_mul(4)?;
142    Some(u32::from_le_bytes(
143        bytes.get(at..at.checked_add(4)?)?.try_into().ok()?,
144    ))
145}
146
147fn value_at(bytes: &[u8], index: usize) -> Option<f64> {
148    let at = index.checked_mul(4)?;
149    let micro = i32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?);
150    Some(f64::from(micro) / SCALE)
151}
152
153impl<'a> LanguageModel<'a> {
154    fn parse(
155        reader: &mut Reader<'a>,
156        expected_alphabet: &str,
157        expected_count: u32,
158    ) -> Result<Self, ModelError> {
159        let letters = reader.u32()? as usize;
160        if letters != expected_alphabet.encode_utf16().count() {
161            return Err(ModelError::Alphabet);
162        }
163        let alphabet = reader.take_array(letters, 2)?;
164        if !expected_alphabet
165            .encode_utf16()
166            .eq((0..letters).filter_map(|i| u16_at(alphabet, i)))
167        {
168            return Err(ModelError::Alphabet);
169        }
170        let count = reader.u32()?;
171        if count != expected_count {
172            return Err(ModelError::WordCount);
173        }
174        let count = count as usize;
175        let offsets = reader.take_array(count.checked_add(1).ok_or(ModelError::Truncated)?, 4)?;
176        if u32_at(offsets, 0) != Some(0) {
177            return Err(ModelError::Offsets);
178        }
179        let mut end = 0;
180        for i in 1..=count {
181            let next = u32_at(offsets, i).ok_or(ModelError::Truncated)? as usize;
182            if next <= end || next - end > MAX_MODEL_WORD {
183                return Err(ModelError::Offsets);
184            }
185            end = next;
186        }
187        let words = reader.take(end)?;
188        if words.iter().any(|&index| usize::from(index) >= letters) {
189            return Err(ModelError::Word);
190        }
191        let frequencies = reader.take_array(count, 4)?;
192        // The chain has two marker indices after the letters: end, then start
193        let size = letters + 2;
194        let chain = reader.take_array(size * size * size, 4)?;
195        let model = Self {
196            alphabet,
197            offsets,
198            words,
199            frequencies,
200            chain,
201        };
202        // Strict order is what `frequency` binary-searches on, and it also rules out duplicates
203        for i in 1..count {
204            let (previous, current) = (model.word(i - 1), model.word(i));
205            let ordered = previous
206                .zip(current)
207                .is_some_and(|(p, c)| model.units(p).lt(model.units(c)));
208            if !ordered {
209                return Err(ModelError::Order);
210            }
211        }
212        Ok(model)
213    }
214
215    fn letters(&self) -> usize {
216        self.alphabet.len() / 2
217    }
218
219    fn word(&self, index: usize) -> Option<&'a [u8]> {
220        let start = u32_at(self.offsets, index)? as usize;
221        let end = u32_at(self.offsets, index.checked_add(1)?)? as usize;
222        self.words.get(start..end)
223    }
224
225    fn units(&self, word: &'a [u8]) -> impl Iterator<Item = u16> + 'a {
226        let alphabet = self.alphabet;
227        word.iter()
228            .map(move |&index| u16_at(alphabet, usize::from(index)).unwrap_or(u16::MAX))
229    }
230
231    fn index(&self, unit: u16) -> Option<usize> {
232        (0..self.letters()).find(|&i| u16_at(self.alphabet, i) == Some(unit))
233    }
234
235    /// Stored log10 corpus frequency of an exact lowercase word, or `None` if absent.
236    /// No case folding or normalization is applied.
237    pub fn frequency(&self, word: &[u16]) -> Option<f64> {
238        if word.is_empty() || word.len() > MAX_MODEL_WORD {
239            return None;
240        }
241        let (mut low, mut high) = (0, self.offsets.len() / 4 - 1);
242        while low < high {
243            let middle = low + (high - low) / 2;
244            match self.units(self.word(middle)?).cmp(word.iter().copied()) {
245                std::cmp::Ordering::Less => low = middle + 1,
246                std::cmp::Ordering::Greater => high = middle,
247                std::cmp::Ordering::Equal => return value_at(self.frequencies, middle),
248            }
249        }
250        None
251    }
252
253    /// log10 likelihood of the word followed by the end marker under the order-2 chain,
254    /// summed left to right from the two start markers. `None` if the word is outside 1..=32
255    /// units or has a unit outside this language's alphabet.
256    pub fn log_likelihood(&self, word: &[u16]) -> Option<f64> {
257        if word.is_empty() || word.len() > MAX_MODEL_WORD {
258            return None;
259        }
260        let letters = self.letters();
261        let size = letters + 2;
262        let (mut a, mut b) = (size - 1, size - 1);
263        let mut total = 0.0;
264        for next in word
265            .iter()
266            .map(|&unit| self.index(unit))
267            .chain([Some(letters)])
268        {
269            let c = next?;
270            total += value_at(self.chain, (a * size + b) * size + c)?;
271            (a, b) = (b, c);
272        }
273        Some(total)
274    }
275}
276
277impl<'a> Model<'a> {
278    /// Parse and validate an asset. The source hash and the frozen alphabets and counts make a
279    /// different or damaged model fail; they are a consistency check, not authentication, so
280    /// bytes from outside the build still need their own provenance. Lookups on the result use
281    /// checked slices.
282    ///
283    /// # Errors
284    ///
285    /// The first structural [`ModelError`] found, from the header through the trailing bytes.
286    pub fn parse(bytes: &'a [u8]) -> Result<Self, ModelError> {
287        let mut reader = Reader { bytes };
288        if reader.take(MAGIC.len())? != MAGIC {
289            return Err(ModelError::Magic);
290        }
291        if reader.u32()? != VERSION {
292            return Err(ModelError::Version);
293        }
294        if reader.take(32)? != SOURCE_SHA256 {
295            return Err(ModelError::SourceHash);
296        }
297        if reader.u32()? != LANGUAGES {
298            return Err(ModelError::LanguageCount);
299        }
300        let en = LanguageModel::parse(&mut reader, "abcdefghijklmnopqrstuvwxyz", 89_656)?;
301        let ru = LanguageModel::parse(&mut reader, "абвгдеёжзийклмнопрстуфхцчшщъыьэюя", 241_624)?;
302        if !reader.bytes.is_empty() {
303            return Err(ModelError::TrailingBytes);
304        }
305        Ok(Self { en, ru })
306    }
307
308    /// Validate the asset compiled into this crate. Validation walks the whole asset, so
309    /// callers should construct it once, outside input callbacks, and keep it.
310    ///
311    /// ```
312    /// use keyrill_core::model::Model;
313    /// use keyrill_core::session::Mode;
314    ///
315    /// # fn main() -> Result<(), keyrill_core::model::ModelError> {
316    /// let model = Model::embedded()?;
317    /// let hello: Vec<u16> = "hello".encode_utf16().collect();
318    /// assert!(model.language(Mode::En).frequency(&hello).is_some());
319    /// # Ok(())
320    /// # }
321    /// ```
322    ///
323    /// # Errors
324    ///
325    /// A [`ModelError`] only if the build embedded a corrupt asset; `tools/pack-model.py --check`
326    /// guards against that.
327    pub fn embedded() -> Result<Model<'static>, ModelError> {
328        Model::parse(EMBEDDED)
329    }
330
331    /// The model for the language a mode types.
332    pub fn language(&self, mode: Mode) -> &LanguageModel<'a> {
333        match mode {
334            Mode::En => &self.en,
335            Mode::Ru => &self.ru,
336        }
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    fn utf16(text: &str) -> Vec<u16> {
345        text.encode_utf16().collect()
346    }
347
348    fn model() -> Model<'static> {
349        Model::embedded().unwrap()
350    }
351
352    #[test]
353    fn embedded_counts_and_table_boundaries() {
354        let model = model();
355        for (mode, count, first, last) in [
356            (Mode::En, 89_656, "a", "zzz"),
357            (Mode::Ru, 241_624, "а", "ёё"),
358        ] {
359            let language = model.language(mode);
360            assert_eq!(language.offsets.len() / 4 - 1, count);
361            assert!(language.frequency(&utf16(first)).is_some());
362            assert!(language.frequency(&utf16(last)).is_some());
363        }
364    }
365
366    #[test]
367    fn known_frequencies_are_exact_source_values() {
368        let model = model();
369        for (mode, word, expected) in [
370            (Mode::En, "a", -1.64_f64),
371            (Mode::En, "the", -1.27),
372            (Mode::En, "hello", -4.28),
373            (Mode::En, "zzz", -6.79),
374            (Mode::Ru, "а", -2.14),
375            (Mode::Ru, "привет", -3.87),
376            // ё sorts after я in UTF-16 order but follows е in the alphabet
377            (Mode::Ru, "еж", -6.06),
378            (Mode::Ru, "ёж", -6.26),
379            (Mode::Ru, "ёлка", -5.99),
380            (Mode::Ru, "ёё", -6.8),
381        ] {
382            let found = model.language(mode).frequency(&utf16(word));
383            assert_eq!(found.map(f64::to_bits), Some(expected.to_bits()), "{word}");
384        }
385    }
386
387    #[test]
388    fn absent_words_and_bounds() {
389        let model = model();
390        let en = model.language(Mode::En);
391        for word in ["ghbdtn", "The", "привет", "", "hello!"] {
392            assert_eq!(en.frequency(&utf16(word)), None, "{word}");
393        }
394        assert_eq!(en.frequency(&[0xd83d, 0xde00]), None);
395        assert_eq!(en.frequency(&utf16(&"a".repeat(MAX_MODEL_WORD + 1))), None);
396        assert_eq!(model.language(Mode::Ru).frequency(&utf16("hello")), None);
397    }
398
399    #[test]
400    fn chain_likelihoods_match_reference_summation_bit_for_bit() {
401        // Expected bit patterns are left-to-right f64 sums of the frozen source text
402        let model = model();
403        for (mode, word, expected) in [
404            (Mode::En, "the", 0xbff6_602b_8412_48d7_u64),
405            (Mode::En, "hello", 0xc01d_6efa_a476_6c6e),
406            (Mode::En, "ghbdtn", 0xc030_c09f_5169_7f20),
407            (Mode::Ru, "привет", 0xc015_f3c9_abb0_1c92),
408            (Mode::Ru, "ёлка", 0xc020_0e1f_3a57_eaa3),
409            (Mode::Ru, "руддщ", 0xc027_bc6f_9b99_4e1a),
410        ] {
411            let found = model.language(mode).log_likelihood(&utf16(word));
412            assert_eq!(found.map(f64::to_bits), Some(expected), "{word}");
413        }
414        let en = model.language(Mode::En);
415        assert_eq!(en.log_likelihood(&[]), None);
416        assert_eq!(en.log_likelihood(&utf16("Hello")), None);
417        assert_eq!(en.log_likelihood(&utf16("привет")), None);
418        assert_eq!(en.log_likelihood(&[97; MAX_MODEL_WORD + 1]), None);
419    }
420
421    #[test]
422    fn every_stored_value_reconstructs_its_six_decimal_text() {
423        let model = model();
424        for mode in [Mode::En, Mode::Ru] {
425            let language = model.language(mode);
426            for bytes in [language.frequencies, language.chain] {
427                let (chunks, rest) = bytes.as_chunks::<4>();
428                assert!(rest.is_empty());
429                for &chunk in chunks {
430                    let micro = i32::from_le_bytes(chunk);
431                    let sign = if micro < 0 { "-" } else { "" };
432                    let magnitude = micro.unsigned_abs();
433                    let text = format!(
434                        "{sign}{}.{:06}",
435                        magnitude / 1_000_000,
436                        magnitude % 1_000_000
437                    );
438                    assert_eq!(
439                        (f64::from(micro) / SCALE).to_bits(),
440                        text.parse::<f64>().unwrap().to_bits()
441                    );
442                }
443            }
444        }
445    }
446
447    // Byte offsets into the embedded asset: header, then the English alphabet of 26 units
448    const EN_COUNT: usize = 48 + 4 + 52;
449    const EN_OFFSETS: usize = EN_COUNT + 4;
450    const EN_WORDS: usize = EN_OFFSETS + (89_656 + 1) * 4;
451
452    fn mutated(at: usize, bytes: &[u8]) -> Result<(), ModelError> {
453        let mut copy = EMBEDDED.to_vec();
454        copy[at..at + bytes.len()].copy_from_slice(bytes);
455        Model::parse(&copy).map(|_| ())
456    }
457
458    #[test]
459    fn malformed_assets_are_rejected_with_exact_errors() {
460        use ModelError::*;
461        let cases: [(usize, &[u8], ModelError); 14] = [
462            (0, b"X", Magic),
463            (8, &2u32.to_le_bytes(), Version),
464            (12, &[0], SourceHash),
465            (44, &3u32.to_le_bytes(), LanguageCount),
466            (48, &0u32.to_le_bytes(), Alphabet),
467            (48, &65u32.to_le_bytes(), Alphabet),
468            (52 + 2, &u16::from(b'a').to_le_bytes(), Alphabet),
469            (52, &0u16.to_le_bytes(), Alphabet),
470            (EN_COUNT, &89_655u32.to_le_bytes(), WordCount),
471            (EN_OFFSETS, &1u32.to_le_bytes(), Offsets),
472            (EN_OFFSETS + 4, &0u32.to_le_bytes(), Offsets),
473            (EN_OFFSETS + 4, &40u32.to_le_bytes(), Offsets),
474            (EN_WORDS, &[26], Word),
475            // "a" becomes "b", which sorts after the following "aa"
476            (EN_WORDS, &[1], Order),
477        ];
478        for (at, bytes, error) in cases {
479            assert_eq!(mutated(at, bytes).err(), Some(error), "offset {at}");
480        }
481        assert_eq!(
482            mutated(EN_COUNT, &u32::MAX.to_le_bytes()).err(),
483            Some(WordCount)
484        );
485    }
486
487    #[test]
488    fn truncated_and_extended_assets_are_rejected() {
489        for length in [
490            0,
491            7,
492            8,
493            11,
494            44,
495            47,
496            51,
497            EN_OFFSETS + 3,
498            EN_WORDS + 1,
499            EMBEDDED.len() - 1,
500        ] {
501            assert_eq!(
502                Model::parse(&EMBEDDED[..length]).err(),
503                Some(ModelError::Truncated),
504                "{length}"
505            );
506        }
507        let mut extended = EMBEDDED.to_vec();
508        extended.push(0);
509        assert_eq!(
510            Model::parse(&extended).err(),
511            Some(ModelError::TrailingBytes)
512        );
513    }
514}