| 1 | use std::collections::HashMap; |
| 2 | use std::io::Cursor; |
| 3 | use std::sync::OnceLock; |
| 4 | |
| 5 | use ort::environment::Environment; |
| 6 | use ort::session::Session; |
| 7 | use ort::session::builder::GraphOptimizationLevel; |
| 8 | use ort::value::Tensor as OrtTensor; |
| 9 | use tract_onnx::prelude::*; |
| 10 | |
| 11 | use super::model::ModelSpec; |
| 12 | |
| 13 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 14 | pub enum Device { |
| 15 | Cpu { threads: usize }, |
| 16 | Gpu, |
| 17 | } |
| 18 | |
| 19 | pub trait Runner: Send { |
| 20 | fn run(&mut self, input: Vec<f32>) -> std::result::Result<Vec<f32>, String>; |
| 21 | } |
| 22 | |
| 23 | static ENVIRONMENT: OnceLock<Option<Environment>> = OnceLock::new(); |
| 24 | |
| 25 | /// The process-wide ONNX Runtime, or `None` when it cannot load; then only tract runs. |
| 26 | pub fn environment() -> Option<&'static Environment> { |
| 27 | ENVIRONMENT.get_or_init(|| builder().and_then(|builder| builder.with_name("segmentation").build().ok())).as_ref() |
| 28 | } |
| 29 | |
| 30 | #[cfg(not(windows))] |
| 31 | fn builder() -> Option<ort::environment::EnvironmentBuilder> { |
| 32 | Some(ort::init()) |
| 33 | } |
| 34 | |
| 35 | #[cfg(windows)] |
| 36 | fn builder() -> Option<ort::environment::EnvironmentBuilder> { |
| 37 | let path = super::embedded::onnxruntime_path()?; |
| 38 | ort::init_from(path).ok() |
| 39 | } |
| 40 | |
| 41 | pub fn gpu_available() -> bool { |
| 42 | cfg!(windows) && environment().is_some() |
| 43 | } |
| 44 | |
| 45 | struct OrtRunner { |
| 46 | session: Session, |
| 47 | shape: [usize; 4], |
| 48 | } |
| 49 | |
| 50 | impl Runner for OrtRunner { |
| 51 | fn run(&mut self, input: Vec<f32>) -> std::result::Result<Vec<f32>, String> { |
| 52 | let tensor = OrtTensor::from_array((self.shape.to_vec(), input.into_boxed_slice())).map_err(|error| error.to_string())?; |
| 53 | let outputs = self.session.run(ort::inputs![tensor]).map_err(|error| error.to_string())?; |
| 54 | let (_, values) = outputs[0].try_extract_tensor::<f32>().map_err(|error| error.to_string())?; |
| 55 | Ok(values.to_vec()) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | fn ort_runner(spec: &ModelSpec, device: Device) -> std::result::Result<OrtRunner, String> { |
| 60 | let environment = environment().ok_or("onnx runtime unavailable")?; |
| 61 | let failed = |error: ort::Error<_>| error.to_string(); |
| 62 | let mut builder = Session::builder(environment).map_err(|error| error.to_string())?.with_optimization_level(GraphOptimizationLevel::Level3).map_err(failed)?; |
| 63 | builder = match device { |
| 64 | Device::Cpu { threads } => builder.with_intra_threads(threads).map_err(failed)?.with_execution_providers([ort::ep::CPU::default().build().error_on_failure()]).map_err(failed)?, |
| 65 | #[cfg(windows)] |
| 66 | Device::Gpu => builder |
| 67 | .with_parallel_execution(false) |
| 68 | .map_err(failed)? |
| 69 | .with_memory_pattern(false) |
| 70 | .map_err(failed)? |
| 71 | .with_execution_providers([ort::ep::DirectML::default().build().error_on_failure()]) |
| 72 | .map_err(failed)?, |
| 73 | #[cfg(not(windows))] |
| 74 | Device::Gpu => return Err("no gpu runtime on this platform".to_owned()), |
| 75 | }; |
| 76 | let session = builder.commit_from_memory(spec.bytes()).map_err(|error| error.to_string())?; |
| 77 | Ok(OrtRunner { session, shape: [1, 3, spec.height, spec.width] }) |
| 78 | } |
| 79 | |
| 80 | struct TractRunner { |
| 81 | plan: std::sync::Arc<TypedRunnableModel>, |
| 82 | shape: [usize; 4], |
| 83 | } |
| 84 | |
| 85 | impl Runner for TractRunner { |
| 86 | fn run(&mut self, input: Vec<f32>) -> std::result::Result<Vec<f32>, String> { |
| 87 | let tensor = Tensor::from_shape(&self.shape, &input).map_err(|error| error.to_string())?; |
| 88 | let outputs = self.plan.run(tvec!(tensor.into())).map_err(|error| error.to_string())?; |
| 89 | let values = outputs[0].to_plain_array_view::<f32>().map_err(|error| error.to_string())?; |
| 90 | Ok(values.iter().copied().collect()) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | fn tract_runner(spec: &ModelSpec) -> TractResult<TractRunner> { |
| 95 | let model = tract_onnx::onnx().model_for_read(&mut Cursor::new(spec.bytes()))?; |
| 96 | let symbols: HashMap<_, _> = ["batch_size", "height", "width"] |
| 97 | .into_iter() |
| 98 | .zip([1, spec.height, spec.width]) |
| 99 | .map(|(name, value)| (model.symbols.sym(name), TDim::from(value as i64))) |
| 100 | .collect(); |
| 101 | let plan = model.into_typed()?.set_symbols(&symbols)?.into_optimized()?.into_runnable()?; |
| 102 | Ok(TractRunner { plan, shape: [1, 3, spec.height, spec.width] }) |
| 103 | } |
| 104 | |
| 105 | pub fn runner(spec: &ModelSpec, device: Device) -> std::result::Result<Box<dyn Runner>, String> { |
| 106 | match ort_runner(spec, device) { |
| 107 | Ok(runner) => Ok(Box::new(runner)), |
| 108 | Err(_) if environment().is_none() && device != Device::Gpu => tract_runner(spec).map(|runner| Box::new(runner) as Box<dyn Runner>).map_err(|error| error.to_string()), |
| 109 | Err(error) => Err(error), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | #[cfg(test)] |
| 114 | pub fn tract_only(spec: &ModelSpec) -> Box<dyn Runner> { |
| 115 | Box::new(tract_runner(spec).expect("tract loads the model")) |
| 116 | } |