trustformers 0.1.1

TrustformeRS - Rust port of Hugging Face Transformers
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
//! # Token Classification Metrics for TrustformeRS
//!
//! This module provides evaluation metrics for token classification tasks, including
//! Named Entity Recognition (NER), part-of-speech tagging, and sequence labeling.
//!
//! ## Overview
//!
//! The `TokenClassificationMetric` implementation provides evaluation for token-level
//! classification tasks using precision, recall, and F1 scores. It handles entity-level
//! evaluation for NER and other structured prediction tasks.
//!
//! ## Features
//!
//! - **Entity-level evaluation**: Evaluates complete entities, not just individual tokens
//! - **Precision/Recall/F1**: Standard metrics for classification quality
//! - **Multiple tag schemes**: Supports various tagging formats (IOB, IOBES, etc.)
//! - **Flexible input**: Handles different input formats for predictions and references
//!
//! ## Usage Examples
//!
//! ### Basic NER Evaluation
//!
//! ```rust,ignore
//! use trustformers::auto::metrics::{TokenClassificationMetric, MetricInput, Metric};
//!
//! let mut metric = TokenClassificationMetric::new();
//!
//! // Token-level predictions and references
//! let predictions = MetricInput::Spans(vec![
//!     vec![(0, 2, "PERSON".to_string()), (5, 8, "LOCATION".to_string())],
//!     vec![(1, 3, "ORG".to_string())],
//! ]);
//! let references = MetricInput::Spans(vec![
//!     vec![(0, 2, "PERSON".to_string()), (5, 8, "LOCATION".to_string())],
//!     vec![(1, 4, "ORG".to_string())], // Different span boundary
//! ]);
//!
//! metric.add_batch(&predictions, &references)?;
//!
//! // Compute results
//! let result = metric.compute()?;
//! println!("Token Classification F1: {:.3}", result.value);
//! println!("Precision: {:.3}", result.details.get("precision").unwrap());
//! println!("Recall: {:.3}", result.details.get("recall").unwrap());
//! ```
//!
//! ### Sequence Labeling with Tags
//!
//! ```rust,ignore
//! use trustformers::auto::metrics::{TokenClassificationMetric, MetricInput, Metric};
//!
//! let mut metric = TokenClassificationMetric::new();
//!
//! // Using text-based tag sequences (simplified for demonstration)
//! // In practice, you would convert IOB tags to spans first
//! let predictions = MetricInput::Text(vec![
//!     "B-PER I-PER O B-LOC O".to_string(),
//! ]);
//! let references = MetricInput::Text(vec![
//!     "B-PER I-PER O B-LOC O".to_string(),
//! ]);
//!
//! metric.add_batch(&predictions, &references)?;
//! let result = metric.compute()?;
//! ```
//!
//! ## Implementation Details
//!
//! ### Entity Evaluation
//!
//! Token classification is evaluated at the entity level:
//! - **Exact Match**: An entity is correct only if both boundaries and type match exactly
//! - **Precision**: `correct_entities / predicted_entities`
//! - **Recall**: `correct_entities / reference_entities`
//! - **F1**: `2 * precision * recall / (precision + recall)`
//!
//! ### Supported Input Formats
//!
//! 1. **Spans**: List of (start, end, label) tuples for each sequence
//! 2. **Text**: Tag sequences that can be parsed into entities
//!
//! ### Performance Characteristics
//!
//! - **Time complexity**: O(n*m) where n and m are numbers of predicted and reference entities
//! - **Space complexity**: O(n) for storing entity spans
//! - **Entity matching**: Fast exact matching for span boundaries and labels

use super::{Metric, MetricInput, MetricResult};
use crate::error::{Result, TrustformersError};
use std::collections::HashMap;

