oxicuda-seq 0.3.0

OxiCUDA: Sequence Models & Structured Prediction (HMM/CRF/Kalman/MRF/alignment)
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Structured perceptron and averaged structured perceptron (Collins 2002).
//!
//! The **structured perceptron** ("Discriminative Training Methods for Hidden
//! Markov Models", Collins, EMNLP 2002) trains a linear sequence tagger by the
//! mistake-driven perceptron rule.  For each training sentence the current
//! weights `w` are used to Viterbi-decode a predicted tag sequence `ŷ`; if
//! `ŷ ≠ y` the weights are corrected toward the gold features and away from the
//! predicted features:
//!
//! ```text
//! w ← w + φ(x, y) − φ(x, ŷ)
//! ```
//!
//! where `φ` is the global feature map decomposing into local emission and
//! transition features.  This crate uses the same parameterisation as the
//! linear-chain CRF: real-valued emission features per position combined with a
//! dense `n_labels × n_labels` transition table.
//!
//! The **averaged perceptron** (Freund & Schapire 1999, popularised by Collins)
//! returns the *average* of all weight vectors seen during training rather than
//! the final one, which dramatically reduces variance and overfitting.  We use
//! the efficient lazy-update trick of Daumé (a running total accumulator
//! `w_total += w` after every example) so averaging costs `O(P)` once at the end
//! rather than `O(P)` per update.

use crate::error::{SeqError, SeqResult};

// ─── Model ───────────────────────────────────────────────────────────────────

/// A linear-chain structured perceptron tagger.
///
/// Parameter layout (identical to `LinearChainCrf`):
/// * `emissions[label*n_features + k]` — weight for feature `k` under `label`.
/// * `transitions[prev*n_labels + cur]` — score of the `prev → cur` bigram.
#[derive(Debug, Clone)]
pub struct StructuredPerceptron {
    /// Number of output labels.
    pub n_labels: usize,
    /// Number of (real-valued) emission features per position.
    pub n_features: usize,
    /// Emission weights, length `n_labels * n_features`.
    pub emissions: Vec<f64>,
    /// Transition weights, length `n_labels * n_labels`.
    pub transitions: Vec<f64>,
}

impl StructuredPerceptron {
    /// Create a zero-initialised perceptron.
    ///
    /// # Errors
    ///
    /// [`SeqError::InvalidConfiguration`] if `n_labels == 0` or `n_features == 0`.
    pub fn zeros(n_labels: usize, n_features: usize) -> SeqResult<Self> {
        if n_labels == 0 || n_features == 0 {
            return Err(SeqError::InvalidConfiguration(
                "n_labels and n_features must be > 0".to_string(),
            ));
        }
        Ok(Self {
            n_labels,
            n_features,
            emissions: vec![0.0; n_labels * n_features],
            transitions: vec![0.0; n_labels * n_labels],
        })
    }

    /// Total number of parameters.
    #[must_use]
    pub fn param_count(&self) -> usize {
        self.n_labels * self.n_features + self.n_labels * self.n_labels
    }

    /// Emission score `w_label · x_t`.
    fn emit_score(&self, label: usize, x: &[f64]) -> f64 {
        let base = label * self.n_features;
        let mut s = 0.0;
        for (k, &xv) in x.iter().enumerate() {
            s += self.emissions[base + k] * xv;
        }
        s
    }

    /// Viterbi decode the highest-scoring label sequence for feature matrix
    /// `x` (`T × n_features`, row-major).
    ///
    /// # Errors
    ///
    /// * [`SeqError::EmptyInput`]    — if `x` is empty.
    /// * [`SeqError::ShapeMismatch`] — if `x.len()` is not a multiple of
    ///   `n_features`.
    pub fn decode(&self, x: &[f64]) -> SeqResult<Vec<usize>> {
        if x.is_empty() {
            return Err(SeqError::EmptyInput);
        }
        let k = self.n_features;
        if x.len() % k != 0 {
            return Err(SeqError::ShapeMismatch {
                expected: x.len().div_ceil(k) * k,
                got: x.len(),
            });
        }
        let n = self.n_labels;
        let t_max = x.len() / k;

        let mut delta = vec![f64::NEG_INFINITY; t_max * n];
        let mut psi = vec![0usize; t_max * n];

        // t = 0: emission only.
        for j in 0..n {
            delta[j] = self.emit_score(j, &x[..k]);
        }
        for t in 1..t_max {
            let xt = &x[t * k..(t + 1) * k];
            for j in 0..n {
                let emit = self.emit_score(j, xt);
                let mut best = f64::NEG_INFINITY;
                let mut argmax = 0usize;
                for i in 0..n {
                    let v = delta[(t - 1) * n + i] + self.transitions[i * n + j];
                    if v > best {
                        best = v;
                        argmax = i;
                    }
                }
                delta[t * n + j] = best + emit;
                psi[t * n + j] = argmax;
            }
        }

        // Termination.
        let mut best = f64::NEG_INFINITY;
        let mut last = 0usize;
        for j in 0..n {
            let v = delta[(t_max - 1) * n + j];
            if v > best {
                best = v;
                last = j;
            }
        }
        let mut path = vec![0usize; t_max];
        path[t_max - 1] = last;
        for t in (1..t_max).rev() {
            path[t - 1] = psi[t * n + path[t]];
        }
        Ok(path)
    }

