You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ONNX Runtime Web中调用动态输入形状的ONNX模型(忽略形状检查)

ONNX Runtime Web调用动态输入形状模型的形状校验问题及解决

问题详情

模型输入形状确认

通过Python代码获取ONNX模型输入形状:

providers = ['AzureExecutionProvider', 'CPUExecutionProvider']
sess_options = onnxruntime.SessionOptions()
sess = onnxruntime.InferenceSession(model_path, sess_options, providers=providers)
input_shape = sess.get_inputs()[0].shape
print(f"Input shape: {input_shape}")

输出显示输入为动态轴:

Input shape: ['input_dynamic_axes_1', 'input_dynamic_axes_2', 'input_dynamic_axes_3', 'input_dynamic_axes_4']

Web端运行代码及报错

使用JavaScript在ONNX Runtime Web中运行模型的代码:

const session = await ort.InferenceSession.create(model, {
  executionProviders: ["webgpu", "webgl"],
});
const feeds = {};
const inputNames = session.inputNames;
feeds[inputNames[0]] = inputTensor;
const results = await session.run(feeds);
const outputData = results[session.outputNames[0]].data;
return outputData;

运行时触发形状校验错误:

Uncaught (in promise) Error: input tensor[0] check failed: expected shape '[,,,]' but got [1,3,800,400]
  validateInputTensorDims   
  normalizeAndValidateInputs    
  (anonymous function)  
  event 
  run   
  run   
  run   
  runInference  

原因分析

模型输入为动态形状时,ONNX Runtime Web会将预期维度设为[null, null, null, null],而实际传入的张量形状[1,3,800,400]在默认校验逻辑下不匹配,触发报错,核心校验代码如下:

private validateInputTensorDims(
    graphInputDims: Array<readonly number[]>, givenInputs: Tensor[], noneDimSupported: boolean) {
  for (let i = 0; i < givenInputs.length; i++) {
    const expectedDims = graphInputDims[i];
    const actualDims = givenInputs[i].dims;
    if (!this.compareTensorDims(expectedDims, actualDims, noneDimSupported)) {
      throw new Error(`input tensor[${i}] check failed: expected shape '[${expectedDims.join(',')}]' but got [${
          actualDims.join(',')}]`);
    }
  }
}

解决方法

1. 直接禁用输入校验

在创建InferenceSession时添加disableInputValidation: true配置,关闭所有输入形状校验:

const session = await ort.InferenceSession.create(model, {
  executionProviders: ["webgpu", "webgl"],
  disableInputValidation: true
});

2. 显式覆盖输入形状

如果不想完全关闭校验,可以在创建Session时指定输入形状,让模型适配实际传入的张量维度:

const session = await ort.InferenceSession.create(model, {
  executionProviders: ["webgpu", "webgl"],
  inputShapeOverrides: {
    // 替换为你的实际输入形状
    [session.inputNames[0]]: [1, 3, 800, 400]
  }
});

注:不同版本的ONNX Runtime Web参数名称可能略有差异,若inputShapeOverrides不生效,可查看对应版本API文档中的类似配置项。

内容的提问来源于stack exchange,提问作者chikadance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:12:52