Skip to main content

lindera_dependency/parser/
model.rs

1//! The model of the parser: the weights of its classifier, and what makes
2//! its features.
3//!
4//! [`ParserModel`] holds the weights in memory, as training gives them or as
5//! they are made by hand. In a model file they are the parser part, which
6//! [`ParserPart`] reads where it is.
7//!
8//! The weights are those of a bias, of the features and of pairs of
9//! features. The weights of the pairs are kept in one of two ways
10//! ([`PairWeights`]): each pair with a weight of its own, or a table of a
11//! fixed size the pairs are hashed into.
12
13use std::collections::HashMap;
14use std::ops::Range;
15
16use super::classifier::Classifier;
17use super::features::FeatureSet;
18use crate::bytes::{Reader, push_string, push_u32};
19use crate::error::{Error, Result};
20use crate::model::table::{self, Layout, Table};
21use crate::schema::Schema;
22
23/// The key of a feature for the table of hashed pairs: the hash of its
24/// string, so that it does not depend on which other features a model has.
25///
26/// # Arguments
27///
28/// * `feature` - The feature string.
29///
30/// # Returns
31///
32/// The key: the 64-bit FNV-1a of the string, folded to 32 bits.
33pub(crate) fn feature_key(feature: &str) -> u32 {
34    table::hash(feature.as_bytes()) as u32
35}
36
37/// The place of a pair of features in a table of hashed pairs.
38///
39/// # Arguments
40///
41/// * `one` - The key of a feature ([`feature_key`]).
42/// * `other` - The key of the other feature.
43/// * `bits` - The size of the table, as a power of two: 1 to 30.
44///
45/// # Returns
46///
47/// The place, the same for the two orders of the features: the two keys,
48/// the smaller first, mixed by the two multiplications of SplitMix64; the
49/// highest `bits` bits of the result.
50pub(crate) fn bucket(one: u32, other: u32, bits: u32) -> u32 {
51    let mut value = (u64::from(one.min(other)) << 32) | u64::from(one.max(other));
52    value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
53    value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
54    (value >> (64 - bits)) as u32
55}
56
57/// The weights of the pairs of features of a model.
58#[derive(Debug, Clone, PartialEq)]
59pub enum PairWeights {
60    /// A weight of its own for each pair: the numbers of its two features,
61    /// the smaller first, and the weight. The pairs are sorted, each once.
62    Exact(Vec<((u32, u32), f32)>),
63    /// A table of `2^bits` weights the pairs are hashed into; pairs that
64    /// fall on the same weight share it.
65    Hashed {
66        /// The size of the table, as a power of two: 1 to 30.
67        bits: u32,
68        /// The weights, `2^bits` of them.
69        weights: Vec<f32>,
70    },
71}
72
73/// How the weights are written to a model file.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Quantization {
76    /// As they are: 4 bytes a weight.
77    F32,
78    /// As whole numbers of 2 bytes, times a scale: the largest weight
79    /// becomes 32,767.
80    I16,
81    /// As whole numbers of 1 byte, times a scale: the largest weight
82    /// becomes 127.
83    I8,
84}
85
86impl Quantization {
87    /// The three, with their names and their codes in a model file.
88    const ALL: [(Quantization, &'static str, u8); 3] = [
89        (Quantization::F32, "f32", 0),
90        (Quantization::I16, "i16", 1),
91        (Quantization::I8, "i8", 2),
92    ];
93
94    /// The name of the quantization: `f32`, `i16` or `i8`.
95    ///
96    /// # Returns
97    ///
98    /// The name.
99    pub fn name(self) -> &'static str {
100        Self::ALL
101            .iter()
102            .find(|(one, _, _)| *one == self)
103            .map_or("", |(_, name, _)| name)
104    }
105
106    /// The quantization with a name.
107    ///
108    /// # Arguments
109    ///
110    /// * `name` - `f32`, `i16` or `i8`.
111    ///
112    /// # Returns
113    ///
114    /// The quantization, or `None` for another name.
115    pub fn from_name(name: &str) -> Option<Self> {
116        Self::ALL
117            .iter()
118            .find(|(_, other, _)| *other == name)
119            .map(|(one, _, _)| *one)
120    }
121
122    /// The code of the quantization in a model file.
123    fn code(self) -> u8 {
124        Self::ALL
125            .iter()
126            .find(|(one, _, _)| *one == self)
127            .map_or(u8::MAX, |(_, _, code)| *code)
128    }
129
130    /// The quantization with a code.
131    fn from_code(code: u8) -> Option<Self> {
132        Self::ALL
133            .iter()
134            .find(|(_, _, other)| *other == code)
135            .map(|(one, _, _)| *one)
136    }
137
138    /// The number of bytes of a weight.
139    fn width(self) -> usize {
140        match self {
141            Quantization::F32 => 4,
142            Quantization::I16 => 2,
143            Quantization::I8 => 1,
144        }
145    }
146
147    /// The largest whole number a weight is written as; `None` for weights
148    /// written as they are.
149    fn largest(self) -> Option<f64> {
150        match self {
151            Quantization::F32 => None,
152            Quantization::I16 => Some(f64::from(i16::MAX)),
153            Quantization::I8 => Some(f64::from(i8::MAX)),
154        }
155    }
156
157    /// Appends a weight.
158    ///
159    /// # Arguments
160    ///
161    /// * `bytes` - The bytes to append to.
162    /// * `weight` - The weight.
163    /// * `scale` - What a whole number is multiplied by to give a weight.
164    fn push(self, bytes: &mut Vec<u8>, weight: f32, scale: f64) {
165        let whole = || (f64::from(weight) / scale).round();
166        match self {
167            Quantization::F32 => bytes.extend_from_slice(&weight.to_le_bytes()),
168            Quantization::I16 => bytes.extend_from_slice(&(whole() as i16).to_le_bytes()),
169            Quantization::I8 => bytes.extend_from_slice(&(whole() as i8).to_le_bytes()),
170        }
171    }
172
173    /// Reads a weight in an array of them, before the scale.
174    ///
175    /// # Arguments
176    ///
177    /// * `bytes` - The array.
178    /// * `index` - The index of the weight.
179    ///
180    /// # Returns
181    ///
182    /// The weight as it is written; 0 past the end of the array.
183    #[inline]
184    fn read(self, bytes: &[u8], index: usize) -> f64 {
185        match self {
186            Quantization::F32 => {
187                let start = index.saturating_mul(4);
188                bytes
189                    .get(start..start.saturating_add(4))
190                    .and_then(|bytes| bytes.try_into().ok())
191                    .map_or(0.0, |bytes| f64::from(f32::from_le_bytes(bytes)))
192            }
193            Quantization::I16 => {
194                let start = index.saturating_mul(2);
195                bytes
196                    .get(start..start.saturating_add(2))
197                    .and_then(|bytes| bytes.try_into().ok())
198                    .map_or(0.0, |bytes| f64::from(i16::from_le_bytes(bytes)))
199            }
200            Quantization::I8 => bytes.get(index).map_or(0.0, |byte| f64::from(*byte as i8)),
201        }
202    }
203}
204
205/// The model of the parser, in memory.
206///
207/// It holds the weights of the classifier, and with them what makes the
208/// feature strings they are for: the schema of the dictionary and the
209/// feature set. It is what training gives. To keep it, put it into a model
210/// file with [`ModelBuilder`](crate::model::ModelBuilder).
211///
212/// It is a [`Classifier`] itself, and scores a decision as the parser part
213/// of a model file written without quantization does, to the last bit.
214#[derive(Debug, Clone, PartialEq)]
215pub struct ParserModel {
216    /// The schema of the dictionary the model is for.
217    schema: Schema,
218    /// The groups of features the weights are for.
219    feature_set: FeatureSet,
220    /// The bias.
221    bias: f64,
222    /// What the sum of the weights is multiplied by: 1 unless the weights
223    /// are in another unit.
224    unit: f64,
225    /// The feature strings, sorted: the number of a feature is its index.
226    names: Vec<String>,
227    /// The weight of each feature.
228    weights: Vec<f32>,
229    /// The weights of the pairs.
230    pairs: PairWeights,
231    /// The number of each feature string.
232    numbers: HashMap<String, u32>,
233    /// The key of each feature for a table of hashed pairs.
234    keys: Vec<u32>,
235    /// The weight of each pair of an exact table, by the two numbers.
236    exact: HashMap<(u32, u32), f32>,
237}
238
239impl ParserModel {
240    /// Makes a model.
241    ///
242    /// # Arguments
243    ///
244    /// * `schema` - The schema of the dictionary the model is for.
245    /// * `feature_set` - The groups of features the weights are for.
246    /// * `bias` - The bias.
247    /// * `features` - The feature strings with their weights, sorted by
248    ///   the bytes of the strings, each once. The number of a feature is
249    ///   its index.
250    /// * `pairs` - The weights of the pairs.
251    ///
252    /// # Returns
253    ///
254    /// The model, or [`Error::Parser`] for a weight that is not finite,
255    /// feature strings that are not sorted, pairs that are not sorted with
256    /// the smaller number first or that name a feature that is not there,
257    /// or a hashed table that has not `2^bits` weights with 1 to 30 bits.
258    pub fn new(
259        schema: Schema,
260        feature_set: FeatureSet,
261        bias: f64,
262        features: Vec<(String, f32)>,
263        pairs: PairWeights,
264    ) -> Result<Self> {
265        let finite = bias.is_finite()
266            && features.iter().all(|(_, weight)| weight.is_finite())
267            && match &pairs {
268                PairWeights::Exact(pairs) => pairs.iter().all(|(_, weight)| weight.is_finite()),
269                PairWeights::Hashed { weights, .. } => {
270                    weights.iter().all(|weight| weight.is_finite())
271                }
272            };
273        if !finite {
274            return Err(Error::Parser("a weight is not finite".to_string()));
275        }
276        if features
277            .windows(2)
278            .any(|pair| pair[0].0.as_bytes() >= pair[1].0.as_bytes())
279        {
280            return Err(Error::Parser(
281                "the features are not sorted, each once".to_string(),
282            ));
283        }
284        if u32::try_from(features.len()).is_err() {
285            return Err(Error::Parser("too many features".to_string()));
286        }
287        match &pairs {
288            PairWeights::Exact(pairs) => {
289                let count = features.len() as u32;
290                if pairs
291                    .iter()
292                    .any(|((one, other), _)| one >= other || *other >= count)
293                {
294                    return Err(Error::Parser(
295                        "a pair does not name two features, the smaller number first".to_string(),
296                    ));
297                }
298                if pairs.windows(2).any(|pair| pair[0].0 >= pair[1].0) {
299                    return Err(Error::Parser(
300                        "the pairs are not sorted, each once".to_string(),
301                    ));
302                }
303            }
304            PairWeights::Hashed { bits, weights } => {
305                if !(1..=30).contains(bits) || weights.len() != 1usize << bits {
306                    return Err(Error::Parser(format!(
307                        "a table of hashed pairs of {bits} bits has {} weights",
308                        weights.len()
309                    )));
310                }
311            }
312        }
313
314        let (names, weights): (Vec<String>, Vec<f32>) = features.into_iter().unzip();
315        let numbers = names
316            .iter()
317            .enumerate()
318            .map(|(index, name)| (name.clone(), index as u32))
319            .collect();
320        let keys = names.iter().map(|name| feature_key(name)).collect();
321        let exact = match &pairs {
322            PairWeights::Exact(pairs) => pairs.iter().copied().collect(),
323            PairWeights::Hashed { .. } => HashMap::new(),
324        };
325        Ok(Self {
326            schema,
327            feature_set,
328            bias,
329            unit: 1.0,
330            names,
331            weights,
332            pairs,
333            numbers,
334            keys,
335            exact,
336        })
337    }
338
339    /// Gives the weights a unit: what their sum is multiplied by before the
340    /// bias is added. The bias is not in the unit.
341    ///
342    /// The unit of a model is 1, and training gives such a model. A unit is
343    /// for weights that come as whole numbers of a step: a model converted
344    /// from CaboCha keeps the whole numbers CaboCha adds up, so that a
345    /// score has the sign CaboCha gives it, and has CaboCha's step as its
346    /// unit.
347    ///
348    /// # Arguments
349    ///
350    /// * `unit` - The unit, greater than 0.
351    ///
352    /// # Returns
353    ///
354    /// The model, or [`Error::Parser`] for a unit that is not a finite
355    /// number greater than 0.
356    pub fn with_unit(mut self, unit: f64) -> Result<Self> {
357        if !unit.is_finite() || unit <= 0.0 {
358            return Err(Error::Parser(format!(
359                "the unit of the weights is {unit}, and has to be greater than 0"
360            )));
361        }
362        self.unit = unit;
363        Ok(self)
364    }
365
366    /// The model without what has no weight: the pairs of an exact table
367    /// whose weight is 0, and the features whose weight is 0 and that are
368    /// in no pair that is kept. With a hashed table, a feature whose weight
369    /// is 0 is taken out: training gives a feature the weight 0 only when
370    /// no decision with it moved the weights.
371    ///
372    /// # Returns
373    ///
374    /// The smaller model.
375    pub fn compact(self) -> Self {
376        let pairs = match self.pairs {
377            PairWeights::Exact(pairs) => PairWeights::Exact(
378                pairs
379                    .into_iter()
380                    .filter(|(_, weight)| *weight != 0.0)
381                    .collect(),
382            ),
383            hashed => hashed,
384        };
385        let mut kept: Vec<bool> = self.weights.iter().map(|weight| *weight != 0.0).collect();
386        if let PairWeights::Exact(pairs) = &pairs {
387            for ((one, other), _) in pairs {
388                kept[*one as usize] = true;
389                kept[*other as usize] = true;
390            }
391        }
392        // The new number of each feature that is kept: the order stays.
393        let mut renumbered = vec![u32::MAX; kept.len()];
394        let mut next = 0;
395        for (index, kept) in kept.iter().enumerate() {
396            if *kept {
397                renumbered[index] = next;
398                next += 1;
399            }
400        }
401        let features = self
402            .names
403            .into_iter()
404            .zip(self.weights)
405            .zip(&kept)
406            .filter(|(_, kept)| **kept)
407            .map(|(feature, _)| feature)
408            .collect();
409        let pairs = match pairs {
410            PairWeights::Exact(pairs) => PairWeights::Exact(
411                pairs
412                    .into_iter()
413                    .map(|((one, other), weight)| {
414                        (
415                            (renumbered[one as usize], renumbered[other as usize]),
416                            weight,
417                        )
418                    })
419                    .collect(),
420            ),
421            hashed => hashed,
422        };
423        // What was valid stays valid: the order of the features and of the
424        // pairs is kept, and the unit was checked when it was given.
425        let unit = self.unit;
426        let mut model = Self::new(self.schema, self.feature_set, self.bias, features, pairs)
427            .expect("a model without what has no weight is a model");
428        model.unit = unit;
429        model
430    }
431
432    /// The schema of the dictionary the model is for.
433    ///
434    /// # Returns
435    ///
436    /// The schema.
437    pub fn schema(&self) -> &Schema {
438        &self.schema
439    }
440
441    /// The groups of features the weights are for.
442    ///
443    /// # Returns
444    ///
445    /// The feature set.
446    pub fn feature_set(&self) -> &FeatureSet {
447        &self.feature_set
448    }
449
450    /// The bias.
451    ///
452    /// # Returns
453    ///
454    /// The bias.
455    pub fn bias(&self) -> f64 {
456        self.bias
457    }
458
459    /// The unit of the weights: what their sum is multiplied by before the
460    /// bias is added. See [`ParserModel::with_unit`].
461    ///
462    /// # Returns
463    ///
464    /// The unit; 1 unless one was given.
465    pub fn unit(&self) -> f64 {
466        self.unit
467    }
468
469    /// The number of features of the model.
470    ///
471    /// # Returns
472    ///
473    /// The number of feature strings.
474    pub fn feature_count(&self) -> usize {
475        self.names.len()
476    }
477
478    /// The weights of the pairs.
479    ///
480    /// # Returns
481    ///
482    /// The weights.
483    pub fn pairs(&self) -> &PairWeights {
484        &self.pairs
485    }
486
487    /// The number of weights of pairs that are not 0.
488    ///
489    /// # Returns
490    ///
491    /// The number of weights: of pairs for an exact table, of places for a
492    /// hashed one.
493    pub fn pair_count(&self) -> usize {
494        match &self.pairs {
495            PairWeights::Exact(pairs) => pairs.iter().filter(|(_, weight)| *weight != 0.0).count(),
496            PairWeights::Hashed { weights, .. } => {
497                weights.iter().filter(|weight| **weight != 0.0).count()
498            }
499        }
500    }
501
502    /// The step of a quantization: what a whole number is multiplied by
503    /// to give a weight. In a model file the scale of the weights is this
504    /// step times the unit of the model.
505    fn scale(&self, quantization: Quantization) -> f64 {
506        let Some(largest) = quantization.largest() else {
507            return 1.0;
508        };
509        let pairs: Box<dyn Iterator<Item = f32> + '_> = match &self.pairs {
510            PairWeights::Exact(pairs) => Box::new(pairs.iter().map(|(_, weight)| *weight)),
511            PairWeights::Hashed { weights, .. } => Box::new(weights.iter().copied()),
512        };
513        let highest = self
514            .weights
515            .iter()
516            .copied()
517            .chain(pairs)
518            .fold(0.0f32, |highest, weight| highest.max(weight.abs()));
519        if highest == 0.0 {
520            1.0
521        } else {
522            f64::from(highest) / largest
523        }
524    }
525
526    /// Appends the model to bytes, as the parser part of a model file.
527    ///
528    /// The feature set, the quantization, the bias, the scale, the table
529    /// of the feature strings with their weights, and the weights of the
530    /// pairs. The schema is not written: a model file holds it once. The
531    /// same model gives the same bytes.
532    ///
533    /// # Arguments
534    ///
535    /// * `bytes` - The bytes to append to.
536    /// * `quantization` - How the weights are written.
537    pub(crate) fn write_part(&self, bytes: &mut Vec<u8>, quantization: Quantization) {
538        let scale = self.scale(quantization);
539        // What a written weight is multiplied by: the step of the
540        // quantization, and the unit of the model.
541        let written_scale = scale * self.unit;
542        push_string(bytes, &self.feature_set.to_string());
543        bytes.push(quantization.code());
544        bytes.push(match self.pairs {
545            PairWeights::Exact(_) => PAIRS_EXACT,
546            PairWeights::Hashed { .. } => PAIRS_HASHED,
547        });
548        bytes.extend_from_slice(&self.bias.to_le_bytes());
549        bytes.extend_from_slice(&written_scale.to_le_bytes());
550
551        // The value of a feature: its weight, and with hashed pairs its
552        // key, so that a pair is hashed without reading a string.
553        let hashed = matches!(self.pairs, PairWeights::Hashed { .. });
554        let width = quantization.width() + if hashed { 4 } else { 0 };
555        let values: Vec<Vec<u8>> = self
556            .weights
557            .iter()
558            .zip(&self.keys)
559            .map(|(weight, key)| {
560                let mut value = Vec::with_capacity(width);
561                quantization.push(&mut value, *weight, scale);
562                if hashed {
563                    value.extend_from_slice(&key.to_le_bytes());
564                }
565                value
566            })
567            .collect();
568        let entries: Vec<(&str, &[u8])> = self
569            .names
570            .iter()
571            .zip(&values)
572            .map(|(name, value)| (name.as_str(), value.as_slice()))
573            .collect();
574        table::write(bytes, width, &entries);
575
576        match &self.pairs {
577            PairWeights::Exact(pairs) => {
578                // The pairs by the smaller number: where the pairs of each
579                // feature start, then the larger numbers, then the weights.
580                bytes.extend_from_slice(&(pairs.len() as u64).to_le_bytes());
581                let mut offsets = vec![0u32; self.names.len() + 1];
582                for ((one, _), _) in pairs {
583                    offsets[*one as usize + 1] += 1;
584                }
585                let mut total = 0;
586                for offset in &mut offsets {
587                    total += *offset;
588                    *offset = total;
589                }
590                for offset in offsets {
591                    push_u32(bytes, offset);
592                }
593                for ((_, other), _) in pairs {
594                    push_u32(bytes, *other);
595                }
596                for (_, weight) in pairs {
597                    quantization.push(bytes, *weight, scale);
598                }
599            }
600            PairWeights::Hashed { bits, weights } => {
601                push_u32(bytes, *bits);
602                for weight in weights {
603                    quantization.push(bytes, *weight, scale);
604                }
605            }
606        }
607    }
608}
609
610impl Classifier for ParserModel {
611    fn id(&self, feature: &str) -> Option<u32> {
612        self.numbers.get(feature).copied()
613    }
614
615    fn score(&self, features: &[u32]) -> f64 {
616        // The sum of the weights first, then the bias, in the order the
617        // parser part of a model file adds them.
618        let mut sum = 0.0;
619        for &feature in features {
620            sum += self
621                .weights
622                .get(feature as usize)
623                .map_or(0.0, |weight| f64::from(*weight));
624        }
625        match &self.pairs {
626            PairWeights::Exact(_) => {
627                for (index, &one) in features.iter().enumerate() {
628                    for &other in &features[index + 1..] {
629                        if let Some(weight) = self.exact.get(&(one, other)) {
630                            sum += f64::from(*weight);
631                        }
632                    }
633                }
634            }
635            PairWeights::Hashed { bits, weights } => {
636                for (index, &one) in features.iter().enumerate() {
637                    let Some(&one) = self.keys.get(one as usize) else {
638                        continue;
639                    };
640                    for &other in &features[index + 1..] {
641                        if let Some(&other) = self.keys.get(other as usize) {
642                            sum += f64::from(weights[bucket(one, other, *bits) as usize]);
643                        }
644                    }
645                }
646            }
647        }
648        self.bias + self.unit * sum
649    }
650}
651
652/// The code of an exact table of pairs in a model file.
653const PAIRS_EXACT: u8 = 0;
654/// The code of a hashed table of pairs in a model file.
655const PAIRS_HASHED: u8 = 1;
656
657/// Where the weights of the pairs are in the bytes of a model.
658#[derive(Debug, Clone, PartialEq, Eq)]
659enum PairsLayout {
660    /// Each pair with a weight of its own, by the smaller number.
661    Exact {
662        /// Where the pairs of each feature start: one more than features.
663        offsets: Range<usize>,
664        /// The larger number of each pair.
665        columns: Range<usize>,
666        /// The weight of each pair.
667        weights: Range<usize>,
668    },
669    /// A table the pairs are hashed into.
670    Hashed {
671        /// The size of the table, as a power of two.
672        bits: u32,
673        /// The weights.
674        weights: Range<usize>,
675    },
676}
677
678/// The parser part of a model: what is small is read, and the tables of
679/// the weights are where they are in the bytes.
680#[derive(Debug, Clone, PartialEq)]
681pub(crate) struct ParserLayout {
682    /// The groups of features the weights are for.
683    feature_set: FeatureSet,
684    /// How the weights are written.
685    quantization: Quantization,
686    /// The bias.
687    bias: f64,
688    /// What a weight as it is written is multiplied by.
689    scale: f64,
690    /// The table of the feature strings.
691    features: Layout,
692    /// The weights of the pairs.
693    pairs: PairsLayout,
694}
695
696/// A number of 4 bytes in an array of them; 0 past the end of the array.
697#[inline]
698fn read_u32(bytes: &[u8], index: usize) -> u32 {
699    let start = index.saturating_mul(4);
700    bytes
701        .get(start..start.saturating_add(4))
702        .and_then(|bytes| bytes.try_into().ok())
703        .map_or(0, u32::from_le_bytes)
704}
705
706impl ParserLayout {
707    /// Reads and checks a parser part.
708    ///
709    /// # Arguments
710    ///
711    /// * `part` - The bytes of the part.
712    /// * `base` - The position of the first byte of the part in the bytes
713    ///   of the model.
714    ///
715    /// # Returns
716    ///
717    /// The layout, or [`Error::Model`] for bytes that are not a parser
718    /// part: a feature set that cannot be read, an unknown quantization or
719    /// table of pairs, a bias, a scale or a weight that is not finite, a
720    /// scale that is not above 0, a
721    /// table that is not one, pairs that are not sorted by their features,
722    /// or bytes after the weights.
723    pub(crate) fn read(part: &[u8], base: usize) -> Result<Self> {
724        let mut reader = Reader::new(part, "model", Error::Model);
725        let feature_set = FeatureSet::parse(&reader.string()?).map_err(|error| {
726            reader.error(format_args!("has a feature set that is not one: {error}"))
727        })?;
728        let code = reader.u8()?;
729        let quantization = Quantization::from_code(code)
730            .ok_or_else(|| reader.error(format_args!("has the unknown quantization {code}")))?;
731        let kind = reader.u8()?;
732        let bias = reader.f64()?;
733        let scale = reader.f64()?;
734        if !(bias.is_finite() && scale.is_finite()) {
735            return Err(reader.error("has a weight that is not finite"));
736        }
737        if scale <= 0.0 {
738            return Err(reader.error(format_args!("has the scale {scale}, which is not above 0")));
739        }
740        let width = quantization.width();
741
742        let hashed = match kind {
743            PAIRS_EXACT => false,
744            PAIRS_HASHED => true,
745            _ => {
746                return Err(reader.error(format_args!("has the unknown table of pairs {kind}")));
747            }
748        };
749        let features = Layout::read(&mut reader, width + if hashed { 4 } else { 0 })?;
750        let count = features.table(part).len();
751
752        let (pairs, weights) = if hashed {
753            let bits = reader.u32()?;
754            if !(1..=30).contains(&bits) {
755                return Err(
756                    reader.error(format_args!("has a table of hashed pairs of {bits} bits"))
757                );
758            }
759            let start = reader.position();
760            let weights = reader.take((1usize << bits).saturating_mul(width))?;
761            (
762                PairsLayout::Hashed {
763                    bits,
764                    weights: start..reader.position(),
765                },
766                weights,
767            )
768        } else {
769            let pair_count = usize::try_from(reader.u64()?)
770                .map_err(|_| reader.error("has more pairs than can be read"))?;
771            let start = reader.position();
772            let offsets = reader.take((count + 1).saturating_mul(4))?;
773            let offsets_range = start..reader.position();
774            let start = reader.position();
775            let columns = reader.take(pair_count.saturating_mul(4))?;
776            let columns_range = start..reader.position();
777            let start = reader.position();
778            let weights = reader.take(pair_count.saturating_mul(width))?;
779            let weights_range = start..reader.position();
780
781            // The pairs of a feature follow those of the feature before,
782            // and name larger features, in their order.
783            let mut end = 0;
784            for feature in 0..count {
785                let from = read_u32(offsets, feature) as usize;
786                let to = read_u32(offsets, feature + 1) as usize;
787                // An offset past the pairs is refused before its pairs are
788                // walked: bytes that claim a huge one do not keep the
789                // reading busy.
790                if from != end || to < from || to > pair_count {
791                    return Err(
792                        reader.error("has pairs that are not in the order of their features")
793                    );
794                }
795                end = to;
796                let mut before = feature as u32;
797                for index in from..to {
798                    let other = read_u32(columns, index);
799                    if other <= before || other as usize >= count {
800                        return Err(
801                            reader.error("has pairs that are not in the order of their features")
802                        );
803                    }
804                    before = other;
805                }
806            }
807            if end != pair_count {
808                return Err(reader.error("has pairs that are not in the order of their features"));
809            }
810            (
811                PairsLayout::Exact {
812                    offsets: offsets_range,
813                    columns: columns_range,
814                    weights: weights_range,
815                },
816                weights,
817            )
818        };
819        if reader.remaining() != 0 {
820            return Err(reader.error(format_args!(
821                "has {} bytes after its parser",
822                reader.remaining()
823            )));
824        }
825
826        if quantization == Quantization::F32 {
827            let table = features.table(part);
828            let finite = (0..count)
829                .all(|index| quantization.read(table.value(index), 0).is_finite())
830                && (0..weights.len() / 4)
831                    .all(|index| quantization.read(weights, index).is_finite());
832            if !finite {
833                return Err(reader.error("has a weight that is not finite"));
834            }
835        }
836
837        let shift = |range: Range<usize>| base + range.start..base + range.end;
838        Ok(Self {
839            feature_set,
840            quantization,
841            bias,
842            scale,
843            features: features.shifted(base),
844            pairs: match pairs {
845                PairsLayout::Exact {
846                    offsets,
847                    columns,
848                    weights,
849                } => PairsLayout::Exact {
850                    offsets: shift(offsets),
851                    columns: shift(columns),
852                    weights: shift(weights),
853                },
854                PairsLayout::Hashed { bits, weights } => PairsLayout::Hashed {
855                    bits,
856                    weights: shift(weights),
857                },
858            },
859        })
860    }
861
862    /// The groups of features the weights are for.
863    pub(crate) fn feature_set(&self) -> &FeatureSet {
864        &self.feature_set
865    }
866
867    /// The part on the bytes of its model.
868    ///
869    /// # Arguments
870    ///
871    /// * `bytes` - The bytes of the model the layout was read from.
872    ///
873    /// # Returns
874    ///
875    /// The part.
876    pub(crate) fn part<'a>(&'a self, bytes: &'a [u8]) -> ParserPart<'a> {
877        let piece = |range: &Range<usize>| bytes.get(range.clone()).unwrap_or_default();
878        ParserPart {
879            layout: self,
880            features: self.features.table(bytes),
881            pairs: match &self.pairs {
882                PairsLayout::Exact {
883                    offsets,
884                    columns,
885                    weights,
886                } => PairsPart::Exact {
887                    offsets: piece(offsets),
888                    columns: piece(columns),
889                    weights: piece(weights),
890                },
891                PairsLayout::Hashed { bits, weights } => PairsPart::Hashed {
892                    bits: *bits,
893                    weights: piece(weights),
894                },
895            },
896        }
897    }
898}
899
900/// The weights of the pairs on the bytes of a model.
901#[derive(Debug, Clone, Copy)]
902enum PairsPart<'a> {
903    /// Each pair with a weight of its own.
904    Exact {
905        /// Where the pairs of each feature start.
906        offsets: &'a [u8],
907        /// The larger number of each pair.
908        columns: &'a [u8],
909        /// The weight of each pair.
910        weights: &'a [u8],
911    },
912    /// A table the pairs are hashed into.
913    Hashed {
914        /// The size of the table, as a power of two.
915        bits: u32,
916        /// The weights.
917        weights: &'a [u8],
918    },
919}
920
921/// The parser part of a model file, read on the bytes of the file: the
922/// classifier of the parser that
923/// [`Model::parser`](crate::model::Model::parser) gives.
924#[derive(Debug, Clone, Copy)]
925pub struct ParserPart<'a> {
926    /// What is small of the part.
927    layout: &'a ParserLayout,
928    /// The table of the feature strings.
929    features: Table<'a>,
930    /// The weights of the pairs.
931    pairs: PairsPart<'a>,
932}
933
934impl ParserPart<'_> {
935    /// The number of features of the part.
936    ///
937    /// # Returns
938    ///
939    /// The number of feature strings.
940    pub fn feature_count(&self) -> usize {
941        self.features.len()
942    }
943
944    /// The number of weights of pairs of the part: of pairs for an exact
945    /// table, of places for a hashed one.
946    ///
947    /// # Returns
948    ///
949    /// The number of weights, those that are 0 included.
950    pub fn pair_count(&self) -> usize {
951        match self.pairs {
952            PairsPart::Exact { columns, .. } => columns.len() / 4,
953            PairsPart::Hashed { bits, .. } => 1usize << bits,
954        }
955    }
956
957    /// How the weights of the part are written.
958    ///
959    /// # Returns
960    ///
961    /// The quantization.
962    pub fn quantization(&self) -> Quantization {
963        self.layout.quantization
964    }
965}
966
967impl Classifier for ParserPart<'_> {
968    fn id(&self, feature: &str) -> Option<u32> {
969        self.features.find(feature).map(|index| index as u32)
970    }
971
972    fn score(&self, features: &[u32]) -> f64 {
973        let quantization = self.layout.quantization;
974        let mut sum = 0.0;
975        for &feature in features {
976            sum += quantization.read(self.features.value(feature as usize), 0);
977        }
978        match self.pairs {
979            PairsPart::Exact {
980                offsets,
981                columns,
982                weights,
983            } => {
984                for (index, &one) in features.iter().enumerate() {
985                    let mut from = read_u32(offsets, one as usize) as usize;
986                    let to = read_u32(offsets, one as usize + 1) as usize;
987                    // The other features are sorted, as the pairs of this
988                    // one are: each is looked for after the one before.
989                    for &other in &features[index + 1..] {
990                        if from >= to {
991                            break;
992                        }
993                        let (mut low, mut high) = (from, to);
994                        while low < high {
995                            let middle = low + (high - low) / 2;
996                            if read_u32(columns, middle) < other {
997                                low = middle + 1;
998                            } else {
999                                high = middle;
1000                            }
1001                        }
1002                        from = low;
1003                        if low < to && read_u32(columns, low) == other {
1004                            sum += quantization.read(weights, low);
1005                            from = low + 1;
1006                        }
1007                    }
1008                }
1009            }
1010            PairsPart::Hashed { bits, weights } => {
1011                let width = quantization.width();
1012                let key = |feature: u32| {
1013                    self.features
1014                        .value(feature as usize)
1015                        .get(width..width + 4)
1016                        .and_then(|bytes| bytes.try_into().ok())
1017                        .map(u32::from_le_bytes)
1018                };
1019                for (index, &one) in features.iter().enumerate() {
1020                    let Some(one) = key(one) else {
1021                        continue;
1022                    };
1023                    for &other in &features[index + 1..] {
1024                        if let Some(other) = key(other) {
1025                            sum += quantization.read(weights, bucket(one, other, bits) as usize);
1026                        }
1027                    }
1028                }
1029            }
1030        }
1031        self.layout.bias + self.layout.scale * sum
1032    }
1033}
1034
1035#[cfg(test)]
1036pub(crate) mod tests {
1037    use super::*;
1038
1039    /// The four features of the models of these tests, sorted.
1040    pub(crate) const NAMES: [&str; 4] = ["DIST:1", "SFS:は", "SFS:を", "a:が"];
1041
1042    /// The features with their weights.
1043    fn features() -> Vec<(String, f32)> {
1044        NAMES
1045            .iter()
1046            .zip([0.5, -1.25, 2.0, 0.0])
1047            .map(|(name, weight)| (name.to_string(), weight))
1048            .collect()
1049    }
1050
1051    /// A model with a weight of its own for three pairs.
1052    pub(crate) fn exact() -> ParserModel {
1053        ParserModel::new(
1054            Schema::ipadic(),
1055            FeatureSet::default(),
1056            -1.0,
1057            features(),
1058            PairWeights::Exact(vec![((0, 2), 1.5), ((1, 3), -0.75), ((2, 3), 0.25)]),
1059        )
1060        .unwrap()
1061    }
1062
1063    /// A model with a table of 16 weights the pairs are hashed into.
1064    pub(crate) fn hashed() -> ParserModel {
1065        ParserModel::new(
1066            Schema::ipadic(),
1067            FeatureSet::cabocha(),
1068            0.25,
1069            features(),
1070            PairWeights::Hashed {
1071                bits: 4,
1072                weights: (0..16).map(|index| index as f32 * 0.125 - 1.0).collect(),
1073            },
1074        )
1075        .unwrap()
1076    }
1077
1078    /// The bytes of the parser part of a model.
1079    fn part(model: &ParserModel, quantization: Quantization) -> Vec<u8> {
1080        let mut part = Vec::new();
1081        model.write_part(&mut part, quantization);
1082        part
1083    }
1084
1085    /// Every set of the four features, as sorted numbers.
1086    fn subsets() -> Vec<Vec<u32>> {
1087        (0..16u32)
1088            .map(|mask| (0..4).filter(|bit| mask & (1 << bit) != 0).collect())
1089            .collect()
1090    }
1091
1092    /// The message of the error of bytes that are not a parser part.
1093    fn error(part: &[u8]) -> String {
1094        let error = ParserLayout::read(part, 0).unwrap_err();
1095        assert!(matches!(error, Error::Model(_)), "{error:?}");
1096        error.to_string()
1097    }
1098
1099    /// The message of the error of what is not a model.
1100    fn refused(bias: f64, features: Vec<(String, f32)>, pairs: PairWeights) -> String {
1101        let error = ParserModel::new(
1102            Schema::ipadic(),
1103            FeatureSet::default(),
1104            bias,
1105            features,
1106            pairs,
1107        )
1108        .unwrap_err();
1109        assert!(matches!(error, Error::Parser(_)), "{error:?}");
1110        error.to_string()
1111    }
1112
1113    #[test]
1114    fn a_model_scores_a_bias_its_features_and_their_pairs() {
1115        let model = exact();
1116        for (index, name) in NAMES.iter().enumerate() {
1117            assert_eq!(model.id(name), Some(index as u32));
1118        }
1119        assert_eq!(model.id("SFS:が"), None);
1120        assert_eq!(model.score(&[]), -1.0);
1121        assert_eq!(model.score(&[0]), -0.5);
1122        // The bias, 0.5 and 2.0, and the pair of the two, 1.5.
1123        assert_eq!(model.score(&[0, 2]), 3.0);
1124        assert_eq!(model.score(&[1, 3]), -3.0);
1125        assert_eq!(model.score(&[0, 1, 2, 3]), 1.25);
1126        // A number that is no feature adds nothing.
1127        assert_eq!(model.score(&[0, 9]), -0.5);
1128        assert_eq!(model.bias(), -1.0);
1129        assert_eq!(model.feature_count(), 4);
1130        assert_eq!(model.pair_count(), 3);
1131        assert_eq!(model.feature_set(), &FeatureSet::default());
1132        assert_eq!(model.schema(), &Schema::ipadic());
1133    }
1134
1135    #[test]
1136    fn hashed_pairs_share_the_weight_of_their_place() {
1137        let model = hashed();
1138        let keys: Vec<u32> = NAMES.iter().map(|name| feature_key(name)).collect();
1139        let PairWeights::Hashed { bits, weights } = model.pairs() else {
1140            panic!("the pairs are hashed");
1141        };
1142        let weights = weights.clone();
1143        let place = |one: usize, other: usize| bucket(keys[one], keys[other], *bits) as usize;
1144        assert_eq!(
1145            model.score(&[0, 2]),
1146            0.25 + 0.5 + 2.0 + f64::from(weights[place(0, 2)])
1147        );
1148        let all: f64 = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
1149            .iter()
1150            .map(|(one, other)| f64::from(weights[place(*one, *other)]))
1151            .sum();
1152        assert_eq!(model.score(&[0, 1, 2, 3]), 0.25 + (1.25 + all));
1153        // 15 of the 16 places have a weight that is not 0.
1154        assert_eq!(model.pair_count(), 15);
1155    }
1156
1157    #[test]
1158    fn the_place_of_a_pair_is_the_same_for_its_two_orders() {
1159        // The key of a feature is the hash of the tables: of `a`, the
1160        // 64-bit FNV-1a af63dc4c8601ec8c folded to 32 bits.
1161        assert_eq!(feature_key("a"), 0xaf63_dc4c ^ 0x8601_ec8c);
1162        let (one, other) = (feature_key("SFS:は"), feature_key("DIST:1"));
1163        for bits in [1, 4, 22, 30] {
1164            let place = bucket(one, other, bits);
1165            assert_eq!(place, bucket(other, one, bits));
1166            assert!(place < 1 << bits);
1167        }
1168        // More bits keep the first ones: a table twice as large splits
1169        // each place in two.
1170        assert_eq!(bucket(one, other, 22) >> 2, bucket(one, other, 20));
1171        // The two keys, the smaller first, mixed by two multiplications.
1172        let mut value = (u64::from(one.min(other)) << 32) | u64::from(one.max(other));
1173        value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1174        value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1175        assert_eq!(bucket(one, other, 30), (value >> 34) as u32);
1176        // The place of two keys, as a number to hold the format to.
1177        assert_eq!(bucket(1, 2, 16), {
1178            let mut value = (1u64 << 32) | 2;
1179            value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1180            value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1181            (value >> 48) as u32
1182        });
1183        // Pairs of the four features do not all fall on one place.
1184        let keys: Vec<u32> = NAMES.iter().map(|name| feature_key(name)).collect();
1185        let mut places: Vec<u32> = vec![
1186            bucket(keys[0], keys[1], 4),
1187            bucket(keys[0], keys[2], 4),
1188            bucket(keys[1], keys[2], 4),
1189            bucket(keys[2], keys[3], 4),
1190        ];
1191        places.dedup();
1192        assert!(places.len() > 1);
1193    }
1194
1195    #[test]
1196    fn what_is_not_a_model_is_refused() {
1197        let pairs = || PairWeights::Exact(vec![((0, 2), 1.5)]);
1198        assert_eq!(
1199            refused(f64::NAN, features(), pairs()),
1200            "a weight is not finite"
1201        );
1202        let mut other = features();
1203        other[1].1 = f32::INFINITY;
1204        assert_eq!(refused(0.0, other, pairs()), "a weight is not finite");
1205        assert_eq!(
1206            refused(
1207                0.0,
1208                features(),
1209                PairWeights::Exact(vec![((0, 2), f32::NAN)])
1210            ),
1211            "a weight is not finite"
1212        );
1213        let table = |weight: f32| PairWeights::Hashed {
1214            bits: 1,
1215            weights: vec![0.0, weight],
1216        };
1217        assert_eq!(
1218            refused(0.0, features(), table(f32::NEG_INFINITY)),
1219            "a weight is not finite"
1220        );
1221        assert!(
1222            ParserModel::new(
1223                Schema::ipadic(),
1224                FeatureSet::default(),
1225                0.0,
1226                features(),
1227                table(1.0)
1228            )
1229            .is_ok()
1230        );
1231
1232        // Features in another order, and a feature twice.
1233        for (one, other) in [(0, 1), (1, 1)] {
1234            let mut unsorted = features();
1235            unsorted[one].0 = features()[other].0.clone();
1236            unsorted[other].0 = features()[one].0.clone();
1237            if one == other {
1238                unsorted[0].0 = unsorted[1].0.clone();
1239            }
1240            assert_eq!(
1241                refused(0.0, unsorted, pairs()),
1242                "the features are not sorted, each once"
1243            );
1244        }
1245
1246        // A pair of a feature with itself, the larger number first, and a
1247        // feature that is not there.
1248        for pair in [(1, 1), (2, 0), (0, 4)] {
1249            assert_eq!(
1250                refused(0.0, features(), PairWeights::Exact(vec![(pair, 1.0)])),
1251                "a pair does not name two features, the smaller number first"
1252            );
1253        }
1254        // Pairs in another order, and a pair twice.
1255        for pairs in [[(1, 3), (0, 2)], [(0, 2), (0, 2)]] {
1256            let pairs = pairs.iter().map(|pair| (*pair, 1.0)).collect();
1257            assert_eq!(
1258                refused(0.0, features(), PairWeights::Exact(pairs)),
1259                "the pairs are not sorted, each once"
1260            );
1261        }
1262
1263        // A table that has not 2^bits weights, and no bits or too many.
1264        for (bits, count) in [(2, 3), (2, 5), (0, 1), (31, 2)] {
1265            let table = PairWeights::Hashed {
1266                bits,
1267                weights: vec![0.0; count],
1268            };
1269            assert_eq!(
1270                refused(0.0, features(), table),
1271                format!("a table of hashed pairs of {bits} bits has {count} weights")
1272            );
1273        }
1274    }
1275
1276    #[test]
1277    fn a_compact_model_has_only_what_has_a_weight() {
1278        // Of five features, `b` has no weight and is in no pair with one,
1279        // and `d` has no weight but is in a pair.
1280        let features: Vec<(String, f32)> = ["a", "b", "c", "d", "e"]
1281            .iter()
1282            .zip([1.0, 0.0, -2.0, 0.0, 0.5])
1283            .map(|(name, weight)| (name.to_string(), weight))
1284            .collect();
1285        let model = ParserModel::new(
1286            Schema::ipadic(),
1287            FeatureSet::default(),
1288            0.5,
1289            features.clone(),
1290            PairWeights::Exact(vec![((0, 1), 0.0), ((0, 4), 3.0), ((2, 3), -1.0)]),
1291        )
1292        .unwrap();
1293        let before: Vec<f64> = [vec![0, 4], vec![2, 3], vec![0, 1, 2, 3, 4]]
1294            .iter()
1295            .map(|features| model.score(features))
1296            .collect();
1297        let compact = model.compact();
1298        assert_eq!(compact.feature_count(), 4);
1299        assert_eq!(compact.id("b"), None);
1300        // The numbers follow the order that is left: a, c, d, e.
1301        assert_eq!(compact.id("c"), Some(1));
1302        assert_eq!(compact.id("d"), Some(2));
1303        assert_eq!(
1304            compact.pairs(),
1305            &PairWeights::Exact(vec![((0, 3), 3.0), ((1, 2), -1.0)])
1306        );
1307        let after: Vec<f64> = [vec![0, 3], vec![1, 2], vec![0, 1, 2, 3]]
1308            .iter()
1309            .map(|features| compact.score(features))
1310            .collect();
1311        assert_eq!(after, before);
1312        // Nothing more is taken out of it.
1313        assert_eq!(compact.clone().compact(), compact);
1314
1315        // With hashed pairs, a feature without a weight is taken out, and
1316        // the table stays.
1317        let table = PairWeights::Hashed {
1318            bits: 2,
1319            weights: vec![0.0, 1.0, 0.0, -1.0],
1320        };
1321        let model = ParserModel::new(
1322            Schema::ipadic(),
1323            FeatureSet::default(),
1324            0.5,
1325            features,
1326            table.clone(),
1327        )
1328        .unwrap()
1329        .compact();
1330        assert_eq!(model.feature_count(), 3);
1331        assert_eq!(model.id("d"), None);
1332        assert_eq!(model.pairs(), &table);
1333    }
1334
1335    #[test]
1336    fn a_quantization_has_a_name_and_a_code() {
1337        for (quantization, name, code) in Quantization::ALL {
1338            assert_eq!(quantization.name(), name);
1339            assert_eq!(Quantization::from_name(name), Some(quantization));
1340            assert_eq!(quantization.code(), code);
1341            assert_eq!(Quantization::from_code(code), Some(quantization));
1342        }
1343        // The names are those of the command, and the codes those of a
1344        // model file.
1345        assert_eq!(Quantization::from_name("f32"), Some(Quantization::F32));
1346        assert_eq!(Quantization::from_name("i16"), Some(Quantization::I16));
1347        assert_eq!(Quantization::from_name("i8"), Some(Quantization::I8));
1348        assert_eq!(
1349            [
1350                Quantization::F32.code(),
1351                Quantization::I16.code(),
1352                Quantization::I8.code()
1353            ],
1354            [0, 1, 2]
1355        );
1356        assert_eq!(Quantization::from_name("f64"), None);
1357        assert_eq!(Quantization::from_code(3), None);
1358        assert_eq!(
1359            [
1360                Quantization::F32.width(),
1361                Quantization::I16.width(),
1362                Quantization::I8.width()
1363            ],
1364            [4, 2, 1]
1365        );
1366    }
1367
1368    #[test]
1369    fn the_part_of_a_file_scores_as_the_model_in_memory() {
1370        for model in [exact(), hashed()] {
1371            let bytes = part(&model, Quantization::F32);
1372            let layout = ParserLayout::read(&bytes, 0).unwrap();
1373            let read = layout.part(&bytes);
1374            assert_eq!(layout.feature_set(), model.feature_set());
1375            assert_eq!(read.feature_count(), 4);
1376            assert_eq!(read.quantization(), Quantization::F32);
1377            for (index, name) in NAMES.iter().enumerate() {
1378                assert_eq!(read.id(name), Some(index as u32));
1379            }
1380            assert_eq!(read.id("SFS:が"), None);
1381            // Without quantization, to the last bit.
1382            for features in subsets() {
1383                assert_eq!(
1384                    read.score(&features).to_bits(),
1385                    model.score(&features).to_bits(),
1386                    "{features:?}"
1387                );
1388            }
1389            // The same model gives the same bytes.
1390            assert_eq!(part(&model.clone(), Quantization::F32), bytes);
1391        }
1392        let bytes = part(&exact(), Quantization::F32);
1393        assert_eq!(
1394            ParserLayout::read(&bytes, 0)
1395                .unwrap()
1396                .part(&bytes)
1397                .pair_count(),
1398            3
1399        );
1400        let bytes = part(&hashed(), Quantization::F32);
1401        assert_eq!(
1402            ParserLayout::read(&bytes, 0)
1403                .unwrap()
1404                .part(&bytes)
1405                .pair_count(),
1406            16
1407        );
1408    }
1409
1410    #[test]
1411    fn the_weights_of_a_model_with_a_unit_are_multiplied_by_it() {
1412        // Whole numbers, and a unit that is not a power of two.
1413        let whole = ParserModel::new(
1414            Schema::ipadic(),
1415            FeatureSet::cabocha(),
1416            -3.0 * 0.3,
1417            NAMES
1418                .iter()
1419                .zip([2.0, -5.0, 8.0, 0.0])
1420                .map(|(name, weight)| (name.to_string(), weight))
1421                .collect(),
1422            PairWeights::Exact(vec![((0, 2), 6.0), ((1, 3), -3.0), ((2, 3), 1.0)]),
1423        )
1424        .unwrap();
1425        assert_eq!(whole.unit(), 1.0);
1426        let model = whole.clone().with_unit(0.3).unwrap();
1427        assert_eq!(model.unit(), 0.3);
1428        assert_ne!(model, whole);
1429        // The bias is not in the unit: -0.9 + 0.3 × (2 + 8 + 6).
1430        assert_eq!(model.score(&[0, 2]), -3.0 * 0.3 + 0.3 * 16.0);
1431        assert_eq!(model.score(&[]), -3.0 * 0.3);
1432        // A sum of whole numbers that is the bias in units gives 0, and
1433        // not a rounding error: the two are multiplied by the same unit.
1434        let three = ParserModel::new(
1435            Schema::ipadic(),
1436            FeatureSet::cabocha(),
1437            -3.0 * 0.3,
1438            vec![("a".to_string(), 3.0)],
1439            PairWeights::Exact(Vec::new()),
1440        )
1441        .unwrap()
1442        .with_unit(0.3)
1443        .unwrap();
1444        assert_eq!(three.score(&[0]), 0.0);
1445
1446        // The part of a file scores the same, to the last bit, and its
1447        // scale is the unit.
1448        let bytes = part(&model, Quantization::F32);
1449        let layout = ParserLayout::read(&bytes, 0).unwrap();
1450        assert_eq!(layout.scale, 0.3);
1451        let read = layout.part(&bytes);
1452        for features in subsets() {
1453            assert_eq!(
1454                read.score(&features).to_bits(),
1455                model.score(&features).to_bits(),
1456                "{features:?}"
1457            );
1458        }
1459        // Quantized, the scale is the step of the whole numbers times the
1460        // unit: the largest weight, 8, is 127.
1461        let bytes = part(&model, Quantization::I8);
1462        let layout = ParserLayout::read(&bytes, 0).unwrap();
1463        assert_eq!(layout.scale, 8.0 / 127.0 * 0.3);
1464        let read = layout.part(&bytes);
1465        assert!((read.score(&[0, 2]) - model.score(&[0, 2])).abs() < 0.3 * 8.0 / 127.0 * 2.0);
1466
1467        // The unit stays when what has no weight is dropped.
1468        let compact = model.clone().compact();
1469        assert_eq!(compact.unit(), 0.3);
1470        assert_eq!(compact.feature_count(), 4);
1471        // A model without a unit has the bytes it had before there was one.
1472        let bytes = part(&whole, Quantization::F32);
1473        assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 1.0);
1474    }
1475
1476    #[test]
1477    fn refuses_a_unit_that_is_not_one() {
1478        for unit in [0.0, -1.0, f64::NAN, f64::INFINITY] {
1479            let error = exact().with_unit(unit).unwrap_err();
1480            assert!(matches!(error, Error::Parser(_)), "{error:?}");
1481            assert!(
1482                error.to_string().contains("has to be greater than 0"),
1483                "{error}"
1484            );
1485        }
1486    }
1487
1488    #[test]
1489    fn quantized_weights_are_whole_numbers_times_a_scale() {
1490        for model in [exact(), hashed()] {
1491            let sizes: Vec<usize> = Quantization::ALL
1492                .iter()
1493                .map(|(quantization, _, _)| part(&model, *quantization).len())
1494                .collect();
1495            assert!(sizes[0] > sizes[1] && sizes[1] > sizes[2], "{sizes:?}");
1496
1497            for (quantization, largest) in [(Quantization::I16, 32767.0), (Quantization::I8, 127.0)]
1498            {
1499                let bytes = part(&model, quantization);
1500                let layout = ParserLayout::read(&bytes, 0).unwrap();
1501                let read = layout.part(&bytes);
1502                assert_eq!(read.quantization(), quantization);
1503                // The largest weight of both models is 2.0.
1504                let scale = 2.0 / largest;
1505                assert_eq!(layout.scale, scale);
1506                for features in subsets() {
1507                    // A weight is off by half a step at most: the four
1508                    // features and their six pairs.
1509                    let weights =
1510                        features.len() + features.len() * features.len().saturating_sub(1) / 2;
1511                    let difference = (read.score(&features) - model.score(&features)).abs();
1512                    assert!(
1513                        difference <= scale / 2.0 * weights as f64 + 1e-12,
1514                        "{quantization:?} {features:?}: {difference}"
1515                    );
1516                }
1517                // The bias is not quantized.
1518                assert_eq!(read.score(&[]), model.bias());
1519            }
1520        }
1521        // The largest weight becomes the largest whole number: 2.0 of
1522        // `SFS:を` is 127, and -1.25 of `SFS:は` is -79 (-79.4).
1523        let bytes = part(&exact(), Quantization::I8);
1524        let read = ParserLayout::read(&bytes, 0).unwrap();
1525        let read = read.part(&bytes);
1526        assert_eq!(read.score(&[2]), -1.0 + 2.0 / 127.0 * 127.0);
1527        assert_eq!(read.score(&[1]), -1.0 + 2.0 / 127.0 * -79.0);
1528        // 0.5 of `DIST:1` is 31.75 steps, and is written as 32: the nearest
1529        // whole number, not the one towards 0.
1530        assert_eq!(read.score(&[0]), -1.0 + 2.0 / 127.0 * 32.0);
1531        // The scale is from the largest weight of all, a pair as well: here
1532        // the pair of 4.0, where the largest feature has 2.0.
1533        let heavy = ParserModel::new(
1534            Schema::ipadic(),
1535            FeatureSet::default(),
1536            0.0,
1537            features(),
1538            PairWeights::Exact(vec![((0, 1), -4.0)]),
1539        )
1540        .unwrap();
1541        let bytes = part(&heavy, Quantization::I8);
1542        assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 4.0 / 127.0);
1543        let table = PairWeights::Hashed {
1544            bits: 1,
1545            weights: vec![0.0, 8.0],
1546        };
1547        let heavy = ParserModel::new(
1548            Schema::ipadic(),
1549            FeatureSet::default(),
1550            0.0,
1551            features(),
1552            table,
1553        )
1554        .unwrap();
1555        let bytes = part(&heavy, Quantization::I16);
1556        assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 8.0 / 32767.0);
1557        // A model without a weight has the scale 1.
1558        let empty = ParserModel::new(
1559            Schema::ipadic(),
1560            FeatureSet::default(),
1561            0.5,
1562            Vec::new(),
1563            PairWeights::Exact(Vec::new()),
1564        )
1565        .unwrap();
1566        let bytes = part(&empty, Quantization::I8);
1567        let layout = ParserLayout::read(&bytes, 0).unwrap();
1568        assert_eq!(layout.scale, 1.0);
1569        assert_eq!(layout.part(&bytes).score(&[]), 0.5);
1570        assert_eq!(layout.part(&bytes).id("a"), None);
1571    }
1572
1573    /// A model of 40 features, with weights from a fixed sequence: every
1574    /// third pair has a weight in the exact table.
1575    fn larger(hashed: bool) -> ParserModel {
1576        let mut state = 0x2545_f491_4f6c_dd1du64;
1577        let mut next = move || {
1578            // Xorshift: any fixed sequence will do.
1579            state ^= state << 13;
1580            state ^= state >> 7;
1581            state ^= state << 17;
1582            ((state % 2001) as f32 - 1000.0) / 250.0
1583        };
1584        let features: Vec<(String, f32)> = (0..40)
1585            .map(|index| (format!("F{index:02}:素性"), next()))
1586            .collect();
1587        let pairs = if hashed {
1588            PairWeights::Hashed {
1589                bits: 7,
1590                weights: (0..128).map(|_| next()).collect(),
1591            }
1592        } else {
1593            let mut pairs = Vec::new();
1594            for one in 0..40u32 {
1595                for other in one + 1..40 {
1596                    if (one * 7 + other) % 3 == 0 {
1597                        pairs.push(((one, other), next()));
1598                    }
1599                }
1600            }
1601            PairWeights::Exact(pairs)
1602        };
1603        ParserModel::new(
1604            Schema::ipadic(),
1605            FeatureSet::default(),
1606            0.125,
1607            features,
1608            pairs,
1609        )
1610        .unwrap()
1611    }
1612
1613    #[test]
1614    fn a_larger_model_scores_the_same_from_a_file() {
1615        for hashed in [false, true] {
1616            let model = larger(hashed);
1617            let bytes = part(&model, Quantization::F32);
1618            let layout = ParserLayout::read(&bytes, 0).unwrap();
1619            let read = layout.part(&bytes);
1620            assert_eq!(read.feature_count(), 40);
1621            // Sets of features of every size, spread over the 40: the
1622            // feature `index` is in the set `mask` when a bit of the mask
1623            // says so.
1624            let mut different = 0;
1625            for mask in 1..400u64 {
1626                let features: Vec<u32> = (0..40u32)
1627                    .filter(|index| (mask.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> index) & 1 == 1)
1628                    .collect();
1629                let (from_file, in_memory) = (read.score(&features), model.score(&features));
1630                assert_eq!(from_file.to_bits(), in_memory.to_bits(), "{features:?}");
1631                different += usize::from(in_memory != model.bias());
1632            }
1633            assert!(different > 390);
1634            // All of them, and each alone.
1635            let all: Vec<u32> = (0..40).collect();
1636            assert_eq!(read.score(&all).to_bits(), model.score(&all).to_bits());
1637            for feature in 0..40 {
1638                assert_eq!(read.score(&[feature]), model.score(&[feature]));
1639                assert_eq!(read.id(&format!("F{feature:02}:素性")), Some(feature));
1640            }
1641        }
1642    }
1643
1644    #[test]
1645    fn the_layout_is_counted_from_the_base() {
1646        for model in [exact(), hashed()] {
1647            let part = part(&model, Quantization::I16);
1648            let mut bytes = vec![0xa5; 13];
1649            bytes.extend_from_slice(&part);
1650            let layout = ParserLayout::read(&part, 13).unwrap();
1651            let read = layout.part(&bytes);
1652            let alone = ParserLayout::read(&part, 0).unwrap();
1653            for features in subsets() {
1654                assert_eq!(read.score(&features), alone.part(&part).score(&features));
1655            }
1656            assert_eq!(read.id("SFS:を"), Some(2));
1657            // On other bytes it finds nothing, and does not panic.
1658            let read = layout.part(&bytes[..20]);
1659            assert_eq!(read.id("SFS:を"), None);
1660            let _ = read.score(&[0, 1, 2, 3]);
1661        }
1662    }
1663
1664    /// The position of the quantization in a part with the default feature
1665    /// set: after the length and the text of the set.
1666    fn after_the_set(model: &ParserModel) -> usize {
1667        4 + model.feature_set().to_string().len()
1668    }
1669
1670    #[test]
1671    fn refuses_a_parser_part_that_is_not_one() {
1672        for model in [exact(), hashed()] {
1673            let bytes = part(&model, Quantization::F32);
1674            assert!(ParserLayout::read(&bytes, 0).is_ok());
1675            let start = after_the_set(&model);
1676
1677            // The feature set is the text of its groups.
1678            let mut other = bytes.clone();
1679            other[4] = b'x';
1680            assert!(
1681                error(&other).starts_with("the model has a feature set that is not one: "),
1682                "{}",
1683                error(&other)
1684            );
1685
1686            let mut other = bytes.clone();
1687            other[start] = 3;
1688            assert_eq!(error(&other), "the model has the unknown quantization 3");
1689            let mut other = bytes.clone();
1690            other[start + 1] = 2;
1691            assert_eq!(error(&other), "the model has the unknown table of pairs 2");
1692
1693            // The bias and the scale are the 16 bytes after the two codes.
1694            for offset in [start + 2, start + 10] {
1695                let mut other = bytes.clone();
1696                other[offset..offset + 8].copy_from_slice(&f64::NAN.to_le_bytes());
1697                assert_eq!(error(&other), "the model has a weight that is not finite");
1698            }
1699
1700            // A scale of 0, and one below.
1701            for scale in [0.0f64, -1.0] {
1702                let mut other = bytes.clone();
1703                other[start + 10..start + 18].copy_from_slice(&scale.to_le_bytes());
1704                assert_eq!(
1705                    error(&other),
1706                    format!("the model has the scale {scale}, which is not above 0")
1707                );
1708            }
1709
1710            // The last weight: of a pair, or of a place.
1711            let mut other = bytes.clone();
1712            let last = other.len() - 4;
1713            other[last..].copy_from_slice(&f32::INFINITY.to_le_bytes());
1714            assert_eq!(error(&other), "the model has a weight that is not finite");
1715
1716            let mut other = bytes.clone();
1717            other.push(0);
1718            assert_eq!(error(&other), "the model has 1 bytes after its parser");
1719            for length in 0..bytes.len() {
1720                let message = error(&bytes[..length]);
1721                assert!(
1722                    message.starts_with("the model ends early"),
1723                    "{length}: {message}"
1724                );
1725            }
1726        }
1727    }
1728
1729    #[test]
1730    fn refuses_weights_of_features_and_pairs_that_are_not_what_the_format_says() {
1731        // The weight of a feature that is not a number: the values of the
1732        // table of the features are before its 8 slots, and the weights of
1733        // the 3 pairs, their columns and the 5 offsets after it.
1734        let bytes = part(&exact(), Quantization::F32);
1735        let pairs = bytes.len() - (8 + 5 * 4 + 3 * 4 + 3 * 4);
1736        let values = pairs - 8 * 4 - 4 * 4;
1737        assert_eq!(bytes[values..values + 4], 0.5f32.to_le_bytes());
1738        let mut other = bytes.clone();
1739        other[values..values + 4].copy_from_slice(&f32::NAN.to_le_bytes());
1740        assert_eq!(error(&other), "the model has a weight that is not finite");
1741
1742        // The pairs: their number, the offsets of the four features and
1743        // the end, the larger numbers, the weights.
1744        assert_eq!(bytes[pairs..pairs + 8], 3u64.to_le_bytes());
1745        let offsets = pairs + 8;
1746        let offset = |index: usize| bytes[offsets + 4 * index];
1747        assert_eq!(
1748            [offset(0), offset(1), offset(2), offset(3), offset(4)],
1749            [0, 1, 2, 3, 3]
1750        );
1751        let columns = offsets + 5 * 4;
1752        assert_eq!(
1753            [bytes[columns], bytes[columns + 4], bytes[columns + 8]],
1754            [2, 3, 3]
1755        );
1756        let order = "the model has pairs that are not in the order of their features";
1757        // The first offset is not 0; an offset goes back; the last is not
1758        // the number of pairs.
1759        for (index, value) in [(0, 1), (2, 0), (4, 2), (4, 4)] {
1760            let mut other = bytes.clone();
1761            other[offsets + 4 * index] = value;
1762            assert_eq!(error(&other), order, "offset {index} = {value}");
1763        }
1764        // The pair of the feature 0 names itself, a smaller feature would
1765        // be the same; the pair of 1 names a feature that is not there.
1766        for (index, value) in [(0, 0), (1, 4), (2, 2)] {
1767            let mut other = bytes.clone();
1768            other[columns + 4 * index] = value;
1769            assert_eq!(error(&other), order, "column {index} = {value}");
1770        }
1771        // Two pairs of one feature in the wrong order.
1772        let model = ParserModel::new(
1773            Schema::ipadic(),
1774            FeatureSet::default(),
1775            0.0,
1776            features(),
1777            PairWeights::Exact(vec![((0, 1), 1.0), ((0, 2), 1.0)]),
1778        )
1779        .unwrap();
1780        let bytes = part(&model, Quantization::F32);
1781        let columns = bytes.len() - 2 * 4 - 2 * 4;
1782        assert_eq!([bytes[columns], bytes[columns + 4]], [1, 2]);
1783        let mut other = bytes.clone();
1784        other[columns] = 2;
1785        other[columns + 4] = 1;
1786        assert_eq!(error(&other), order);
1787        let mut other = bytes.clone();
1788        other[columns + 4] = 1;
1789        assert_eq!(error(&other), order);
1790        // Offsets that go back, with pairs that are in order all the same:
1791        // of five features, the pairs of the third start before the end of
1792        // those of the first.
1793        let five: Vec<(String, f32)> = ["a", "b", "c", "d", "e"]
1794            .iter()
1795            .map(|name| (name.to_string(), 1.0))
1796            .collect();
1797        let model = ParserModel::new(
1798            Schema::ipadic(),
1799            FeatureSet::default(),
1800            0.0,
1801            five,
1802            PairWeights::Exact(vec![((0, 1), 1.0), ((0, 3), 1.0), ((2, 4), 1.0)]),
1803        )
1804        .unwrap();
1805        let bytes = part(&model, Quantization::F32);
1806        let columns = bytes.len() - 3 * 4 - 3 * 4;
1807        let offsets = columns - 6 * 4;
1808        let offset = |index: usize| bytes[offsets + 4 * index];
1809        assert_eq!(
1810            [
1811                offset(0),
1812                offset(1),
1813                offset(2),
1814                offset(3),
1815                offset(4),
1816                offset(5)
1817            ],
1818            [0, 2, 2, 3, 3, 3]
1819        );
1820        assert_eq!(
1821            [bytes[columns], bytes[columns + 4], bytes[columns + 8]],
1822            [1, 3, 4]
1823        );
1824        let mut other = bytes.clone();
1825        other[offsets + 4 * 2] = 1;
1826        assert_eq!(error(&other), order);
1827        // Offsets that end before the last pair: a pair of no feature.
1828        let mut other = bytes.clone();
1829        other[offsets + 4 * 3] = 2;
1830        other[offsets + 4 * 4] = 2;
1831        other[offsets + 4 * 5] = 2;
1832        assert_eq!(error(&other), order);
1833
1834        // More pairs than the bytes hold.
1835        let pairs = columns - 5 * 4 - 8;
1836        let mut other = bytes.clone();
1837        other[pairs..pairs + 8].copy_from_slice(&u64::MAX.to_le_bytes());
1838        assert!(error(&other).starts_with("the model ends early"));
1839
1840        // A table of hashed pairs of no bit, and of too many.
1841        let bytes = part(&hashed(), Quantization::I8);
1842        let bits = bytes.len() - 16 - 4;
1843        assert_eq!(bytes[bits..bits + 4], 4u32.to_le_bytes());
1844        for value in [0, 31] {
1845            let mut other = bytes.clone();
1846            other[bits] = value;
1847            assert_eq!(
1848                error(&other),
1849                format!("the model has a table of hashed pairs of {value} bits")
1850            );
1851        }
1852        let mut other = bytes.clone();
1853        other[bits] = 5;
1854        assert!(error(&other).starts_with("the model ends early"));
1855    }
1856
1857    #[test]
1858    fn no_changed_byte_makes_reading_or_scoring_panic() {
1859        for (model, quantization) in [
1860            (exact(), Quantization::F32),
1861            (exact(), Quantization::I8),
1862            (hashed(), Quantization::I16),
1863        ] {
1864            let bytes = part(&model, quantization);
1865            let mut read = 0;
1866            for position in 0..bytes.len() {
1867                for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1868                    if value == bytes[position] {
1869                        continue;
1870                    }
1871                    let mut other = bytes.clone();
1872                    other[position] = value;
1873                    if let Ok(layout) = ParserLayout::read(&other, 0) {
1874                        read += 1;
1875                        let part = layout.part(&other);
1876                        for name in NAMES {
1877                            let _ = part.id(name);
1878                        }
1879                        let _ = part.score(&[0, 1, 2, 3]);
1880                        let _ = part.score(&[3, 2, 1, 0, 9, 9]);
1881                    }
1882                }
1883            }
1884            assert!(read > 0);
1885        }
1886    }
1887}