crfs 0.4.1

Pure Rust port of CRFsuite: a fast implementation of Conditional Random Fields (CRFs)
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
use std::io;

use rand::seq::SliceRandom;
use rand::{SeedableRng, rngs::StdRng};

use super::super::crf_context::ForwardBackwardContext;
use super::super::feature_gen::FeatureGenerator;
use super::{L2Sgd, Trainer, TrainingAlgorithm};

/// L2SGD training parameters.
#[derive(Debug, Clone)]
pub struct L2SgdParams {
    c2: f64,
    max_iterations: usize,
    period: usize,
    delta: f64,
    calibration_eta: f64,
    calibration_rate: f64,
    calibration_samples: usize,
    calibration_candidates: usize,
    calibration_max_trials: usize,
    shuffle_seed: Option<u64>,
}

impl Default for L2SgdParams {
    fn default() -> Self {
        Self {
            c2: 1.0,
            max_iterations: 1000,
            period: 10,
            delta: 1e-6,
            calibration_eta: 0.1,
            calibration_rate: 2.0,
            calibration_samples: 1000,
            calibration_candidates: 10,
            calibration_max_trials: 20,
            shuffle_seed: None,
        }
    }
}

impl L2SgdParams {
    pub fn c2(&self) -> f64 {
        self.c2
    }

    pub fn set_c2(&mut self, c2: f64) -> io::Result<()> {
        if c2 < 0.0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "c2 must be non-negative",
            ));
        }
        self.c2 = c2;
        Ok(())
    }

    pub fn max_iterations(&self) -> usize {
        self.max_iterations
    }

    pub fn set_max_iterations(&mut self, max_iterations: usize) -> io::Result<()> {
        if max_iterations < 1 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "max_iterations must be at least 1",
            ));
        }
        self.max_iterations = max_iterations;
        Ok(())
    }

    pub fn period(&self) -> usize {
        self.period
    }

    pub fn set_period(&mut self, period: usize) -> io::Result<()> {
        if period == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "period must be positive",
            ));
        }
        self.period = period;
        Ok(())
    }

    pub fn delta(&self) -> f64 {
        self.delta
    }

    pub fn set_delta(&mut self, delta: f64) -> io::Result<()> {
        if delta <= 0.0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "delta must be positive",
            ));
        }
        self.delta = delta;
        Ok(())
    }

    pub fn calibration_eta(&self) -> f64 {
        self.calibration_eta
    }

    pub fn set_calibration_eta(&mut self, calibration_eta: f64) -> io::Result<()> {
        if calibration_eta <= 0.0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "calibration.eta must be positive",
            ));
        }
        self.calibration_eta = calibration_eta;
        Ok(())
    }

    pub fn calibration_rate(&self) -> f64 {
        self.calibration_rate
    }

    pub fn set_calibration_rate(&mut self, calibration_rate: f64) -> io::Result<()> {
        if calibration_rate <= 1.0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "calibration.rate must be greater than 1.0",
            ));
        }
        self.calibration_rate = calibration_rate;
        Ok(())
    }

    pub fn calibration_samples(&self) -> usize {
        self.calibration_samples
    }

    pub fn set_calibration_samples(&mut self, calibration_samples: usize) -> io::Result<()> {
        if calibration_samples == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "calibration.samples must be positive",
            ));
        }
        self.calibration_samples = calibration_samples;
        Ok(())
    }

    pub fn calibration_candidates(&self) -> usize {
        self.calibration_candidates
    }

    pub fn set_calibration_candidates(&mut self, calibration_candidates: usize) -> io::Result<()> {
        if calibration_candidates == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "calibration.candidates must be positive",
            ));
        }
        self.calibration_candidates = calibration_candidates;
        Ok(())
    }

    pub fn calibration_max_trials(&self) -> usize {
        self.calibration_max_trials
    }

    pub fn set_calibration_max_trials(&mut self, calibration_max_trials: usize) -> io::Result<()> {
        if calibration_max_trials == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "calibration.max_trials must be positive",
            ));
        }
        self.calibration_max_trials = calibration_max_trials;
        Ok(())
    }

    pub fn shuffle_seed(&self) -> Option<u64> {
        self.shuffle_seed
    }

    pub fn set_shuffle_seed(&mut self, seed: Option<u64>) {
        self.shuffle_seed = seed;
    }
}