    /// Total linear score of a full label sequence `y` under `x`.
    ///
    /// # Errors
    ///
    /// * [`SeqError::EmptyInput`]      — if `y` is empty.
    /// * [`SeqError::ShapeMismatch`]   — if `x.len() ≠ y.len() * n_features`.
    /// * [`SeqError::IndexOutOfBounds`] — if any label `≥ n_labels`.
    pub fn sequence_score(&self, x: &[f64], y: &[usize]) -> SeqResult<f64> {
        if y.is_empty() {
            return Err(SeqError::EmptyInput);
        }
        let k = self.n_features;
        let t_max = y.len();
        if x.len() != t_max * k {
            return Err(SeqError::ShapeMismatch {
                expected: t_max * k,
                got: x.len(),
            });
        }
        let mut s = 0.0;
        for t in 0..t_max {
            if y[t] >= self.n_labels {
                return Err(SeqError::IndexOutOfBounds {
                    index: y[t],
                    len: self.n_labels,
                });
            }
            s += self.emit_score(y[t], &x[t * k..(t + 1) * k]);
            if t > 0 {
                s += self.transitions[y[t - 1] * self.n_labels + y[t]];
            }
        }
        Ok(s)
    }

    /// Apply the perceptron correction `θ ← θ + φ(gold) − φ(pred)` in place,
    /// returning the number of positions where `gold` and `pred` differ.
    ///
    /// Both label sequences must have length `T = x.len() / n_features`.
    ///
    /// # Errors
    ///
    /// * [`SeqError::LengthMismatch`]  — if `gold.len() ≠ pred.len()`.
    /// * [`SeqError::ShapeMismatch`]   — if shapes are inconsistent.
    /// * [`SeqError::IndexOutOfBounds`] — if any label is out of range.
    pub fn update(&mut self, x: &[f64], gold: &[usize], pred: &[usize]) -> SeqResult<usize> {
        if gold.len() != pred.len() {
            return Err(SeqError::LengthMismatch {
                a: gold.len(),
                b: pred.len(),
            });
        }
        let k = self.n_features;
        let t_max = gold.len();
        if x.len() != t_max * k {
            return Err(SeqError::ShapeMismatch {
                expected: t_max * k,
                got: x.len(),
            });
        }
        let n = self.n_labels;
        for &lbl in gold.iter().chain(pred.iter()) {
            if lbl >= n {
                return Err(SeqError::IndexOutOfBounds { index: lbl, len: n });
            }
        }

        let mut mistakes = 0usize;
        // Emission features.
        for t in 0..t_max {
            if gold[t] == pred[t] {
                continue;
            }
            mistakes += 1;
            let xt = &x[t * k..(t + 1) * k];
            let gbase = gold[t] * k;
            let pbase = pred[t] * k;
            for (idx, &xv) in xt.iter().enumerate() {
                self.emissions[gbase + idx] += xv;
                self.emissions[pbase + idx] -= xv;
            }
        }
        // Transition features.
        for t in 1..t_max {
            let g = gold[t - 1] * n + gold[t];
            let p = pred[t - 1] * n + pred[t];
            if g != p {
                self.transitions[g] += 1.0;
                self.transitions[p] -= 1.0;
            }
        }
        Ok(mistakes)
    }
}

// ─── Training configuration ──────────────────────────────────────────────────

