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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! NuNER ONNX inference engine and feature extraction.
use super::*;
impl NuNER {
/// Create NuNER with default configuration (512-token context).
///
/// Uses standard NER labels. Call `from_pretrained` (requires `onnx` feature)
/// to load actual model weights.
#[must_use]
pub fn new() -> Self {
Self {
model_id: "numind/NuNER_Zero".to_string(),
threshold: 0.5,
#[cfg(feature = "onnx")]
requires_span_tensors: std::sync::atomic::AtomicBool::new(false),
default_labels: vec![
"person".to_string(),
"organization".to_string(),
"location".to_string(),
"date".to_string(),
"product".to_string(),
"event".to_string(),
],
max_input_chars: super::MAX_INPUT_CHARS_512,
#[cfg(feature = "onnx")]
session: None,
#[cfg(feature = "onnx")]
tokenizer: None,
}
}
/// Create NuNER with 4096-token context configuration.
///
/// Uses `numind/NuNER_Zero-4k` which handles up to 4096 tokens natively,
/// reducing chunking overhead for long documents. Chunks at ~16000 chars
/// instead of ~2000.
///
/// Call `from_pretrained("numind/NuNER_Zero-4k")` to load model weights.
#[must_use]
pub fn new_4k() -> Self {
Self {
model_id: "numind/NuNER_Zero-4k".to_string(),
threshold: 0.5,
#[cfg(feature = "onnx")]
requires_span_tensors: std::sync::atomic::AtomicBool::new(false),
default_labels: vec![
"person".to_string(),
"organization".to_string(),
"location".to_string(),
"date".to_string(),
"product".to_string(),
"event".to_string(),
],
max_input_chars: super::MAX_INPUT_CHARS_4K,
#[cfg(feature = "onnx")]
session: None,
#[cfg(feature = "onnx")]
tokenizer: None,
}
}
/// Load NuNER model from HuggingFace.
///
/// Automatically loads `.env` for HF_TOKEN if present. Auto-detects the 4k
/// variant from the model ID (looks for "4k" case-insensitively) and sets
/// the chunk threshold accordingly.
///
/// # Arguments
/// * `model_id` - HuggingFace model ID (e.g., "deepanwa/NuNerZero_onnx",
/// "numind/NuNER_Zero-4k")
///
/// # Example
/// ```rust,ignore
/// let ner = NuNER::from_pretrained("numind/NuNER_Zero-4k")?;
/// ```
#[cfg(feature = "onnx")]
pub fn from_pretrained(model_id: &str) -> Result<Self> {
use crate::backends::hf_loader;
let api = hf_loader::hf_api()?;
let repo = api.model(model_id.to_string());
let model_path = hf_loader::download_model_file(&repo, &["onnx/model.onnx", "model.onnx"])?;
let tokenizer_path = hf_loader::download_model_file(&repo, &["tokenizer.json"])?;
let session =
hf_loader::create_onnx_session(&model_path, hf_loader::OnnxSessionConfig::default())?;
let tokenizer = hf_loader::load_tokenizer(&tokenizer_path)?;
let is_4k = model_id.to_lowercase().contains("4k");
Ok(Self {
model_id: model_id.to_string(),
threshold: 0.5,
requires_span_tensors: std::sync::atomic::AtomicBool::new(false),
default_labels: vec![
"person".to_string(),
"organization".to_string(),
"location".to_string(),
],
max_input_chars: if is_4k {
super::MAX_INPUT_CHARS_4K
} else {
super::MAX_INPUT_CHARS_512
},
session: Some(std::sync::Mutex::new(session)),
tokenizer: Some(tokenizer),
})
}
/// Create with custom model identifier (for configuration only).
///
/// Auto-detects the 4k variant from the model ID and sets the chunk
/// threshold accordingly.
#[must_use]
pub fn with_model(model_id: impl Into<String>) -> Self {
let id = model_id.into();
let is_4k = id.to_lowercase().contains("4k");
let mut new = if is_4k { Self::new_4k() } else { Self::new() };
new.model_id = id;
new
}
/// Set confidence threshold.
#[must_use]
pub fn with_threshold(mut self, threshold: f64) -> Self {
self.threshold = threshold.clamp(0.0, 1.0);
self
}
/// Set default entity labels for Model trait.
#[must_use]
pub fn with_labels(mut self, labels: Vec<String>) -> Self {
self.default_labels = labels;
self
}
/// Get the model identifier.
#[must_use]
pub fn model_id(&self) -> &str {
&self.model_id
}
/// Get the confidence threshold.
#[must_use]
pub fn threshold(&self) -> f64 {
self.threshold
}
/// Get the max input chars before chunking kicks in.
#[must_use]
pub fn max_input_chars(&self) -> usize {
self.max_input_chars
}
/// Extract entities with custom labels.
///
/// Unlike the `Model` trait which uses default labels, this method
/// allows specifying arbitrary entity types at runtime.
///
/// # Arguments
/// Extract entities with custom labels.
///
/// Unlike the `Model` trait which uses default labels, this method allows specifying
/// arbitrary entity types at runtime. Chunking for long inputs is handled by
/// `Model::extract_entities` in `mod.rs`.
///
/// # Arguments
///
/// * `text` - Text to extract from
/// * `entity_types` - Entity type labels (e.g., `["person", "company"]`)
/// * `threshold` - Confidence threshold (0.0-1.0)
#[cfg(feature = "onnx")]
pub fn extract(
&self,
text: &str,
entity_types: &[&str],
threshold: f32,
) -> Result<Vec<Entity>> {
if text.is_empty() || entity_types.is_empty() {
return Ok(vec![]);
}
// Debug tracing
if std::env::var("ANNO_DEBUG_NUNER_EXTRACT").is_ok() {
eprintln!(
"DEBUG nuner extract: text.len={} entity_types={:?}",
text.len(),
entity_types
);
}
// Chunking is handled by Model::extract_entities in mod.rs.
// This method processes a single (already-chunked) piece of text.
self.extract_single(text, entity_types, threshold)
}
/// Run NuNER inference on a single (non-chunked) piece of text.
#[cfg(feature = "onnx")]
fn extract_single(
&self,
text: &str,
entity_types: &[&str],
threshold: f32,
) -> Result<Vec<Entity>> {
let session = self.session.as_ref().ok_or_else(|| {
Error::Retrieval("Model not loaded. Call from_pretrained() first.".to_string())
})?;
let tokenizer = self
.tokenizer
.as_ref()
.ok_or_else(|| Error::Retrieval("Tokenizer not loaded.".to_string()))?;
// Split text into words
let text_words: Vec<&str> = text.split_whitespace().collect();
if text_words.is_empty() {
return Ok(vec![]);
}
// Encode input (token mode - no span tensors)
let (input_ids, attention_mask, words_mask, text_lengths) =
self.encode_prompt(tokenizer, &text_words, entity_types)?;
let batch_size = 1;
let seq_len = input_ids.len();
// Note: ort tensors are consumed by `into_dyn()`, so we rebuild them for retries.
let make_token_tensors = || -> Result<(_, _, _, _)> {
use ndarray::Array2;
let input_ids_array = Array2::from_shape_vec((batch_size, seq_len), input_ids.clone())
.map_err(|e| Error::Parse(format!("Array error: {}", e)))?;
let attention_mask_array =
Array2::from_shape_vec((batch_size, seq_len), attention_mask.clone())
.map_err(|e| Error::Parse(format!("Array error: {}", e)))?;
let words_mask_array =
Array2::from_shape_vec((batch_size, seq_len), words_mask.clone())
.map_err(|e| Error::Parse(format!("Array error: {}", e)))?;
let text_lengths_array = Array2::from_shape_vec((batch_size, 1), vec![text_lengths])
.map_err(|e| Error::Parse(format!("Array error: {}", e)))?;
let input_ids_t = crate::backends::ort_compat::tensor_from_ndarray(input_ids_array)
.map_err(|e| Error::Parse(format!("Tensor error: {}", e)))?;
let attention_mask_t =
crate::backends::ort_compat::tensor_from_ndarray(attention_mask_array)
.map_err(|e| Error::Parse(format!("Tensor error: {}", e)))?;
let words_mask_t = crate::backends::ort_compat::tensor_from_ndarray(words_mask_array)
.map_err(|e| Error::Parse(format!("Tensor error: {}", e)))?;
let text_lengths_t =
crate::backends::ort_compat::tensor_from_ndarray(text_lengths_array)
.map_err(|e| Error::Parse(format!("Tensor error: {}", e)))?;
Ok((input_ids_t, attention_mask_t, words_mask_t, text_lengths_t))
};
// Some NuNER ONNX exports require span tensors (span_idx/span_mask), others are token-only.
// We default to token-only, and flip to span tensors on the first "missing input" error.
use std::sync::atomic::Ordering;
let mut needs_span_tensors = self.requires_span_tensors.load(Ordering::Relaxed);
// Use blocking lock for thread-safe parallel access
let mut session_guard = session.lock().unwrap_or_else(|e| e.into_inner());
let outputs = loop {
if needs_span_tensors {
let (input_ids_t, attention_mask_t, words_mask_t, text_lengths_t) =
make_token_tensors()?;
// Generate span tensors similar to GLiNER
// Use checked_mul to prevent overflow (same as gliner_multitask/onnx.rs)
let num_spans = match text_words.len().checked_mul(MAX_SPAN_WIDTH) {
Some(v) => v,
None => {
return Err(Error::InvalidInput(format!(
"Span count overflow: {} words * {} MAX_SPAN_WIDTH",
text_words.len(),
MAX_SPAN_WIDTH
)));
}
};
let (span_idx, span_mask) = NuNER::make_span_tensors(text_words.len());
use ndarray::Array2;
use ndarray::Array3;
let span_idx_array = Array3::from_shape_vec((1, num_spans, 2), span_idx)
.map_err(|e| Error::Parse(format!("Span idx array error: {}", e)))?;
let span_mask_array = Array2::from_shape_vec((1, num_spans), span_mask)
.map_err(|e| Error::Parse(format!("Span mask array error: {}", e)))?;
let span_idx_t =
crate::backends::ort_compat::tensor_from_ndarray(span_idx_array)
.map_err(|e| Error::Parse(format!("Span idx tensor error: {}", e)))?;
let span_mask_t = crate::backends::ort_compat::tensor_from_ndarray(span_mask_array)
.map_err(|e| Error::Parse(format!("Span mask tensor error: {}", e)))?;
break session_guard
.run(ort::inputs![
"input_ids" => input_ids_t.into_dyn(),
"attention_mask" => attention_mask_t.into_dyn(),
"words_mask" => words_mask_t.into_dyn(),
"text_lengths" => text_lengths_t.into_dyn(),
"span_idx" => span_idx_t.into_dyn(),
"span_mask" => span_mask_t.into_dyn(),
])
.map_err(|e| {
Error::Parse(format!(
"ONNX inference failed: {}\n\n\
NuNER model: {}\n\
requires_span_tensors={}\n\
input_ids=(1,{seq_len}) attention_mask=(1,{seq_len}) words_mask=(1,{seq_len}) text_lengths=(1,1)\n\
span_idx=(1,{num_spans},2) span_mask=(1,{num_spans})\n\n\
Hint: If this looks like a shape mismatch, the ONNX export may have fixed span dimensions.\n\
Try a different NuNER export (e.g., deepanwa/NuNerZero_onnx) or re-export with dynamic axes.",
e,
self.model_id,
self.requires_span_tensors.load(Ordering::Relaxed)
))
})?;
} else {
let (input_ids_t, attention_mask_t, words_mask_t, text_lengths_t) =
make_token_tensors()?;
// Token mode - only 4 inputs
let res = session_guard.run(ort::inputs![
"input_ids" => input_ids_t.into_dyn(),
"attention_mask" => attention_mask_t.into_dyn(),
"words_mask" => words_mask_t.into_dyn(),
"text_lengths" => text_lengths_t.into_dyn(),
]);
match res {
Ok(o) => break o,
Err(e) => {
let msg = format!("{e}");
let looks_like_missing_span = msg.contains("Missing Input: span_mask")
|| msg.contains("Missing Input: span_idx")
|| msg.contains("span_mask")
|| msg.contains("span_idx");
if looks_like_missing_span {
// Memoize and retry once in span mode (same request).
self.requires_span_tensors.store(true, Ordering::Relaxed);
needs_span_tensors = true;
continue;
}
return Err(Error::Parse(format!(
"ONNX inference failed: {}\n\n\
NuNER model: {}\n\
requires_span_tensors={}\n\
input_ids=(1,{seq_len}) attention_mask=(1,{seq_len}) words_mask=(1,{seq_len}) text_lengths=(1,1)\n\n\
Hint: If this looks like an input-name mismatch, your ONNX export may expect span tensors or different input names.",
e,
self.model_id,
self.requires_span_tensors.load(Ordering::Relaxed),
)));
}
}
}
};
// Decode span-level output to entities
// NuNER with span_mode=marker and max_width=1 outputs: [batch, num_words, max_width, num_classes]
let entities =
self.decode_span_output(&outputs, text, &text_words, entity_types, threshold)?;
Ok(entities)
}
/// Generate span tensors for span-based inference (if model requires it).
///
/// Matches Python GLiNER's prepare_span_idx function:
/// `span_idx = [(i, i + j) for i in range(num_tokens) for j in range(max_width)]`
///
/// With MAX_SPAN_WIDTH=1, generates single-word spans only: (0,0), (1,1), etc.
/// Span indices use INCLUSIVE end positions (matching Python GLiNER).
///
/// Returns: (span_idx, span_mask)
/// - span_idx: [num_spans, 2] - (start, end) word indices (both 0-indexed, inclusive)
/// - span_mask: [num_spans] - boolean mask indicating valid spans
#[cfg(feature = "onnx")]
pub(crate) fn make_span_tensors(num_words: usize) -> (Vec<i64>, Vec<bool>) {
// Use checked_mul to prevent overflow (same as gliner_multitask/onnx.rs)
let num_spans = match num_words.checked_mul(MAX_SPAN_WIDTH) {
Some(v) => v,
None => {
// Overflow - return empty tensors (shouldn't happen in practice)
log::warn!(
"Span count overflow: {} words * {} MAX_SPAN_WIDTH, returning empty tensors",
num_words,
MAX_SPAN_WIDTH
);
return (Vec::new(), Vec::new());
}
};
// Check for overflow in num_spans * 2
let span_idx_len = match num_spans.checked_mul(2) {
Some(v) => v,
None => {
log::warn!(
"Span idx length overflow: {} spans * 2, returning empty tensors",
num_spans
);
return (Vec::new(), Vec::new());
}
};
let mut span_idx: Vec<i64> = vec![0; span_idx_len];
let mut span_mask: Vec<bool> = vec![false; num_spans];
for start in 0..num_words {
let remaining_width = num_words - start;
let actual_max_width = MAX_SPAN_WIDTH.min(remaining_width);
for width in 0..actual_max_width {
// Check for overflow in dim calculation
let dim = match start.checked_mul(MAX_SPAN_WIDTH) {
Some(v) => match v.checked_add(width) {
Some(d) => d,
None => {
log::warn!(
"Dim calculation overflow: {} * {} + {}, skipping span",
start,
MAX_SPAN_WIDTH,
width
);
continue;
}
},
None => {
log::warn!(
"Dim calculation overflow: {} * {}, skipping span",
start,
MAX_SPAN_WIDTH
);
continue;
}
};
// Check bounds before array access (dim * 2 could overflow or exceed span_idx_len)
if let Some(dim2) = dim.checked_mul(2) {
if dim2 + 1 < span_idx_len && dim < num_spans {
span_idx[dim2] = start as i64; // start offset (0-indexed, inclusive)
span_idx[dim2 + 1] = (start + width) as i64; // end offset (0-indexed, INCLUSIVE per Python GLiNER)
span_mask[dim] = true;
} else {
log::warn!(
"Span idx access out of bounds: dim={}, dim*2={}, span_idx_len={}, num_spans={}, skipping",
dim, dim2, span_idx_len, num_spans
);
}
} else {
log::warn!("Dim * 2 overflow: dim={}, skipping span", dim);
}
}
}
(span_idx, span_mask)
}
/// Encode prompt for token mode (no span tensors).
#[cfg(feature = "onnx")]
fn encode_prompt(
&self,
tokenizer: &tokenizers::Tokenizer,
text_words: &[&str],
entity_types: &[&str],
) -> Result<EncodedPrompt> {
// Performance: Pre-allocate vectors with estimated capacity
// Most prompts have 50-200 tokens
let mut input_ids: Vec<i64> = Vec::with_capacity(128);
let mut word_mask: Vec<i64> = Vec::with_capacity(128);
// [START]
input_ids.push(TOKEN_START as i64);
word_mask.push(0);
// <<ENT>> type1 <<ENT>> type2 ...
for entity_type in entity_types {
input_ids.push(TOKEN_ENT as i64);
word_mask.push(0);
let encoding = tokenizer
.encode(entity_type.to_string(), false)
.map_err(|e| Error::Parse(format!("Tokenizer error: {}", e)))?;
for token_id in encoding.get_ids() {
input_ids.push(*token_id as i64);
word_mask.push(0);
}
}
// <<SEP>>
input_ids.push(TOKEN_SEP as i64);
word_mask.push(0);
// Text words (word_mask starts from 1)
let mut word_id: i64 = 0;
for word in text_words {
let encoding = tokenizer
.encode(word.to_string(), false)
.map_err(|e| Error::Parse(format!("Tokenizer error: {}", e)))?;
word_id += 1;
for (token_idx, token_id) in encoding.get_ids().iter().enumerate() {
input_ids.push(*token_id as i64);
word_mask.push(if token_idx == 0 { word_id } else { 0 });
}
}
// [END]
input_ids.push(TOKEN_END as i64);
word_mask.push(0);
let seq_len = input_ids.len();
let attention_mask: Vec<i64> = vec![1; seq_len];
Ok((input_ids, attention_mask, word_mask, word_id))
}
/// Decode token classification output to entities.
///
/// Token mode output shape: [batch, seq_len, num_entity_types]
/// Each position has scores for each entity type (BIO-style).
#[cfg(feature = "onnx")]
fn decode_token_output(
&self,
outputs: &ort::session::SessionOutputs,
text: &str,
text_words: &[&str],
entity_types: &[&str],
threshold: f32,
) -> Result<Vec<Entity>> {
let output = outputs
.iter()
.next()
.map(|(_, v)| v)
.ok_or_else(|| Error::Parse("No output from NuNER model".to_string()))?;
let (_, data_slice) = output
.try_extract_tensor::<f32>()
.map_err(|e| Error::Parse(format!("Failed to extract output tensor: {}", e)))?;
let output_data: Vec<f32> = data_slice.to_vec();
// Get shape: [batch, num_words, num_classes]
let shape: Vec<i64> = match output.dtype() {
ort::value::ValueType::Tensor { shape, .. } => shape.iter().copied().collect(),
_ => return Err(Error::Parse("Expected tensor output".to_string())),
};
// Debug output shape
if std::env::var("ANNO_DEBUG_NUNER_DECODE").is_ok() {
eprintln!(
"DEBUG nuner decode: shape={:?} text_words.len={} data.len={}",
shape,
text_words.len(),
output_data.len()
);
// Sample first few values
let sample: Vec<f32> = output_data.iter().take(10).copied().collect();
eprintln!("DEBUG nuner decode: sample data={:?}", sample);
}
if shape.len() < 3 {
return Err(Error::Parse(format!(
"Unexpected output shape: {:?}",
shape
)));
}
let num_words = shape[1] as usize;
let num_classes = shape[2] as usize;
if std::env::var("ANNO_DEBUG_NUNER_DECODE").is_ok() {
eprintln!(
"DEBUG nuner decode: num_words={} num_classes={} entity_types.len={}",
num_words,
num_classes,
entity_types.len()
);
}
// Calculate word positions in original text
// Validate that all words are found to prevent silent failures
let word_positions: Vec<(usize, usize)> = {
// Performance: Pre-allocate positions vec with known size
let mut positions = Vec::with_capacity(text_words.len());
let mut pos = 0;
for (idx, word) in text_words.iter().enumerate() {
if let Some(start) = text[pos..].find(word) {
let abs_start = pos + start;
let abs_end = abs_start + word.len();
// Validate position is after previous word (words should be in order)
if !positions.is_empty() {
let (_prev_start, prev_end) = positions[positions.len() - 1];
if abs_start < prev_end {
log::warn!(
"Word '{}' at position {} overlaps with previous word ending at {}",
word,
abs_start,
prev_end
);
}
}
positions.push((abs_start, abs_end));
pos = abs_end;
} else {
// Word not found - return error to prevent silent entity skipping
return Err(Error::Parse(format!(
"Word '{}' (index {}) not found in text starting at position {}",
word, idx, pos
)));
}
}
positions
};
// Validate that we found positions for all words
if word_positions.len() != text_words.len() {
return Err(Error::Parse(format!(
"Word position mismatch: found {} positions for {} words",
word_positions.len(),
text_words.len()
)));
}
// Word positions are byte offsets; `Entity` requires character offsets.
let span_converter = crate::offset::SpanConverter::new(text);
// Performance: Pre-allocate entities vec with estimated capacity
let mut entities = Vec::with_capacity(16);
let mut current_entity: Option<(usize, usize, usize, f32)> = None; // (start_word, end_word, type_idx, score)
// Process each word position
for word_idx in 0..num_words.min(text_words.len()) {
let base_idx = word_idx * num_classes;
// Find best class for this word
let mut best_class = 0;
let mut best_score = 0.0f32;
for class_idx in 0..num_classes {
let score = output_data
.get(base_idx + class_idx)
.copied()
.unwrap_or(0.0);
if score > best_score {
best_score = score;
best_class = class_idx;
}
}
// BIO decoding: class 0 = O, odd = B-type, even = I-type
let is_begin = best_class > 0 && best_class % 2 == 1;
let is_inside = best_class > 0 && best_class % 2 == 0;
let type_idx = if best_class > 0 {
(best_class - 1) / 2
} else {
0
};
if best_score >= threshold {
if is_begin {
// Flush previous entity
if let Some((start, end, etype, score)) = current_entity.take() {
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
start,
end,
etype,
score,
entity_types,
) {
entities.push(e);
}
}
// Start new entity
current_entity = Some((word_idx, word_idx + 1, type_idx, best_score));
} else if is_inside {
// Extend current entity if same type
if let Some((_start, end, etype, score)) = current_entity.as_mut() {
if *etype == type_idx {
*end = word_idx + 1;
*score = (*score + best_score) / 2.0; // Average confidence
}
}
}
} else {
// Low confidence or O tag - flush current entity
if let Some((start, end, etype, score)) = current_entity.take() {
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
start,
end,
etype,
score,
entity_types,
) {
entities.push(e);
}
}
}
}
// Flush final entity
if let Some((start, end, etype, score)) = current_entity.take() {
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
start,
end,
etype,
score,
entity_types,
) {
entities.push(e);
}
}
Ok(entities)
}
/// Decode span classification output to entities.
///
/// Span mode output shape: [batch, num_words, max_width, num_classes]
/// With max_width=1, each word has logits for each entity type.
/// We apply sigmoid and compare to threshold.
#[cfg(feature = "onnx")]
fn decode_span_output(
&self,
outputs: &ort::session::SessionOutputs,
text: &str,
text_words: &[&str],
entity_types: &[&str],
threshold: f32,
) -> Result<Vec<Entity>> {
// Find the logits output
let logits_output = outputs
.iter()
.find(|(name, _)| name.contains("logits"))
.map(|(_, v)| v)
.or_else(|| outputs.iter().next().map(|(_, v)| v))
.ok_or_else(|| Error::Parse("No logits output from NuNER model".to_string()))?;
let (_, data_slice) = logits_output
.try_extract_tensor::<f32>()
.map_err(|e| Error::Parse(format!("Failed to extract output tensor: {}", e)))?;
let output_data: Vec<f32> = data_slice.to_vec();
// Get shape: [batch, num_words, max_width, num_classes]
let shape: Vec<i64> = match logits_output.dtype() {
ort::value::ValueType::Tensor { shape, .. } => shape.iter().copied().collect(),
_ => return Err(Error::Parse("Expected tensor output".to_string())),
};
if shape.len() != 4 {
// Fall back to token decoding if shape doesn't match span format
return self.decode_token_output(outputs, text, text_words, entity_types, threshold);
}
let num_words = shape[1] as usize;
let max_width = shape[2] as usize; // Should be 1 for NuNER
let num_classes = shape[3] as usize;
// Debug
if std::env::var("ANNO_DEBUG_NUNER_DECODE").is_ok() {
eprintln!(
"DEBUG nuner decode_span: shape={:?} num_words={} max_width={} num_classes={} entity_types.len={}",
shape, num_words, max_width, num_classes, entity_types.len()
);
}
// Calculate word positions in original text
let word_positions: Vec<(usize, usize)> = {
let mut positions = Vec::with_capacity(text_words.len());
let mut pos = 0;
for word in text_words.iter() {
if let Some(start) = text[pos..].find(word) {
let abs_start = pos + start;
let abs_end = abs_start + word.len();
positions.push((abs_start, abs_end));
pos = abs_end;
} else {
// Word not found - this shouldn't happen with whitespace split
return Err(Error::Parse(format!(
"Word '{}' not found in text starting at position {}",
word, pos
)));
}
}
positions
};
// Word positions are byte offsets; `Entity` requires character offsets.
let span_converter = crate::offset::SpanConverter::new(text);
let mut entities = Vec::with_capacity(16);
let mut current_entity: Option<(usize, usize, usize, f32)> = None; // (start_word, end_word, type_idx, score)
// Process each word
for word_idx in 0..num_words.min(text_words.len()) {
// For span mode with max_width=1, each word has one set of class logits
// Index: [batch=0, word_idx, width=0, class_idx]
let base_idx = word_idx * max_width * num_classes;
// Find best class above threshold
let mut best_class: Option<usize> = None;
let mut best_prob = 0.0f32;
for class_idx in 0..num_classes {
let logit = output_data
.get(base_idx + class_idx)
.copied()
.unwrap_or(f32::NEG_INFINITY);
// Apply sigmoid: prob = 1 / (1 + exp(-logit))
let prob = 1.0 / (1.0 + (-logit).exp());
if prob >= threshold && prob > best_prob {
best_prob = prob;
best_class = Some(class_idx);
}
}
if let Some(class_idx) = best_class {
// We found an entity at this word
if let Some((start, end, etype, score)) = current_entity.as_mut() {
if *etype == class_idx {
// Extend current entity (same type)
*end = word_idx + 1;
*score = (*score + best_prob) / 2.0;
} else {
// Different type - flush and start new
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
*start,
*end,
*etype,
*score,
entity_types,
) {
entities.push(e);
}
current_entity = Some((word_idx, word_idx + 1, class_idx, best_prob));
}
} else {
// Start new entity
current_entity = Some((word_idx, word_idx + 1, class_idx, best_prob));
}
} else {
// No entity at this word - flush current
if let Some((start, end, etype, score)) = current_entity.take() {
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
start,
end,
etype,
score,
entity_types,
) {
entities.push(e);
}
}
}
}
// Flush final entity
if let Some((start, end, etype, score)) = current_entity.take() {
if let Some(e) = self.create_entity(
text,
&span_converter,
&word_positions,
start,
end,
etype,
score,
entity_types,
) {
entities.push(e);
}
}
if std::env::var("ANNO_DEBUG_NUNER_DECODE").is_ok() {
eprintln!("DEBUG nuner decode_span: found {} entities", entities.len());
}
Ok(entities)
}
#[cfg(feature = "onnx")]
#[allow(clippy::too_many_arguments)]
pub(super) fn create_entity(
&self,
text: &str,
span_converter: &crate::offset::SpanConverter,
word_positions: &[(usize, usize)],
start_word: usize,
end_word: usize,
type_idx: usize,
score: f32,
entity_types: &[&str],
) -> Option<Entity> {
// Validate indices to prevent underflow
if end_word == 0 || end_word > word_positions.len() || start_word >= word_positions.len() {
return None;
}
let start_pos = word_positions.get(start_word)?.0;
let end_pos = word_positions.get(end_word.saturating_sub(1))?.1;
let raw_text = text.get(start_pos..end_pos)?;
let label = entity_types.get(type_idx)?;
let entity_type = Self::map_label_to_entity_type(label);
// Trim trailing punctuation that leaks from word-boundary tokenization
// (e.g. "thrive capital." -> "thrive capital",
// "marie curie's" -> "marie curie").
let (entity_text, _chars_removed) = textprep::spans::clean_span_tail(raw_text);
if entity_text.is_empty() {
return None;
}
let trimmed_bytes = raw_text.len() - entity_text.len();
let adj_end_pos = end_pos - trimmed_bytes;
let char_start = span_converter.byte_to_char(start_pos);
let char_end = span_converter.byte_to_char_ceil(adj_end_pos);
Some(Entity::new(
entity_text,
entity_type,
char_start,
char_end,
score as f64,
))
}
/// Map label string to EntityType.
pub(super) fn map_label_to_entity_type(label: &str) -> EntityType {
match label.to_lowercase().as_str() {
"person" | "per" => EntityType::Person,
"organization" | "org" | "company" => EntityType::Organization,
"location" | "loc" | "place" | "gpe" => EntityType::Location,
"date" => EntityType::Date,
"time" => EntityType::Time,
"money" | "currency" => EntityType::Money,
"percent" | "percentage" => EntityType::Percent,
_ => EntityType::custom(label, EntityCategory::Misc),
}
}
}