impl TrainingAlgorithm for L2Sgd {
    type Params = L2SgdParams;

    fn train(trainer: &mut Trainer<Self>, fgen: &mut FeatureGenerator) -> io::Result<()> {
        trainer.train_l2sgd(fgen)
    }
}

impl Trainer<L2Sgd> {
    /// Train using L2SGD algorithm
    pub(super) fn train_l2sgd(&mut self, fgen: &mut FeatureGenerator) -> io::Result<()> {
        let num_features = fgen.num_features();
        let num_labels = self.labels.len();
        let max_items = self
            .instances
            .iter()
            .map(|inst| inst.num_items as usize)
            .max()
            .unwrap_or(0);

        let c2 = self.params.c2();
        let max_iterations = self.params.max_iterations();
        let period = self.params.period();
        let delta = self.params.delta();
        let verbose = self.verbose;

        let mut weights = vec![0.0; num_features];
        let num_instances = self.instances.len();
        let lambda = 2.0 * c2 / num_instances as f64;

        // Create CRF context
        let mut ctx = ForwardBackwardContext::new(num_labels, max_items);

        if verbose {
            println!("Training with L2SGD (c2={})...", c2);
        }

        let mut rng = match self.params.shuffle_seed() {
            Some(seed) => StdRng::seed_from_u64(seed),
            None => {
                let mut thread_rng = rand::rng();
                StdRng::from_rng(&mut thread_rng)
            }
        };

        // Calibration phase: find optimal learning rate
        let t0 = self.calibrate_learning_rate(fgen, &mut ctx, lambda, &mut rng)?;

        if verbose {
            let eta = 1.0 / (lambda * t0);
            println!("Calibrated learning rate: {:.6}", eta);
        }

        // Training loop
        let mut indices: Vec<usize> = (0..self.instances.len()).collect();
        let mut objective_history = vec![0.0; period];
        let mut best_objective = f64::INFINITY;
        let mut best_weights = vec![0.0; num_features];
        let mut t = 0.0f64;

        for epoch in 1..=max_iterations {
            // Shuffle instances for better convergence
            indices.shuffle(&mut rng);

            let mut sum_loss = 0.0;
            let mut loss = 0.0;
            let mut expected = vec![0.0; num_features];
            let mut observed = vec![0.0; num_features];

            for &idx in &indices {
                let inst = &self.instances[idx];
                let seq_len = inst.num_items as usize;

                // Compute learning rate with decay
                let eta = 1.0 / (lambda * (t0 + t));

                // Apply weight decay (L2 regularization)
                let decay = 1.0 - eta * lambda;
                for w in &mut weights {
                    *w *= decay;
                }

                // Compute scores and run forward-backward
                fgen.set_weights(&weights);
                ctx.compute_scores(inst, fgen);
                let log_z = ctx.forward(seq_len);
                ctx.backward(seq_len);
                ctx.compute_marginals(seq_len, log_z);

                // Compute expected and observed counts
                expected.fill(0.0);
                observed.fill(0.0);
                ctx.expected_counts_into(inst, fgen, &mut expected);
                ctx.observed_counts_into(inst, fgen, &mut observed);

                // Update weights: w += eta * (observed - expected)
                let inst_weight = inst.weight;
                for i in 0..num_features {
                    weights[i] += eta * (observed[i] - expected[i]) * inst_weight;
                }

                // Compute loss for this instance
                loss = -ctx.log_likelihood(inst, log_z) * inst_weight;
                sum_loss += loss;
                t += 1.0;
            }

            if !loss.is_finite() {
                return Err(io::Error::other("L2SGD overflow loss"));
            }

            // Include the L2 norm of feature weights to the objective.
            let norm2: f64 = weights.iter().map(|w| w * w).sum();
            sum_loss += 0.5 * lambda * norm2 * num_instances as f64;

            if verbose {
                println!(
                    "Epoch {}: loss = {:.6}, feature_norm = {:.6}",
                    epoch,
                    sum_loss,
                    norm2.sqrt()
                );
            }

            if sum_loss < best_objective {
                best_objective = sum_loss;
                best_weights.clone_from_slice(&weights);
            }

            let improvement = if epoch > period {
                let prev = objective_history[(epoch - 1) % period];
                (prev - sum_loss) / sum_loss
            } else {
                delta
            };

            objective_history[(epoch - 1) % period] = sum_loss;

            if verbose && epoch > period {
                println!("Improvement ratio: {:.6}", improvement);
            }

            if epoch > period && improvement < delta {
                if verbose {
                    println!("Converged at epoch {}", epoch);
                }
                break;
            }
        }

        // Update feature weights
        fgen.set_weights(&best_weights);

        Ok(())
    }

