-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmodel.rs
More file actions
1898 lines (1743 loc) · 73.9 KB
/
model.rs
File metadata and controls
1898 lines (1743 loc) · 73.9 KB
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
// Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
//! YOLO model loading and inference.
//!
//! This module provides the main `YOLOModel` struct for loading ONNX models
//! and running inference.
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
use half::f16;
use image::{DynamicImage, GenericImageView};
use ndarray::Array3;
use ort::session::Session;
use ort::value::TensorElementType;
use ort::value::TensorRef;
use ort::value::ValueType;
use crate::download::{DEFAULT_IMAGES, DEFAULT_OBB_IMAGE, download_image, try_download_model};
use crate::error::{InferenceError, Result};
use crate::inference::InferenceConfig;
use crate::metadata::ModelMetadata;
use crate::postprocessing::postprocess;
use crate::preprocessing::{
calculate_rect_size, image_to_array, preprocess_image_center_crop,
preprocess_image_with_precision,
};
use crate::results::{Results, Speed};
use crate::task::Task;
use crate::{verbose, warn};
/// YOLO model for inference.
///
/// This struct wraps an ONNX Runtime session and provides methods for
/// running inference on images, videos, and other sources.
///
/// # Example
///
/// ```no_run
/// use ultralytics_inference::YOLOModel;
///
/// let mut model = YOLOModel::load("yolo26n.onnx").unwrap();
/// let results = model.predict("image.jpg").unwrap();
/// println!("Found {} detections", results.len());
/// ```
pub struct YOLOModel {
/// ONNX Runtime session.
session: Session,
/// Model metadata (task, classes, etc.).
metadata: ModelMetadata,
/// Input tensor name.
input_name: String,
/// Output tensor names.
output_names: Vec<String>,
/// Inference configuration.
config: InferenceConfig,
/// Whether model has been warmed up.
warmed_up: bool,
/// Whether model expects FP16 input.
fp16_input: bool,
/// Execution provider used for inference
execution_provider: String,
/// Whether the model accepts dynamic input shapes.
is_dynamic: bool,
/// Fast-path GPU preprocessor (`cuda-preprocess` feature only).
///
/// Populated at load time when the user hasn't opted out and the device
/// is CUDA/TensorRT. When `Some`, [`Self::predict_image`] routes through
/// a fused CUDA kernel + zero-copy device input. `None` means the
/// standard CPU preprocess path runs.
#[cfg(feature = "cuda-preprocess")]
cuda_preprocessor: Option<crate::cuda_inference::CudaPreprocessor>,
}
#[allow(
clippy::too_many_lines,
clippy::needless_pass_by_value,
clippy::missing_errors_doc,
clippy::missing_panics_doc,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::if_not_else,
clippy::manual_is_multiple_of,
clippy::cast_sign_loss,
clippy::cast_precision_loss
)]
impl YOLOModel {
/// Load a YOLO model from an ONNX file.
///
/// The model metadata (class names, task type, input size) is automatically
/// extracted from the ONNX model's custom metadata properties.
///
/// # Arguments
///
/// * `path` - Path to the ONNX model file.
///
/// # Errors
///
/// Returns an error if the model file doesn't exist or can't be loaded.
///
/// # Example
///
/// ```no_run
/// use ultralytics_inference::YOLOModel;
///
/// let model = YOLOModel::load("yolo26n.onnx")?;
/// # Ok::<(), ultralytics_inference::InferenceError>(())
/// ```
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::load_with_config(path, InferenceConfig::default())
}
/// Load a YOLO model with custom configuration.
///
/// # Arguments
///
/// * `path` - Path to the ONNX model file.
/// * `config` - Custom inference configuration.
///
/// # Errors
///
/// Returns an error if the model file doesn't exist or can't be loaded.
pub fn load_with_config<P: AsRef<Path>>(path: P, config: InferenceConfig) -> Result<Self> {
let path = path.as_ref();
// Check if file exists, attempt auto-download if not
let path = if path.exists() {
std::borrow::Cow::Borrowed(path)
} else {
// Try to download the model if it's a known downloadable model
std::borrow::Cow::Owned(try_download_model(path)?)
};
let path = path.as_ref();
// Establish a shared cudarc stream up-front when the cuda-preprocess
// fast path is eligible. The TRT/CUDA EPs below bind to this stream
// via `with_compute_stream`, so the preprocess kernel and ORT see
// each other's enqueued ops without an explicit synchronize.
//
// The handle is consumed by `CudaPreprocessor::finalize` further down
// (after metadata is known) or dropped silently if the fast path
// can't engage. Either way it outlives EP construction.
#[cfg(feature = "cuda-preprocess")]
let cuda_pre_stream: Option<crate::cuda_inference::CudaStreamHandle> = {
let device_eligible = matches!(
config.device,
None | Some(crate::Device::Cuda(_) | crate::Device::TensorRt(_))
);
if config.cuda_preprocess && device_eligible {
match crate::cuda_inference::CudaStreamHandle::open(0) {
Ok(h) => Some(h),
Err(e) => {
warn!("cuda-preprocess: stream init failed ({e:?}); using CPU preprocess");
None
}
}
} else {
None
}
};
#[cfg(any(feature = "cuda", feature = "tensorrt"))]
let cuda_pre_stream_ptr: Option<*mut ()> = {
#[cfg(feature = "cuda-preprocess")]
{
cuda_pre_stream
.as_ref()
.map(crate::cuda_inference::CudaStreamHandle::raw_stream_ptr)
}
#[cfg(not(feature = "cuda-preprocess"))]
{
None
}
};
// Determine optimal thread count based on available parallelism
let num_threads = if config.num_threads > 0 {
config.num_threads
} else {
// Use all available cores for intra-op parallelism (single inference)
std::thread::available_parallelism().map_or(4, std::num::NonZero::get)
};
// Create ONNX Runtime session with optimizations
let mut session_builder = Session::builder().map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to create session builder: {e}"))
})?;
// Register execution providers based on features and device config
#[allow(unused_mut)]
let mut eps: Vec<ort::execution_providers::ExecutionProviderDispatch> = Vec::new();
#[allow(unused_mut)]
let mut provider_name = "CPUExecutionProvider";
if let Some(device) = &config.device {
// User requested specific device
match device {
crate::Device::Cpu => {}
#[cfg(feature = "cuda")]
crate::Device::Cuda(i) => {
eps.push(Self::build_cuda_ep(*i as i32, cuda_pre_stream_ptr));
provider_name = "CUDAExecutionProvider";
}
#[cfg(feature = "coreml")]
crate::Device::CoreMl => {
if matches!(Self::macos_version(), Some((major, _)) if major >= 11) {
eps.push(Self::build_coreml_ep(path));
provider_name = "CoreMLExecutionProvider";
} else {
warn!("WARNING ⚠️ CoreML requires macOS 11+; falling back to CPU.");
}
}
#[cfg(feature = "tensorrt")]
crate::Device::TensorRt(i) => {
eps.push(Self::build_tensorrt_ep(
path,
*i as i32,
config.half,
cuda_pre_stream_ptr,
));
provider_name = "TensorRTExecutionProvider";
}
#[cfg(feature = "rocm")]
crate::Device::Rocm(i) => {
eps.push(
ort::execution_providers::ROCmExecutionProvider::default()
.with_device_id(*i as i32)
.build(),
);
provider_name = "ROCmExecutionProvider";
}
#[cfg(feature = "directml")]
crate::Device::DirectMl(i) => {
eps.push(
ort::execution_providers::DirectMLExecutionProvider::default()
.with_device_id(*i as i32)
.build(),
);
provider_name = "DirectMLExecutionProvider";
}
#[cfg(feature = "openvino")]
crate::Device::OpenVino => {
eps.push(
ort::execution_providers::OpenVINOExecutionProvider::default().build(),
);
provider_name = "OpenVINOExecutionProvider";
}
#[cfg(feature = "xnnpack")]
crate::Device::Xnnpack => {
eps.push(ort::execution_providers::XNNPACKExecutionProvider::default().build());
provider_name = "XNNPACKExecutionProvider";
}
// Handle cases where feature is disabled but enum variant exists
#[allow(unreachable_patterns)]
_ => {
warn!(
"Device '{device}' requested but feature not enabled or supported. Falling back to available providers."
);
}
}
} else {
// Default: Register all available providers in preference order
#[cfg(feature = "tensorrt")]
{
eps.push(Self::build_tensorrt_ep(
path,
0,
config.half,
cuda_pre_stream_ptr,
));
provider_name = "TensorRTExecutionProvider";
}
#[cfg(feature = "cuda")]
{
eps.push(Self::build_cuda_ep(0, cuda_pre_stream_ptr));
if provider_name == "CPUExecutionProvider" {
provider_name = "CUDAExecutionProvider";
}
}
#[cfg(feature = "coreml")]
if matches!(Self::macos_version(), Some((major, _)) if major >= 11) {
eps.push(Self::build_coreml_ep(path));
if provider_name == "CPUExecutionProvider" {
provider_name = "CoreMLExecutionProvider";
}
}
#[cfg(feature = "rocm")]
{
eps.push(ort::execution_providers::ROCmExecutionProvider::default().build());
if provider_name == "CPUExecutionProvider" {
provider_name = "ROCmExecutionProvider";
}
}
#[cfg(feature = "directml")]
{
eps.push(ort::execution_providers::DirectMLExecutionProvider::default().build());
if provider_name == "CPUExecutionProvider" {
provider_name = "DirectMLExecutionProvider";
}
}
#[cfg(feature = "openvino")]
{
eps.push(ort::execution_providers::OpenVINOExecutionProvider::default().build());
if provider_name == "CPUExecutionProvider" {
provider_name = "OpenVINOExecutionProvider";
}
}
#[cfg(feature = "xnnpack")]
{
eps.push(ort::execution_providers::XNNPACKExecutionProvider::default().build());
if provider_name == "CPUExecutionProvider" {
provider_name = "XNNPACKExecutionProvider";
}
}
}
if !eps.is_empty() {
crate::info!(
"Registering {} execution providers (primary: {})",
eps.len(),
provider_name
);
session_builder = session_builder.with_execution_providers(eps).map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to set execution providers: {e}"))
})?;
}
// CPU is the default - no warning needed when no accelerators are registered
let session = session_builder
.with_optimization_level(ort::session::builder::GraphOptimizationLevel::Level3)
.map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to set optimization level: {e}"))
})?
.with_intra_threads(num_threads)
.map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to set intra-op thread count: {e}"))
})?
.with_inter_threads(1)
.map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to set inter-op thread count: {e}"))
})?
.with_memory_pattern(true)
.map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to enable memory pattern: {e}"))
})?
.commit_from_file(path)
.map_err(|e| InferenceError::ModelLoadError(format!("Failed to load model: {e}")))?;
// Extract metadata from model
let metadata = Self::extract_metadata(&session)?;
// Get input/output names and detect input type
let input_info = session.inputs().first();
let input_name = input_info.map_or_else(|| "images".to_string(), |i| i.name().to_string());
// Check if model input tensor expects FP16 (rare most models use FP32 input even with half weights)
let fp16_input = input_info.is_some_and(|i| {
matches!(
i.dtype(),
ValueType::Tensor {
ty: TensorElementType::Float16,
..
}
)
});
// Check for dynamic input dimensions
// Dimensions are typically [-1, 3, -1, -1] for dynamic batch/height/width
// ort 2.0 returns Option<i64> (None means dynamic/unknown)
let is_dynamic = input_info.is_some_and(|i| {
if let ValueType::Tensor { shape, .. } = i.dtype() {
shape.iter().any(|d| *d == -1 || *d == 0)
} else {
false
}
});
let output_names: Vec<String> = session
.outputs()
.iter()
.map(|o| o.name().to_string())
.collect();
// Resolve image size
// Priority:
// 1. User config
// 2. Model metadata
// 3. Dynamic default (1024 for OBB, 640 for others)
// 4. Static input shape
// 5. Hard default (640)
let resolved_imgsz = if let Some(sz) = config.imgsz {
sz
} else if let Some(sz) = metadata.imgsz {
sz
} else if is_dynamic {
// Dynamic input without metadata -> apply robust defaults
match metadata.task {
Task::Obb => InferenceConfig::DEFAULT_OBB_IMGSZ,
_ => InferenceConfig::DEFAULT_IMGSZ,
}
} else {
// Static input without metadata -> try to read from tensor shape
// Typically [1, 3, H, W]
let task_default = match metadata.task {
Task::Obb => InferenceConfig::DEFAULT_OBB_IMGSZ,
_ => InferenceConfig::DEFAULT_IMGSZ,
};
input_info
.and_then(|i| {
if let ValueType::Tensor { shape, .. } = i.dtype() {
if shape.len() == 4 && shape[2] > 0 && shape[3] > 0 {
#[allow(clippy::cast_sign_loss)]
Some((shape[2] as usize, shape[3] as usize))
} else {
None
}
} else {
None
}
})
.unwrap_or(task_default)
};
// Update config with resolved values
let config = InferenceConfig {
imgsz: Some(resolved_imgsz),
half: config.half || metadata.half, // Use half if user requested OR model was exported with half
..config
};
// Ensure metadata reflects the resolved size
let mut metadata = metadata;
metadata.imgsz = Some(resolved_imgsz);
// Finalize the GPU preprocessor now that we know the model input edge.
// The handle MUST be consumed (not dropped) once `with_compute_stream`
// has been wired into the EPs above — dropping the last `Arc<CudaStream>`
// would invalidate the raw pointer held by ORT. So if the stream was
// opened we always finalize the preprocessor, sizing the input buffer to
// the resolved (possibly non-square) model input; `predict_image`'s
// runtime gate keeps it unused for Classify / fp16-input models.
#[cfg(feature = "cuda-preprocess")]
let cuda_preprocessor = if let Some(handle) = cuda_pre_stream {
let (dst_h, dst_w) = resolved_imgsz;
match crate::cuda_inference::CudaPreprocessor::finalize(handle, dst_h, dst_w) {
Ok(p) => Some(p),
Err(e) => {
return Err(InferenceError::ModelLoadError(format!(
"cuda-preprocess: finalize failed ({e:?}) but stream was already \
bound to EPs; cannot safely drop the stream. Disable the \
`cuda-preprocess` feature or set with_cuda_preprocess(false)."
)));
}
}
} else {
None
};
let mut model = Self {
session,
metadata,
input_name,
output_names,
config,
warmed_up: false,
fp16_input,
execution_provider: provider_name.to_string(),
is_dynamic,
#[cfg(feature = "cuda-preprocess")]
cuda_preprocessor,
};
// Warmup inference to trigger JIT compilation and memory allocation
model.warmup()?;
Ok(model)
}
/// Build the CUDA execution provider.
///
/// TF32 is enabled. TF32 is a reduced-precision format available on
/// NVIDIA Tensor cores (Ampere and newer) that accelerates FP32
/// `MatMul` and `Conv` ops by truncating the mantissa to 10 bits before
/// multiplying, while keeping FP32 range for accumulation. It typically
/// gives a significant speedup on FP32 models with accuracy loss well
/// below detection-threshold sensitivity. On GPUs without TF32
/// hardware (pre-Ampere), the flag is a silent no-op cuDNN falls
/// back to standard FP32.
///
/// `compute_stream` (when `Some`) binds the EP to an external cudarc stream
/// for the `cuda-preprocess` fast path; this requires an `unsafe` ORT call.
#[cfg(feature = "cuda")]
#[allow(unsafe_code)]
fn build_cuda_ep(
device_id: i32,
compute_stream: Option<*mut ()>,
) -> ort::execution_providers::ExecutionProviderDispatch {
let ep = ort::execution_providers::CUDAExecutionProvider::default()
.with_device_id(device_id)
.with_tf32(true);
// Bind to the cuda-preprocess stream when supplied; this keeps the
// ORT inference enqueued behind the preprocess kernel without an
// explicit synchronize. SAFETY: caller (load_with_config) keeps the
// CudaStreamHandle alive for the lifetime of the Session.
match compute_stream {
Some(s) => unsafe { ep.with_compute_stream(s).build() },
None => ep.build(),
}
}
/// Build the `TensorRT` execution provider with engine + timing caches enabled.
///
/// FP16 is enabled when `fp16` is true (driven by `config.half`). On Ada and
/// newer GPUs this is ~2x faster than FP32 with negligible accuracy delta
/// for YOLO detection. Engine and timing caches are written under
/// `<model_dir>/.trt_cache/<model_stem>_{fp16,fp32}/` so subsequent loads
/// skip the multi-minute TRT engine compile.
///
/// `compute_stream` (when `Some`) binds the EP to an external cudarc stream
/// for the `cuda-preprocess` fast path; this requires an `unsafe` ORT call.
#[cfg(feature = "tensorrt")]
#[allow(unsafe_code)]
fn build_tensorrt_ep(
model_path: &Path,
device_id: i32,
fp16: bool,
compute_stream: Option<*mut ()>,
) -> ort::execution_providers::ExecutionProviderDispatch {
let stem = model_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("model");
let parent = model_path.parent().unwrap_or_else(|| Path::new("."));
let suffix = if fp16 { "fp16" } else { "fp32" };
let cache_dir = parent.join(".trt_cache").join(format!("{stem}_{suffix}"));
let _ = std::fs::create_dir_all(&cache_dir);
let cache_str = cache_dir.to_string_lossy().into_owned();
let ep = ort::execution_providers::TensorRTExecutionProvider::default()
.with_device_id(device_id)
.with_fp16(fp16)
.with_engine_cache(true)
.with_engine_cache_path(cache_str.clone())
.with_timing_cache(true)
.with_timing_cache_path(cache_str)
.with_max_workspace_size(4 * 1024 * 1024 * 1024)
.with_builder_optimization_level(5);
// SAFETY: see build_cuda_ep above.
match compute_stream {
Some(s) => unsafe { ep.with_compute_stream(s).build() },
None => ep.build(),
}
}
#[cfg(feature = "coreml")]
fn macos_version() -> Option<(u32, u32)> {
let out = std::process::Command::new("sw_vers")
.arg("-productVersion")
.output()
.ok()?;
let s = std::str::from_utf8(&out.stdout).ok()?.trim();
let mut p = s.split('.');
Some((
p.next()?.parse().ok()?,
p.next().unwrap_or("0").parse().ok()?,
))
}
#[cfg(feature = "coreml")]
fn build_coreml_ep(model_path: &Path) -> ort::execution_providers::ExecutionProviderDispatch {
use ort::ep::coreml::{ModelFormat, SpecializationStrategy};
// MLProgram with static input shapes and FastPrediction avoids the ORT CoreML EP
// input-rename bug: the rename ("images" -> "graph_input_cast_0") only occurs when
// CoreML inserts a dynamic FP32->FP16 cast, which static-shape specialization skips.
let mut ep = ort::execution_providers::CoreMLExecutionProvider::default()
.with_model_format(ModelFormat::MLProgram)
.with_specialization_strategy(SpecializationStrategy::FastPrediction)
.with_static_input_shapes(true);
if let Some(cache_base) = dirs::cache_dir() {
let canonical = model_path
.canonicalize()
.unwrap_or_else(|_| model_path.to_path_buf());
let stem = canonical
.file_stem()
.map_or_else(|| "model".to_owned(), |s| s.to_string_lossy().into_owned());
let hash = canonical
.as_os_str()
.as_encoded_bytes()
.iter()
.fold(14_695_981_039_346_656_037u64, |h, &b| {
h.wrapping_mul(1_099_511_628_211) ^ u64::from(b)
});
let cache_dir = cache_base
.join("ultralytics-inference")
.join("coreml")
.join(format!("{stem}_{hash:016x}_mlprogram"));
if std::fs::create_dir_all(&cache_dir).is_ok() {
ep = ep.with_model_cache_dir(cache_dir.to_string_lossy());
}
}
ep.build()
}
/// Distribute the elapsed wall time since `start` evenly across every result in the
/// batch and stamp it onto `res.speed.postprocess`. Shared by both postprocess closures.
fn apply_postprocess_time(batch: &mut [Vec<Results>], start: Instant, n_images_f: f64) {
#[allow(clippy::cast_precision_loss)]
let ms = start.elapsed().as_secs_f64() * 1000.0 / n_images_f;
for img_results in batch {
for res in img_results {
res.speed.postprocess = Some(ms);
}
}
}
/// Concatenate per-image FP32 input tensors along the batch axis.
fn concat_f32_batch(
preprocessed: &[crate::preprocessing::PreprocessResult],
) -> Result<ndarray::Array4<f32>> {
let arrays: Vec<_> = preprocessed.iter().map(|r| r.tensor.view()).collect();
let batch = ndarray::concatenate(ndarray::Axis(0), &arrays).map_err(|e| {
InferenceError::InferenceError(format!("Failed to concatenate FP32 tensors: {e}"))
})?;
batch.into_dimensionality::<ndarray::Ix4>().map_err(|e| {
InferenceError::InferenceError(format!(
"Failed to convert concatenated tensor to 4D: {e}"
))
})
}
/// Concatenate per-image FP16 input tensors along the batch axis.
fn concat_f16_batch(
preprocessed: &[crate::preprocessing::PreprocessResult],
) -> Result<ndarray::Array4<f16>> {
let arrays: Vec<_> = preprocessed
.iter()
.map(|r| {
r.tensor_f16
.as_ref()
.expect("FP16 tensor should be available")
.view()
})
.collect();
let batch = ndarray::concatenate(ndarray::Axis(0), &arrays).map_err(|e| {
InferenceError::InferenceError(format!("Failed to concatenate FP16 tensors: {e}"))
})?;
batch.into_dimensionality::<ndarray::Ix4>().map_err(|e| {
InferenceError::InferenceError(format!(
"Failed to convert concatenated tensor to 4D: {e}"
))
})
}
/// Returns true when the ONNX has `ArgMax` + `Cast(uint8)` baked in, so the only output is
/// a `[B, H, W] uint8` class map. Lets us skip f32 logits extraction + CPU argmax for semantic segmentation.
fn has_semantic_mask_output(&self) -> bool {
let outs = self.session.outputs();
outs.len() == 1
&& matches!(
outs[0].dtype(),
ValueType::Tensor { ty: ort::value::TensorElementType::Uint8, shape, .. }
if shape.len() == 3
)
}
/// Maximum allowed image dimension to prevent OOM during warmup.
const MAX_IMGSZ: usize = 8192;
/// Warm up the model by running inference with a dummy input.
///
/// This pre-allocates memory and optimizes the execution graph for faster
/// subsequent inferences. Warmup is automatically called on first predict.
pub fn warmup(&mut self) -> Result<()> {
if self.warmed_up {
return Ok(());
}
let target_size = self
.config
.imgsz
.or(self.metadata.imgsz)
.unwrap_or(InferenceConfig::DEFAULT_IMGSZ);
// Sanity check to prevent huge allocations from invalid imgsz
if target_size.0 > Self::MAX_IMGSZ || target_size.1 > Self::MAX_IMGSZ {
return Err(InferenceError::ConfigError(format!(
"Image size {}x{} exceeds maximum allowed {}x{}",
target_size.0,
target_size.1,
Self::MAX_IMGSZ,
Self::MAX_IMGSZ
)));
}
let warmup_result = Self::run_warmup(
&mut self.session,
&self.input_name,
self.fp16_input,
target_size,
);
if let Err(e) = warmup_result {
let msg = e.to_string();
if !is_benign_coreml_warmup_error(&self.execution_provider, &msg) {
return Err(e);
}
}
self.warmed_up = true;
Ok(())
}
/// Extract metadata from the ONNX model session.
pub(crate) fn extract_metadata(session: &Session) -> Result<ModelMetadata> {
// Get metadata from the model
let model_metadata = session.metadata().map_err(|e| {
InferenceError::ModelLoadError(format!("Failed to get model metadata: {e}"))
})?;
// Ultralytics stores metadata under individual keys
// Try to get each key separately and build a YAML string
let mut metadata_map: HashMap<String, String> = HashMap::new();
// List of all Ultralytics metadata keys
let keys = [
"description",
"author",
"date",
"version",
"license",
"docs",
"stride",
"task",
"batch",
"imgsz",
"names",
"half",
"channels",
"args",
"end2end",
"kpt_shape",
];
for key in &keys {
if let Some(value) = model_metadata.custom(key) {
metadata_map.insert((*key).to_string(), value);
}
}
// If we found individual keys, build a YAML string from them
if !metadata_map.is_empty() {
let mut yaml_parts = Vec::new();
for (key, value) in &metadata_map {
yaml_parts.push(format!("{key}: {value}"));
}
let combined_yaml = yaml_parts.join("\n");
let mut combined_map = HashMap::new();
combined_map.insert(String::new(), combined_yaml);
return ModelMetadata::from_onnx_metadata(&combined_map);
}
// Also try getting metadata from a single combined key
for key in &["", "metadata", "model_metadata"] {
if let Some(value) = model_metadata.custom(key) {
metadata_map.insert((*key).to_string(), value);
}
}
if metadata_map.is_empty() {
// Return defaults
return Ok(ModelMetadata::default());
}
ModelMetadata::from_onnx_metadata(&metadata_map)
}
/// Returns the execution provider used for inference.
#[must_use]
pub fn execution_provider(&self) -> &str {
&self.execution_provider
}
/// Run inference on an image file.
///
/// # Arguments
///
/// * `path` - Path to the image file.
///
/// # Returns
///
/// Vector of Results (one per image in batch).
///
/// # Errors
///
/// Returns an error if the image can't be loaded or inference fails.
pub fn predict<P: AsRef<Path>>(&mut self, path: P) -> Result<Vec<Results>> {
let path = path.as_ref();
// Warmup first to fail fast before loading/decoding the image
self.warmup()?;
// Load image using standard image crate
let img = image::open(path).map_err(|e| {
InferenceError::ImageError(format!("Failed to load image {}: {e}", path.display()))
})?;
self.predict_image(&img, path.to_string_lossy().to_string())
}
/// Run inference on a `DynamicImage`.
///
/// # Arguments
///
/// * `image` - The image to run inference on.
/// * `path` - Optional path/identifier for the image.
///
/// # Returns
///
/// Vector of Results.
pub fn predict_image(&mut self, image: &DynamicImage, path: String) -> Result<Vec<Results>> {
// Fast path: GPU preprocess + zero-copy device input.
//
// Allowlisted to the tasks whose preprocessing is a letterbox (square or
// non-square) + f32 input. Classify uses center-crop (not letterbox), so
// it's excluded. Semantic is included: `predict_image_cuda_pre` handles
// both its f32-logits and baked-in ArgMax (u8) output forms. The kernel
// emits the model's fixed dst_h × dst_w; the only requirement is f32
// input (the kernel writes f32, not f16).
#[cfg(feature = "cuda-preprocess")]
if self.cuda_preprocessor.is_some()
&& !self.fp16_input
&& matches!(
self.metadata.task,
Task::Detect | Task::Segment | Task::Pose | Task::Obb | Task::Semantic
)
{
let results = self.predict_image_cuda_pre(image, path)?;
if let Some(result) = results.first() {
let shape = result.inference_shape();
verbose!(
"image 1/1 {}: {}x{} {}, {:.1}ms",
result.path,
shape.0,
shape.1,
result.detection_summary(),
result.speed.inference.unwrap_or(0.0)
);
}
return Ok(results);
}
let images = [image];
let paths = [path];
let mut results = self.predict_internal(&images, &paths)?;
let results = results.pop().unwrap_or_default();
if let Some(result) = results.first() {
let shape = result.inference_shape();
verbose!(
"image 1/1 {}: {}x{} {}, {:.1}ms",
result.path,
shape.0,
shape.1,
result.detection_summary(),
result.speed.inference.unwrap_or(0.0)
);
}
Ok(results)
}
/// CUDA-preprocess fast path used by [`Self::predict_image`] when
/// `cuda_preprocessor` is populated. Runs the fused letterbox+normalize kernel,
/// hands the resulting device buffer to ORT via `TensorRefMut::from_raw`,
/// then post-processes with the standard pipeline.
#[cfg(feature = "cuda-preprocess")]
#[allow(unsafe_code)]
fn predict_image_cuda_pre(
&mut self,
image: &DynamicImage,
path: String,
) -> Result<Vec<Results>> {
use ort::memory::{AllocationDevice, AllocatorType, MemoryInfo, MemoryType};
use ort::value::TensorRefMut;
// Computed before `run_binding` borrows the session: true when the
// ONNX bakes in ArgMax+Cast(u8) so the single output is a uint8 class
// map (semantic segmentation fast form).
let semantic_u8 = self.has_semantic_mask_output();
let start_preprocess = Instant::now();
let rgb_img = image.to_rgb8();
let (w, h) = (rgb_img.width(), rgb_img.height());
let rgb_bytes = rgb_img.into_raw();
let pre = self
.cuda_preprocessor
.as_mut()
.expect("predict_image_cuda_pre invariant: cuda_preprocessor.is_some()");
let geom = pre.preprocess(&rgb_bytes, h, w, false)?;
let (dst_h, dst_w) = pre.dst_hw();
let dev_ptr = pre.input_dev_ptr();
#[allow(clippy::cast_precision_loss)]
let preprocess_time = start_preprocess.elapsed().as_secs_f64() * 1000.0;
let cuda_mem = MemoryInfo::new(
AllocationDevice::CUDA,
0,
AllocatorType::Device,
MemoryType::Default,
)
.map_err(|e| InferenceError::InferenceError(format!("cuda meminfo: {e}")))?;
let cpu_mem = MemoryInfo::new(
AllocationDevice::CPU,
0,
AllocatorType::Device,
MemoryType::Default,
)
.map_err(|e| InferenceError::InferenceError(format!("cpu meminfo: {e}")))?;
let shape: Vec<i64> = vec![1, 3, dst_h as i64, dst_w as i64];
// SAFETY: dev_ptr is owned by `cuda_preprocessor` (stored on `self`) and remains
// valid for the duration of this call. ORT consumes it during
// `run_binding`, which is synchronized via the shared cuda stream.
let in_tensor = unsafe {
TensorRefMut::<f32>::from_raw(cuda_mem, dev_ptr as *mut core::ffi::c_void, shape.into())
.map_err(|e| InferenceError::InferenceError(format!("from_raw: {e}")))?
};
let start_inference = Instant::now();
let mut binding = self
.session
.create_binding()
.map_err(|e| InferenceError::InferenceError(format!("create_binding: {e}")))?;
binding
.bind_input(&self.input_name, &in_tensor)
.map_err(|e| InferenceError::InferenceError(format!("bind_input: {e}")))?;
for n in &self.output_names {
binding
.bind_output_to_device(n, &cpu_mem)
.map_err(|e| InferenceError::InferenceError(format!("bind_output: {e}")))?;
}
let outputs = self
.session
.run_binding(&binding)
.map_err(|e| InferenceError::InferenceError(format!("run_binding: {e}")))?;
binding
.synchronize_outputs()
.map_err(|e| InferenceError::InferenceError(format!("sync_outputs: {e}")))?;
#[allow(clippy::cast_precision_loss)]
let inference_time = start_inference.elapsed().as_secs_f64() * 1000.0;
// HWC u8 ndarray for annotators/postprocess reuses the rgb buffer
// (moved in), no copy.
let orig_img = ndarray::Array3::from_shape_vec((h as usize, w as usize, 3), rgb_bytes)
.map_err(|e| InferenceError::InferenceError(format!("Array3 from rgb: {e}")))?;
let start_postprocess = Instant::now();
let speed = Speed::new(preprocess_time, inference_time, 0.0);
// Semantic fast form: the ONNX emits a single uint8 class map. Extract
// it directly (no f32 logits, no CPU argmax) and run the dedicated
// mask post-processor — mirrors the CPU `run_inference_u8_with` path.
if semantic_u8 {
let name = self.output_names.first().ok_or_else(|| {
InferenceError::InferenceError("semantic model has no output".into())
})?;
let output = outputs.get(name.as_str()).ok_or_else(|| {
InferenceError::InferenceError(format!("Output '{name}' not found"))
})?;
let (oshape, data) = output.try_extract_tensor::<u8>().map_err(|e| {
InferenceError::InferenceError(format!("extract uint8 semantic output: {e}"))
})?;
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let shape_vec: Vec<usize> = oshape.iter().map(|&d| d as usize).collect();
// Drop the leading batch dim (batch == 1 here).
let img_shape: &[usize] = if shape_vec.len() > 1 {
&shape_vec[1..]
} else {
&shape_vec
};
let mut result = crate::postprocessing::postprocess_semantic_mask(
data,
img_shape,
Arc::clone(&self.metadata.names),
orig_img,
path,
speed,
(dst_h as u32, dst_w as u32),
);
#[allow(clippy::cast_precision_loss)]
let postprocess_time = start_postprocess.elapsed().as_secs_f64() * 1000.0;
result.speed.postprocess = Some(postprocess_time);