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
use std::collections::HashMap;

use crate::{Error, Result};
use half::{bf16, f16};
use ndarray::{Array, IxDyn};
use ort::session::{Input, SessionBuilder};
use ort::tensor::{DynOrtTensor, FromArray, InputTensor, TensorElementDataType};
use ort::{ExecutionProvider, GraphOptimizationLevel};

pub enum ORTSession<'a> {
    InMemory(ort::InMemorySession<'a>),
    Owned(ort::Session),
}

pub fn match_to_inputs(
    inputs: &Vec<Input>,
    mut values: HashMap<String, InputTensor>,
) -> Result<Vec<InputTensor>> {
    let mut inputs_array_vector: Vec<InputTensor> = Default::default();
    let input_names = inputs
        .iter()
        .map(|input| input.name.clone())
        .collect::<Vec<String>>();
    // check if inputs contain `.1` and remove it if it won't lead to duplicate inputs
    let input_names = input_names
        .iter()
        .map(|input_name| {
            if input_name.ends_with(".1") {
                let input_name = input_name.trim_end_matches(".1");
                if !input_names.contains(&input_name.to_string()) {
                    return input_name.to_string();
                }
            }
            input_name.to_string()
        })
        .collect::<Vec<String>>();
    for (input, input_name) in inputs.iter().zip(input_names.iter()) {
        inputs_array_vector.push(match input.input_type {
            TensorElementDataType::Float32 => {
                if let Some(value) = values.remove(input_name) {
                    Ok::<_, Error>(cast_input_tensor_f32(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Uint8 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_u8(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Int8 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_i8(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Uint16 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_u16(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Int16 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_i16(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Int32 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_i32(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Int64 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_i64(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::String => {
                if let Some(value) = values.remove(input_name) {
                    Ok(value)
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Float64 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_f64(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Uint32 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_u32(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Uint64 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_u64(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Bool => {
                if let Some(value) = values.remove(input_name) {
                    Ok(value)
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Float16 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_f16(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
            TensorElementDataType::Bfloat16 => {
                if let Some(value) = values.remove(input_name) {
                    Ok(cast_input_tensor_bf16(value))
                } else {
                    return Err(format!("Missing input: {}", input.name).into());
                }
            }
        }?);
    }
    Ok(inputs_array_vector)
}

macro_rules! impl_cast_input_array {
    ($type_:ty) => {
        ::paste::paste! {
            fn [<cast_input_tensor_ $type_>](input: InputTensor) -> InputTensor
            {
                let array = match input {
                    InputTensor::FloatTensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Uint8Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Int8Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Uint16Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Int16Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Int32Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Int64Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::DoubleTensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Uint32Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::Uint64Tensor(array) => { array.mapv(|x| x as $type_) }
                    InputTensor::StringTensor(array) => { array.mapv(|x| x.parse::<$type_>().unwrap()) }
                    InputTensor::Float16Tensor(array) => { array.mapv(|x| x.to_f32() as $type_) }
                    InputTensor::Bfloat16Tensor(array) => { array.mapv(|x| x.to_f32() as $type_) }
                };
                InputTensor::from_array(array)
            }
        }
    };
}

macro_rules! impl_cast_non_primitive_array {
    ($type_:ty) => {
        ::paste::paste! {
            fn [<cast_input_tensor_ $type_>](input: InputTensor) -> InputTensor
            {
                let array = match input {
                    InputTensor::FloatTensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Uint8Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Int8Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Uint16Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Int16Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Int32Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Int64Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::DoubleTensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Uint32Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::Uint64Tensor(array) => { array.mapv(|x| $type_::from_f64(x as f64)) }
                    InputTensor::StringTensor(array) => { array.mapv(|x| x.parse::<$type_>().unwrap()) }
                    InputTensor::Float16Tensor(array) => { array.mapv(|x| $type_::from_f64(x.to_f64())) }
                    InputTensor::Bfloat16Tensor(array) => { array.mapv(|x| $type_::from_f64(x.to_f64())) }
                };
                InputTensor::from_array(array)
            }
        }
    };
}

impl_cast_input_array!(f32);
impl_cast_input_array!(u8);
impl_cast_input_array!(i8);
impl_cast_input_array!(u16);
impl_cast_input_array!(i16);
impl_cast_input_array!(i32);
impl_cast_input_array!(i64);
impl_cast_input_array!(f64);
impl_cast_input_array!(u32);
impl_cast_input_array!(u64);
impl_cast_non_primitive_array!(f16);
impl_cast_non_primitive_array!(bf16);

#[derive(Debug, Clone)]
/// Device enum to specify the device to run the model on
pub enum Device {
    CPU,
    #[cfg(feature = "directml")]
    DML,
    #[cfg(feature = "cuda")]
    CUDA,
}

pub fn apply_device(
    session_builder: SessionBuilder,
    device: Device,
) -> std::result::Result<SessionBuilder, Error> {
    match device {
        Device::CPU => session_builder
            .with_execution_providers([ExecutionProvider::cpu()])
            .map_err(|e| e.into()),
        #[cfg(feature = "directml")]
        Device::DML => {
            if cfg!(feature = "directml") {
                session_builder
                    .with_execution_providers([ExecutionProvider::directml()])
                    .map_err(|e| e.into())
            } else {
                return Err(Error::GenericError {
                    message: "DML feature is not enabled".to_string(),
                });
            }
        }
        #[cfg(feature = "cuda")]
        Device::CUDA => {
            if cfg!(feature = "cuda") {
                session_builder
                    .with_execution_providers([ExecutionProvider::cuda()])
                    .map_err(|e| e.into())
            } else {
                return Err(Error::GenericError {
                    message: "CUDA feature is not enabled".to_string(),
                });
            }
        }
    }
}

pub fn clone(opt_level: &GraphOptimizationLevel) -> GraphOptimizationLevel {
    match opt_level {
        GraphOptimizationLevel::Disable => GraphOptimizationLevel::Disable,
        GraphOptimizationLevel::Level1 => GraphOptimizationLevel::Level1,
        GraphOptimizationLevel::Level2 => GraphOptimizationLevel::Level2,
        GraphOptimizationLevel::Level3 => GraphOptimizationLevel::Level3,
    }
}

pub fn try_extract_to_f32(tensor: DynOrtTensor<IxDyn>) -> Result<Array<f32, IxDyn>> {
    Ok(match tensor.data_type() {
        TensorElementDataType::Float16 => tensor
            .try_extract::<f16>()?
            .view()
            .to_owned()
            .mapv(|v| v.to_f32()),
        TensorElementDataType::Float32 => tensor.try_extract::<f32>()?.view().to_owned(),
        TensorElementDataType::Float64 => tensor
            .try_extract::<f64>()?
            .view()
            .to_owned()
            .mapv(|v| v as f32),
        TensorElementDataType::Bfloat16 => tensor
            .try_extract::<bf16>()?
            .view()
            .to_owned()
            .mapv(|v| v.to_f32()),
        _ => return Err(format!("Unsupported output data type {:?}", tensor.data_type()).into()),
    })
}