// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/common/span_utils.h" #include "core/framework/tensor.h" #include "core/session/inference_session.h" #include "test/common/tensor_op_test_utils.h" #include "test/unittest_util/framework_test_utils.h" #include "test/providers/provider_test_utils.h" #include "test/unittest_util/graph_transform_test_builder.h" #include "test/util/include/default_providers.h" #include "core/util/qmath.h" #include "core/mlas/lib/mlasi.h" // for MLAS_CPUIDINFO #include #include #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace std; namespace onnxruntime { namespace test { template static void CalculateDynamicQuantizeMatMul(const int64_t M, const int64_t N, const int64_t K, const std::vector& A_data, const std::vector& B_data, std::vector& B_scale, std::vector& B_zero_point, const std::vector& Bias, std::vector& Y_data, bool per_column, bool has_zp, bool has_bias) { // DynamicQuantize Matrix A const uint32_t num_elements = static_cast(M * K); std::vector QuantA_data(num_elements); std::vector A_scale; std::vector A_zero_point; // Get max and min float min = std::numeric_limits::max(); float max = std::numeric_limits::lowest(); float qmax = static_cast(std::numeric_limits::max()); float qmin = static_cast(std::numeric_limits::lowest()); for (uint32_t i = 0; i < num_elements; ++i) { max = std::max(A_data[i], max); min = std::min(A_data[i], min); } // Adjust the maximum and minimum to include zero max = std::max(max, 0.0f); min = std::min(min, 0.0f); float scale = static_cast(max - min) / (qmax - qmin); T zeroPoint = static_cast(std::round(std::clamp(qmin - min / scale, qmin, qmax))); A_scale.push_back(scale); A_zero_point.push_back(zeroPoint); // Matrix Multiplication for (uint32_t i = 0; i < num_elements; ++i) { QuantA_data[i] = static_cast(std::round((A_data[i] / scale) + zeroPoint)); } if (!per_column) { B_zero_point.resize(N, B_zero_point[0]); B_scale.resize(N, B_scale[0]); } for (int64_t m = 0; m < M; m++) { for (int64_t n = 0; n < N; n++) { float sum = 0.0f; for (int64_t k = 0; k < K; k++) { float A_dequantized = (static_cast(QuantA_data[m * K + k]) - static_cast(A_zero_point[0])) * A_scale[0]; float B_dequantized = has_zp ? (static_cast(B_data[k * N + n]) - static_cast(B_zero_point[n])) * B_scale[n] : B_data[k * N + n] * B_scale[n]; sum += A_dequantized * B_dequantized; } if (has_bias) { sum += Bias[n]; } Y_data[m * N + n] = sum; } } } struct TestDynamicQuantizeMatMulOptions { bool is_matrix_b_constant = true; bool per_column = false; bool is_scale_constant = false; bool has_zp = true; bool is_zp_constant = false; bool is_zp_zero = false; bool has_bias = false; bool is_bias_constant = false; bool empty_input = false; }; template void TestDynamicQuantizeMatMul(const TestDynamicQuantizeMatMulOptions& opts) { static_assert(std::is_same_v || std::is_same_v); SCOPED_TRACE(MakeString( "b data type:", (std::is_same_v ? "uint8" : "int8"), ", is_matrix_b_constant:", opts.is_matrix_b_constant, ", per_column:", opts.per_column, ", is_scale_constant:", opts.is_scale_constant, ", has_zp:", opts.has_zp, ", is_zp_constant:", opts.is_zp_constant, ", is_zp_zero:", opts.is_zp_zero, ", has_bias:", opts.has_bias, ", is_bias_constant:", opts.is_bias_constant, ", empty_input:", opts.empty_input)); // create rand inputs RandomValueGenerator random{1668426375}; int64_t M = opts.empty_input ? 1 : 4; int64_t N = 128; int64_t K = 128; std::vector A_dims{opts.empty_input ? 0 : M, K}; std::vector B_dims{K, N}; std::vector Y_dims{opts.empty_input ? 0 : M, K}; std::vector A_data = random.Uniform(A_dims, -1.0f, 1.0f); std::vector B_data; std::vector tmp_B_data = random.Uniform(B_dims, (std::is_same_v) ? std::numeric_limits::lowest() / 2 : std::numeric_limits::lowest(), std::numeric_limits::max() / 2); std::transform(tmp_B_data.begin(), tmp_B_data.end(), std::back_inserter(B_data), [](int32_t v) -> T { return static_cast(v); }); int64_t b_scale_zp_size = opts.per_column ? B_dims.back() : 1; std::vector B_scale = random.Uniform(AsSpan({b_scale_zp_size}), -0.1f, 0.1f); std::vector B_zero_point(b_scale_zp_size); if (!opts.is_zp_zero) { std::for_each(B_zero_point.begin(), B_zero_point.end(), [&random](T& zp) { zp = static_cast(random.Uniform(std::array{1}, std::numeric_limits::min(), std::numeric_limits::max())[0]); }); } std::vector Bias = random.Uniform(AsSpan({B_dims.back()}), -0.1f, 0.1f); OpTester test("DynamicQuantizeMatMul", 1, onnxruntime::kMSDomain); test.AddInput("A", A_dims, A_data); test.AddInput("B", B_dims, B_data, opts.is_matrix_b_constant); test.AddInput("b_scale", {b_scale_zp_size}, B_scale, opts.is_scale_constant); if (opts.has_zp) { test.AddInput("b_zero_point", {b_scale_zp_size}, B_zero_point, opts.is_zp_constant); } else { test.AddOptionalInputEdge(); } if (opts.has_bias) { test.AddInput("bias", {B_dims.back()}, Bias, opts.is_bias_constant); } else { test.AddOptionalInputEdge(); } std::vector Y_data(M * N); CalculateDynamicQuantizeMatMul(M, N, K, A_data, B_data, B_scale, B_zero_point, Bias, Y_data, opts.per_column, opts.has_zp, opts.has_bias); test.AddOutput("Y", Y_dims, Y_data); test.SetOutputRelErr("Y", 0.02f); test.Run(OpTester::ExpectResult::kExpectSuccess, "", {kOpenVINOExecutionProvider}); } template void TestDynamicQuantizeMatMul(bool is_matrix_b_constant, bool per_column = false, bool has_zp = true, bool has_bias = false, bool empty_input = false) { TestDynamicQuantizeMatMulOptions opts{}; opts.is_matrix_b_constant = is_matrix_b_constant; opts.per_column = per_column; opts.has_zp = has_zp; opts.has_bias = has_bias; opts.empty_input = empty_input; TestDynamicQuantizeMatMul(opts); } template void RunDynamicQuantizeMatMulTest() { for (bool is_matrix_b_constant : {false, true}) { for (bool per_column : {false, true}) { for (bool has_zp : {false, true}) { for (bool has_bias : {false, true}) { TestDynamicQuantizeMatMul(is_matrix_b_constant, per_column, has_zp, has_bias); } } } } } TEST(DynamicQuantizeMatMul, Int8) { RunDynamicQuantizeMatMulTest(); } TEST(DynamicQuantizeMatMul, UInt8) { RunDynamicQuantizeMatMulTest(); } TEST(DynamicQuantizeMatMul, WithConstantBInputs) { TestDynamicQuantizeMatMulOptions base_opts{}; base_opts.is_matrix_b_constant = true; base_opts.is_scale_constant = true; base_opts.is_zp_constant = true; { // no zp auto opts = base_opts; opts.has_zp = false; TestDynamicQuantizeMatMul(opts); TestDynamicQuantizeMatMul(opts); } { // zp that is zero (symmetric quantization) auto opts = base_opts; opts.has_zp = true; opts.is_zp_zero = true; TestDynamicQuantizeMatMul(opts); TestDynamicQuantizeMatMul(opts); } { // zp that is non-zero auto opts = base_opts; opts.has_zp = true; opts.is_zp_zero = false; TestDynamicQuantizeMatMul(opts); TestDynamicQuantizeMatMul(opts); } } TEST(DynamicQuantizeMatMul, UInt8_test_with_empty_input) { std::vector A_dims{0, 2}; std::vector B_dims{2, 2}; std::vector Y_dims{0, 2}; OpTester test("DynamicQuantizeMatMul", 1, onnxruntime::kMSDomain); test.AddInput("T1", A_dims, {}); test.AddInput("T2", B_dims, {1, 6, 0, 8}); test.AddInput("b_scale", {1}, {1.0f}); test.AddInput("b_zero_point", {1}, {0}); test.AddOptionalInputEdge(); test.AddOutput("Y", {0, 2}, {}); test.Run(); } #if defined(USE_KLEIDIAI) static bool HasArmSME() { return (MLAS_CPUIDINFO::GetCPUIDInfo().HasArm_SME() || MLAS_CPUIDINFO::GetCPUIDInfo().HasArm_SME2()); } // Helper to build a tiny 2x3×4 case we reuse. struct KleidiDynMatMulData { static constexpr int64_t M = 2; static constexpr int64_t K = 4; static constexpr int64_t N = 3; std::vector a = { 1.f, 2.f, 3.f, 4.f, -1.f, -2.f, -3.f, -4.f}; std::vector b = { 1, 0, -1, 2, -1, 0, 0, 1, 2, -2, 0, 1}; std::vector b_scale = {0.5f, 0.25f, 0.125f}; std::vector b_zp = {0, 0, 0}; std::vector Reference(float bias0, float bias1, float bias2) const { std::vector out(M * N, 0.f); for (int64_t m = 0; m < M; ++m) { for (int64_t n = 0; n < N; ++n) { float sum = 0.f; for (int64_t k = 0; k < K; ++k) { const float b_val = (static_cast(b[k * N + n]) - b_zp[n]) * b_scale[n]; sum += a[m * K + k] * b_val; } const float bias = (n == 0 ? bias0 : n == 1 ? bias1 : bias2); out[m * N + n] = sum + bias; } } return out; } std::vector Reference3D(float bias0, float bias1, float bias2, int64_t leading = 1) const { auto base = Reference(bias0, bias1, bias2); std::vector out; out.reserve(leading * M * N); for (int64_t i = 0; i < leading; ++i) { out.insert(out.end(), base.begin(), base.end()); } return out; } }; // 1. Bias provided as initializer -> Kleidi packs bias and skips runtime add. TEST(DynamicQuantizeMatMul, KleidiBiasInitializer) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; const std::vector bias = {0.25f, -0.5f, 1.125f}; auto expected = data.Reference(bias[0], bias[1], bias[2]); OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true /*initializer*/); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp, true /*initializer*/); test.AddInput("bias", {data.N}, bias, true /*initializer*/); test.AddOutput("Y", {data.M, data.N}, expected); test.SetOutputAbsErr("Y", 0.03f); test.Run(); } // 2. Bias as runtime tensor -> exercise deferred bias add branch. TEST(DynamicQuantizeMatMul, KleidiBiasRuntime) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; const std::vector bias = {1.0f, 0.0f, -0.75f}; auto expected = data.Reference(bias[0], bias[1], bias[2]); OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp, true); test.AddInput("bias", {data.N}, bias, false /*runtime*/); test.AddOutput("Y", {data.M, data.N}, expected); test.SetOutputAbsErr("Y", 0.03f); test.Run(); } // 3. Non-zero zero-points -> Kleidi pack rejected, falls back to generic path. TEST(DynamicQuantizeMatMul, KleidiRejectsNonZeroZeroPoint) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; data.b_zp = {1, 0, 0}; // violates symmetry, Kleidi path disabled auto expected = data.Reference(0.f, 0.f, 0.f); // still compare to reference OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp); test.AddOptionalInputEdge(); // no bias test.AddOutput("Y", {data.M, data.N}, expected); test.SetOutputAbsErr("Y", 0.03f); test.Run(); // succeeds, but exercises the “fallback” branch } // 4. Invalid scales -> Kleidi pack rejected. TEST(DynamicQuantizeMatMul, KleidiRejectsInvalidScale) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; data.b_scale[1] = 0.f; // invalid auto expected = data.Reference(0.f, 0.f, 0.f); OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp, true); test.AddOptionalInputEdge(); test.AddOutput("Y", {data.M, data.N}, expected); test.SetOutputAbsErr("Y", 0.03f); test.Run(); } // 5. Unsupported B-shape (e.g., 3D) -> Kleidi pack rejected. TEST(DynamicQuantizeMatMul, KleidiRejectsUnsupportedBShape) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; std::vector b_3d; b_3d.reserve(2 * data.b.size()); b_3d.insert(b_3d.end(), data.b.begin(), data.b.end()); b_3d.insert(b_3d.end(), data.b.begin(), data.b.end()); std::vector b_shape = {2, data.K, data.N}; std::vector b_scale_3d; b_scale_3d.reserve(2 * data.N); b_scale_3d.insert(b_scale_3d.end(), data.b_scale.begin(), data.b_scale.end()); b_scale_3d.insert(b_scale_3d.end(), data.b_scale.begin(), data.b_scale.end()); std::vector b_zp_3d; b_zp_3d.reserve(2 * data.N); b_zp_3d.insert(b_zp_3d.end(), data.b_zp.begin(), data.b_zp.end()); b_zp_3d.insert(b_zp_3d.end(), data.b_zp.begin(), data.b_zp.end()); auto expected = data.Reference3D(0.f, 0.f, 0.f, /*leading=*/2); OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", b_shape, b_3d, true); test.AddInput("b_scale", {2, 1, data.N}, b_scale_3d, true); test.AddInput("b_zero_point", {2, 1, data.N}, b_zp_3d, true); test.AddOptionalInputEdge(); test.AddOutput("Y", {2, data.M, data.N}, expected); test.SetOutputAbsErr("Y", 0.03f); test.Run(); } // 6. Mismatched bias (runtime tensor) -> must be rejected at compute time. TEST(DynamicQuantizeMatMul, KleidiBiasRuntimeShapeMismatch) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; // Bias has only 1 element but N=3 — this must be rejected. const std::vector bad_bias = {1.0f}; OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true /*initializer*/); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp, true); test.AddInput("bias", {1}, bad_bias, false /*runtime*/); test.AddOutput("Y", {data.M, data.N}, std::vector(data.M * data.N, 0.0f)); test.ConfigEp(DefaultCpuExecutionProvider()) .Config(OpTester::ExpectResult::kExpectFailure, "bias tensor's element count must equal B's last dimension") .RunWithConfig(); } // 7. Mismatched bias (constant initializer) -> KleidiAI pre-pack rejects -> falls back to ComputeCommon // -> rejected TEST(DynamicQuantizeMatMul, KleidiBiasInitializerShapeMismatch) { if (!HasArmSME()) GTEST_SKIP(); KleidiDynMatMulData data; // Bias has only 1 element but N=3 — this must be rejected. const std::vector bad_bias = {1.0f}; OpTester test("DynamicQuantizeMatMul", 1, kMSDomain); test.AddInput("A", {data.M, data.K}, data.a); test.AddInput("B", {data.K, data.N}, data.b, true /*initializer*/); test.AddInput("b_scale", {data.N}, data.b_scale, true); test.AddInput("b_zero_point", {data.N}, data.b_zp, true); test.AddInput("bias", {1}, bad_bias, true /*initializer*/); test.AddOutput("Y", {data.M, data.N}, std::vector(data.M * data.N, 0.0f)); test.ConfigEp(DefaultCpuExecutionProvider()) .Config(OpTester::ExpectResult::kExpectFailure, "bias tensor's element count must equal B's last dimension") .RunWithConfig(); } #endif // USE_KLEIDIAI TEST(DynamicQuantizeMatMul, B_PerColumn_ND) { auto test_case = [&](const std::vector& input_shape, const std::vector& weights_shape, const std::vector& b_scale_zp_shape) { auto build_test_case = [&](ModelTestBuilder& builder) { auto* input_arg = builder.MakeInput(input_shape, -1.0f, 1.0f); auto* output_arg = builder.MakeOutput(); auto* weight = builder.MakeInitializer(weights_shape, std::numeric_limits::min() / 2, std::numeric_limits::max() / 2); // add DynamicQuantizeLinear auto* dql_output = builder.MakeIntermediate(); auto* dql_scale = builder.MakeIntermediate(); auto* dql_zp = builder.MakeIntermediate(); builder.AddNode("DynamicQuantizeLinear", {input_arg}, {dql_output, dql_scale, dql_zp}); // add MatMulInteger auto* matmul_integer_output = builder.MakeIntermediate(); auto* B_zp_arg = builder.MakeInput(b_scale_zp_shape, std::numeric_limits::min() / 2, std::numeric_limits::max() / 2); builder.AddNode("MatMulInteger", {dql_output, weight, dql_zp, B_zp_arg}, {matmul_integer_output}); // add Cast auto* cast_output = builder.MakeIntermediate(); Node& cast_node = builder.AddNode("Cast", {matmul_integer_output}, {cast_output}); cast_node.AddAttribute("to", (int64_t)1); // add Mul1 auto* B_scale_arg = builder.MakeInput(b_scale_zp_shape, -0.1f, 0.f); auto* mul1_output = builder.MakeIntermediate(); builder.AddNode("Mul", {dql_scale, B_scale_arg}, {mul1_output}); // add Mul2 builder.AddNode("Mul", {mul1_output, cast_output}, {output_arg}); }; auto check_mp_reshape_graph = [&](InferenceSessionWrapper& session) { auto op_to_count = CountOpsInGraph(session.GetGraph()); EXPECT_EQ(op_to_count["com.microsoft.DynamicQuantizeMatMul"], 1); }; TransformerTester(build_test_case, check_mp_reshape_graph, TransformerLevel::Level1, TransformerLevel::Level2, 12 /*opset_version*/, 1e-5 /*per_sample_tolerance*/, 1e-5 /*relative_per_sample_tolerance*/); }; // Scale Scalar test_case({5, 4, 3}, {3, 4}, {1}); // 2D B per-column test_case({5, 4, 3}, {3, 4}, {4}); test_case({5, 4, 3}, {3, 4}, {1, 4}); // ND B per-column test_case({15, 14, 13}, {15, 13, 27}, {15, 1, 27}); } // Test that a bias tensor with length mismatched to B's last dimension is rejected. // This reproduces a heap OOB read when bias is shorter than N. TEST(DynamicQuantizeMatMul, BiasShapeMismatch) { constexpr int64_t M = 2; constexpr int64_t K = 4; constexpr int64_t N = 8; std::vector A_data(M * K, 1.0f); std::vector B_data(K * N, 128); std::vector B_scale = {0.5f}; std::vector B_zero_point = {128}; // Bias has only 1 element but N=8 — this must be rejected. std::vector bad_bias = {1.0f}; OpTester test("DynamicQuantizeMatMul", 1, onnxruntime::kMSDomain); test.AddInput("A", {M, K}, A_data); test.AddInput("B", {K, N}, B_data); test.AddInput("b_scale", {1}, B_scale); test.AddInput("b_zero_point", {1}, B_zero_point); test.AddInput("bias", {1}, bad_bias); test.AddOutput("Y", {M, N}, std::vector(M * N, 0.0f)); test.ConfigEp(DefaultCpuExecutionProvider()) .Config(OpTester::ExpectResult::kExpectFailure, "bias tensor's element count must equal B's last dimension") .RunWithConfig(); } } // namespace test } // namespace onnxruntime