A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
wasi-nn: return errors for invalid ONNX input tensors (#14532)
Zhiwei Liang6f6813d6e0b9
diff --git a/crates/test-programs/src/bin/nn_wit_invalid_input_onnx.rs b/crates/test-programs/src/bin/nn_wit_invalid_input_onnx.rsnew file mode 100644index 0000000000..21ce8d751f--- /dev/null+++ b/crates/test-programs/src/bin/nn_wit_invalid_input_onnx.rs@@ -0,0 +1,33 @@+//! Send an input tensor with the wrong byte length to the ONNX backend.+//! Check that the backend returns an error and does not trap.++use anyhow::{Context, Result, anyhow, ensure};+use std::fs;+use test_programs::nn::wit::{self, Tensor, TensorType};++/// The byte length of the `[1, 3, 224, 224]` `f32` input of MobileNet.+const INPUT_BYTES: usize = 1 * 3 * 224 * 224 * 4;++pub fn main() -> Result<()> {+ let model = fs::read("fixture/model.onnx")+ .context("the model file to be mapped to the fixture directory")?;+ let graph = wit::load(+ &[model],+ wit::GraphEncoding::Onnx,+ wit::ExecutionTarget::Cpu,+ )?;+ let context = graph+ .init_execution_context()+ .map_err(|e| anyhow!("{e:?}"))?;++ for len in [INPUT_BYTES - 1, INPUT_BYTES + 1] {+ let tensor = Tensor::new(&[1, 3, 224, 224], TensorType::Fp32, &vec![0u8; len]);+ let result = context.compute(vec![("input".to_string(), tensor)]);+ ensure!(+ result.is_err(),+ "expected an error for an input tensor of {len} bytes"+ );+ println!("[nn] rejected an input tensor of {len} bytes");+ }+ Ok(())+}diff --git a/crates/test-programs/src/bin/nn_witx_invalid_input_onnx.rs b/crates/test-programs/src/bin/nn_witx_invalid_input_onnx.rsnew file mode 100644index 0000000000..eae9155dc2--- /dev/null+++ b/crates/test-programs/src/bin/nn_witx_invalid_input_onnx.rs@@ -0,0 +1,30 @@+//! Send an input tensor with the wrong byte length to the ONNX backend.+//! Check that the backend returns an error and does not trap.++use anyhow::{Context, Result, ensure};+use std::fs;+use test_programs::nn::witx::{self, TensorType};++/// The byte length of the `[1, 3, 224, 224]` `f32` input of MobileNet.+const INPUT_BYTES: usize = 1 * 3 * 224 * 224 * 4;++pub fn main() -> Result<()> {+ let model = fs::read("fixture/model.onnx")+ .context("the model file to be mapped to the fixture directory")?;+ let graph = witx::load(+ &[&model],+ witx::GraphEncoding::Onnx,+ witx::ExecutionTarget::CPU,+ )?;+ let mut context = graph.init_execution_context()?;++ for len in [INPUT_BYTES - 1, INPUT_BYTES + 1] {+ let result = context.set_input(0, TensorType::F32, &[1, 3, 224, 224], &vec![0u8; len]);+ ensure!(+ result.is_err(),+ "expected an error for an input tensor of {len} bytes"+ );+ println!("[nn] rejected an input tensor of {len} bytes");+ }+ Ok(())+}diff --git a/crates/test-programs/src/nn.rs b/crates/test-programs/src/nn.rsindex 456a5efeaf..31ae6f5466 100644--- a/crates/test-programs/src/nn.rs+++ b/crates/test-programs/src/nn.rs@@ -22,7 +22,7 @@ pub mod wit {use self::wasi::nn::errors;use self::wasi::nn::graph::{self, Graph};pub use self::wasi::nn::graph::{ExecutionTarget, GraphEncoding}; // Used by tests.- use self::wasi::nn::tensor::{Tensor, TensorType};+ pub use self::wasi::nn::tensor::{Tensor, TensorType}; // Used by tests./// Load a wasi-nn graph from a set of bytes.pub fn load(@@ -85,8 +85,8 @@ pub mod wit {pub mod witx {use anyhow::Result;use std::time::Instant;- pub use wasi_nn::{ExecutionTarget, GraphEncoding};- use wasi_nn::{Graph, GraphBuilder, TensorType};+ pub use wasi_nn::{ExecutionTarget, GraphEncoding, TensorType};+ use wasi_nn::{Graph, GraphBuilder};/// Load a wasi-nn graph from a set of bytes.pub fn load(diff --git a/crates/wasi-nn/src/backend/onnx.rs b/crates/wasi-nn/src/backend/onnx.rsindex c7cc645d35..42274a580d 100644--- a/crates/wasi-nn/src/backend/onnx.rs+++ b/crates/wasi-nn/src/backend/onnx.rs@@ -367,6 +367,15 @@ impl Shape {tensor.ty));}+ let expected = byte_count(&tensor.dimensions, tensor.ty)?;+ if tensor.data.len() != expected {+ return Err(wasmtime::format_err!(+ "input tensor has {} bytes of data but dimensions {:?} of type {:?} need {expected} bytes",+ tensor.data.len(),+ tensor.dimensions,+ tensor.ty+ ));+ }Ok(())}}@@ -423,9 +432,10 @@ fn to_input_value(slot: &TensorSlot) -> Result<[SessionInputValue<'_>; 1], Backe})?;Ok(inputs![ort_tensor])}- _ => {- unimplemented!("{:?} not supported by ONNX", tensor.ty);- }+ _ => Err(BackendError::UnsupportedTensorType(format!(+ "{:?}",+ tensor.ty+ ))),},None => {return Err(BackendError::BackendAccess(wasmtime::format_err!(@@ -436,6 +446,27 @@ fn to_input_value(slot: &TensorSlot) -> Result<[SessionInputValue<'_>; 1], Backe}}+/// Return the number of bytes in a tensor of type `ty` with the given+/// dimensions.+fn byte_count(dimensions: &[u32], ty: TensorType) -> wasmtime::Result<usize> {+ dimensions+ .iter()+ .try_fold(bytes_per_element(ty), |count, d| {+ count.checked_mul(usize::try_from(*d).ok()?)+ })+ .ok_or_else(|| wasmtime::format_err!("tensor dimensions are too large: {dimensions:?}"))+}++/// Return the size in bytes of one element of type `ty`.+fn bytes_per_element(ty: TensorType) -> usize {+ match ty {+ TensorType::U8 => 1,+ TensorType::Fp16 | TensorType::Bf16 => 2,+ TensorType::Fp32 | TensorType::I32 => 4,+ TensorType::Fp64 | TensorType::I64 => 8,+ }+}+pub fn f32_vec_to_bytes(data: Vec<f32>) -> Vec<u8> {data.into_iter().flat_map(f32::to_le_bytes).collect()}diff --git a/crates/wasi-nn/tests/test-programs.rs b/crates/wasi-nn/tests/test-programs.rsindex 98b0339b97..3a7f0dcc7a 100644--- a/crates/wasi-nn/tests/test-programs.rs+++ b/crates/wasi-nn/tests/test-programs.rs@@ -83,6 +83,7 @@ fn check_test_program(name: &str) -> (fn() -> Result<()>, IgnoreCheck) {"nn_witx_image_classification_onnx" => {(nn_witx_image_classification_onnx, IgnoreCheck::for_onnx())}+ "nn_witx_invalid_input_onnx" => (nn_witx_invalid_input_onnx, IgnoreCheck::for_onnx()),"nn_witx_image_classification_winml_named" => (nn_witx_image_classification_winml_named,IgnoreCheck::for_winml(),@@ -103,6 +104,7 @@ fn check_test_program(name: &str) -> (fn() -> Result<()>, IgnoreCheck) {"nn_wit_image_classification_onnx" => {(nn_wit_image_classification_onnx, IgnoreCheck::for_onnx())}+ "nn_wit_invalid_input_onnx" => (nn_wit_invalid_input_onnx, IgnoreCheck::for_onnx()),"nn_wit_image_classification_winml_named" => (nn_wit_image_classification_winml_named,IgnoreCheck::for_winml(),@@ -140,6 +142,17 @@ fn nn_witx_image_classification_onnx() -> Result<()> {wasmtime::bail!("this test requires the `onnx` feature")}+#[cfg(feature = "onnx")]+fn nn_witx_invalid_input_onnx() -> Result<()> {+ check::onnx::are_artifacts_available()?;+ let backend = Backend::from(backend::onnx::OnnxBackend::default());+ exec::witx::run(NN_WITX_INVALID_INPUT_ONNX, backend, false)+}+#[cfg(not(feature = "onnx"))]+fn nn_witx_invalid_input_onnx() -> Result<()> {+ wasmtime::bail!("this test requires the `onnx` feature")+}+#[cfg(all(feature = "winml", target_os = "windows"))]fn nn_witx_image_classification_winml_named() -> Result<()> {check::winml::is_available()?;@@ -196,6 +209,17 @@ fn nn_wit_image_classification_onnx() -> Result<()> {wasmtime::bail!("this test requires the `onnx` feature")}+#[cfg(feature = "onnx")]+fn nn_wit_invalid_input_onnx() -> Result<()> {+ check::onnx::are_artifacts_available()?;+ let backend = Backend::from(backend::onnx::OnnxBackend::default());+ exec::wit::run(NN_WIT_INVALID_INPUT_ONNX_COMPONENT, backend, false)+}+#[cfg(not(feature = "onnx"))]+fn nn_wit_invalid_input_onnx() -> Result<()> {+ wasmtime::bail!("this test requires the `onnx` feature")+}+#[cfg(feature = "pytorch")]fn nn_wit_image_classification_pytorch() -> Result<()> {check::pytorch::are_artifacts_available()?;