/// Configuration for perceptron training.
#[derive(Debug, Clone)]
pub struct PerceptronConfig {
    /// Number of passes (epochs) over the training set.
    pub epochs: usize,
    /// Whether to return the averaged weight vector (Collins averaging).
    pub averaged: bool,
}

impl Default for PerceptronConfig {
    fn default() -> Self {
        Self {
            epochs: 10,
            averaged: true,
        }
    }
}

/// One training example: a feature matrix `x` (`T × n_features`) and a gold
/// label sequence `y` (`T`).
#[derive(Debug, Clone)]
pub struct PerceptronExample {
    /// Feature matrix, row-major `T × n_features`.
    pub x: Vec<f64>,
    /// Gold labels, length `T`.
    pub y: Vec<usize>,
}

/// Result of perceptron training.
#[derive(Debug, Clone)]
pub struct PerceptronTrainResult {
    /// The trained model (averaged iff `config.averaged`).
    pub model: StructuredPerceptron,
    /// Total number of mistaken positions over the final epoch.
    pub final_epoch_mistakes: usize,
    /// Number of epochs actually run.
    pub epochs_run: usize,
}

/// Train a structured perceptron on the given examples.
///
/// The model is updated example-by-example.  When `config.averaged` is set the
/// returned model is the running average of all weight vectors (the standard
/// "averaged perceptron"); the running total is accumulated after every example
/// so that each weight vector contributes once per example it survived.
///
/// # Errors
///
/// * [`SeqError::EmptyInput`]    — if `examples` is empty.
/// * [`SeqError::ShapeMismatch`] — if any example's `x` length is not
///   `y.len() * n_features`.
/// * Propagates decode/update errors.
pub fn train_perceptron(
    n_labels: usize,
    n_features: usize,
    examples: &[PerceptronExample],
    config: &PerceptronConfig,
) -> SeqResult<PerceptronTrainResult> {
    if examples.is_empty() {
        return Err(SeqError::EmptyInput);
    }
    let mut model = StructuredPerceptron::zeros(n_labels, n_features)?;
    let p = model.param_count();
    // Running total for averaging (emissions then transitions, same layout).
    let mut total = vec![0.0_f64; p];
    let mut n_updates = 0u64;
    let mut final_mistakes = 0usize;

    for epoch in 0..config.epochs.max(1) {
        let mut epoch_mistakes = 0usize;
        for ex in examples {
            let t_max = ex.y.len();
            if t_max == 0 || ex.x.len() != t_max * n_features {
                return Err(SeqError::ShapeMismatch {
                    expected: t_max * n_features,
                    got: ex.x.len(),
                });
            }
            let pred = model.decode(&ex.x)?;
            let mistakes = model.update(&ex.x, &ex.y, &pred)?;
            epoch_mistakes += mistakes;

            if config.averaged {
                // Accumulate the *current* weight vector after the update.
                accumulate(&model, &mut total);
                n_updates += 1;
            }
        }
        final_mistakes = epoch_mistakes;
        // Early-stop hint: a perfectly separable pass converges.
        if epoch_mistakes == 0 {
            // Still keep accumulating handled above; break after recording.
            return finish(model, total, n_updates, final_mistakes, epoch + 1, config);
        }
    }

    finish(
        model,
        total,
        n_updates,
        final_mistakes,
        config.epochs.max(1),
        config,
    )
}

/// Add the model's current weights into the running total.
fn accumulate(model: &StructuredPerceptron, total: &mut [f64]) {
    let cut = model.emissions.len();
    for (t, &e) in total[..cut].iter_mut().zip(model.emissions.iter()) {
        *t += e;
    }
    for (t, &tr) in total[cut..].iter_mut().zip(model.transitions.iter()) {
        *t += tr;
    }
}

