essyntax 0.1.0-dev.3

Fast Spanish dependency parser: heads and Universal Dependencies relations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]

mod error;
mod format;
mod kernels;
mod model;
mod tree;

use std::path::Path;

pub use error::Error;

use kernels::BATCH;
use model::{Input, Model};

/// Word of a sentence with UD morphology; made by [`Word::new`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Word<'a> {
    /// Form of the word as in the text
    pub form: &'a str,
    /// UD part of speech (`NOUN`, `VERB`, ...), one of the 17 in capitals; a part of speech unknown to the
    /// model is parsed as `X`
    pub upos: &'a str,
    /// UD features in the CoNLL-U notation: `Gender=Fem|Number=Sing`; `_` or an empty string - no features
    pub feats: &'a str,
}

impl<'a> Word<'a> {
    /// Word from its form, part of speech and features
    #[must_use]
    pub fn new(form: &'a str, upos: &'a str, feats: &'a str) -> Self {
        Word { form, upos, feats }
    }
}

/// Relation of a word to its head
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Relation<'p> {
    /// Number of the head among the words of the sentence from 1; 0 is the root of the sentence
    pub head: usize,
    /// UD relation with its subtype, if any (`nsubj`, `obl:arg`, `root`, ...); `root` only at the word
    /// with head 0
    pub deprel: &'p str,
    /// Number of the relation in [`Parser::relations`]
    pub label: usize,
    /// Probability of the head by the model, from 0 to 1: softmax of the scores of all head candidates of
    /// the word (in sentences longer than 1024 words, of 64 words on each side, the root and the head
    /// given by the assembly of the tree)
    pub head_prob: f32,
    /// Probability of the relation with this head, from 0 to 1: softmax of the scores of the relations
    /// except `root`; 1 for `root`, which a rule gives to the word with head 0
    pub deprel_prob: f32,
}

/// Dependency parser: the model in memory. Parsing does not change the parser, so one parser can be
/// shared between threads
pub struct Parser {
    model: Model,
}

impl std::fmt::Debug for Parser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Parser")
            .field("relations", &self.model.relations.len())
            .field("sources", &self.model.sources)
            .finish_non_exhaustive()
    }
}

