|
| 1 | +use std::{env, fs}; |
| 2 | +use wasmedge_nn::nn::{ctx::WasiNnCtx, Dtype, ExecutionTarget, GraphEncoding, Tensor}; |
| 3 | + |
| 4 | +fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 5 | + let args: Vec<String> = env::args().collect(); |
| 6 | + let model_xml_name: &str = &args[1]; |
| 7 | + let model_bin_name: &str = &args[2]; |
| 8 | + let tensor_name: &str = &args[3]; |
| 9 | + |
| 10 | + let tensor_data = fs::read(tensor_name).unwrap(); |
| 11 | + println!("Load input tensor, size in bytes: {}", tensor_data.len()); |
| 12 | + let tensor = Tensor { |
| 13 | + dimensions: &[1, 3, 512, 896], |
| 14 | + r#type: Dtype::F32.into(), // wasi_nn::TENSOR_TYPE_F32, |
| 15 | + data: &tensor_data, |
| 16 | + }; |
| 17 | + |
| 18 | + let mut ctx = WasiNnCtx::new()?; |
| 19 | + |
| 20 | + println!("Load model files ..."); |
| 21 | + let graph_id = ctx.load( |
| 22 | + model_xml_name, |
| 23 | + model_bin_name, |
| 24 | + GraphEncoding::Openvino, |
| 25 | + ExecutionTarget::CPU, |
| 26 | + )?; |
| 27 | + |
| 28 | + println!("initialize the execution context ..."); |
| 29 | + let exec_context_id = ctx.init_execution_context(graph_id)?; |
| 30 | + |
| 31 | + println!("Set input tensor ..."); |
| 32 | + ctx.set_input(exec_context_id, 0, tensor)?; |
| 33 | + |
| 34 | + println!("Do inference ..."); |
| 35 | + ctx.compute(exec_context_id)?; |
| 36 | + |
| 37 | + println!("Extract result ..."); |
| 38 | + let mut out_buffer = vec![0u8; 1 * 4 * 512 * 896 * 4]; |
| 39 | + ctx.get_output(exec_context_id, 0, out_buffer.as_mut_slice())?; |
| 40 | + |
| 41 | + println!("Dump result ..."); |
| 42 | + dump( |
| 43 | + "wasinn-openvino-inference-output-1x4x512x896xf32.tensor", |
| 44 | + out_buffer.as_slice(), |
| 45 | + )?; |
| 46 | + |
| 47 | + Ok(()) |
| 48 | +} |
| 49 | + |
| 50 | +/// Dump data to the specified binary file. |
| 51 | +fn dump<T>( |
| 52 | + path: impl AsRef<std::path::Path>, |
| 53 | + buffer: impl AsRef<[T]>, |
| 54 | +) -> Result<(), Box<dyn std::error::Error>> { |
| 55 | + println!("\tdump tensor to {:?}", path.as_ref()); |
| 56 | + |
| 57 | + let dst_slice: &[u8] = unsafe { |
| 58 | + std::slice::from_raw_parts( |
| 59 | + buffer.as_ref().as_ptr() as *const u8, |
| 60 | + buffer.as_ref().len() * std::mem::size_of::<T>(), |
| 61 | + ) |
| 62 | + }; |
| 63 | + println!("\tThe size of bytes: {}", dst_slice.len()); |
| 64 | + |
| 65 | + std::fs::write(path, &dst_slice).expect("failed to write file"); |
| 66 | + |
| 67 | + Ok(()) |
| 68 | +} |
0 commit comments