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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Dependency tree by the scores of heads: every word has one head, there is one root and no cycles.
//!
//! First every word takes its best head; if that is already a tree with one root, it is the tree of the
//! maximum weight. Otherwise Chu - Liu - Edmonds runs on the log probabilities of heads with the root
//! candidates enumerated. The work is bounded (`CONTRACTIONS` contractions of cycles, `CANDIDATES`
//! root candidates): beyond that, as in sentences longer than `FULL` words, the extra roots and the
//! nodes of cycles are attached to the best root. In sentences longer than `FULL` words the head is
//! looked for among `WINDOW` words on each side and the root: the time grows linearly, not
//! quadratically.

/// Length of a sentence up to which the full matrix of scores is built and the tree of the maximum
/// weight is searched
pub(crate) const FULL: usize = 1024;
/// How many cycles Chu - Liu - Edmonds contracts (no UD dev part needs more than 6)
const CONTRACTIONS: usize = 16;
/// How many root candidates are enumerated (no UD dev part has more than 2)
const CANDIDATES: usize = 8;
/// How many words on each side of the dependent are head candidates in sentences longer than `FULL`
/// words. In UD train 0.04 % of heads are farther than 64 words; joined dev sentences are parsed more
/// accurately with the window than without it
pub(crate) const WINDOW: usize = 64;

/// Score without NaN and infinities: otherwise the comparisons break the choice of the best head
pub(crate) fn finite(value: f32) -> f32 {
    if value.is_nan() {
        f32::MIN
    } else {
        value.clamp(f32::MIN, f32::MAX)
    }
}

/// Heads of the positions `0..n` (0 - the root, its head is 0) by the score `score(dependent, head)`
/// and the probability of every head - softmax of the scores of the head candidates of the word, as in
/// training (1 at the position of the root)
pub(crate) fn heads(n: usize, score: &impl Fn(usize, usize) -> f32) -> (Vec<usize>, Vec<f32>) {
    if n > FULL + 1 {
        return long(n, score);
    }
    let mut s = vec![f32::NEG_INFINITY; n * n];
    for d in 1..n {
        for h in 0..n {
            if h != d {
                s[d * n + h] = finite(score(d, h));
            }
        }
    }
    let mut heads: Vec<usize> = (0..n)
        .map(|d| {
            if d == 0 {
                0
            } else {
                argmax(&s[d * n..(d + 1) * n])
            }
        })
        .collect();
    heads[0] = 0;
    let log_sums: Vec<f64> = (0..n)
        .map(|d| {
            if d == 0 {
                0.0
            } else {
                log_sum(&s[d * n..(d + 1) * n])
            }
        })
        .collect();
    if roots(&heads) != 1 || cycle(&heads).is_some() {
        // Log probabilities of heads by row
        let mut logp = vec![vec![f64::NEG_INFINITY; n]; n];
        for d in 1..n {
            for h in 0..n {
                if h != d {
                    logp[d][h] = s[d * n + h] as f64 - log_sums[d];
                }
            }
        }
        heads = one_root(&logp).unwrap_or_else(|| {
            let root_score: Vec<f32> = (0..n).map(|d| s[d * n]).collect();
            repair(heads, &root_score)
        });
    }
    let probs = (0..n)
        .map(|d| {
            if d == 0 {
                1.0
            } else {
                (s[d * n + heads[d]] as f64 - log_sums[d]).exp() as f32
            }
        })
        .collect();
    (heads, probs)
}

/// Logarithm of the sum of the exponents of the scores
fn log_sum(row: &[f32]) -> f64 {
    let max = row.iter().copied().fold(f32::NEG_INFINITY, f32::max) as f64;
    let sum: f64 = row.iter().map(|&x| (x as f64 - max).exp()).sum();
    max + sum.ln()
}

fn argmax(row: &[f32]) -> usize {
    (0..row.len()).fold(0, |best, h| if row[h] > row[best] { h } else { best })
}