/// Token classification metric implementation
///
/// Provides evaluation metrics for token classification tasks with entity-level
/// evaluation using precision, recall, and F1 scores.
///
/// ## Design Principles
///
/// - **Entity-centric**: Evaluates complete entities rather than individual tokens
/// - **Strict matching**: Requires exact boundary and label agreement
/// - **Standard metrics**: Implements widely-used NER evaluation measures
/// - **Flexible input**: Supports multiple input formats for different use cases
///
/// ## Supported Input Types
///
/// - `Spans`: Entity spans as (start, end, label) tuples
/// - `Text`: Tag sequences (for backward compatibility and simple cases)
///
/// ## Evaluation Philosophy
///
/// Entity-level evaluation is stricter but more meaningful than token-level evaluation
/// because it requires models to correctly identify complete entities, not just
/// individual tokens within entities.
#[derive(Debug, Clone)]
pub struct TokenClassificationMetric {
    /// Accumulated predicted entity spans for each sequence
    predictions: Vec<Vec<String>>,
    /// Accumulated reference entity spans for each sequence
    references: Vec<Vec<String>>,
}

impl TokenClassificationMetric {
    /// Create a new token classification metric instance
    ///
    /// Initializes an empty metric ready to accumulate entity predictions and references.
    ///
    /// # Returns
    ///
    /// New `TokenClassificationMetric` instance with empty state.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use trustformers::auto::metrics::TokenClassificationMetric;
    ///
    /// let metric = TokenClassificationMetric::new();
    /// assert_eq!(metric.name(), "token_classification");
    /// ```
    pub fn new() -> Self {
        Self {
            predictions: Vec::new(),
            references: Vec::new(),
        }
    }

    /// Convert spans to comparable string representations
    ///
    /// Converts entity spans to string format for easy comparison and storage.
    /// Each span becomes a string in the format "start:end:label".
    ///
    /// # Arguments
    ///
    /// * `spans` - Vector of (start, end, label) tuples
    ///
    /// # Returns
    ///
    /// Vector of string representations for each span
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let spans = vec![(0, 3, "PERSON".to_string()), (5, 8, "LOC".to_string())];
    /// let strings = convert_spans_to_strings(&spans);
    /// assert_eq!(strings, vec!["0:3:PERSON", "5:8:LOC"]);
    /// ```
    fn convert_spans_to_strings(&self, spans: &[(usize, usize, String)]) -> Vec<String> {
        spans
            .iter()
            .map(|(start, end, label)| format!("{}:{}:{}", start, end, label))
            .collect()
    }

    /// Parse tag sequence into entity spans
    ///
    /// Converts IOB/IOBES tag sequences into entity spans. This is a simplified
    /// implementation that handles basic tag patterns.
    ///
    /// # Arguments
    ///
    /// * `tags` - Space-separated tag sequence (e.g., "B-PER I-PER O B-LOC")
    ///
    /// # Returns
    ///
    /// Vector of entity spans as (start, end, label) tuples
    ///
    /// # Tag Format
    ///
    /// Supports IOB format:
    /// - `B-LABEL`: Beginning of entity with given label
    /// - `I-LABEL`: Inside/continuation of entity with given label
    /// - `O`: Outside any entity
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let tags = "B-PER I-PER O B-LOC O";
    /// let spans = parse_tags_to_spans(tags);
    /// assert_eq!(spans, vec![(0, 2, "PER".to_string()), (3, 4, "LOC".to_string())]);
    /// ```
    fn parse_tags_to_spans(&self, tags: &str) -> Vec<(usize, usize, String)> {
        let tag_list: Vec<&str> = tags.split_whitespace().collect();
        let mut spans = Vec::new();
        let mut current_start = None;
        let mut current_label: Option<String> = None;

        for (i, tag) in tag_list.iter().enumerate() {
            if tag.starts_with("B-") {
                // End previous entity if exists
                if let (Some(start), Some(label)) = (current_start, &current_label) {
                    spans.push((start, i, label.clone()));
                }
                // Start new entity
                current_start = Some(i);
                current_label = Some(tag[2..].to_string());
            } else if tag.starts_with("I-") {
                // Continue current entity (no action needed)
                // Could add validation that label matches current entity
            } else {
                // "O" or other tag - end current entity
                if let (Some(start), Some(label)) = (current_start, &current_label) {
                    spans.push((start, i, label.clone()));
                }
                current_start = None;
                current_label = None;
            }
        }

        // End final entity if exists
        if let (Some(start), Some(label)) = (current_start, current_label) {
            spans.push((start, tag_list.len(), label));
        }

        spans
    }
}

