forked from nbigaouette/onnxruntime-rs
-
Notifications
You must be signed in to change notification settings - Fork 13
/
integration_tests.rs
335 lines (283 loc) · 10.9 KB
/
integration_tests.rs
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
use std::{
fs,
io::{self, BufRead, BufReader},
path::Path,
time::Duration,
};
use onnxruntime::error::OrtDownloadError;
use onnxruntime::tensor::OrtOwnedTensor;
mod download {
use super::*;
use image::{imageops::FilterType, ImageBuffer, Luma, Pixel, Rgb};
use ndarray::s;
use test_env_log::test;
use onnxruntime::{
download::vision::{DomainBasedImageClassification, ImageClassification},
environment::Environment,
GraphOptimizationLevel, LoggingLevel,
};
#[test]
fn squeezenet_mushroom() {
const IMAGE_TO_LOAD: &str = "mushroom.png";
let environment = Environment::builder()
.with_name("integration_test")
.with_log_level(LoggingLevel::Warning)
.build()
.unwrap();
let mut session = environment
.new_session_builder()
.unwrap()
.with_optimization_level(GraphOptimizationLevel::Basic)
.unwrap()
.with_intra_op_num_threads(1)
.unwrap()
.with_model_downloaded(ImageClassification::SqueezeNet)
.expect("Could not download model from file");
let class_labels = get_imagenet_labels().unwrap();
let input0_shape: Vec<usize> = session.inputs[0].dimensions().map(|d| d.unwrap()).collect();
let output0_shape: Vec<usize> = session.outputs[0]
.dimensions()
.map(|d| d.unwrap())
.collect();
assert_eq!(input0_shape, [1, 3, 224, 224]);
assert_eq!(output0_shape, [1, 1000]);
// Load image and resize to model's shape, converting to RGB format
let image_buffer: ImageBuffer<Rgb<u8>, Vec<u8>> = image::open(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("data")
.join(IMAGE_TO_LOAD),
)
.unwrap()
.resize(
input0_shape[2] as u32,
input0_shape[3] as u32,
FilterType::Nearest,
)
.to_rgb8();
// Python:
// # image[y, x, RGB]
// # x==0 --> left
// # y==0 --> top
// See https://github.com/onnx/models/blob/master/vision/classification/imagenet_inference.ipynb
// for pre-processing image.
// WARNING: Note order of declaration of arguments: (_,c,j,i)
let mut array = ndarray::Array::from_shape_fn((1, 3, 224, 224), |(_, c, j, i)| {
let pixel = image_buffer.get_pixel(i as u32, j as u32);
let channels = pixel.channels();
// range [0, 255] -> range [0, 1]
(channels[c] as f32) / 255.0
});
// Normalize channels to mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225]
let mean = [0.485, 0.456, 0.406];
let std = [0.229, 0.224, 0.225];
for c in 0..3 {
let mut channel_array = array.slice_mut(s![0, c, .., ..]);
channel_array -= mean[c];
channel_array /= std[c];
}
// Batch of 1
let input_tensor_values = vec![array];
// Perform the inference
let outputs: Vec<
onnxruntime::tensor::OrtOwnedTensor<f32, ndarray::Dim<ndarray::IxDynImpl>>,
> = session.run(input_tensor_values).unwrap();
// Downloaded model does not have a softmax as final layer; call softmax on second axis
// and iterate on resulting probabilities, creating an index to later access labels.
let output: &OrtOwnedTensor<f32, _> = &outputs[0];
let mut probabilities: Vec<(usize, f32)> = output
.softmax(ndarray::Axis(1))
.iter()
.copied()
.enumerate()
.collect::<Vec<_>>();
// Sort probabilities so highest is at beginning of vector.
probabilities.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
assert_eq!(
class_labels[probabilities[0].0], "n07734744 mushroom",
"Expecting class for {} to be a mushroom",
IMAGE_TO_LOAD
);
assert_eq!(
probabilities[0].0, 947,
"Expecting class for {} to be a mushroom (index 947 in labels file)",
IMAGE_TO_LOAD
);
// for i in 0..5 {
// println!(
// "class={} ({}); probability={}",
// labels[probabilities[i].0], probabilities[i].0, probabilities[i].1
// );
// }
}
#[test]
fn mnist_5() {
const IMAGE_TO_LOAD: &str = "mnist_5.jpg";
let environment = Environment::builder()
.with_name("integration_test")
.with_log_level(LoggingLevel::Warning)
.build()
.unwrap();
let mut session = environment
.new_session_builder()
.unwrap()
.with_optimization_level(GraphOptimizationLevel::Basic)
.unwrap()
.with_intra_op_num_threads(1)
.unwrap()
.with_model_downloaded(DomainBasedImageClassification::Mnist)
.expect("Could not download model from file");
let input0_shape: Vec<usize> = session.inputs[0].dimensions().map(|d| d.unwrap()).collect();
let output0_shape: Vec<usize> = session.outputs[0]
.dimensions()
.map(|d| d.unwrap())
.collect();
assert_eq!(input0_shape, [1, 1, 28, 28]);
assert_eq!(output0_shape, [1, 10]);
// Load image and resize to model's shape, converting to RGB format
let image_buffer: ImageBuffer<Luma<u8>, Vec<u8>> = image::open(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("data")
.join(IMAGE_TO_LOAD),
)
.unwrap()
.resize(
input0_shape[2] as u32,
input0_shape[3] as u32,
FilterType::Nearest,
)
.to_luma8();
let array = ndarray::Array::from_shape_fn((1, 1, 28, 28), |(_, c, j, i)| {
let pixel = image_buffer.get_pixel(i as u32, j as u32);
let channels = pixel.channels();
// range [0, 255] -> range [0, 1]
(channels[c] as f32) / 255.0
});
// Batch of 1
let input_tensor_values = vec![array];
// Perform the inference
let outputs: Vec<
onnxruntime::tensor::OrtOwnedTensor<f32, ndarray::Dim<ndarray::IxDynImpl>>,
> = session.run(input_tensor_values).unwrap();
let output: &OrtOwnedTensor<f32, _> = &outputs[0];
let mut probabilities: Vec<(usize, f32)> = output
.softmax(ndarray::Axis(1))
.iter()
.copied()
.enumerate()
.collect::<Vec<_>>();
// Sort probabilities so highest is at beginning of vector.
probabilities.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
assert_eq!(
probabilities[0].0, 5,
"Expecting class for {} is '5' (not {})",
IMAGE_TO_LOAD, probabilities[0].0
);
}
// This test verifies that dynamically sized inputs and outputs work. It loads and runs
// upsample.onnx, which was produced via:
//
// ```
// import subprocess
// from tensorflow import keras
//
// m = keras.Sequential([
// keras.layers.UpSampling2D(size=2)
// ])
// m.build(input_shape=(None, None, None, 3))
// m.summary()
// m.save('saved_model')
//
// subprocess.check_call([
// 'python', '-m', 'tf2onnx.convert',
// '--saved-model', 'saved_model',
// '--opset', '12',
// '--output', 'upsample.onnx',
// ])
// ```
#[test]
fn upsample() {
const IMAGE_TO_LOAD: &str = "mushroom.png";
let environment = Environment::builder()
.with_name("integration_test")
.with_log_level(LoggingLevel::Warning)
.build()
.unwrap();
let mut session = environment
.new_session_builder()
.unwrap()
.with_optimization_level(GraphOptimizationLevel::Basic)
.unwrap()
.with_intra_op_num_threads(1)
.unwrap()
.with_model_from_file(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("data")
.join("upsample.onnx"),
)
.expect("Could not open model from file");
assert_eq!(
session.inputs[0].dimensions().collect::<Vec<_>>(),
[None, None, None, Some(3)]
);
assert_eq!(
session.outputs[0].dimensions().collect::<Vec<_>>(),
[None, None, None, Some(3)]
);
// Load image, converting to RGB format
let image_buffer: ImageBuffer<Rgb<u8>, Vec<u8>> = image::open(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("data")
.join(IMAGE_TO_LOAD),
)
.unwrap()
.to_rgb8();
let array = ndarray::Array::from_shape_fn((1, 224, 224, 3), |(_, j, i, c)| {
let pixel = image_buffer.get_pixel(i as u32, j as u32);
let channels = pixel.channels();
// range [0, 255] -> range [0, 1]
(channels[c] as f32) / 255.0
});
// Just one input
let input_tensor_values = vec![array];
// Perform the inference
let outputs: Vec<
onnxruntime::tensor::OrtOwnedTensor<f32, ndarray::Dim<ndarray::IxDynImpl>>,
> = session.run(input_tensor_values).unwrap();
assert_eq!(outputs.len(), 1);
let output = &outputs[0];
// The image should have doubled in size
assert_eq!(output.shape(), [1, 448, 448, 3]);
}
}
fn get_imagenet_labels() -> Result<Vec<String>, OrtDownloadError> {
// Download the ImageNet class labels, matching SqueezeNet's classes.
let labels_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("synset.txt");
if !labels_path.exists() {
let url = "https://s3.amazonaws.com/onnx-model-zoo/synset.txt";
println!("Downloading {:?} to {:?}...", url, labels_path);
let resp = ureq::get(url)
.timeout(Duration::from_secs(180)) // 3 minutes
.call()
.map_err(Box::new)
.map_err(OrtDownloadError::UreqError)?;
assert!(resp.has("Content-Length"));
let len = resp
.header("Content-Length")
.and_then(|s| s.parse::<usize>().ok())
.unwrap();
println!("Downloading {} bytes...", len);
let mut reader = resp.into_reader();
let f = fs::File::create(&labels_path).unwrap();
let mut writer = io::BufWriter::new(f);
let bytes_io_count = io::copy(&mut reader, &mut writer).unwrap();
assert_eq!(bytes_io_count, len as u64);
}
let file = BufReader::new(fs::File::open(labels_path).unwrap());
file.lines()
.map(|line| line.map_err(|io_err| OrtDownloadError::IoError(io_err)))
.collect()
}