    /// Calibrate learning rate for L2SGD
    fn calibrate_learning_rate(
        &self,
        fgen: &mut FeatureGenerator,
        ctx: &mut ForwardBackwardContext,
        lambda: f64,
        rng: &mut StdRng,
    ) -> io::Result<f64> {
        let num_features = fgen.num_features();
        let num_instances = self.instances.len();

        // Select calibration samples
        let num_samples = self.params.calibration_samples().min(num_instances);
        let mut sample_indices: Vec<usize> = (0..num_instances).collect();
        sample_indices.shuffle(rng);
        sample_indices.truncate(num_samples);

        let mut eta = self.params.calibration_eta();
        let mut best_eta = eta;
        let mut best_loss = f64::INFINITY;
        let mut dec = false;
        let mut num = self.params.calibration_candidates();
        let mut trials = 1;

        // Compute the initial loss without instance weights.
        let mut weights = vec![0.0; num_features];
        let mut initial_loss = 0.0;
        fgen.set_weights(&weights);
        for &idx in &sample_indices {
            let inst = &self.instances[idx];
            let seq_len = inst.num_items as usize;
            ctx.compute_scores(inst, fgen);
            let log_z = ctx.forward(seq_len);
            ctx.backward(seq_len);
            initial_loss += -ctx.log_likelihood(inst, log_z);
        }

        while num > 0 || !dec {
            let t0 = 1.0 / (lambda * eta);
            let mut t = 0.0f64;
            let mut sum_loss = 0.0;
            let mut loss = 0.0;
            let mut expected = vec![0.0; num_features];
            let mut observed = vec![0.0; num_features];
            weights.fill(0.0);

            // Perform SGD for one epoch using the calibration samples.
            for &idx in &sample_indices {
                let inst = &self.instances[idx];
                let seq_len = inst.num_items as usize;

                let eta_step = 1.0 / (lambda * (t0 + t));
                let decay = 1.0 - eta_step * lambda;
                for w in &mut weights {
                    *w *= decay;
                }

                fgen.set_weights(&weights);
                ctx.compute_scores(inst, fgen);
                let log_z = ctx.forward(seq_len);
                ctx.backward(seq_len);
                ctx.compute_marginals(seq_len, log_z);

                expected.fill(0.0);
                observed.fill(0.0);
                ctx.expected_counts_into(inst, fgen, &mut expected);
                ctx.observed_counts_into(inst, fgen, &mut observed);

                let inst_weight = inst.weight;
                for i in 0..num_features {
                    weights[i] += eta_step * (observed[i] - expected[i]) * inst_weight;
                }

                loss = -ctx.log_likelihood(inst, log_z) * inst_weight;
                sum_loss += loss;
                t += 1.0;
            }

            if !loss.is_finite() {
                sum_loss = loss;
            } else {
                let norm2: f64 = weights.iter().map(|w| w * w).sum();
                sum_loss += 0.5 * lambda * norm2 * num_samples as f64;
            }

            let ok = sum_loss.is_finite() && sum_loss < initial_loss;
            if ok {
                num = num.saturating_sub(1);
            }

            if sum_loss.is_finite() && sum_loss < best_loss {
                best_loss = sum_loss;
                best_eta = eta;
            }

            if !dec {
                if ok && num > 0 {
                    eta *= self.params.calibration_rate();
                } else {
                    dec = true;
                    num = self.params.calibration_candidates();
                    eta = self.params.calibration_eta() / self.params.calibration_rate();
                }
            } else {
                eta /= self.params.calibration_rate();
            }

            trials += 1;
            if self.params.calibration_max_trials() <= trials {
                break;
            }
        }

        Ok(1.0 / (lambda * best_eta))
    }
}