/// Finalise training, applying averaging if requested.
fn finish(
    mut model: StructuredPerceptron,
    total: Vec<f64>,
    n_updates: u64,
    final_mistakes: usize,
    epochs_run: usize,
    config: &PerceptronConfig,
) -> SeqResult<PerceptronTrainResult> {
    if config.averaged && n_updates > 0 {
        let inv = 1.0 / n_updates as f64;
        let cut = model.emissions.len();
        for (e, &t) in model.emissions.iter_mut().zip(total[..cut].iter()) {
            *e = t * inv;
        }
        for (tr, &t) in model.transitions.iter_mut().zip(total[cut..].iter()) {
            *tr = t * inv;
        }
    }
    Ok(PerceptronTrainResult {
        model,
        final_epoch_mistakes: final_mistakes,
        epochs_run,
    })
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    /// Build a separable toy dataset: 2 labels, 2 features where feature `j`
    /// is an indicator that the gold label is `j`.  A perceptron must learn to
    /// route feature 0 → label 0 and feature 1 → label 1.
    fn toy_examples() -> Vec<PerceptronExample> {
        vec![
            PerceptronExample {
                // tags 0,1,0
                x: vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0],
                y: vec![0, 1, 0],
            },
            PerceptronExample {
                // tags 1,0,1
                x: vec![0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
                y: vec![1, 0, 1],
            },
        ]
    }

    #[test]
    fn zeros_rejects_bad_dims() {
        assert!(StructuredPerceptron::zeros(0, 3).is_err());
        assert!(StructuredPerceptron::zeros(3, 0).is_err());
        assert!(StructuredPerceptron::zeros(2, 2).is_ok());
    }

    #[test]
    fn param_count_correct() {
        let m = StructuredPerceptron::zeros(3, 4).expect("ok");
        assert_eq!(m.param_count(), 3 * 4 + 3 * 3);
    }

    #[test]
    fn zero_model_decodes_first_label() {
        // All-zero weights: every path scores 0; argmax ties resolve to label 0.
        let m = StructuredPerceptron::zeros(2, 2).expect("ok");
        let y = m.decode(&[1.0, 0.0, 0.0, 1.0]).expect("ok");
        assert_eq!(y, vec![0, 0]);
    }

    #[test]
    fn decode_rejects_empty() {
        let m = StructuredPerceptron::zeros(2, 2).expect("ok");
        assert!(matches!(m.decode(&[]), Err(SeqError::EmptyInput)));
    }

    #[test]
    fn decode_rejects_bad_shape() {
        let m = StructuredPerceptron::zeros(2, 3).expect("ok");
        // length 4 is not a multiple of n_features=3.
        assert!(matches!(
            m.decode(&[1.0, 2.0, 3.0, 4.0]),
            Err(SeqError::ShapeMismatch { .. })
        ));
    }

    #[test]
    fn sequence_score_rejects_oob_label() {
        let m = StructuredPerceptron::zeros(2, 2).expect("ok");
        assert!(matches!(
            m.sequence_score(&[1.0, 0.0], &[5]),
            Err(SeqError::IndexOutOfBounds { .. })
        ));
    }

    #[test]
    fn update_rejects_length_mismatch() {
        let mut m = StructuredPerceptron::zeros(2, 2).expect("ok");
        assert!(matches!(
            m.update(&[1.0, 0.0], &[0], &[0, 1]),
            Err(SeqError::LengthMismatch { .. })
        ));
    }

    #[test]
    fn update_counts_mistakes_and_moves_weights() {
        let mut m = StructuredPerceptron::zeros(2, 2).expect("ok");
        let x = vec![1.0, 0.0, 0.0, 1.0]; // T=2
        let gold = vec![0, 1];
        let pred = vec![1, 0];
        let mistakes = m.update(&x, &gold, &pred).expect("ok");
        assert_eq!(mistakes, 2);
        // emission[label0, feat0] should have increased (gold uses feat0→label0).
        assert!(m.emissions[0] > 0.0);
        // After the correction, gold now scores higher than pred.
        let sg = m.sequence_score(&x, &gold).expect("ok");
        let sp = m.sequence_score(&x, &pred).expect("ok");
        assert!(sg > sp, "gold {sg} should exceed pred {sp}");
    }

    #[test]
    fn update_no_mistakes_is_noop() {
        let mut m = StructuredPerceptron::zeros(2, 2).expect("ok");
        let x = vec![1.0, 0.0, 0.0, 1.0];
        let y = vec![0, 1];
        let before = m.emissions.clone();
        let mistakes = m.update(&x, &y, &y).expect("ok");
        assert_eq!(mistakes, 0);
        assert_eq!(before, m.emissions);
    }

    #[test]
    fn train_rejects_empty() {
        let cfg = PerceptronConfig::default();
        assert!(matches!(
            train_perceptron(2, 2, &[], &cfg),
            Err(SeqError::EmptyInput)
        ));
    }

    #[test]
    fn train_learns_separable_data() {
        let ex = toy_examples();
        let cfg = PerceptronConfig {
            epochs: 20,
            averaged: false,
        };
        let res = train_perceptron(2, 2, &ex, &cfg).expect("ok");
        // After training the model must decode every example correctly.
        for e in &ex {
            let pred = res.model.decode(&e.x).expect("ok");
            assert_eq!(pred, e.y, "model failed to fit training example");
        }
    }

    #[test]
    fn train_converges_to_zero_mistakes() {
        let ex = toy_examples();
        let cfg = PerceptronConfig {
            epochs: 50,
            averaged: false,
        };
        let res = train_perceptron(2, 2, &ex, &cfg).expect("ok");
        assert_eq!(
            res.final_epoch_mistakes, 0,
            "separable data should converge to 0 mistakes"
        );
        assert!(res.epochs_run <= 50);
    }

    #[test]
    fn averaged_perceptron_fits_and_is_finite() {
        let ex = toy_examples();
        let cfg = PerceptronConfig {
            epochs: 20,
            averaged: true,
        };
        let res = train_perceptron(2, 2, &ex, &cfg).expect("ok");
        assert!(res.model.emissions.iter().all(|v| v.is_finite()));
        for e in &ex {
            let pred = res.model.decode(&e.x).expect("ok");
            assert_eq!(pred, e.y);
        }
    }

    #[test]
    fn averaging_equals_mean_of_trajectory() {
        // Deterministic averaging check on a *single* example over 2 epochs.
        // Epoch 0: weights start at 0, prediction is all-label-0, the example
        // has a mistake → one update giving weight vector w₁.  Epoch 1: the
        // example is now classified correctly → no update, weight stays w₁.
        // The averaged model accumulates [w₁ (after ep0), w₁ (after ep1)], so
        // the average is exactly w₁ == the raw final weights here.
        let ex = vec![PerceptronExample {
            x: vec![1.0, 0.0, 0.0, 1.0],
            y: vec![0, 1],
        }];
        let avg = train_perceptron(
            2,
            2,
            &ex,
            &PerceptronConfig {
                epochs: 2,
                averaged: true,
            },
        )
        .expect("ok");
        let raw = train_perceptron(
            2,
            2,
            &ex,
            &PerceptronConfig {
                epochs: 2,
                averaged: false,
            },
        )
        .expect("ok");
        // Both should decode the example correctly.
        assert_eq!(avg.model.decode(&ex[0].x).expect("d"), ex[0].y);
        assert_eq!(raw.model.decode(&ex[0].x).expect("d"), ex[0].y);
        // Averaged weights are a convex mean of the trajectory, hence finite
        // and never larger in magnitude than the raw final weights.
        for (a, r) in avg.model.emissions.iter().zip(raw.model.emissions.iter()) {
            assert!(a.abs() <= r.abs() + 1e-9, "avg {a} exceeds raw {r}");
        }
    }

    #[test]
    fn averaging_shrinks_when_trajectory_varies() {
        // A dataset whose two examples *pull weights in opposite directions*
        // each epoch keeps the weight trajectory oscillating, so the running
        // average has strictly smaller magnitude than the final weights for at
        // least one coordinate.
        let ex = vec![
            PerceptronExample {
                x: vec![1.0, 0.0],
                y: vec![0],
            },
            PerceptronExample {
                x: vec![1.0, 0.0],
                y: vec![1],
            },
        ];
        let avg = train_perceptron(
            2,
            2,
            &ex,
            &PerceptronConfig {
                epochs: 6,
                averaged: true,
            },
        )
        .expect("ok");
        let raw = train_perceptron(
            2,
            2,
            &ex,
            &PerceptronConfig {
                epochs: 6,
                averaged: false,
            },
        )
        .expect("ok");
        let diff: f64 = avg
            .model
            .emissions
            .iter()
            .zip(raw.model.emissions.iter())
            .map(|(a, b)| (a - b).abs())
            .sum();
        assert!(
            diff > 1e-9,
            "with a non-separable oscillating dataset averaging must differ from final"
        );
    }

    #[test]
    fn train_rejects_inconsistent_example_shape() {
        let bad = vec![PerceptronExample {
            x: vec![1.0, 0.0, 0.0], // 3 entries, but T=2 needs 4
            y: vec![0, 1],
        }];
        let cfg = PerceptronConfig::default();
        assert!(matches!(
            train_perceptron(2, 2, &bad, &cfg),
            Err(SeqError::ShapeMismatch { .. })
        ));
    }
}