impl Metric for TokenClassificationMetric {
    /// Add a batch of token classification predictions and references
    ///
    /// Accumulates entity data for later metric computation. Supports both
    /// span-based and text-based input formats.
    ///
    /// # Arguments
    ///
    /// * `predictions` - Model predictions (Spans or Text)
    /// * `references` - Ground truth references (Spans or Text)
    ///
    /// # Input Format Requirements
    ///
    /// - **Spans**: Vector of sequences, each containing (start, end, label) tuples
    /// - **Text**: Vector of tag sequences (space-separated IOB tags)
    /// - Both predictions and references must use the same format
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, error if input formats are incompatible.
    ///
    /// # Errors
    ///
    /// - `InvalidInput`: If input types don't match expected formats
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    ///    /// use trustformers::auto::metrics::{TokenClassificationMetric, MetricInput, Metric};
    ///
    /// let mut metric = TokenClassificationMetric::new();
    ///
    /// // Using spans
    /// let predictions = MetricInput::Spans(vec![
    ///     vec![(0, 2, "PERSON".to_string())],
    /// ]);
    /// let references = MetricInput::Spans(vec![
    ///     vec![(0, 2, "PERSON".to_string())],
    /// ]);
    ///
    /// metric.add_batch(&predictions, &references)?;
    ///
    /// // Using text tags
    /// let predictions = MetricInput::Text(vec!["B-PER I-PER O".to_string()]);
    /// let references = MetricInput::Text(vec!["B-PER I-PER O".to_string()]);
    ///
    /// metric.add_batch(&predictions, &references)?;

    fn add_batch(&mut self, predictions: &MetricInput, references: &MetricInput) -> Result<()> {
        match (predictions, references) {
            (MetricInput::Spans(pred_spans), MetricInput::Spans(ref_spans)) => {
                // Convert spans to string representations for easy comparison
                for pred_seq in pred_spans {
                    self.predictions.push(self.convert_spans_to_strings(pred_seq));
                }
                for ref_seq in ref_spans {
                    self.references.push(self.convert_spans_to_strings(ref_seq));
                }
                Ok(())
            },
            (MetricInput::Text(pred_text), MetricInput::Text(ref_text)) => {
                // Parse tag sequences into spans, then convert to strings
                for pred_tags in pred_text {
                    let spans = self.parse_tags_to_spans(pred_tags);
                    self.predictions.push(self.convert_spans_to_strings(&spans));
                }
                for ref_tags in ref_text {
                    let spans = self.parse_tags_to_spans(ref_tags);
                    self.references.push(self.convert_spans_to_strings(&spans));
                }
                Ok(())
            },
            _ => Err(TrustformersError::invalid_input_simple("Invalid input types for token classification metric: expected Spans or Text for both predictions and references".to_string()
            )),
        }
    }

    /// Compute token classification metrics
    ///
    /// Calculates entity-level precision, recall, and F1 scores based on
    /// exact matching of entity boundaries and labels.
    ///
    /// # Returns
    ///
    /// `MetricResult` containing:
    /// - **Primary value**: F1 score (harmonic mean of precision and recall)
    /// - **Details**:
    ///   - `precision`: Proportion of predicted entities that are correct
    ///   - `recall`: Proportion of reference entities that were predicted
    ///   - `f1`: F1 score (same as primary value)
    ///
    /// # Errors
    ///
    /// - Returns valid results even with no data (all metrics = 0.0)
    /// - No errors are returned from this method
    ///
    /// # Algorithm Details
    ///
    /// 1. **Entity Matching**: Count entities that appear in both predictions and references
    /// 2. **Precision**: `correct_entities / total_predicted_entities`
    /// 3. **Recall**: `correct_entities / total_reference_entities`
    /// 4. **F1**: `2 * precision * recall / (precision + recall)`
    ///
    /// # Entity Matching Criteria
    ///
    /// Entities match if:
    /// - Start position is identical
    /// - End position is identical
    /// - Entity label is identical
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    ///    /// use trustformers::auto::metrics::{TokenClassificationMetric, MetricInput, Metric};
    ///
    /// let mut metric = TokenClassificationMetric::new();
    /// metric.add_batch(
    ///     &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]),
    ///     &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]])
    /// )?;
    ///
    /// let result = metric.compute()?;
    /// assert_eq!(result.name, "token_classification");
    /// assert_eq!(result.value, 1.0); // Perfect match
    /// assert_eq!(result.details.get("precision"), Some(&1.0));
    /// assert_eq!(result.details.get("recall"), Some(&1.0));
    /// assert_eq!(result.details.get("f1"), Some(&1.0));

