vecboost 0.2.0

High-performance embedding vector service written in Rust
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
// Copyright (c) 2025-2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

use super::{InferenceEngine, Precision};
use crate::config::model::{DeviceType, ModelConfig};
use crate::device::memory_limit::{MemoryLimitController, MemoryLimitStatus};
use crate::error::VecboostError;
use crate::monitor::MemoryMonitor;
use crate::utils::hash::verify_sha256;
use crate::utils::hf_hub::build_hf_repo;
use async_trait::async_trait;
use ndarray::{Array1, Array2};
use ort::session::{Session, builder::GraphOptimizationLevel};
use ort::value::Tensor;
use std::sync::{Arc, Mutex};
#[cfg(target_os = "macos")]
use tokenizers::Tokenizer;

#[cfg(target_os = "macos")]
use tokenizers::{PaddingParams, PaddingStrategy};

#[cfg(not(target_os = "macos"))]
type Tokenizer = crate::text::Tokenizer;

pub struct OnnxEngine {
    session: Arc<Mutex<Session>>,
    tokenizer: Tokenizer,
    hidden_size: usize,
    max_input_length: usize,
    precision: Precision,
    memory_monitor: Option<Arc<MemoryMonitor>>,
    memory_limit_controller: Option<Arc<MemoryLimitController>>,
    fallback_triggered: bool,
    fallback_lock: Arc<Mutex<()>>, // 保护降级过程的互斥锁
    device_type: DeviceType,
    supports_cuda: bool,
}

impl OnnxEngine {
    pub fn new(config: &ModelConfig, precision: Precision) -> Result<Self, VecboostError> {
        Self::with_device(config, precision, config.device.clone())
    }

