Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[ONNX] Prevent division-by-zero in MatMulNBits conversion (#34068)

Maxim Vafin387140fec396
diff --git a/src/frontends/onnx/frontend/src/op/com.microsoft/matmulnbits.cpp b/src/frontends/onnx/frontend/src/op/com.microsoft/matmulnbits.cpp
index a0760a04b09..22b10612099 100644
--- a/src/frontends/onnx/frontend/src/op/com.microsoft/matmulnbits.cpp
+++ b/src/frontends/onnx/frontend/src/op/com.microsoft/matmulnbits.cpp
@@ -47,7 +47,19 @@ ov::OutputVector matmulnbits(const ov::frontend::onnx::Node& node) {
"bits",
4); // required, in docs: number of bits used for weight quantization (default 4)
- const uint64_t n_blocks_per_col = (K + block_size - 1) / block_size;
+ // Validate attributes before any arithmetic to prevent division-by-zero and signed overflow
+ CHECK_VALID_NODE(node, K > 0, "Wrong K attribute value: ", K);
+ CHECK_VALID_NODE(node, N > 0, "Wrong N attribute value: ", N);
+ CHECK_VALID_NODE(node,
+ block_size >= 16 && (block_size & (block_size - 1)) == 0,
+ "Wrong block size, should be >=16 and be a power of 2, got: ",
+ block_size);
+ CHECK_VALID_NODE(node, bits == 2 || bits == 4 || bits == 8, "Unsupported bits value: ", bits);
+ CHECK_VALID_NODE(node, accuracy_level >= 0 && accuracy_level <= 4, "Unsupported accuracy level: ", accuracy_level);
+
+ const auto u_K = static_cast<uint64_t>(K);
+ const auto u_block_size = static_cast<uint64_t>(block_size);
+ const uint64_t n_blocks_per_col = (u_K + u_block_size - 1) / u_block_size;
const auto blob_size = (block_size * bits + 7) / 8;
const uint64_t expected_b_size = N * n_blocks_per_col * blob_size;
@@ -83,12 +95,6 @@ ov::OutputVector matmulnbits(const ov::frontend::onnx::Node& node) {
"Unsupported input B type, accepted U8 or I32, got: ",
b_quantized.get_element_type());
- CHECK_VALID_NODE(node,
- block_size >= 16 && (block_size & (block_size - 1)) == 0,
- "Wrong block size, should be >=16 and be a power of 2, got: ",
- block_size);
- CHECK_VALID_NODE(node, accuracy_level >= 0 && accuracy_level <= 4, "Unsupported accuracy level: ", accuracy_level);
-
if (common::is_input_valid(node, 3)) {
zero_points = inputs[3];
CHECK_VALID_NODE(node,