    fn compute(&self) -> Result<MetricResult> {
        let mut total_predicted = 0;
        let mut total_reference = 0;
        let mut total_correct = 0;

        // Count entities across all sequences
        let num_sequences = self.predictions.len().min(self.references.len());

        for i in 0..num_sequences {
            let pred_entities = &self.predictions[i];
            let ref_entities = &self.references[i];

            total_predicted += pred_entities.len();
            total_reference += ref_entities.len();

            // Count correct predictions (entities that appear in both)
            for pred_entity in pred_entities {
                if ref_entities.contains(pred_entity) {
                    total_correct += 1;
                }
            }
        }

        // Calculate metrics
        let precision = if total_predicted > 0 {
            total_correct as f64 / total_predicted as f64
        } else {
            0.0
        };

        let recall = if total_reference > 0 {
            total_correct as f64 / total_reference as f64
        } else {
            0.0
        };

        let f1 = if precision + recall > 0.0 {
            2.0 * precision * recall / (precision + recall)
        } else {
            0.0
        };

        // Build result details
        let mut details = HashMap::new();
        details.insert("precision".to_string(), precision);
        details.insert("recall".to_string(), recall);
        details.insert("f1".to_string(), f1);

        Ok(MetricResult {
            name: "token_classification".to_string(),
            value: f1, // Primary metric is F1 score
            details,
            metadata: HashMap::new(),
        })
    }

    /// Reset the metric state
    ///
    /// Clears all accumulated predictions and references, preparing the metric
    /// for a new evaluation run. This is more efficient than creating a new
    /// metric instance.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    ///    /// use trustformers::auto::metrics::{TokenClassificationMetric, MetricInput, Metric};
    ///
    /// let mut metric = TokenClassificationMetric::new();
    /// metric.add_batch(
    ///     &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]),
    ///     &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]])
    /// )?;
    ///
    /// metric.reset();
    /// // Metric is now ready for new entity data

    fn reset(&mut self) {
        self.predictions.clear();
        self.references.clear();
    }

    /// Get the metric name
    ///
    /// Returns the identifier for this metric type, used in logging and results.
    ///
    /// # Returns
    ///
    /// String slice "token_classification"
    fn name(&self) -> &str {
        "token_classification"
    }
}

impl Default for TokenClassificationMetric {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_token_classification_metric_spans() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Spans(vec![vec![
            (0, 2, "PERSON".to_string()),
            (3, 5, "LOCATION".to_string()),
        ]]);
        let references = MetricInput::Spans(vec![vec![
            (0, 2, "PERSON".to_string()),
            (3, 5, "LOCATION".to_string()),
        ]]);

        metric.add_batch(&predictions, &references).expect("add operation failed");