    pub fn with_device(
        config: &ModelConfig,
        precision: Precision,
        device_type: DeviceType,
    ) -> Result<Self, VecboostError> {
        let model_path = &config.model_path;
        let is_local_path = model_path.exists() && model_path.is_dir();

        let (onnx_filename, tokenizer_filename) = if is_local_path {
            log::info!("Using local model path: {:?}", model_path);
            let onnx_filename = if model_path.join("model_quantized.onnx").exists() {
                model_path.join("model_quantized.onnx")
            } else if model_path.join("model.onnx").exists() {
                model_path.join("model.onnx")
            } else {
                return Err(VecboostError::ModelLoadError(format!(
                    "No ONNX model found in {:?}",
                    model_path
                )));
            };
            let tokenizer_filename = if model_path.join("tokenizer.json").exists() {
                model_path.join("tokenizer.json")
            } else {
                let parent = model_path.parent().and_then(|p| p.parent());
                let cache_path = parent.ok_or_else(|| {
                    VecboostError::ModelLoadError(format!(
                        "Cannot determine HuggingFace cache path from {:?}",
                        model_path
                    ))
                })?;
                let cache_tokenizer = cache_path.join("tokenizer.json");
                if cache_tokenizer.exists() {
                    log::info!(
                        "Using tokenizer from HuggingFace cache: {:?}",
                        cache_tokenizer
                    );
                    cache_tokenizer
                } else {
                    return Err(VecboostError::ModelLoadError(format!(
                        "Tokenizer not found at {:?} or {:?}",
                        model_path.join("tokenizer.json"),
                        cache_tokenizer
                    )));
                }
            };
            (onnx_filename, tokenizer_filename)
        } else {
            log::info!("Using HuggingFace Hub for model: {:?}", model_path);
            let repo_id = model_path.to_string_lossy().into_owned();
            let repo = build_hf_repo(&repo_id)?;

            log::info!("Downloading/Loading ONNX model files...");
            let onnx_filename = repo
                .download_file()
                .filename("model.onnx")
                .send()
                .or_else(|_| repo.download_file().filename("model_quantized.onnx").send())
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

            let tokenizer_filename = repo
                .download_file()
                .filename("tokenizer.json")
                .send()
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
            (onnx_filename, tokenizer_filename)
        };

        let num_threads = std::thread::available_parallelism()
            .map(|p| p.get())
            .unwrap_or(4);

        let supports_cuda = device_type == DeviceType::Cuda;
        let supports_amd = matches!(device_type, DeviceType::Amd | DeviceType::OpenCL);

        log::info!("Initializing ONNX Runtime session...");
        let session = Session::builder()
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            .with_optimization_level(GraphOptimizationLevel::Level3)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            .with_intra_threads(num_threads)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        let mut session = if supports_cuda {
            log::info!("Attempting to configure CUDA execution provider for ONNX Runtime");
            #[cfg(feature = "cuda")]
            {
                let cuda_provider =
                    ort::execution_providers::CUDAExecutionProvider::default().build();
                session
                    .with_execution_providers([cuda_provider])
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            }
            #[cfg(not(feature = "cuda"))]
            {
                log::warn!(
                    "CUDA execution provider not available. ONNX Runtime CUDA support requires cuda feature flag. Using CPU execution provider."
                );
                session
            }
        } else if supports_amd {
            log::info!(
                "AMD GPU detected but ROCm execution provider is not configured in this build. Using CPU execution provider."
            );
            session
        } else {
            session
        };

        if let Some(ref expected_hash) = config.model_sha256 {
            log::info!("Verifying model file SHA256 hash...");
            let is_valid = verify_sha256(&onnx_filename, expected_hash).map_err(|e| {
                VecboostError::ModelLoadError(format!("Failed to verify SHA256: {}", e))
            })?;

            if !is_valid {
                return Err(VecboostError::ModelLoadError(format!(
                    "Model file SHA256 verification failed. Expected: {}, File: {:?}",
                    expected_hash, onnx_filename
                )));
            }

            log::info!("Model file SHA256 verification passed");
        }

        let session = session
            .commit_from_file(onnx_filename)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        log::info!("Loading tokenizer...");
        #[allow(unused_mut)]
        let mut tokenizer = Tokenizer::from_file(&tokenizer_filename.to_string_lossy())
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        #[cfg(target_os = "macos")]
        {
            if let Some(pp) = tokenizer.get_padding_mut() {
                pp.strategy = PaddingStrategy::BatchLongest;
            } else {
                let pp = PaddingParams {
                    strategy: PaddingStrategy::BatchLongest,
                    ..Default::default()
                };
                tokenizer.with_padding(Some(pp));
            }
        }

        let vocab_size = tokenizer.get_vocab_size();
        let hidden_size = config.expected_dimension.unwrap_or(1024);
        log::info!(
            "Using hidden_size from configuration: {:?}",
            config.expected_dimension
        );
        log::info!("Final hidden_size value: {}", hidden_size);
        let max_input_length = std::cmp::min(vocab_size, 512);

        let actual_precision = match precision {
            Precision::Fp16 => {
                if supports_cuda || supports_amd {
                    log::info!("Using FP16 precision with GPU acceleration");
                    Precision::Fp16
                } else {
                    log::warn!("FP16 not supported without GPU acceleration, falling back to FP32");
                    Precision::Fp32
                }
            }
            _ => {
                log::info!("Using {} precision", precision);
                precision
            }
        };

        log::info!(
            "ONNX Engine initialized: hidden_size={}, max_input_length={}, vocab_size={}, precision={:?}",
            hidden_size,
            max_input_length,
            vocab_size,
            actual_precision
        );

        let memory_monitor = if supports_cuda || supports_amd {
            Some(Arc::new(MemoryMonitor::new()))
        } else {
            None
        };

        Ok(Self {
            session: Arc::new(Mutex::new(session)),
            tokenizer,
            hidden_size,
            max_input_length,
            precision: actual_precision,
            memory_monitor,
            memory_limit_controller: None,
            fallback_triggered: false,
            fallback_lock: Arc::new(Mutex::new(())),
            device_type,
            supports_cuda,
        })
    }

    pub fn set_memory_limit_controller(&mut self, controller: Arc<MemoryLimitController>) {
        self.memory_limit_controller = Some(controller);
    }

    pub fn device_type(&self) -> DeviceType {
        self.device_type.clone()
    }

    pub fn is_fallback_triggered(&self) -> bool {
        self.fallback_triggered
    }

