BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / segmentation / runtime.rs

runtime.rs

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