fn roots(heads: &[usize]) -> usize {
    heads.iter().skip(1).filter(|&&h| h == 0).count()
}

/// Nodes of the first cycle found
fn cycle(heads: &[usize]) -> Option<Vec<usize>> {
    let n = heads.len();
    // 0 - not visited, 1 - on the current path, 2 - the paths from it to the root are checked
    let mut color = vec![0u8; n];
    for start in 1..n {
        let mut path = Vec::new();
        let mut v = start;
        while v != 0 && color[v] == 0 {
            color[v] = 1;
            path.push(v);
            v = heads[v];
        }
        if v != 0 && color[v] == 1 {
            let at = path.iter().position(|&p| p == v).unwrap_or(0);
            return Some(path[at..].to_vec());
        }
        for p in path {
            color[p] = 2;
        }
    }
    None
}

/// Chu - Liu - Edmonds with one root: if the root has several children in the best tree, the trees
/// with each of them as the only child of the root are enumerated. `None` - the work is out of bounds
fn one_root(scores: &[Vec<f64>]) -> Option<Vec<usize>> {
    let n = scores.len();
    let tree = edmonds(scores.to_vec())?;
    let candidates: Vec<usize> = (1..n).filter(|&d| tree[d] == 0).collect();
    if candidates.len() == 1 {
        return Some(tree);
    }
    if candidates.len() > CANDIDATES {
        return None;
    }
    let mut best = (f64::NEG_INFINITY, tree);
    for &root in &candidates {
        let mut s = scores.to_vec();
        for (d, row) in s.iter_mut().enumerate() {
            if d != root {
                row[0] = f64::NEG_INFINITY;
            }
        }
        let total = |tree: &[usize]| -> f64 { (1..n).map(|d| s[d][tree[d]]).sum() };
        let candidate = edmonds(s.clone())?;
        let value = total(&candidate);
        if value > best.0 {
            best = (value, candidate);
        }
    }
    Some(best.1)
}

/// Contraction of a cycle: what is needed to expand the nodes of the graph of the level below
struct Level {
    heads: Vec<usize>,
    rest: Vec<usize>,
    out_from: Vec<usize>,
    in_to: Vec<usize>,
}

/// Tree of the maximum weight with the root 0: `s[d][h]` is the score of the head `h` of `d`, row 0 and
/// the diagonal are -inf. Without recursion: one matrix of the current level is in memory; more than
/// `CONTRACTIONS` contractions give `None`
fn edmonds(mut s: Vec<Vec<f64>>) -> Option<Vec<usize>> {
    let mut levels: Vec<Level> = Vec::new();
    let mut result = loop {
        let n = s.len();
        let mut heads: Vec<usize> = (0..n)
            .map(|d| (0..n).fold(0, |best, h| if s[d][h] > s[d][best] { h } else { best }))
            .collect();
        heads[0] = 0;
        let Some(cyc) = cycle(&heads) else {
            break heads;
        };
        if levels.len() == CONTRACTIONS {
            return None;
        }
        // The cycle is contracted into the node m; the other nodes are rest (0 is the first of them)
        let mut in_cycle = vec![false; n];
        cyc.iter().for_each(|&v| in_cycle[v] = true);
        let rest: Vec<usize> = (0..n).filter(|&v| !in_cycle[v]).collect();
        let m = rest.len();
        let mut t = vec![vec![f64::NEG_INFINITY; m + 1]; m + 1];
        let mut out_from = vec![0usize; m];
        let mut in_to = vec![0usize; m];
        for (i, &v) in rest.iter().enumerate() {
            for (j, &h) in rest.iter().enumerate() {
                t[i][j] = s[v][h];
            }
            // The best head of the node v inside the cycle
            let (h, value) = (cyc.iter())
                .map(|&c| (c, s[v][c]))
                .fold((cyc[0], f64::NEG_INFINITY), max_pair);
            t[i][m] = value;
            out_from[i] = h;
            // The best entry into the cycle from v: a replacement of a link of the cycle
            let (c, value) = (cyc.iter())
                .map(|&c| (c, s[c][v] - s[c][heads[c]]))
                .fold((cyc[0], f64::NEG_INFINITY), max_pair);
            t[m][i] = value;
            in_to[i] = c;
        }
        t[0] = vec![f64::NEG_INFINITY; m + 1];
        levels.push(Level {
            heads,
            rest,
            out_from,
            in_to,
        });
        s = t;
    };
    while let Some(level) = levels.pop() {
        let m = level.rest.len();
        let mut outer = level.heads;
        for i in 1..m {
            outer[level.rest[i]] = if result[i] == m {
                level.out_from[i]
            } else {
                level.rest[result[i]]
            };
        }
        let h = result[m];
        outer[level.in_to[h]] = level.rest[h];
        result = outer;
    }
    Some(result)
}