        let result = metric.compute().expect("operation failed in test");
        assert_eq!(result.name, "token_classification");
        assert_eq!(result.value, 1.0); // Perfect match
        assert_eq!(result.details.get("precision"), Some(&1.0));
        assert_eq!(result.details.get("recall"), Some(&1.0));
        assert_eq!(result.details.get("f1"), Some(&1.0));
    }

    #[test]
    fn test_token_classification_metric_partial_match() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Spans(vec![vec![
            (0, 2, "PERSON".to_string()),
            (3, 5, "LOCATION".to_string()),
        ]]);
        let references = MetricInput::Spans(vec![
            vec![(0, 2, "PERSON".to_string()), (3, 6, "LOCATION".to_string())], // Different end
        ]);

        metric.add_batch(&predictions, &references).expect("add operation failed");

        let result = metric.compute().expect("operation failed in test");
        // Only PERSON matches exactly, LOCATION has different boundaries
        assert_eq!(result.details.get("precision"), Some(&0.5)); // 1/2 predicted correct
        assert_eq!(result.details.get("recall"), Some(&0.5)); // 1/2 reference found
        assert_eq!(result.details.get("f1"), Some(&0.5));
    }

    #[test]
    fn test_token_classification_metric_no_match() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]);
        let references = MetricInput::Spans(vec![vec![(3, 5, "LOCATION".to_string())]]);

        metric.add_batch(&predictions, &references).expect("add operation failed");

        let result = metric.compute().expect("operation failed in test");
        assert_eq!(result.details.get("precision"), Some(&0.0));
        assert_eq!(result.details.get("recall"), Some(&0.0));
        assert_eq!(result.details.get("f1"), Some(&0.0));
    }

    #[test]
    fn test_token_classification_metric_text_tags() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Text(vec!["B-PER I-PER O B-LOC O".to_string()]);
        let references = MetricInput::Text(vec!["B-PER I-PER O B-LOC O".to_string()]);

        metric.add_batch(&predictions, &references).expect("add operation failed");

        let result = metric.compute().expect("operation failed in test");
        assert_eq!(result.value, 1.0); // Perfect match
    }

    #[test]
    fn test_token_classification_metric_empty() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Spans(vec![vec![]]);
        let references = MetricInput::Spans(vec![vec![]]);

        metric.add_batch(&predictions, &references).expect("add operation failed");

        let result = metric.compute().expect("operation failed in test");
        // No entities to evaluate
        assert_eq!(result.details.get("precision"), Some(&0.0));
        assert_eq!(result.details.get("recall"), Some(&0.0));
        assert_eq!(result.details.get("f1"), Some(&0.0));
    }

    #[test]
    fn test_token_classification_metric_reset() {
        let mut metric = TokenClassificationMetric::new();

        metric
            .add_batch(
                &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]),
                &MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]),
            )
            .expect("operation failed in test");

        metric.reset();

        let result = metric.compute().expect("operation failed in test");
        // Should have no data after reset
        assert_eq!(result.value, 0.0);
    }

    #[test]
    fn test_token_classification_metric_invalid_input() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Classifications(vec![0, 1]);
        let references = MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]);

        let result = metric.add_batch(&predictions, &references);
        assert!(result.is_err());
    }

    #[test]
    fn test_convert_spans_to_strings() {
        let metric = TokenClassificationMetric::new();
        let spans = vec![(0, 3, "PERSON".to_string()), (5, 8, "LOC".to_string())];
        let strings = metric.convert_spans_to_strings(&spans);

        assert_eq!(strings, vec!["0:3:PERSON", "5:8:LOC"]);
    }

    #[test]
    fn test_parse_tags_to_spans() {
        let metric = TokenClassificationMetric::new();
        let tags = "B-PER I-PER O B-LOC O B-ORG";
        let spans = metric.parse_tags_to_spans(tags);

        assert_eq!(
            spans,
            vec![
                (0, 2, "PER".to_string()),
                (3, 4, "LOC".to_string()),
                (5, 6, "ORG".to_string()),
            ]
        );
    }

    #[test]
    fn test_parse_tags_empty() {
        let metric = TokenClassificationMetric::new();
        let tags = "O O O";
        let spans = metric.parse_tags_to_spans(tags);

        assert_eq!(spans, vec![]);
    }

    #[test]
    fn test_mixed_input_types() {
        let mut metric = TokenClassificationMetric::new();

        let predictions = MetricInput::Spans(vec![vec![(0, 2, "PERSON".to_string())]]);
        let references = MetricInput::Text(vec!["B-PER I-PER".to_string()]);

        let result = metric.add_batch(&predictions, &references);
        assert!(result.is_err()); // Should reject mixed input types
    }
}