impl Parser {
    /// Parser from a model file
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the file cannot be read, and [`Error::Format`] if it is not an esSyntax model,
    /// its format version is another, the checksum does not match or the sizes of the weights disagree
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
        Self::from_bytes(&std::fs::read(path)?)
    }

    /// Parser from the contents of a model file
    ///
    /// # Errors
    ///
    /// [`Error::Format`] if it is not an esSyntax model, its format version is another, the checksum
    /// does not match or the sizes of the weights disagree
    pub fn from_bytes(data: &[u8]) -> Result<Self, Error> {
        Ok(Parser {
            model: Model::parse(data)?,
        })
    }

    /// Relations the model gives
    #[must_use]
    pub fn relations(&self) -> &[String] {
        &self.model.relations
    }

    /// How the model was trained (the entry `sources` of the file, JSON), if the file has it
    #[must_use]
    pub fn sources(&self) -> Option<&str> {
        self.model.sources.as_deref()
    }

    /// Checksum of the model - CRC32 of the file after its header: it tells one model from another
    #[must_use]
    pub fn checksum(&self) -> u32 {
        self.model.checksum
    }

    /// Parse of a sentence: the relation of every word in the same order; an empty sentence gives an
    /// empty list
    #[must_use]
    pub fn parse(&self, words: &[Word<'_>]) -> Vec<Relation<'_>> {
        self.parse_many(&[words]).pop().unwrap_or_default()
    }

    /// Parse of several sentences: the same as [`Parser::parse`] for each, but sentences of close length
    /// are parsed four at once, which is faster
    #[must_use]
    pub fn parse_many<'w, S: AsRef<[Word<'w>]>>(&self, sentences: &[S]) -> Vec<Vec<Relation<'_>>> {
        let mut out: Vec<Vec<Relation<'_>>> = vec![Vec::new(); sentences.len()];
        let mut order: Vec<usize> = (0..sentences.len())
            .filter(|&i| !sentences[i].as_ref().is_empty())
            .collect();
        order.sort_by_key(|&i| std::cmp::Reverse(sentences[i].as_ref().len()));
        let inputs: Vec<Vec<Input<'_>>> = sentences
            .iter()
            .map(|words| {
                (words.as_ref().iter())
                    .map(|word| Input {
                        form: word.form,
                        upos: word.upos,
                        feats: word.feats,
                    })
                    .collect()
            })
            .collect();
        for group in order.chunks(BATCH) {
            let batch: Vec<&[Input<'_>]> = group.iter().map(|&i| inputs[i].as_slice()).collect();
            for (&i, parse) in group.iter().zip(self.model.parse_group(&batch)) {
                out[i] = (parse.into_iter())
                    .map(|link| Relation {
                        head: link.head,
                        deprel: &self.model.relations[link.label],
                        label: link.label,
                        head_prob: link.head_prob,
                        deprel_prob: link.label_prob,
                    })
                    .collect();
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::write::{Item, file};

    struct Rng(u64);

    impl Rng {
        fn values(&mut self, count: usize) -> Vec<f32> {
            (0..count)
                .map(|_| {
                    self.0 ^= self.0 << 13;
                    self.0 ^= self.0 >> 7;
                    self.0 ^= self.0 << 17;
                    ((self.0 >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 0.6
                })
                .collect()
        }
    }

    const RELATIONS: [&str; 5] = ["root", "nsubj", "obj", "punct", "obl:arg"];

    /// Entries of a model with random weights: `int8` - matrices of int8 by rows, `word_dim` 0 - no words
    fn items(layers: usize, word_dim: usize, int8: bool) -> Vec<(&'static str, Item<'static>)> {
        let (hidden, suffix_dim, tag_dim, arc, rel) = (8, 3, 4, 6, 5);
        let mut rng = Rng(0x2545_f491_4f6c_dd1d);
        let mut matrix = |rows: usize, cols: usize| {
            let data = rng.values(rows * cols);
            if int8 {
                Item::Int8(rows, cols, data)
            } else {
                Item::F32(rows, cols, data)
            }
        };
        let name = |text: String| -> &'static str { Box::leak(text.into_boxed_str()) };
        let mut out = vec![
            (
                "config",
                Item::Numbers(vec![
                    hidden as u32,
                    layers as u32,
                    word_dim as u32,
                    3,
                    4,
                    6,
                    5,
                    12,
                ]),
            ),
            ("sources", Item::Strings(vec![r#"{"train": ["test"]}"#])),
            (
                "vocab.suffixes",
                Item::Strings(vec!["1:a", "2:sa", "1:o", "1:.", "2:^."]),
            ),
            ("embed.suffix", matrix(7, suffix_dim)),
            (
                "vocab.upos",
                Item::Strings(vec!["NOUN", "VERB", "PUNCT", "X"]),
            ),
            ("embed.upos", matrix(6, tag_dim)),
            (
                "vocab.feats",
                Item::Strings(vec!["Gender=Fem", "Gender=Masc", "Number=Sing", "Mood=Ind"]),
            ),
            ("embed.feats", matrix(6, tag_dim)),
            ("relations", Item::Strings(RELATIONS.to_vec())),
        ];
        if word_dim > 0 {
            out.push((
                "vocab.words",
                Item::Strings(vec!["la", "niña", "lee", "un", "libro", "."]),
            ));
            out.push(("embed.word", matrix(8, word_dim)));
        }
        let mut din = word_dim + model::SUFFIXES * suffix_dim + 2 * tag_dim;
        for layer in 0..layers {
            for direction in ["forward", "backward"] {
                let prefix = format!("lstm.{layer}.{direction}");
                out.push((name(format!("{prefix}.ih")), matrix(4 * hidden, din)));
                out.push((name(format!("{prefix}.hh")), matrix(4 * hidden, hidden)));
                out.push((name(format!("{prefix}.bias")), matrix(1, 4 * hidden)));
            }
            din = 2 * hidden;
        }
        for (layer, rows) in [
            ("arc_dep", arc),
            ("arc_head", arc),
            ("rel_dep", rel),
            ("rel_head", rel),
        ] {
            out.push((name(format!("{layer}.weight")), matrix(rows, 2 * hidden)));
            out.push((name(format!("{layer}.bias")), matrix(1, rows)));
        }
        out.push(("arc.weight", matrix(arc + 1, arc)));
        out.push(("label.weight", matrix(RELATIONS.len(), 2 * rel)));
        out.push(("label.bias", matrix(1, RELATIONS.len())));
        out
    }

    fn model(layers: usize, word_dim: usize, int8: bool) -> Vec<u8> {
        file(&items(layers, word_dim, int8))
    }

    fn sentences() -> Vec<Vec<Word<'static>>> {
        let w = Word::new;
        vec![
            vec![
                w(
                    "La",
                    "DET",
                    "Definite=Def|Gender=Fem|Number=Sing|PronType=Art",
                ),
                w("niña", "NOUN", "Gender=Fem|Number=Sing"),
                w(
                    "lee",
                    "VERB",
                    "Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin",
                ),
                w(
                    "un",
                    "DET",
                    "Definite=Ind|Gender=Masc|Number=Sing|PronType=Art",
                ),
                w("libro", "NOUN", "Gender=Masc|Number=Sing"),
                w(".", "PUNCT", "_"),
            ],
            vec![w("Ñandú", "PROPN", "Gender=Masc|Foo=Bar"), w("", "X", "")],
            vec![w("yo", "PRON", "Number=Sing")],
            vec![],
            (0..37)
                .map(|i| {
                    w(
                        if i % 3 == 0 { "casa" } else { "libro" },
                        "NOUN",
                        "Number=Sing",
                    )
                })
                .collect(),
            vec![
                w("libro", "NOUN", "Gender=Masc"),
                w("lee", "VERB", "_"),
                w("niña", "NOUN", "Gender=Fem"),
            ],
        ]
    }

    fn is_tree(relations: &[Relation<'_>]) -> bool {
        let n = relations.len();
        if relations.iter().filter(|r| r.head == 0).count() != 1
            || relations.iter().any(|r| r.head > n)
        {
            return false;
        }
        (1..=n).all(|start| {
            let (mut v, mut steps) = (start, 0);
            while v != 0 && steps <= n {
                v = relations[v - 1].head;
                steps += 1;
            }
            v == 0
        })
    }

    #[test]
    fn every_word_gets_one_relation_in_a_tree() {
        for (layers, word_dim, int8) in [(1, 5, false), (2, 5, true), (2, 0, false)] {
            let parser = Parser::from_bytes(&model(layers, word_dim, int8)).unwrap();
            assert_eq!(parser.relations(), RELATIONS);
            assert_eq!(parser.sources(), Some(r#"{"train": ["test"]}"#));
            for words in sentences() {
                let relations = parser.parse(&words);
                assert_eq!(relations.len(), words.len());
                assert!(words.is_empty() || is_tree(&relations), "{relations:?}");
                assert!(relations.iter().all(|r| RELATIONS[r.label] == r.deprel));
                assert!(
                    relations
                        .iter()
                        .all(|r| (r.head == 0) == (r.deprel == "root"))
                );
                // Probabilities from 0 to 1, the relation root of the root has 1
                assert!(relations.iter().all(|r| {
                    r.head_prob > 0.0
                        && r.head_prob <= 1.0
                        && r.deprel_prob > 0.0
                        && r.deprel_prob <= 1.0
                        && (r.head != 0 || r.deprel_prob == 1.0)
                }));
            }
        }
    }

    #[test]
    fn int8_scale_overflow_is_format_error() {
        // The row scale is finite, and the value after it is not: 127 × 1e37
        let mut body = 1u32.to_le_bytes().to_vec();
        body.extend(1u16.to_le_bytes());
        body.extend(b"m");
        body.push(2);
        body.extend(1u32.to_le_bytes());
        body.extend(1u32.to_le_bytes());
        body.extend(1e37f32.to_le_bytes());
        body.push(127);
        let mut data = format::MAGIC.to_vec();
        data.extend(format::FORMAT.to_le_bytes());
        data.extend(crc32fast::hash(&body).to_le_bytes());
        data.extend(body);
        let err = format::read(&data).err().expect("a format error");
        assert!(
            err.to_string().contains("infinity after the row scale"),
            "{err}"
        );
    }

    #[test]
    fn huge_label_weights_give_finite_probabilities() {
        // Finite but huge weights of the relations: the scores go to infinity, the probabilities do not
        let mut huge = items(1, 5, false);
        huge.retain(|(name, _)| *name != "label.weight");
        huge.push((
            "label.weight",
            Item::F32(RELATIONS.len(), 10, vec![3e38; 50]),
        ));
        let parser = Parser::from_bytes(&file(&huge)).unwrap();
        for words in sentences() {
            let relations = parser.parse(&words);
            assert_eq!(relations, parser.parse(&words));
            assert!(relations.iter().all(
                |r| (0.0..=1.0).contains(&r.deprel_prob) && (0.0..=1.0).contains(&r.head_prob)
            ));
        }
    }

    #[test]
    fn checksum_is_crc_of_body() {
        let data = model(1, 5, false);
        let parser = Parser::from_bytes(&data).unwrap();
        assert_eq!(parser.checksum(), crc32fast::hash(&data[format::HEADER..]));
    }

    #[test]
    fn many_sentences_match_one_by_one() {
        let parser = Parser::from_bytes(&model(2, 5, false)).unwrap();
        let all = sentences();
        let many = parser.parse_many(&all);
        let one: Vec<_> = all.iter().map(|words| parser.parse(words)).collect();
        assert_eq!(many, one);
        assert!(parser.parse_many::<Vec<Word<'_>>>(&[]).is_empty());
    }

    #[test]
    fn parse_is_deterministic() {
        let parser = Parser::from_bytes(&model(2, 5, true)).unwrap();
        let words = &sentences()[0];
        assert_eq!(parser.parse(words), parser.parse(words));
    }

    #[test]
    fn debug_is_short() {
        let parser = Parser::from_bytes(&model(1, 5, false)).unwrap();
        assert_eq!(
            format!("{parser:?}"),
            r#"Parser { relations: 5, sources: Some("{\"train\": [\"test\"]}"), .. }"#
        );
    }

    #[test]
    fn parser_is_shared_between_threads() {
        fn shared<T: Send + Sync>() {}
        shared::<Parser>();
    }

    fn format_error(data: &[u8]) -> String {
        match Parser::from_bytes(data) {
            Err(Error::Format(message)) => message,
            other => panic!("expected a format error: {other:?}"),
        }
    }

    /// File with the checksum written again: damage the checksum does not catch
    fn resum(mut data: Vec<u8>) -> Vec<u8> {
        let checksum = crc32fast::hash(&data[format::HEADER..]);
        data[12..16].copy_from_slice(&checksum.to_le_bytes());
        data
    }

    #[test]
    fn damaged_files_are_rejected() {
        let good = model(1, 5, false);
        assert!(format_error(b"").contains("signature"));
        assert!(format_error(b"ESSYNTAX").contains("truncated"));
        let mut version = good.clone();
        version[8] = 2;
        assert!(format_error(&version).contains("format version 2"));
        let mut flipped = good.clone();
        let last = flipped.len() - 1;
        flipped[last] ^= 1;
        assert!(format_error(&flipped).contains("checksum"));
        assert!(format_error(&resum(good[..good.len() - 3].to_vec())).contains("truncated"));
        let mut extra = good.clone();
        extra.push(0);
        assert!(format_error(&resum(extra)).contains("data after the entries"));
    }

    #[test]
    fn inconsistent_models_are_rejected() {
        let without = |skip: &str| {
            let rest: Vec<_> = items(1, 5, false)
                .into_iter()
                .filter(|(name, _)| *name != skip)
                .collect();
            format_error(&file(&rest))
        };
        assert!(without("label.bias").contains("no entry label.bias"));
        assert!(without("vocab.words").contains("no entry vocab.words"));
        let mut extra = items(1, 5, false);
        extra.push(("lstm.1.forward.ih", Item::F32(1, 1, vec![0.0])));
        assert!(format_error(&file(&extra)).contains("extra entry lstm.1.forward.ih"));
        let mut duplicate = items(1, 5, false);
        duplicate.push(("sources", Item::Strings(vec!["{}"])));
        assert!(format_error(&file(&duplicate)).contains("entry sources is repeated"));
        let mut wrong = items(1, 5, false);
        wrong.retain(|(name, _)| *name != "arc.weight");
        wrong.push(("arc.weight", Item::F32(6, 6, vec![0.0; 36])));
        assert!(format_error(&file(&wrong)).contains("arc.weight: size 6×6, expected 7×6"));
        let mut repeated = items(1, 5, false);
        repeated.retain(|(name, _)| *name != "vocab.upos");
        repeated.push(("vocab.upos", Item::Strings(vec!["NOUN", "NOUN", "PUNCT"])));
        assert!(format_error(&file(&repeated)).contains("vocab.upos repeat a string"));
        let mut nan = items(1, 5, false);
        nan.retain(|(name, _)| *name != "label.bias");
        nan.push(("label.bias", Item::F32(1, 5, vec![f32::NAN; 5])));
        assert!(format_error(&file(&nan)).contains("NaN"));
        let mut config = items(1, 5, false);
        config[0] = ("config", Item::Numbers(vec![8, 9, 5, 3, 4, 6, 5, 12]));
        assert!(format_error(&file(&config)).contains("config"));
    }

    #[test]
    fn missing_file_is_io_error() {
        let err = Parser::from_path("/no/such/file.bin").unwrap_err();
        assert!(matches!(err, Error::Io(_)));
        assert!(err.to_string().starts_with("cannot read the model file: "));
    }

    #[test]
    fn unknown_upos_is_parsed_as_x() {
        let parser = Parser::from_bytes(&model(1, 5, false)).unwrap();
        let embed = |upos| {
            (parser.model).embed(&[model::Input {
                form: "niña",
                upos,
                feats: "_",
            }])
        };
        assert_eq!(embed("noun"), embed("X"));
        assert_eq!(embed("ADJ"), embed("X"));
        assert_ne!(embed("NOUN"), embed("X"));
    }
}