fn max_pair(best: (usize, f64), next: (usize, f64)) -> (usize, f64) {
    if next.1 > best.1 { next } else { best }
}

/// Long sentence: the best heads among the root and `WINDOW` words on each side, then `repair`; the
/// probability of a head is among the same candidates
fn long(n: usize, score: &impl Fn(usize, usize) -> f32) -> (Vec<usize>, Vec<f32>) {
    let mut heads = vec![0usize; n];
    let mut root_score = vec![f32::MIN; n];
    let mut log_sums = vec![0.0f64; n];
    let mut values = Vec::with_capacity(2 * WINDOW + 1);
    for d in 1..n {
        let mut best = (0, f32::NEG_INFINITY);
        let window = d.saturating_sub(WINDOW).max(1)..=(d + WINDOW).min(n - 1);
        values.clear();
        for h in std::iter::once(0).chain(window) {
            if h == d {
                continue;
            }
            let value = finite(score(d, h));
            values.push(value);
            if h == 0 {
                root_score[d] = value;
            }
            if value > best.1 {
                best = (h, value);
            }
        }
        heads[d] = best.0;
        log_sums[d] = log_sum(&values);
    }
    let heads = repair(heads, &root_score);
    let probs = (0..n)
        .map(|d| {
            if d == 0 {
                return 1.0;
            }
            let value = finite(score(d, heads[d])) as f64;
            // A head beyond the window was given by the repair: it is one more candidate
            let log_sum = if heads[d] == 0 || heads[d].abs_diff(d) <= WINDOW {
                log_sums[d]
            } else {
                let max = log_sums[d].max(value);
                max + ((log_sums[d] - max).exp() + (value - max).exp()).ln()
            };
            (value - log_sum).exp() as f32
        })
        .collect();
    (heads, probs)
}

