diff --git a/onnxruntime/core/providers/webnn/builders/impl/conv_op_builder.cc b/onnxruntime/core/providers/webnn/builders/impl/conv_op_builder.cc index af3293dd3d92c..b37340624f850 100644 --- a/onnxruntime/core/providers/webnn/builders/impl/conv_op_builder.cc +++ b/onnxruntime/core/providers/webnn/builders/impl/conv_op_builder.cc @@ -251,8 +251,18 @@ Status ConvOpBuilder::AddToModelBuilderImpl(ModelBuilder& model_builder, const N std::vector input_shape; ORT_RETURN_IF_NOT(GetShape(*input_defs[0], input_shape, logger), "Cannot get shape"); for (size_t i = 0; i < 2; i++) { - total_padding[i] = strides[i] * (narrow(input_shape[i + 1]) - 1) + - output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]; + // Get the dimensions of H and W. + // For NHWC layout, the dimensions of H and W correspond to index 1 and 2. + // For NCHW layout, the dimensions of H and W correspond to index 2 and 3. + if (model_builder.GetPreferredLayout() == DataLayout::NHWC) { + total_padding[i] = strides[i] * (narrow(input_shape[i + 1]) - 1) + + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]; + } else { + ORT_RETURN_IF_NOT(model_builder.GetPreferredLayout() == DataLayout::NCHW, + "WebNN GPU backend preferred layout should be NCHW."); + total_padding[i] = strides[i] * (narrow(input_shape[i + 2]) - 1) + + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]; + } } pads[0] = total_padding[0] - (total_padding[0] / 2); pads[1] = total_padding[0] / 2;