    pub fn check_memory_pressure(&self, threshold_percent: u64) -> bool {
        if let Some(ref monitor) = self.memory_monitor {
            if let Ok(handle) = tokio::runtime::Handle::try_current() {
                handle.block_on(async {
                    let stats = monitor.get_memory_stats().await;
                    let usage_percent = (stats.current_bytes * 100)
                        .checked_div(stats.total_bytes)
                        .unwrap_or(0);
                    usage_percent >= threshold_percent
                })
            } else {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap_or_else(|_| {
                        log::error!("Failed to create Tokio runtime for memory check");
                        std::process::exit(1);
                    });
                rt.block_on(async {
                    let stats = monitor.get_memory_stats().await;
                    let usage_percent = (stats.current_bytes * 100)
                        .checked_div(stats.total_bytes)
                        .unwrap_or(0);
                    usage_percent >= threshold_percent
                })
            }
        } else {
            false
        }
    }

    pub async fn check_memory_limit_and_fallback(
        &mut self,
        config: &ModelConfig,
    ) -> Result<bool, VecboostError> {
        if self.fallback_triggered {
            return Ok(false);
        }

        if let Some(ref controller) = self.memory_limit_controller {
            let status = controller.check_limit().await;

            if status == MemoryLimitStatus::Exceeded {
                log::warn!("Memory limit exceeded for ONNX engine, attempting fallback to CPU");
                self.try_fallback_to_cpu(config).await?;
                return Ok(true);
            } else if status == MemoryLimitStatus::Critical {
                log::warn!(
                    "Memory limit critical for ONNX engine, checking memory pressure for fallback"
                );
                if self.check_memory_pressure(90) {
                    self.try_fallback_to_cpu(config).await?;
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    pub async fn update_memory_limit(&self, used_bytes: u64) {
        if let Some(ref controller) = self.memory_limit_controller {
            controller.update_usage(used_bytes).await;
        }
    }

    pub async fn get_memory_status(&self) -> Option<MemoryLimitStatus> {
        if let Some(ref controller) = self.memory_limit_controller {
            Some(controller.check_limit().await)
        } else {
            None
        }
    }

    pub async fn update_gpu_memory(&self) {
        if let Some(ref monitor) = self.memory_monitor {
            #[cfg(feature = "onnx")]
            monitor.update_gpu_memory_from_ort().await;
        }
    }

    fn forward_pass(&self, text: &str) -> Result<Vec<f32>, VecboostError> {
        let tokens = self
            .tokenizer
            .encode(text, true)
            .map_err(|e| VecboostError::TokenizationError(e.to_string()))?;

        let input_ids: Vec<i64> = tokens
            .get_ids()
            .iter()
            .take(self.max_input_length)
            .map(|&id| id as i64)
            .collect();

        let attention_mask: Vec<i64> = tokens
            .get_attention_mask()
            .iter()
            .take(self.max_input_length)
            .map(|&v| v as i64)
            .collect();

        let input_ids_array = Array1::from(input_ids);
        let attention_mask_array = Array1::from(attention_mask.clone());

        let input_ids_tensor = Tensor::from_array(input_ids_array.into_dyn())
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
        let attention_mask_tensor = Tensor::from_array(attention_mask_array.into_dyn())
            .map_err(|e: ort::Error| VecboostError::InferenceError(e.to_string()))?;

        let last_hidden_state = {
            let mut session_guard = self
                .session
                .lock()
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
            let outputs = session_guard
                .run(ort::inputs![
                    "input_ids" => input_ids_tensor,
                    "attention_mask" => attention_mask_tensor
                ])
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
            let output_array = outputs["last_hidden_state"]
                .try_extract_array::<f32>()
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?
                .to_owned();
            log::debug!("ONNX model output shape: {:?}", output_array.shape());
            output_array
        };

        let seq_len = attention_mask.iter().filter(|&&v| v == 1).count();
        if seq_len == 0 {
            return Err(VecboostError::InferenceError(
                "Empty sequence after mask".to_string(),
            ));
        }

        let mut weighted_sum = vec![0.0f32; self.hidden_size];
        let mut mask_sum = 0.0f32;

        for (seq_idx, &mask_val) in attention_mask.iter().enumerate().take(seq_len) {
            if mask_val == 1 {
                for h in 0..self.hidden_size {
                    let token_embedding = last_hidden_state[[seq_idx, h]];
                    weighted_sum[h] += token_embedding * mask_val as f32;
                    mask_sum += mask_val as f32;
                }
            }
        }

        if mask_sum > 0.0 {
            weighted_sum.iter_mut().for_each(|v| *v /= mask_sum);
        }

        Ok(weighted_sum)
    }

    pub async fn try_fallback_to_cpu(&mut self, config: &ModelConfig) -> Result<(), VecboostError> {
        // 使用互斥锁确保只有一个线程执行降级
        let _lock = self.fallback_lock.lock().map_err(|e| {
            VecboostError::InferenceError(format!("Failed to acquire fallback lock: {}", e))
        })?;

        // 双重检查:获取锁后再次检查是否已经降级
        if self.fallback_triggered {
            return Ok(());
        }

        log::info!("Attempting fallback from GPU to CPU for ONNX engine");

        self.memory_monitor = None;
        self.device_type = DeviceType::Cpu;
        self.supports_cuda = false;
        self.fallback_triggered = true;

        let repo_id = config.model_path.to_string_lossy().into_owned();
        let repo = build_hf_repo(&repo_id)?;

        let onnx_filename = repo
            .download_file()
            .filename("model.onnx")
            .send()
            .or_else(|_| repo.download_file().filename("model_quantized.onnx").send())
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        let num_threads = std::thread::available_parallelism()
            .map(|p| p.get())
            .unwrap_or(4);

        let new_session = Session::builder()
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            .with_optimization_level(GraphOptimizationLevel::Level3)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            .with_intra_threads(num_threads)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
            .commit_from_file(onnx_filename)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        let mut session_guard = self
            .session
            .lock()
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
        *session_guard = new_session;
        drop(session_guard);

        self.precision = Precision::Fp32;

        log::info!("Successfully fell back to CPU for ONNX engine");
        Ok(())
    }

    fn forward_pass_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, VecboostError> {
        let batch_size = texts.len();
        if batch_size == 0 {
            return Ok(vec![]);
        }

        let mut all_input_ids: Vec<Vec<i64>> = Vec::with_capacity(batch_size);
        let mut all_attention_masks: Vec<Vec<i64>> = Vec::with_capacity(batch_size);
        let mut max_seq_len = 0;

        for text in texts {
            let text_ref: &str = text.as_str();
            let tokens = self
                .tokenizer
                .encode(text_ref, true)
                .map_err(|e| VecboostError::TokenizationError(e.to_string()))?;

            let input_ids: Vec<i64> = tokens
                .get_ids()
                .iter()
                .take(self.max_input_length)
                .map(|&id| id as i64)
                .collect();

            let attention_mask: Vec<i64> = tokens
                .get_attention_mask()
                .iter()
                .take(self.max_input_length)
                .map(|&v| v as i64)
                .collect();

            if input_ids.len() > max_seq_len {
                max_seq_len = input_ids.len();
            }

            all_input_ids.push(input_ids);
            all_attention_masks.push(attention_mask);
        }

        let padded_batch_size = all_input_ids.len();
        let mut batch_input_ids = vec![0i64; padded_batch_size * max_seq_len];
        let mut batch_attention_mask = vec![0i64; padded_batch_size * max_seq_len];

        for (batch_idx, (input_ids, attention_mask)) in all_input_ids
            .iter()
            .zip(all_attention_masks.iter())
            .enumerate()
        {
            for (seq_idx, (&id, &mask)) in input_ids.iter().zip(attention_mask.iter()).enumerate() {
                let pos = batch_idx * max_seq_len + seq_idx;
                batch_input_ids[pos] = id;
                batch_attention_mask[pos] = mask;
            }
        }

        let input_ids_array =
            Array2::from_shape_vec((padded_batch_size, max_seq_len), batch_input_ids)
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
        let attention_mask_array =
            Array2::from_shape_vec((padded_batch_size, max_seq_len), batch_attention_mask)
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        let input_ids_tensor = Tensor::from_array(input_ids_array.into_dyn())
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
        let attention_mask_tensor = Tensor::from_array(attention_mask_array.into_dyn())
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        let last_hidden_state = {
            let mut session_guard = self
                .session
                .lock()
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
            let outputs = session_guard
                .run(ort::inputs![
                    "input_ids" => input_ids_tensor,
                    "attention_mask" => attention_mask_tensor
                ])
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
            outputs["last_hidden_state"]
                .try_extract_array::<f32>()
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?
                .to_owned()
        };

        let mut results = Vec::with_capacity(padded_batch_size);
        for batch_idx in 0..padded_batch_size {
            let attention_mask = &all_attention_masks[batch_idx];
            let actual_seq_len = attention_mask.len();
            log::debug!(
                "batch_idx: {}, max_seq_len: {}, actual_seq_len: {}",
                batch_idx,
                max_seq_len,
                actual_seq_len
            );

            let mut weighted_sum = vec![0.0f32; self.hidden_size];
            let mut mask_sum = 0.0f32;

            let effective_max_seq = std::cmp::min(max_seq_len, actual_seq_len);
            for seq_idx in 0..effective_max_seq {
                let mask_val = attention_mask[seq_idx];
                if mask_val == 1 {
                    for h in 0..self.hidden_size {
                        let token_embedding = last_hidden_state[[batch_idx, seq_idx, h]];
                        weighted_sum[h] += token_embedding * mask_val as f32;
                        mask_sum += mask_val as f32;
                    }
                }
            }

            if mask_sum > 0.0 {
                weighted_sum
                    .iter_mut()
                    .take(self.hidden_size)
                    .for_each(|v| *v /= mask_sum);
            }

            results.push(weighted_sum);
        }

        Ok(results)
    }
}

#[async_trait]
impl InferenceEngine for OnnxEngine {
    fn embed(&self, text: &str) -> Result<Vec<f32>, VecboostError> {
        self.forward_pass(text)
    }

    fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, VecboostError> {
        self.forward_pass_batch(texts)
    }

    fn precision(&self) -> &Precision {
        &self.precision
    }

    fn supports_mixed_precision(&self) -> bool {
        self.memory_monitor.is_some()
    }

    fn is_fallback_triggered(&self) -> bool {
        self.fallback_triggered
    }

    async fn try_fallback_to_cpu(&mut self, config: &ModelConfig) -> Result<(), VecboostError> {
        OnnxEngine::try_fallback_to_cpu(self, config).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::model::{EngineType, ModelConfig};
    use std::path::PathBuf;

    fn test_config() -> ModelConfig {
        ModelConfig {
            name: "test-onnx".to_string(),
            engine_type: EngineType::Onnx,
            model_path: PathBuf::from("/nonexistent/onnx-model"),
            tokenizer_path: None,
            device: DeviceType::Cpu,
            max_batch_size: 32,
            pooling_mode: None,
            expected_dimension: Some(1024),
            memory_limit_bytes: None,
            oom_fallback_enabled: true,
            model_sha256: None,
        }
    }

    /// 验证 OnnxEngine::new 在空目录上返回 ModelLoadError
    #[test]
    fn test_onnx_engine_new_returns_error_for_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::new(&config, Precision::Fp32);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError, got {:?}",
                e
            );
        }
    }

    /// 验证 with_device 在空目录(CPU)上返回带特定消息的 ModelLoadError
    #[test]
    fn test_onnx_engine_with_device_empty_dir_cpu() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("No ONNX model found"),
                "Expected 'No ONNX model found', got: {}",
                msg
            );
        }
    }

    /// 验证 FP16 精度在空目录上仍返回错误
    #[test]
    fn test_onnx_engine_with_device_fp16_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp16, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 INT8 精度在空目录上仍返回错误
    #[test]
    fn test_onnx_engine_with_device_int8_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Int8, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 CUDA 设备类型在空目录上返回错误(覆盖 supports_cuda 分支)
    #[test]
    fn test_onnx_engine_with_device_cuda_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cuda);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError, got {:?}",
                e
            );
        }
    }

    /// 验证 AMD 设备类型在空目录上返回错误(覆盖 supports_amd 分支)
    #[test]
    fn test_onnx_engine_with_device_amd_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Amd);
        assert!(result.is_err());
    }

    /// 验证 OpenCL 设备类型在空目录上返回错误
    #[test]
    fn test_onnx_engine_with_device_opencl_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::OpenCL);
        assert!(result.is_err());
    }

    /// 验证存在 model.onnx 但缺失 tokenizer.json 时返回 "Tokenizer not found" 错误
    #[test]
    fn test_onnx_engine_with_model_but_no_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Tokenizer not found"),
                "Expected 'Tokenizer not found', got: {}",
                msg
            );
        }
    }

    /// 验证存在 model_quantized.onnx(优先于 model.onnx)但缺失 tokenizer.json 时返回错误
    #[test]
    fn test_onnx_engine_prefers_quantized_model_but_no_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(
            temp_dir.path().join("model_quantized.onnx"),
            b"fake quantized",
        )
        .expect("Failed to write fake model_quantized.onnx");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Tokenizer not found"),
                "Expected 'Tokenizer not found', got: {}",
                msg
            );
        }
    }

    /// 验证 `Precision` 的 Display 实现
    #[test]
    fn test_precision_display() {
        assert_eq!(Precision::Fp32.to_string(), "fp32");
        assert_eq!(Precision::Fp16.to_string(), "fp16");
        assert_eq!(Precision::Int8.to_string(), "int8");
    }

    /// 验证 `DeviceType` 的序列化形式(serde rename)
    #[test]
    fn test_device_type_serialization() {
        assert_eq!(
            serde_json::to_string(&DeviceType::Cpu).expect("serialize Cpu"),
            "\"cpu\""
        );
        assert_eq!(
            serde_json::to_string(&DeviceType::Amd).expect("serialize Amd"),
            "\"amd\""
        );
        assert_eq!(
            serde_json::to_string(&DeviceType::OpenCL).expect("serialize OpenCL"),
            "\"opencl\""
        );
    }

    /// 验证 model.onnx + tokenizer.json 同时存在时,在 commit_from_file 阶段失败
    /// (fake ONNX 文件无法被 ONNX Runtime 解析)
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_model_and_tokenizer_fails_at_session() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from session commit, got {:?}",
                e
            );
        }
    }

    /// 验证 model_quantized.onnx 优先于 model.onnx 被选择,且在 session 阶段失败
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_quantized_preferred_with_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(
            temp_dir.path().join("model_quantized.onnx"),
            b"fake quantized",
        )
        .expect("Failed to write fake model_quantized.onnx");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from session commit, got {:?}",
                e
            );
        }
    }

    /// 验证 tokenizer.json 不在 model_path 中但从 HuggingFace cache 路径(parent's parent)加载
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_tokenizer_from_cache_path() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let cache_dir = temp_dir.path();
        let intermediate = cache_dir.join("intermediate");
        let model_dir = intermediate.join("model_dir");
        std::fs::create_dir_all(&model_dir).expect("Failed to create model_dir");
        std::fs::write(model_dir.join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(cache_dir.join("tokenizer.json"), b"{}")
            .expect("Failed to write cache tokenizer.json");

        let mut config = test_config();
        config.model_path = model_dir;

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError after cache tokenizer load, got {:?}",
                e
            );
        }
    }

    /// 验证设置 model_sha256 时,SHA256 校验失败返回 ModelLoadError
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_sha256_verification_mismatch() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();
        config.model_sha256 =
            Some("0000000000000000000000000000000000000000000000000000000000000000".to_string());

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("SHA256 verification failed"),
                "Expected SHA256 verification failure, got: {}",
                msg
            );
        }
    }

    /// 验证 CUDA 设备类型在 model.onnx + tokenizer.json 存在时,
    /// 进入 CUDA 配置分支(非 cuda feature 下走 warn 路径)后在 commit_from_file 失败
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_cuda_device_with_model_and_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cuda);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from CUDA path, got {:?}",
                e
            );
        }
    }

    /// 验证 AMD 设备类型在 model.onnx + tokenizer.json 存在时,
    /// 进入 AMD 配置分支后在 commit_from_file 失败
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_amd_device_with_model_and_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Amd);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from AMD path, got {:?}",
                e
            );
        }
    }

    /// 验证 OpenCL 设备类型在 model.onnx + tokenizer.json 存在时,
    /// 进入 AMD/OpenCL 配置分支后在 commit_from_file 失败
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_opencl_device_with_model_and_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::OpenCL);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from OpenCL path, got {:?}",
                e
            );
        }
    }

    /// 验证 FP16 + CUDA 设备在 model.onnx + tokenizer.json 存在时进入 CUDA 分支后失败
    #[ignore = "ort crate environment cleanup crashes test runner when Session::builder() is called"]
    #[test]
    fn test_onnx_engine_fp16_cuda_device_with_model() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");
        std::fs::write(temp_dir.path().join("tokenizer.json"), b"{}")
            .expect("Failed to write fake tokenizer.json");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp16, DeviceType::Cuda);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError from FP16+CUDA path, got {:?}",
                e
            );
        }
    }

    /// 验证 model_path 无 parent's parent 时返回 "Cannot determine HuggingFace cache path" 错误
    #[test]
    fn test_onnx_engine_no_cache_path_determinable() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Tokenizer not found") || msg.contains("Cannot determine"),
                "Expected tokenizer/cache path error, got: {}",
                msg
            );
        }
    }

    /// 验证 cache path 可确定(parent's parent 存在)但 tokenizer 不在 cache path 时,
    /// 返回包含两个路径的 "Tokenizer not found" 错误
    #[test]
    fn test_onnx_engine_cache_path_determinable_no_tokenizer() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let intermediate = temp_dir.path().join("intermediate");
        let model_dir = intermediate.join("model_dir");
        std::fs::create_dir_all(&model_dir).expect("Failed to create model_dir");
        std::fs::write(model_dir.join("model.onnx"), b"fake onnx")
            .expect("Failed to write fake model.onnx");

        let mut config = test_config();
        config.model_path = model_dir;

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Tokenizer not found"),
                "Expected 'Tokenizer not found', got: {}",
                msg
            );
            assert!(
                !msg.contains("Cannot determine"),
                "Should not be 'Cannot determine' since cache path exists, got: {}",
                msg
            );
        }
    }

    /// 验证仅存在 model_quantized.onnx(无 model.onnx)且无 tokenizer 时返回错误
    #[test]
    fn test_onnx_engine_only_quantized_no_model_onnx() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(
            temp_dir.path().join("model_quantized.onnx"),
            b"fake quantized",
        )
        .expect("Failed to write fake model_quantized.onnx");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Tokenizer not found") || msg.contains("Cannot determine"),
                "Expected tokenizer/cache error, got: {}",
                msg
            );
        }
    }

    /// 验证 FP16 + AMD 设备在空目录上返回错误(覆盖 FP16 + supports_amd 分支)
    #[test]
    fn test_onnx_engine_fp16_amd_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp16, DeviceType::Amd);
        assert!(result.is_err());
    }

    /// 验证 FP16 + OpenCL 设备在空目录上返回错误(覆盖 FP16 + supports_amd 分支)
    #[test]
    fn test_onnx_engine_fp16_opencl_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp16, DeviceType::OpenCL);
        assert!(result.is_err());
    }

    /// 验证 INT8 + CUDA 设备在空目录上返回错误
    #[test]
    fn test_onnx_engine_int8_cuda_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Int8, DeviceType::Cuda);
        assert!(result.is_err());
    }

    /// 验证 INT8 + AMD 设备在空目录上返回错误
    #[test]
    fn test_onnx_engine_int8_amd_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Int8, DeviceType::Amd);
        assert!(result.is_err());
    }

    /// 验证 model_path 指向文件(非目录)时进入 HuggingFace Hub 下载路径并失败
    #[test]
    fn test_onnx_engine_model_path_is_file_not_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let file_path = temp_dir.path().join("not_a_dir");
        std::fs::write(&file_path, b"file").expect("Failed to write file");

        let mut config = test_config();
        config.model_path = file_path;

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 Metal 设备类型在空目录上返回错误
    #[test]
    fn test_onnx_engine_metal_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = OnnxEngine::with_device(&config, Precision::Fp32, DeviceType::Metal);
        assert!(result.is_err());
    }
}