/// Tree from the best heads: of the root candidates (or of all words, if there are none) the one with
/// the best root score stays, the other candidates and the nodes of cycles are attached to it
fn repair(mut heads: Vec<usize>, root_score: &[f32]) -> Vec<usize> {
    let n = heads.len();
    let candidates: Vec<usize> = (1..n).filter(|&d| heads[d] == 0).collect();
    let pool: Vec<usize> = if candidates.is_empty() {
        (1..n).collect()
    } else {
        candidates
    };
    let root = pool.iter().copied().fold(pool[0], |best, d| {
        if root_score[d] > root_score[best] {
            d
        } else {
            best
        }
    });
    for (d, head) in heads.iter_mut().enumerate().skip(1) {
        if *head == 0 && d != root {
            *head = root;
        }
    }
    heads[root] = 0;
    // All cycles in one pass: the node where a path closes is attached to the root. The paths from
    // smaller numbers are already checked and do not go through this node, so the cycles and their
    // order are those of the search for one cycle from the start, and the time is linear
    let mut color = vec![0u8; n];
    let mut path = Vec::new();
    for start in 1..n {
        let mut v = start;
        while v != 0 && color[v] == 0 {
            color[v] = 1;
            path.push(v);
            v = heads[v];
        }
        if v != 0 && color[v] == 1 {
            heads[v] = root;
        }
        for p in path.drain(..) {
            color[p] = 2;
        }
    }
    heads
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Rng(u64);

    impl Rng {
        fn next(&mut self) -> f32 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            (self.0 >> 40) as f32 / (1u64 << 24) as f32 * 4.0 - 2.0
        }
    }

    fn is_tree(heads: &[usize]) -> bool {
        heads[0] == 0 && roots(heads) == 1 && cycle(heads).is_none()
    }

    /// The best tree with one root by enumerating all heads
    fn brute(n: usize, s: &[Vec<f64>]) -> f64 {
        let mut best = f64::NEG_INFINITY;
        let mut heads = vec![0usize; n];
        let total = n.pow((n - 1) as u32);
        for code in 0..total {
            let mut c = code;
            for head in heads.iter_mut().skip(1) {
                *head = c % n;
                c /= n;
            }
            if (1..n).any(|d| heads[d] == d) || !is_tree(&heads) {
                continue;
            }
            best = best.max((1..n).map(|d| s[d][heads[d]]).sum());
        }
        best
    }

    #[test]
    fn edmonds_with_one_root_matches_brute_force() {
        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
        for trial in 0..2000 {
            let n = 2 + trial % 6;
            // In half of the graphs the root has several children among the best heads: the candidates
            // are enumerated
            let root_bias = if trial % 2 == 0 { 3.0 } else { 0.0 };
            let mut s = vec![vec![f64::NEG_INFINITY; n]; n];
            for (d, row) in s.iter_mut().enumerate().skip(1) {
                for (h, value) in row.iter_mut().enumerate() {
                    if h != d {
                        *value = f64::from(rng.next()) + if h == 0 { root_bias } else { 0.0 };
                    }
                }
            }
            let tree = one_root(&s).expect("a small graph fits the bounds");
            assert!(is_tree(&tree), "{tree:?}");
            let total: f64 = (1..n).map(|d| s[d][tree[d]]).sum();
            assert!((total - brute(n, &s)).abs() < 1e-9, "trial {trial}");
        }
    }

    #[test]
    fn head_probabilities_are_softmax_of_rows() {
        let mut rng = Rng(11);
        for n in [2, 7, 30, FULL + 40] {
            let values: Vec<f32> = (0..n * n.min(200)).map(|_| rng.next()).collect();
            let score =
                |d: usize, h: usize| values[(d * n.min(200) + h % n.min(200)) % values.len()];
            let (tree, probs) = heads(n, &score);
            assert_eq!(probs[0], 1.0);
            for d in 1..n {
                let p = probs[d];
                assert!(p > 0.0 && p <= 1.0, "{d}: {p}");
                if n <= FULL {
                    let row: Vec<f32> = (0..n).filter(|&h| h != d).map(|h| score(d, h)).collect();
                    let sum: f64 = row.iter().map(|&x| f64::from(x).exp()).sum();
                    let expected = f64::from(score(d, tree[d])).exp() / sum;
                    assert!(
                        (f64::from(p) - expected).abs() < 1e-5,
                        "{d}: {p} {expected}"
                    );
                }
            }
        }
    }

    #[test]
    fn heads_always_form_tree() {
        let mut rng = Rng(7);
        for n in 2..40 {
            let values: Vec<f32> = (0..n * n).map(|_| rng.next()).collect();
            let score = |d: usize, h: usize| values[d * n + h];
            assert!(is_tree(&heads(n, &score).0));
            assert!(is_tree(&long(n, &score).0));
        }
    }

    #[test]
    fn nan_and_infinite_scores_give_tree() {
        // A tree and probabilities from 0 to 1
        let check = |(tree, probs): (Vec<usize>, Vec<f32>)| {
            is_tree(&tree) && probs.iter().all(|p| (0.0..=1.0).contains(p))
        };
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            assert!(check(heads(5, &|_, _| bad)));
            assert!(check(heads(5, &|d, h| if h == 0 { bad } else { d as f32 })));
            assert!(check(long(5, &|_, _| bad)));
        }
    }

    #[test]
    fn degenerate_sentence_is_bounded_and_stack_safe() {
        // Pairs of neighbors want each other: hundreds of 2-cycles, the threads of musl have a stack of
        // 128 KiB
        let n = FULL + 1;
        let score = move |d: usize, h: usize| {
            if h != 0 && d.div_ceil(2) == h.div_ceil(2) {
                10.0
            } else {
                -(d as f32) / n as f32
            }
        };
        let tree = std::thread::Builder::new()
            .stack_size(128 * 1024)
            .spawn(move || heads(n, &score).0)
            .and_then(|thread| {
                thread
                    .join()
                    .map_err(|_| std::io::Error::other("the thread panicked"))
            })
            .expect("parse in a small stack");
        assert!(is_tree(&tree));
    }

    /// The former repair: cycles one by one, each time a search from the start
    fn repair_one_by_one(mut heads: Vec<usize>, root_score: &[f32]) -> Vec<usize> {
        let root = repair(heads.clone(), root_score)
            .iter()
            .skip(1)
            .position(|&h| h == 0)
            .map_or(1, |at| at + 1);
        for (d, head) in heads.iter_mut().enumerate().skip(1) {
            if *head == 0 && d != root {
                *head = root;
            }
        }
        heads[root] = 0;
        while let Some(cyc) = cycle(&heads) {
            heads[cyc[0]] = root;
        }
        heads
    }

    #[test]
    fn repair_in_one_pass_matches_one_by_one() {
        let mut rng = Rng(11);
        for trial in 0..3000 {
            let n = 2 + trial % 40;
            let heads: Vec<usize> = (0..n)
                .map(|d| {
                    if d == 0 {
                        0
                    } else {
                        ((rng.next() + 2.0) / 4.0 * n as f32) as usize % n
                    }
                })
                .collect();
            let root_score: Vec<f32> = (0..n).map(|_| rng.next()).collect();
            let tree = repair(heads.clone(), &root_score);
            assert!(is_tree(&tree), "trial {trial}");
            assert_eq!(tree, repair_one_by_one(heads, &root_score), "trial {trial}");
        }
    }

    #[test]
    fn argmax_tree_is_kept() {
        // Every word attaches best to the previous one: this is already a tree
        let score = |d: usize, h: usize| if h + 1 == d { 5.0 } else { 0.0 };
        let (tree, probs) = heads(5, &score);
        assert_eq!(tree, [0, 0, 1, 2, 3]);
        // At the word 2: e⁵ at the head 1 and e⁰ at three other candidates
        let e5 = 5f32.exp();
        assert!((probs[2] - e5 / (e5 + 3.0)).abs() < 1e-6);
    }

    #[test]
    fn long_sentence_looks_for_heads_in_window() {
        let n = FULL + 500;
        // Every word attaches best to the first word, but for the far ones it is beyond the window
        let score = |d: usize, h: usize| match h {
            0 => {
                if d == 1 {
                    1.0
                } else {
                    -10.0
                }
            }
            1 => 5.0,
            _ => -(d.abs_diff(h) as f32),
        };
        let tree = heads(n, &score).0;
        assert!(is_tree(&tree));
        assert!((2..=WINDOW + 1).all(|d| tree[d] == 1));
        assert!((WINDOW + 2..n).all(|d| tree[d].abs_diff(d) == 1));
    }

    #[test]
    fn long_sentence_without_full_matrix() {
        let n = FULL + 50;
        // All words want the root, except the cycle 5 <-> 6
        let score = |d: usize, h: usize| match (d, h) {
            (5, 6) | (6, 5) => 9.0,
            (_, 0) => 1.0 + d as f32 / n as f32,
            _ => 0.0,
        };
        let tree = heads(n, &score).0;
        assert!(is_tree(&tree));
        assert_eq!(tree[n - 1], 0);
    }
}