|
| 1 | +//! This test originates from some strange segfaults that we observed while using the OpenVINO C |
| 2 | +//! library. Because OpenVINO is taking a pointer to a tensor when constructing a model, we want to |
| 3 | +//! be sure that we do the right thing on this side of the FFI boundary. |
| 4 | +
|
| 5 | +mod fixtures; |
| 6 | + |
| 7 | +use fixtures::mobilenet::Fixture; |
| 8 | +use openvino::{Core, DeviceType, ElementType, Shape, Tensor}; |
| 9 | +use std::fs; |
| 10 | + |
| 11 | +#[test] |
| 12 | +fn memory_safety() -> anyhow::Result<()> { |
| 13 | + let mut core = Core::new()?; |
| 14 | + let xml = fs::read_to_string(Fixture::graph())?; |
| 15 | + let weights = fs::read(Fixture::weights())?; |
| 16 | + |
| 17 | + // Copy the fixture weights into a tensor. Once we're done here we want to get rid of the |
| 18 | + // original weights buffer as a sanity check. |
| 19 | + let shape = Shape::new(&[1, weights.len() as i64])?; |
| 20 | + let mut weights_tensor = Tensor::new(ElementType::U8, &shape)?; |
| 21 | + weights_tensor.get_raw_data_mut()?.copy_from_slice(&weights); |
| 22 | + drop(weights); |
| 23 | + |
| 24 | + // Now create a model from a reference to the weights tensor. We observed segfault crashes when |
| 25 | + // passing weights by value but not by reference. |
| 26 | + let model = core.read_model_from_buffer(xml.as_bytes(), Some(&weights_tensor))?; |
| 27 | + drop(weights_tensor); |
| 28 | + |
| 29 | + // Here we double-check that the model is usable. Though it has captured a reference to the |
| 30 | + // `weights_tensor` and that tensor has been dropped, whatever OpenVINO is doing internally must |
| 31 | + // be safe enough. See |
| 32 | + // https://github.com/openvinotoolkit/openvino/blob/d840d86905f013d95cccbafaa0ddff266e250f75/src/inference/src/model_reader.cpp#L178. |
| 33 | + assert_eq!(model.get_inputs_len()?, 1); |
| 34 | + assert!(core.compile_model(&model, DeviceType::CPU).is_ok()); |
| 35 | + Ok(()) |
| 36 | +} |
0 commit comments