Skip to main content

lindera_dependency/chunker/
model.rs

1//! The model of the chunker: its weights, and what makes its features.
2
3use std::collections::HashMap;
4
5use super::columns::Column;
6use super::template::Template;
7use crate::bytes::{push_string, push_u32};
8use crate::error::{Error, Result};
9use crate::model::table;
10use crate::schema::Schema;
11
12/// The width of the weights of a feature string in a model file: two
13/// numbers of 8 bytes, the weight of `B` and the weight of `I`.
14pub(crate) const WEIGHTS_WIDTH: usize = 16;
15
16/// A label of the chunker.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Label {
19    /// The morpheme starts a bunsetsu.
20    Begin,
21    /// The morpheme continues the bunsetsu of the one before it.
22    Inside,
23}
24
25impl Label {
26    /// The two labels, in the order of their weights.
27    pub(crate) const ALL: [Label; 2] = [Label::Begin, Label::Inside];
28
29    /// The index of the weight of the label in the weights of a feature.
30    ///
31    /// # Returns
32    ///
33    /// 0 for [`Label::Begin`], 1 for [`Label::Inside`].
34    pub(crate) fn index(self) -> usize {
35        match self {
36            Label::Begin => 0,
37            Label::Inside => 1,
38        }
39    }
40}
41
42/// The index of the start and of the end of a sentence in the transitions.
43pub(crate) const BOUNDARY: usize = 0;
44
45/// What a chunker reads of a model: what makes the feature strings, and
46/// their weights.
47///
48/// [`ChunkerModel`] holds them in memory, as training gives them or as they
49/// are made by hand; the chunker of a model file
50/// ([`Model::chunker`](crate::model::Model::chunker)) reads them on the
51/// bytes of the file.
52pub trait ChunkerData {
53    /// The schema of the dictionary the model is for.
54    ///
55    /// # Returns
56    ///
57    /// The schema.
58    fn schema(&self) -> &Schema;
59
60    /// The columns the template reads.
61    ///
62    /// # Returns
63    ///
64    /// The columns, in the order of their numbers in the template.
65    fn columns(&self) -> &[Column];
66
67    /// The template.
68    ///
69    /// # Returns
70    ///
71    /// The template.
72    fn template(&self) -> &Template;
73
74    /// The weight of a transition.
75    ///
76    /// # Arguments
77    ///
78    /// * `from` - 0 for the start of the sentence, 1 for `B`, 2 for `I`.
79    /// * `to` - 0 for the end of the sentence, 1 for `B`, 2 for `I`.
80    ///
81    /// # Returns
82    ///
83    /// The weight; 0 for an index over 2.
84    fn transition(&self, from: usize, to: usize) -> f64;
85
86    /// The weights of a feature string.
87    ///
88    /// # Arguments
89    ///
90    /// * `feature` - The feature string, as the template expands it.
91    ///
92    /// # Returns
93    ///
94    /// The weight of `B` and the weight of `I`, or `None` for a string the
95    /// model does not have.
96    fn feature(&self, feature: &str) -> Option<[f64; 2]>;
97}
98
99/// The model of the chunker, in memory.
100///
101/// It holds the weights, and with them what makes the feature strings they
102/// are for: the schema of the dictionary, the columns and the template.
103/// Training and inference then cannot disagree on the features.
104///
105/// It is what training gives. To keep it, put it into a model file with
106/// [`ModelBuilder`](crate::model::ModelBuilder).
107#[derive(Debug, Clone, PartialEq)]
108pub struct ChunkerModel {
109    /// The schema of the dictionary the model is for.
110    schema: Schema,
111    /// The columns the template reads.
112    columns: Vec<Column>,
113    /// The template.
114    template: Template,
115    /// The weights of the transitions, as `[from][to]`: 0 is the start of
116    /// the sentence as `from` and its end as `to`, 1 is `B`, 2 is `I`.
117    transitions: [[f64; 3]; 3],
118    /// The weights of the feature strings: of `B`, then of `I`.
119    features: HashMap<String, [f64; 2]>,
120}
121
122impl ChunkerModel {
123    /// Makes a model.
124    ///
125    /// # Arguments
126    ///
127    /// * `schema` - The schema of the dictionary the model is for.
128    /// * `columns` - The columns the template reads, in the order of their
129    ///   numbers in the template.
130    /// * `template` - The template.
131    /// * `transitions` - The weights of the transitions, as `[from][to]`: 0
132    ///   is the start of the sentence as `from` and its end as `to`, 1 is
133    ///   `B`, 2 is `I`.
134    /// * `features` - The weights of the feature strings: of `B`, then of
135    ///   `I`.
136    ///
137    /// # Returns
138    ///
139    /// The model, or [`Error::Chunker`] when the template reads a column
140    /// that `columns` does not have, or a weight is not finite.
141    pub fn new(
142        schema: Schema,
143        columns: Vec<Column>,
144        template: Template,
145        transitions: [[f64; 3]; 3],
146        features: HashMap<String, [f64; 2]>,
147    ) -> Result<Self> {
148        if template.columns() > columns.len() {
149            return Err(Error::Chunker(format!(
150                "the template reads {} columns, and {} are given",
151                template.columns(),
152                columns.len()
153            )));
154        }
155        let finite = transitions
156            .iter()
157            .flatten()
158            .all(|weight| weight.is_finite())
159            && features.values().flatten().all(|weight| weight.is_finite());
160        if !finite {
161            return Err(Error::Chunker("a weight is not finite".to_string()));
162        }
163        Ok(Self {
164            schema,
165            columns,
166            template,
167            transitions,
168            features,
169        })
170    }
171
172    /// The schema of the dictionary the model is for.
173    ///
174    /// # Returns
175    ///
176    /// The schema.
177    pub fn schema(&self) -> &Schema {
178        &self.schema
179    }
180
181    /// The columns the template reads.
182    ///
183    /// # Returns
184    ///
185    /// The columns.
186    pub fn columns(&self) -> &[Column] {
187        &self.columns
188    }
189
190    /// The template.
191    ///
192    /// # Returns
193    ///
194    /// The template.
195    pub fn template(&self) -> &Template {
196        &self.template
197    }
198
199    /// The weight of a transition.
200    ///
201    /// # Arguments
202    ///
203    /// * `from` - 0 for the start of the sentence, 1 for `B`, 2 for `I`.
204    /// * `to` - 0 for the end of the sentence, 1 for `B`, 2 for `I`.
205    ///
206    /// # Returns
207    ///
208    /// The weight; 0 for an index over 2.
209    pub fn transition(&self, from: usize, to: usize) -> f64 {
210        self.transitions
211            .get(from)
212            .and_then(|row| row.get(to))
213            .copied()
214            .unwrap_or(0.0)
215    }
216
217    /// The weights of a feature string.
218    ///
219    /// # Arguments
220    ///
221    /// * `feature` - The feature string, as the template expands it.
222    ///
223    /// # Returns
224    ///
225    /// The weight of `B` and the weight of `I`, or `None` for a string the
226    /// model does not have.
227    pub fn feature(&self, feature: &str) -> Option<[f64; 2]> {
228        self.features.get(feature).copied()
229    }
230
231    /// The number of feature strings of the model.
232    ///
233    /// # Returns
234    ///
235    /// The number of strings.
236    pub fn feature_count(&self) -> usize {
237        self.features.len()
238    }
239
240    /// The number of weights of the model that are not 0: those of the
241    /// feature strings and those of the transitions.
242    ///
243    /// # Returns
244    ///
245    /// The number of weights.
246    pub fn weight_count(&self) -> usize {
247        self.features
248            .values()
249            .flatten()
250            .chain(self.transitions.iter().flatten())
251            .filter(|weight| **weight != 0.0)
252            .count()
253    }
254
255    /// Appends the model to bytes, as the chunker part of a model file.
256    ///
257    /// The columns, the template, the transitions, and the table of the
258    /// feature strings with their weights. The schema is not written: a
259    /// model file holds it once, for all its parts. The same model gives
260    /// the same bytes.
261    ///
262    /// # Arguments
263    ///
264    /// * `bytes` - The bytes to append to.
265    pub(crate) fn write_part(&self, bytes: &mut Vec<u8>) {
266        push_u32(bytes, self.columns.len() as u32);
267        for column in &self.columns {
268            bytes.push(column.code());
269        }
270
271        push_string(bytes, &self.template.to_string());
272
273        for weight in self.transitions.iter().flatten() {
274            bytes.extend_from_slice(&weight.to_le_bytes());
275        }
276
277        let mut features: Vec<(&str, [u8; WEIGHTS_WIDTH])> = self
278            .features
279            .iter()
280            .map(|(feature, weights)| {
281                let mut value = [0; WEIGHTS_WIDTH];
282                value[..8].copy_from_slice(&weights[0].to_le_bytes());
283                value[8..].copy_from_slice(&weights[1].to_le_bytes());
284                (feature.as_str(), value)
285            })
286            .collect();
287        features.sort_by(|left, right| left.0.as_bytes().cmp(right.0.as_bytes()));
288        let entries: Vec<(&str, &[u8])> = features
289            .iter()
290            .map(|(feature, value)| (*feature, value.as_slice()))
291            .collect();
292        table::write(bytes, WEIGHTS_WIDTH, &entries);
293    }
294}
295
296impl ChunkerData for ChunkerModel {
297    fn schema(&self) -> &Schema {
298        &self.schema
299    }
300
301    fn columns(&self) -> &[Column] {
302        &self.columns
303    }
304
305    fn template(&self) -> &Template {
306        &self.template
307    }
308
309    fn transition(&self, from: usize, to: usize) -> f64 {
310        ChunkerModel::transition(self, from, to)
311    }
312
313    fn feature(&self, feature: &str) -> Option<[f64; 2]> {
314        ChunkerModel::feature(self, feature)
315    }
316}
317
318#[cfg(test)]
319pub(crate) mod tests {
320    use super::*;
321
322    /// A model with the template of CaboCha and the given weights of
323    /// feature strings and transitions.
324    pub(crate) fn model(features: &[(&str, [f64; 2])], transitions: [[f64; 3]; 3]) -> ChunkerModel {
325        ChunkerModel::new(
326            Schema::ipadic(),
327            vec![Column::Surface, Column::PartOfSpeech],
328            Template::cabocha(),
329            transitions,
330            features
331                .iter()
332                .map(|(feature, weights)| (feature.to_string(), *weights))
333                .collect(),
334        )
335        .unwrap()
336    }
337
338    #[test]
339    fn a_model_gives_back_what_it_was_made_of() {
340        let model = model(
341            &[("U02:は", [-1.5, 2.0]), ("U12:名詞", [0.5, 0.0])],
342            [[0.0, 0.25, 0.0], [0.0, -0.5, 1.0], [0.75, 0.0, 0.0]],
343        );
344        assert_eq!(model.schema(), &Schema::ipadic());
345        assert_eq!(model.columns(), [Column::Surface, Column::PartOfSpeech]);
346        assert_eq!(model.template(), &Template::cabocha());
347        assert_eq!(model.feature("U02:は"), Some([-1.5, 2.0]));
348        assert_eq!(model.feature("U02:が"), None);
349        assert_eq!(model.transition(0, 1), 0.25);
350        assert_eq!(model.transition(1, 2), 1.0);
351        assert_eq!(model.transition(2, 0), 0.75);
352        assert_eq!(model.transition(3, 0), 0.0);
353        assert_eq!(model.feature_count(), 2);
354        // 3 weights of features and 4 of transitions are not 0.
355        assert_eq!(model.weight_count(), 7);
356    }
357
358    #[test]
359    fn new_refuses_a_template_with_more_columns_and_weights_that_are_not_finite() {
360        let make = |columns: Vec<Column>, weight: f64| {
361            ChunkerModel::new(
362                Schema::ipadic(),
363                columns,
364                Template::cabocha(),
365                [[0.0, weight, 0.0], [0.0; 3], [0.0; 3]],
366                HashMap::new(),
367            )
368        };
369        assert_eq!(
370            make(vec![Column::Surface], 0.0).unwrap_err().to_string(),
371            "the template reads 2 columns, and 1 are given"
372        );
373        assert_eq!(
374            make(vec![Column::Surface, Column::PartOfSpeech], f64::INFINITY)
375                .unwrap_err()
376                .to_string(),
377            "a weight is not finite"
378        );
379        assert!(make(vec![Column::Surface, Column::PartOfSpeech], 1.0).is_ok());
380    }
381}