// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef ORT_MINIMAL_BUILD #include #include #include "gtest/gtest.h" #include "gmock/gmock.h" #include "core/common/narrow.h" #include "core/common/span_utils.h" #include "core/framework/tensor.h" #include "core/graph/onnx_protobuf.h" #include "core/mlas/inc/mlas_qnbit.h" #include "core/mlas/inc/mlas_q4.h" #include "core/mlas/inc/mlas.h" #include "core/session/inference_session.h" #include "test/common/cuda_op_test_utils.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/util/include/compare_ortvalue.h" #include "test/unittest_util/graph_transform_test_builder.h" #include "test/util/include/default_providers.h" #include "test/util/include/inference_session_wrapper.h" #include "test/util/include/scoped_env_vars.h" #include "test/contrib_ops/matmul_nbits_prepack_sharing_test_util.h" #include "core/session/onnxruntime_cxx_api.h" #include "core/session/ort_env.h" #include "core/util/qmath.h" #include "core/providers/webgpu/webgpu_provider_options.h" #include "core/framework/prepacked_weights_container.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "test/util/include/test/test_environment.h" extern std::unique_ptr ort_env; namespace onnxruntime { namespace test { namespace { constexpr int QBits = 4; void QuantizeDequantize(std::vector& raw_vals, std::vector& quant_vals, std::vector& scales, std::vector* zp, int32_t N, int32_t K, int32_t block_size) { auto& ortenv = **ort_env.get(); onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool(); MlasQuantizeBlockwise( quant_vals.data(), scales.data(), zp != nullptr ? zp->data() : nullptr, raw_vals.data(), block_size, true, K, N, N, tp); // Note that raw_vals is NxK after dequant MlasDequantizeBlockwise( raw_vals.data(), // dequantized output quant_vals.data(), // quantized input scales.data(), // quantization scales zp != nullptr ? zp->data() : nullptr, // quantization zero points block_size, // quantization block size true, // columnwise quantization K, // number of rows N, // number of columns tp); } struct TestOptions { int64_t batch_count{1}; int64_t M{1}; int64_t N{1}; int64_t K{1}; int64_t block_size{32}; int64_t accuracy_level{0}; bool disable_cpu_ep_fallback{false}; bool force_fp32{false}; bool use_lut_gemm{false}; bool has_zero_point{false}; bool zp_is_4bit{true}; bool scales_are_initializers{true}; bool zero_points_are_initializers{true}; bool has_g_idx{false}; bool has_bias{false}; bool legacy_shape{false}; // for backward compatibility // When set, RunTest validates cross-session sharing of the pre-packed weights instead of doing a // single run. The model is run in two sessions that use the same pre-packed weights container. std::optional prepack_sharing_mode{}; std::optional weight_prepacked{}; std::optional expected_failure{}; std::optional output_abs_error{}; std::optional output_rel_error{}; }; [[maybe_unused]] std::ostream& operator<<(std::ostream& os, const TestOptions& opts) { return os << "batch_count:" << opts.batch_count << ", M:" << opts.M << ", N:" << opts.N << ", K:" << opts.K << ", block_size:" << opts.block_size << ", accuracy_level:" << opts.accuracy_level << ", has_zero_point:" << opts.has_zero_point << ", zp_is_4bit:" << opts.zp_is_4bit << ", scales_are_initializers:" << opts.scales_are_initializers << ", zero_points_are_initializers:" << opts.zero_points_are_initializers << ", has_g_idx:" << opts.has_g_idx << ", has_bias:" << opts.has_bias; } template void RunTest(const TestOptions& opts, std::vector>&& explicit_eps = {}) { SCOPED_TRACE(opts); static_assert(std::is_same_v || std::is_same_v || std::is_same_v, "unexpected type for T1"); #ifdef USE_CUDA if (opts.accuracy_level != 0 && !opts.legacy_shape) { return; // CUDA EP does not handle accuracy level, so only test one level to avoid unnecessary tests. } #endif const bool zp_is_4bit = opts.zp_is_4bit || opts.has_g_idx; const int64_t batch_count = opts.batch_count; const int64_t M = opts.M; const int64_t K = opts.K; const int64_t N = opts.N; RandomValueGenerator random{1234}; std::vector input0_vals(random.Gaussian(AsSpan({batch_count, M, K}), 0.0f, 0.25f)); std::vector input1_f_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f)); int64_t k_blocks = (K + opts.block_size - 1) / opts.block_size; int64_t blob_size = (opts.block_size * QBits + 7) / 8; size_t q_scale_size = static_cast(N * k_blocks); size_t q_data_size_in_bytes = static_cast(N * k_blocks * blob_size); // packed as UInt4x2 const int64_t zero_point_blob_size = (k_blocks * QBits + 7) / 8; size_t q_zp_size_in_bytes = static_cast(N * zero_point_blob_size); // packed as UInt4x2 std::vector input1_vals(q_data_size_in_bytes); std::vector scales(q_scale_size); std::vector zp(q_zp_size_in_bytes); QuantizeDequantize(input1_f_vals, input1_vals, scales, opts.has_zero_point ? &zp : nullptr, static_cast(N), static_cast(K), static_cast(opts.block_size)); const std::vector bias_shape = {N}; const auto bias = [&]() -> std::optional> { if (opts.has_bias) { return random.Uniform(bias_shape, 1.0f, 5.0f); } return std::nullopt; }(); std::vector expected_vals(batch_count * M * N); for (int64_t b = 0; b < batch_count; b++) { 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++) { sum += input0_vals[b * M * K + m * K + k] * input1_f_vals[n * K + k]; } expected_vals[b * M * N + m * N + n] = sum + (bias.has_value() ? (*bias)[n] : 0.0f); } } } OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", opts.block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", opts.accuracy_level); if (opts.weight_prepacked.has_value()) { test.AddAttribute("weight_prepacked", *opts.weight_prepacked); } if constexpr (std::is_same_v) { test.AddInput("A", {batch_count, M, K}, input0_vals, false); } else if constexpr (std::is_same::value) { test.AddInput("A", {batch_count, M, K}, FloatsToMLFloat16s(input0_vals), false); } else if constexpr (std::is_same::value) { test.AddInput("A", {batch_count, M, K}, FloatsToBFloat16s(input0_vals), false); } test.AddInput("B", {N, k_blocks, blob_size}, input1_vals, true); auto scales_shape = opts.legacy_shape ? std::vector{N * k_blocks} : std::vector{N, k_blocks}; if constexpr (std::is_same::value) { test.AddInput("scales", scales_shape, scales, opts.scales_are_initializers); } else if constexpr (std::is_same::value) { test.AddInput("scales", scales_shape, FloatsToMLFloat16s(scales), opts.scales_are_initializers); } else if constexpr (std::is_same::value) { test.AddInput("scales", scales_shape, FloatsToBFloat16s(scales), opts.scales_are_initializers); } if (opts.has_zero_point) { if (zp_is_4bit) { auto zp_shape = opts.legacy_shape ? std::vector{N * zero_point_blob_size} : std::vector{N, zero_point_blob_size}; test.AddInput("zero_points", zp_shape, zp, opts.zero_points_are_initializers); } else { std::vector zp_f; zp_f.reserve(q_zp_size_in_bytes * 2); for (size_t i = 0; i < zp.size(); i++) { zp_f.push_back(static_cast(zp[i] & 0xf)); zp_f.push_back(static_cast((zp[i] >> 4) & 0xf)); } size_t ind = zp_f.size() - 1; while (zp_f.size() != q_scale_size) { zp_f.erase(zp_f.begin() + ind); ind -= q_scale_size / N + 1; } if constexpr (std::is_same_v) { test.AddInput("zero_points", scales_shape, zp_f, opts.zero_points_are_initializers); } else if constexpr (std::is_same_v) { test.AddInput("zero_points", scales_shape, FloatsToMLFloat16s(zp_f), opts.zero_points_are_initializers); } else if constexpr (std::is_same_v) { test.AddInput("zero_points", scales_shape, FloatsToBFloat16s(zp_f), opts.zero_points_are_initializers); } } } else { if (zp_is_4bit) { test.AddOptionalInputEdge(); } else { test.AddOptionalInputEdge(); } } if (opts.has_g_idx) { auto ceildiv = [](int64_t a, int64_t b) { return (a + b - 1) / b; }; int K_pad = narrow(ceildiv(K, opts.block_size) * opts.block_size); std::vector g_idx(K_pad); for (int64_t i = 0; i < K_pad; i++) { g_idx[i] = narrow(i / opts.block_size); } test.AddInput("g_idx", {static_cast(K_pad)}, g_idx, true); } else { test.AddOptionalInputEdge(); } if (bias.has_value()) { if constexpr (std::is_same::value) { test.AddInput("bias", bias_shape, *bias, true); } else if constexpr (std::is_same::value) { test.AddInput("bias", bias_shape, FloatsToMLFloat16s(*bias), true); } else if constexpr (std::is_same::value) { test.AddInput("bias", bias_shape, FloatsToBFloat16s(*bias), true); } } else { test.AddOptionalInputEdge(); } if constexpr (std::is_same::value) { test.AddOutput("Y", {batch_count, M, N}, expected_vals); } else if constexpr (std::is_same::value) { test.AddOutput("Y", {batch_count, M, N}, FloatsToMLFloat16s(expected_vals)); } else if constexpr (std::is_same::value) { test.AddOutput("Y", {batch_count, M, N}, FloatsToBFloat16s(expected_vals)); } if (opts.output_abs_error.has_value()) { test.SetOutputAbsErr("Y", *opts.output_abs_error); } if (opts.output_rel_error.has_value()) { test.SetOutputRelErr("Y", *opts.output_rel_error); } if (opts.prepack_sharing_mode.has_value()) { // Pre-packed weight sharing is a CPU-EP-only feature; the helper runs the model on the CPU EP // in two sessions and validates the sharing counters. CheckSharedPrepackedWeights(test, *opts.prepack_sharing_mode, {N, k_blocks, blob_size}, input1_vals, opts.force_fp32); return; } if (!explicit_eps.empty()) { test.ConfigEps(std::move(explicit_eps)); } else if (opts.force_fp32 || opts.use_lut_gemm) { test.ConfigEp(DefaultCpuExecutionProvider()); } if (opts.disable_cpu_ep_fallback || opts.force_fp32 || opts.use_lut_gemm) { SessionOptions session_options; session_options.use_per_session_threads = false; if (opts.disable_cpu_ep_fallback) { ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1")); } if (opts.force_fp32) { ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsMlasQNBitForceFp32, "1")); } if (opts.use_lut_gemm) { ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1")); } test.Config(session_options); } if (opts.expected_failure.has_value()) { test.Config(OpTester::ExpectResult::kExpectFailure, *opts.expected_failure); test.RunWithConfig(); return; } test.RunWithConfig(); } } // namespace template void TestMatMulNBitsTyped(std::optional abs_error = std::nullopt, std::optional rel_error = std::nullopt) { TestOptions base_opts{}; base_opts.M = M, base_opts.N = N, base_opts.K = K; base_opts.block_size = block_size; base_opts.accuracy_level = accuracy_level; base_opts.legacy_shape = legacy_shape; if (abs_error.has_value()) { base_opts.output_abs_error = *abs_error; } else if (base_opts.accuracy_level == 4) { base_opts.output_abs_error = 0.1f; } else if constexpr (std::is_same::value) { // The fp16 provider paths compare against a float reference while native kernels may accumulate // in fp16 (for example native HGEMM on SME; see PR #28786), so allow slightly wider drift. #if defined(USE_WEBGPU) // WebGPU's fp16 path has additional provider-specific rounding drift for these quantized matmul cases. base_opts.output_abs_error = 0.1f; #else base_opts.output_abs_error = 0.065f; #endif } else { base_opts.output_abs_error = 0.05f; } if (rel_error.has_value()) { base_opts.output_rel_error = *rel_error; } else if (base_opts.accuracy_level == 4) { base_opts.output_rel_error = 0.02f; } else if constexpr (std::is_same::value) { base_opts.output_rel_error = 0.02f; } else { base_opts.output_rel_error = 0.02f; } { TestOptions opts = base_opts; RunTest(opts); } { TestOptions opts = base_opts; opts.has_zero_point = true; RunTest(opts); } #if !defined(USE_DML) && !defined(USE_WEBGPU) { TestOptions opts = base_opts; opts.has_g_idx = true; RunTest(opts); } { TestOptions opts = base_opts; opts.has_g_idx = true; opts.has_bias = true; if constexpr (std::is_same::value) { if (opts.accuracy_level == 0 || opts.accuracy_level == 1) { // CI failure (not able to repro on either local machines): // M:100, N:288, K:1234, block_size:16, accuracy_level:0, has_zero_point:0, zp_is_4bit:1, has_g_idx:1, has_bias:1 // The difference between cur_expected[i] and cur_actual[i] is 1.0401010513305664e-05, which exceeds tolerance, // tolerance evaluates to 1.006456386676291e-05. opts.output_abs_error = 0.0001f; } } // only enabled for CPU EP for now std::vector> explicit_eps; explicit_eps.emplace_back(DefaultCpuExecutionProvider()); RunTest(opts, std::move(explicit_eps)); } { TestOptions opts = base_opts; opts.has_zero_point = true; opts.zp_is_4bit = false; RunTest(opts); } #endif // !defined(USE_DML) && !defined(USE_WEBGPU) #if defined(USE_WEBGPU) { // WebGPU does support bias but no g_idx TestOptions opts = base_opts; opts.has_bias = true; RunTest(opts); } #endif } TEST(MatMulNBits, Float32_4b_Accuracy0) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } TEST(MatMulNBits, Float32_4b_Accuracy1) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } TEST(MatMulNBits, Float32_4b_Accuracy4) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } TEST(MatMulNBits, Float32_4b_Accuracy4_ForceFp32) { #if !defined(MLAS_TARGET_AMD64_IX86) GTEST_SKIP() << "Forced QNBit CompFp32 is currently supported only on x86/x64."; #else TestOptions opts{}; opts.N = 256; opts.K = 256; opts.block_size = 32; opts.accuracy_level = 4; opts.force_fp32 = true; opts.output_abs_error = 0.02f; for (bool use_lut_gemm : {false, true}) { SCOPED_TRACE(MakeString("use_lut_gemm=", use_lut_gemm)); opts.use_lut_gemm = use_lut_gemm; opts.batch_count = 1; opts.M = 1; RunTest(opts); opts.batch_count = 4; opts.M = 64; RunTest(opts); } #endif } TEST(MatMulNBits, Float32_4b_Accuracy4_ForceFp32DynamicMetadata) { #if !defined(MLAS_TARGET_AMD64_IX86) GTEST_SKIP() << "Forced QNBit CompFp32 is currently supported only on x86/x64."; #else TestOptions opts{}; opts.M = 256; opts.N = 64; opts.K = 64; opts.block_size = 32; opts.accuracy_level = 4; opts.force_fp32 = true; opts.output_abs_error = 0.02f; opts.scales_are_initializers = false; RunTest(opts); opts.scales_are_initializers = true; opts.has_zero_point = true; opts.zero_points_are_initializers = false; RunTest(opts); #endif } #if defined(MLAS_TARGET_AMD64_IX86) || defined(MLAS_TARGET_ARM64) #if !defined(USE_DML) // Actual and expected difference is over 0.01 with DmlExecutionProvider. // Skip the tests instead of raising the tolerance to make is pass. TEST(MatMulNBits, Float16_4b_Accuracy2) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } TEST(MatMulNBits, Float16_4b_Accuracy0) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } TEST(MatMulNBits, Float16_4b_Accuracy4) { TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); // See PR #27412 for details on the following test case, // which is added to cover a specific failure case in the past. // 6144, 2048 // Since K is larger (more chance of larger error), // and N is larger (more chance of having a value with larger error), // we set a higher tolerance for this case to avoid false positives // and flaky failures. TestMatMulNBitsTyped(0.2f, 0.03f); } TEST(MatMulNBits, LegacyShape_4b) { constexpr bool legacy_shape = true; TestMatMulNBitsTyped(); TestMatMulNBitsTyped(); } // Batch tests for DP4A path (accuracy_level 4) TEST(MatMulNBits, Float32_4b_Accuracy4_Batch) { // Test batch support with DP4A requirements: // - accuracy_level == 4 // - block_size % 32 == 0 // - K % 128 == 0 // - N % 16 == 0 // Small batch tests TestOptions opts{}; opts.accuracy_level = 4; opts.output_abs_error = 0.1f; opts.output_rel_error = 0.02f; // Batch=2 tests opts.batch_count = 2; opts.M = 1; opts.N = 16; opts.K = 128; opts.block_size = 32; RunTest(opts); opts.M = 2; opts.N = 32; opts.K = 128; opts.block_size = 32; RunTest(opts); opts.M = 32; opts.N = 64; opts.K = 256; opts.block_size = 64; RunTest(opts); opts.M = 100; opts.N = 288; opts.K = 1024; opts.block_size = 128; RunTest(opts); // Batch=4 tests opts.batch_count = 4; opts.M = 1; opts.N = 16; opts.K = 128; opts.block_size = 32; RunTest(opts); opts.M = 32; opts.N = 64; opts.K = 256; opts.block_size = 64; RunTest(opts); opts.M = 100; opts.N = 288; opts.K = 1024; opts.block_size = 128; RunTest(opts); // Batch=8 test opts.batch_count = 8; opts.M = 32; opts.N = 128; opts.K = 256; opts.block_size = 64; RunTest(opts); // Test with bias opts.batch_count = 2; opts.M = 32; opts.N = 64; opts.K = 256; opts.block_size = 64; opts.has_bias = true; RunTest(opts); } #ifndef ENABLE_TRAINING // Pre-packing (and therefore cross-session sharing of pre-packed weights) is disabled in a full // training build, so there is nothing to exercise there. namespace { // Builds a representative MatMulNBits TestOptions for the pre-packed weight sharing tests. TestOptions MakeSharingTestOptions(int64_t N, int64_t K, int64_t block_size, int64_t accuracy_level, bool has_zero_point, bool has_bias, PrepackSharingMode mode) { TestOptions opts{}; opts.M = 8; opts.N = N; opts.K = K; opts.block_size = block_size; opts.accuracy_level = accuracy_level; opts.has_zero_point = has_zero_point; opts.zp_is_4bit = true; opts.has_bias = has_bias; opts.prepack_sharing_mode = mode; opts.output_abs_error = 0.1f; opts.output_rel_error = 0.02f; return opts; } } // namespace // Legacy sharing path: the weight B is registered as a shared initializer via // SessionOptions::AddInitializer. Covers float and float16 activations, symmetric/asymmetric, +/- bias. TEST(MatMulNBits, SharedPrepackedWeights_AddInitializer) { for (bool has_zero_point : {false, true}) { for (bool has_bias : {false, true}) { RunTest(MakeSharingTestOptions(32, 256, /*block_size*/ 32, /*accuracy_level*/ 0, has_zero_point, has_bias, PrepackSharingMode::kAddInitializer)); RunTest(MakeSharingTestOptions(32, 256, /*block_size*/ 32, /*accuracy_level*/ 0, has_zero_point, has_bias, PrepackSharingMode::kAddInitializer)); } } } // Covers backends that fold asymmetric scales and zero points into the shared B buffer. TEST(MatMulNBits, SharedPrepackedWeights_AsymmetricPackedScales) { auto opts = MakeSharingTestOptions(288, 1024, /*block_size*/ 128, /*accuracy_level*/ 4, /*has_zero_point*/ true, /*has_bias*/ false, PrepackSharingMode::kAddInitializer); opts.M = 1; RunTest(opts); } // Uses a KleidiAI-compatible symmetric Q4 CompInt8 shape. Runtime scales cannot be embedded during // PrePack(B), so the kernel must decline B packing and use the runtime scales through the unpacked path. TEST(MatMulNBits, DynamicScales_SymmetricCompInt8) { #if !defined(MLAS_TARGET_ARM64) GTEST_SKIP() << "This test targets the Arm64 KleidiAI path."; #else if (!MlasQNBitGemmScalesPacked(1024, QBits, 128, SQNBIT_CompInt8, false, nullptr)) { GTEST_SKIP() << "KleidiAI Q4 packed-scales path is not active."; } #endif TestOptions opts{}; opts.M = 1; opts.N = 288; opts.K = 1024; opts.block_size = 128; opts.accuracy_level = 4; opts.scales_are_initializers = false; opts.output_abs_error = 0.1f; opts.output_rel_error = 0.02f; RunTest(opts); RunTest(opts); } // A runtime-scale node must not adopt a shared KleidiAI B buffer whose packed bytes contain scales // from another node or session. TEST(MatMulNBits, SharedPrepackedWeights_DynamicScales_SymmetricCompInt8) { #if !defined(MLAS_TARGET_ARM64) GTEST_SKIP() << "This test targets the Arm64 KleidiAI path."; #else if (!MlasQNBitGemmScalesPacked(1024, QBits, 128, SQNBIT_CompInt8, false, nullptr)) { GTEST_SKIP() << "KleidiAI Q4 packed-scales path is not active."; } #endif auto opts = MakeSharingTestOptions(288, 1024, /*block_size*/ 128, /*accuracy_level*/ 4, /*has_zero_point*/ false, /*has_bias*/ false, PrepackSharingMode::kAddInitializerExpectNoPrepack); opts.M = 1; opts.scales_are_initializers = false; RunTest(opts); } TEST(MatMulNBits, SharedPrepackedWeights_ForceFp32) { #if !defined(MLAS_TARGET_AMD64_IX86) GTEST_SKIP() << "Forced QNBit CompFp32 is currently supported only on x86/x64."; #else auto opts = MakeSharingTestOptions(64, 64, /*block_size*/ 32, /*accuracy_level*/ 4, /*has_zero_point*/ true, /*has_bias*/ true, PrepackSharingMode::kAddInitializer); opts.M = 256; opts.force_fp32 = true; opts.output_abs_error = 0.02f; RunTest(opts); #endif } // Uses a KleidiAI-compatible Q4 CompInt8 shape. Runtime zero points must not reuse a B pack // generated without them. TEST(MatMulNBits, DynamicZeroPoints_AsymmetricCompInt8) { #if !defined(MLAS_TARGET_ARM64) GTEST_SKIP() << "This test targets the Arm64 KleidiAI path."; #else if (!MlasQNBitGemmScalesPacked(1024, QBits, 128, SQNBIT_CompInt8, true, nullptr)) { GTEST_SKIP() << "KleidiAI Q4 packed-scales path is not active."; } #endif TestOptions opts{}; opts.M = 1; opts.N = 288; opts.K = 1024; opts.block_size = 128; opts.accuracy_level = 4; opts.has_zero_point = true; opts.zero_points_are_initializers = false; opts.output_abs_error = 0.1f; opts.output_rel_error = 0.02f; RunTest(opts); } // Same runtime-ZP case with the shared container enabled. PrePack must decline B packing, so the // second session must not adopt a shared B buffer built without those runtime zero points. TEST(MatMulNBits, SharedPrepackedWeights_DynamicZeroPoints_AsymmetricCompInt8) { if (!MlasQNBitGemmScalesPacked(1024, QBits, 128, SQNBIT_CompInt8, true, nullptr)) { GTEST_SKIP() << "KleidiAI Q4 packed-scales path is not active."; } auto opts = MakeSharingTestOptions(288, 1024, /*block_size*/ 128, /*accuracy_level*/ 4, /*has_zero_point*/ true, /*has_bias*/ false, PrepackSharingMode::kAddInitializerExpectNoPrepack); opts.M = 1; opts.zero_points_are_initializers = false; RunTest(opts); } // Negative control: with the shared container present but neither opt-in mechanism enabled, no // pre-packed weights are shared across sessions. TEST(MatMulNBits, SharedPrepackedWeights_NotSharedWithoutOptIn) { RunTest(MakeSharingTestOptions(32, 256, /*block_size*/ 32, /*accuracy_level*/ 0, /*has_zero_point*/ true, /*has_bias*/ true, PrepackSharingMode::kNoSharing)); RunTest(MakeSharingTestOptions(32, 256, /*block_size*/ 32, /*accuracy_level*/ 0, /*has_zero_point*/ false, /*has_bias*/ false, PrepackSharingMode::kNoSharing)); } struct MatMulNBitsLutOptions { int64_t bits; int64_t block_size; int64_t accuracy_level; }; class MatMulNBitsLutOptionsTest : public testing::TestWithParam {}; TEST_P(MatMulNBitsLutOptionsTest, ForceFp32Eligibility) { constexpr int64_t rows = 1; constexpr int64_t columns = 128; constexpr int64_t depth = 128; const auto& configuration = GetParam(); if (!MlasIsLutGemmAvailable(columns, depth, configuration.bits, configuration.block_size)) { GTEST_SKIP() << "LUT GEMM implementation is not available for this configuration."; } const int64_t blocks = depth / configuration.block_size; const int64_t blob_size = configuration.block_size * configuration.bits / 8; const std::unordered_map domain_to_version{{"", 21}, {kMSDomain, 1}}; Model model("matmul_nbits_force_fp32_lut", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, std::vector(), DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); NodeArg* input = builder.MakeInput({rows, depth}, std::vector(rows * depth, 1.0f)); NodeArg* weight = builder.MakeInitializer( {columns, blocks, blob_size}, std::vector(columns * blocks * blob_size, configuration.bits == 2 ? 0x55 : 0x11)); NodeArg* scales = builder.MakeInitializer({columns, blocks}, std::vector(columns * blocks, 0.25f)); NodeArg* zero_points = builder.MakeInitializer({columns, blocks}, std::vector(columns * blocks, 1.5f)); NodeArg* output = builder.MakeOutput(std::vector{rows, columns}); Node& node = builder.AddNode("MatMulNBits", {input, weight, scales, zero_points}, {output}, kMSDomain); node.AddAttribute("K", depth); node.AddAttribute("N", columns); node.AddAttribute("bits", configuration.bits); node.AddAttribute("block_size", configuration.block_size); node.AddAttribute("accuracy_level", configuration.accuracy_level); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); std::string model_bytes; ASSERT_TRUE(model.ToProto().SerializeToString(&model_bytes)); for (bool force_fp32 : {false, true}) { SCOPED_TRACE(MakeString("force_fp32=", force_fp32)); SessionOptions session_options; ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1")); ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsMlasQNBitForceFp32, force_fp32 ? "1" : "0")); InferenceSessionWrapper session{session_options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(model_bytes.data(), static_cast(model_bytes.size()))); ASSERT_STATUS_OK(session.Initialize()); bool eligible = false; #if defined(MLAS_TARGET_AMD64_IX86) eligible = configuration.bits == 4 && configuration.block_size == 32 && configuration.accuracy_level == 4 && MlasIsQNBitGemmAvailable(4, 32, SQNBIT_CompFp32); #endif const size_t expected_prepacks = force_fp32 && eligible ? 0 : 1; EXPECT_EQ(session.GetSessionState().GetNumberOfPrepacksCounter(), expected_prepacks) << "Only LUT GEMM can prepack B with float zero points."; std::vector fetches; ASSERT_STATUS_OK(session.Run(RunOptions{}, builder.feeds_, builder.output_names_, &fetches)); ASSERT_EQ(fetches.size(), size_t{1}); for (float value : fetches[0].Get().DataAsSpan()) { EXPECT_NEAR(value, -16.0f, 0.02f); } } } INSTANTIATE_TEST_SUITE_P(MatMulNBits, MatMulNBitsLutOptionsTest, testing::Values(MatMulNBitsLutOptions{2, 32, 4}, MatMulNBitsLutOptions{4, 64, 4}, MatMulNBitsLutOptions{4, 32, 0}, MatMulNBitsLutOptions{4, 32, 4})); // Covers multiple concurrent PrePack calls, including two nodes sharing an initializer while a // third consumes a distinct initializer. Outputs and prepack counts must match the sequential path. TEST(MatMulNBits, ParallelPrepack) { constexpr int64_t M = 8; constexpr int64_t N = 64; constexpr int64_t K = 128; constexpr int64_t block_size = 32; constexpr int64_t k_blocks = K / block_size; constexpr int64_t blob_size = block_size * QBits / 8; if (!MlasIsLutGemmAvailable(static_cast(N), static_cast(K), QBits, static_cast(block_size))) { GTEST_SKIP() << "LUT GEMM implementation is not available."; } RandomValueGenerator random{1234}; const std::unordered_map domain_to_version{{"", 21}, {kMSDomain, 1}}; Model model("parallel_matmul_nbits_prepack", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, std::vector(), DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); NodeArg* input = builder.MakeInput({M, K}, random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f)); auto make_quantized_initializer = [&](int seed_offset) { RandomValueGenerator weight_random{static_cast(1234 + seed_offset)}; std::vector weights(weight_random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f)); std::vector quantized(static_cast(N * k_blocks * blob_size)); std::vector scales(static_cast(N * k_blocks)); QuantizeDequantize(weights, quantized, scales, nullptr, static_cast(N), static_cast(K), static_cast(block_size)); return std::pair{ builder.MakeInitializer({N, k_blocks, blob_size}, quantized), builder.MakeInitializer({N, k_blocks}, scales)}; }; const auto shared_weight = make_quantized_initializer(0); const auto distinct_weight = make_quantized_initializer(1); auto add_matmul = [&](NodeArg* weight, NodeArg* scales) { NodeArg* output = builder.MakeOutput(std::vector{M, N}); Node& node = builder.AddNode("MatMulNBits", {input, weight, scales}, {output}, kMSDomain); node.AddAttribute("K", K); node.AddAttribute("N", N); node.AddAttribute("block_size", block_size); node.AddAttribute("bits", static_cast(QBits)); node.AddAttribute("accuracy_level", static_cast(0)); }; add_matmul(shared_weight.first, shared_weight.second); add_matmul(shared_weight.first, shared_weight.second); add_matmul(distinct_weight.first, distinct_weight.second); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); std::string model_bytes; ASSERT_TRUE(model.ToProto().SerializeToString(&model_bytes)); auto run_model = [&](bool parallel, std::vector& fetches, size_t& prepack_count) { SessionOptions session_options; session_options.intra_op_param.thread_pool_size = 4; ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1")); ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry( kOrtSessionOptionsEnableParallelPrepack, parallel ? "1" : "0")); InferenceSessionWrapper session{session_options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(model_bytes.data(), static_cast(model_bytes.size()))); ASSERT_STATUS_OK(session.Initialize()); prepack_count = session.GetSessionState().GetNumberOfPrepacksCounter(); ASSERT_STATUS_OK(session.Run(RunOptions{}, builder.feeds_, builder.output_names_, &fetches)); }; std::vector sequential_fetches; size_t sequential_prepack_count = 0; ASSERT_NO_FATAL_FAILURE(run_model(false, sequential_fetches, sequential_prepack_count)); std::vector parallel_fetches; size_t parallel_prepack_count = 0; ASSERT_NO_FATAL_FAILURE(run_model(true, parallel_fetches, parallel_prepack_count)); ASSERT_EQ(sequential_prepack_count, static_cast(3)); ASSERT_EQ(parallel_prepack_count, sequential_prepack_count); ASSERT_EQ(parallel_fetches.size(), sequential_fetches.size()); for (size_t i = 0; i < parallel_fetches.size(); ++i) { const auto result = CompareOrtValue(parallel_fetches[i], sequential_fetches[i], 0.0, 0.0, false); EXPECT_EQ(result.first, COMPARE_RESULT::SUCCESS) << result.second; } } #endif // !ENABLE_TRAINING #endif #endif #if defined(USE_CUDA) || defined(USE_DML) || defined(USE_WEBGPU) namespace { // Legacy test function. // This has too many parameters of the same type that must be specified in the correct order. // Consider using the overload with a TestOptions parameter. template void RunTest(int64_t M, int64_t N, int64_t K, int64_t block_size, bool has_zeropoint, bool zp_is_4bit = true, float abs_error = 0.f, bool has_g_idx = false, bool has_bias = false) { TestOptions opts{}; opts.M = M; opts.N = N; opts.K = K; opts.block_size = block_size; opts.accuracy_level = 0; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = zp_is_4bit; opts.has_g_idx = has_g_idx; opts.has_bias = has_bias; if (abs_error > 0.f) { opts.output_abs_error = abs_error; } if (std::is_same_v) { opts.output_rel_error = 0.001f; } else if (std::is_same_v) { opts.output_rel_error = 0.0005f; } std::vector> execution_providers; if (std::is_same_v) { #ifdef USE_CUDA execution_providers.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(execution_providers)); #endif #ifdef USE_DML execution_providers.push_back(DefaultDmlExecutionProvider()); RunTest(opts, std::move(execution_providers)); #endif #ifdef USE_WEBGPU execution_providers.push_back(DefaultWebGpuExecutionProvider()); RunTest(opts, std::move(execution_providers)); #endif } else { #ifdef USE_WEBGPU ConfigOptions config_options{}; ORT_ENFORCE(config_options.AddConfigEntry(webgpu::options::kMaxStorageBufferBindingSize, "134217728").IsOK()); execution_providers.push_back(WebGpuExecutionProviderWithOptions(config_options)); #endif RunTest(opts, std::move(execution_providers)); } } constexpr bool kPipelineMode = true; // CI pipeline? } // namespace TEST(MatMulNBits, Float16_Comprehensive) { if constexpr (kPipelineMode) { GTEST_SKIP() << "Skipping in pipeline mode"; // This test has too many combinations. Skip it in CI pipeline. } else { constexpr float abs_error = 0.02f; for (auto M : {1, 2, 100}) { for (auto N : {1, 2, 32, 288}) { for (auto K : {16, 32, 64, 128, 256, 1024, 93, 1234}) { for (auto block_size : {16, 32, 64, 128}) { for (auto has_g_idx : {false, true}) { for (auto has_zero_point : {false, true}) { for (auto is_zero_point_4bit : {false, true}) { RunTest(M, N, K, block_size, has_zero_point, is_zero_point_4bit, abs_error, has_g_idx); } } } } } } } } } TEST(MatMulNBits, Float16_Large) { #ifdef USE_DML // For some reason, the A10 machine that runs these tests during CI has a much bigger error than all retail // machines we tested on. All consumer-grade machines from Nvidia/AMD/Intel seem to pass these tests with an // absolute error of 0.08, but the A10 has errors going as high as 0.22. Ultimately, given the large number // of elements in this test, ULPs should probably be used instead of absolute/relative tolerances. constexpr float abs_error = 0.3f; #else constexpr float abs_error = 0.1f; #endif constexpr bool zp_is_4bit = true; for (auto block_size : {16, 32, 64, 128}) { for (auto has_zeropoint : {false, true}) { RunTest(1, 4096, 4096, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(1, 4096, 11008, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(1, 11008, 4096, block_size, has_zeropoint, zp_is_4bit, abs_error); } } } #ifdef USE_WEBGPU // Similar to Float16_Large but for float32 and crafted so that the input_b and output buffer size exceeds // maxStorageBufferBindingSize (128MB) so it must be split into 2 segments internally (~128.00006MB). // // input_b size(4-bits): N * K / 2 = 8388612 * 32 / 2 = 134217792 bytes > 134217728 bytes (128MB) // output size(float32): M * N * 4 = 4 * 8388612 * 4 = 134217792 bytes > 134217728 bytes (128MB) TEST(MatMulNBits, Float32_Large) { // Keep tolerance similar to Float16_Large (float path typically equal or better numerically). constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; constexpr auto block_size = 16; RunTest(4 /*M*/, 8388612 /*N*/, 32 /*K*/, block_size, has_zeropoint, zp_is_4bit, abs_error); } // Guards the accumulator precision of the MatMulNBits WebGPU kernel along K. // // Every other MatMulNBits test in this file draws its inputs from Gaussian(0, 0.25), which keeps the // running partial sum in the single digits even at K = 11008. That is why an f16 accumulator has never // been caught here: the tests cannot reach the f16 ceiling, not even by accident. // // This case is built so that the partial sum crosses 65504 while both the inputs and the exact result // stay comfortably inside the f16 range: // // A = 8 everywhere // B, first half of K = +112 (quantized 15, zero point 8, scale 16) // B, second half of K = -112 (quantized 1, zero point 8, scale 16) // exact Y = 0 // // In both cases the accumulator climbs on the first half of K and comes back down on the second. With // f32 every partial sum is exact and Y is exactly 0; with f16 the midpoint saturates to +Inf and no // later subtraction recovers it, so Y comes back Inf or NaN even though the correct answer is 0. // // M selects the dispatch, and the two that the option reaches from a MatMulNBits node are both covered: // M = 1 -> matmul_nbits.wgsl.template. K is split over tile_size_k_vec lanes and carried in // inter_results, so a lane walks K/tile_size_k_vec = 256 elements and peaks at // 128 * 8 * 112 = 114688. The block-local `sum` follows the same accumulator type, but // it spans at most 32 products and peaks at 32 * 896 = 28672, inside the f16 range in // either mode, so what this case actually isolates is the cross-K accumulator. // M = 8 -> matmul_nbits_wide_tile.wgsl.template. No cross-lane split of K here: results[m] carries // the whole prefix and peaks at 4096 * 8 * 112 = 3670016, which is still exact in f32 // (under 2^24) and far outside f16. // // One limitation, so nobody reads more into a pass than it carries: WGSL permits extra intermediate // precision, and Intel's D3D12 compiler promotes unrolled f16 `acc +=` chains to f32 on its own. On // such a configuration this test can pass even with an f16 accumulator. It is a regression guard for // the backends that round strictly (Vulkan, and the looped code shapes), not a universal detector. // // The EP is built with enableMatmulFp32Accumulation on because that is the setting under test; the // shipped default is off and would legitimately produce +Inf here. TEST(MatMulNBits, Float16_LargeK_AccumulatorOverflow) { constexpr int64_t N = 8; constexpr int64_t K = 8192; constexpr int64_t block_size = 32; constexpr int64_t k_blocks = K / block_size; constexpr int64_t blob_size = block_size / 2; // 4 bits per element constexpr float scale = 16.0f; constexpr float a_value = 8.0f; ConfigOptions config_options{}; ORT_ENFORCE(config_options.AddConfigEntry(webgpu::options::kEnableMatmulFp32Accumulation, webgpu::options::kEnableMatmulFp32Accumulation_ON) .IsOK()); // Checked before any OpTester exists: on a build where the WebGPU EP is a dynamic plugin this // returns nullptr, and both ConfigEps and the OpTester destructor object to a test that never ran. if (!WebGpuExecutionProviderWithOptions(config_options)) { GTEST_SKIP() << "WebGPU EP unavailable in this build."; } // Quantized B, laid out as {N, k_blocks, blob_size}. Every nibble in a block is 15 (dequantizes to // +112) for the first half of K and 1 (dequantizes to -112) for the second half. std::vector input1_vals(static_cast(N * k_blocks * blob_size)); std::vector scales(static_cast(N * k_blocks), scale); for (int64_t n = 0; n < N; ++n) { for (int64_t kb = 0; kb < k_blocks; ++kb) { const uint8_t packed = (kb * block_size < K / 2) ? 0xFF : 0x11; auto* blob = input1_vals.data() + (n * k_blocks + kb) * blob_size; for (int64_t i = 0; i < blob_size; ++i) { blob[i] = packed; } } } for (const int64_t M : {int64_t{1}, int64_t{8}}) { SCOPED_TRACE("M:" + std::to_string(M)); std::vector input0_vals(static_cast(M * K), a_value); // Exact result: the two halves of K cancel to zero for every output column. std::vector expected_vals(static_cast(M * N), 0.0f); OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); test.AddInput("A", {1, M, K}, FloatsToMLFloat16s(input0_vals), false); test.AddInput("B", {N, k_blocks, blob_size}, input1_vals, true); test.AddInput("scales", {N, k_blocks}, FloatsToMLFloat16s(scales), true); test.AddOptionalInputEdge(); // zero_points: unset, so the default 8 applies test.AddOptionalInputEdge(); // g_idx test.AddOptionalInputEdge(); // bias test.AddOutput("Y", {1, M, N}, FloatsToMLFloat16s(expected_vals)); // The f32 accumulator path is exact here, so the tolerance only has to exclude Inf/NaN. test.SetOutputAbsErr("Y", 0.05f); std::vector> execution_providers; execution_providers.push_back(WebGpuExecutionProviderWithOptions(config_options)); test.ConfigEps(std::move(execution_providers)); test.RunWithConfig(); } } // Float16_LargeK_AccumulatorOverflow above is the numerical case, and it covers the generic and // wide-tile kernels with the option on. This one is the opposite: ordinary Gaussian inputs, but every // dispatch that reads the option, in both of its states. It is there so that a shader variant that // fails to compile, an uninitialised accumulator flag or a cache hint that cannot tell the two variants // apart shows up as a test failure rather than as garbage on someone's GPU. // // Being explicit about what it does not do: on Gaussian(0, 0.25) both accumulator widths give the same // answer to within the tolerance, so a run that quietly ignored the flag would still pass here. The // numerical discrimination lives in the test above, and only for the two dispatches it reaches. The // dp4a paths have no equivalent case: A is int8-quantized before the kernel sees it, so a construction // whose exact result stays in range while the f16 prefix saturates needs a different setup, and I have // not written one. // // The shapes below pick the dispatch: // M = 1 -> matmul_nbits.wgsl.template // M = 8, block_size 32 -> matmul_nbits_wide_tile.wgsl.template // accuracy_level 4, M = 8 -> dp4a_matmul.wgsl.template (where the adapter supports it) // CanApplyDP4AMatrixMatMulNBits also needs subgroups, a non-Apple vendor and M >= 4 // (kMinMForTileOptimization) for an fp16 output, so the M = 2 case below only reaches // dp4a_matmul_small_m on an fp32-output or Qualcomm adapter; elsewhere it lands on the generic // kernel and is one more shape for it rather than dp4a coverage. // With the option on and an adapter that has subgroup matrices, the subgroup-matrix path declines // itself (its cooperative-matrix result type is f16 and cannot honour the request) and the dispatch // falls through to one of the kernels above; that fallback is exercised here too. // // The fused MLP and QKV decode kernels also read the option, but they are reached through graph fusion // rather than through a MatMulNBits node; they are covered by the option-enabled cases in // matmul_nbits_mlp_fusion_test.cc and matmul_nbits_qkv_fusion_test.cc. TEST(MatMulNBits, Float16_AccumulatorPrecisionOption_AllPaths) { struct Case { int64_t M; int64_t N; int64_t K; int64_t block_size; int64_t accuracy_level; bool has_bias; }; constexpr Case cases[] = { {1, 128, 1024, 32, 0, false}, // generic, decode shape {1, 128, 1024, 32, 0, true}, // generic, with bias {8, 128, 1024, 32, 0, false}, // wide tile, prefill shape {8, 128, 1024, 32, 0, true}, // wide tile, with bias {8, 128, 4096, 32, 4, false}, // dp4a where available, otherwise wide tile {2, 128, 4096, 32, 4, false}, // dp4a small-M only on fp32-output/Qualcomm, generic otherwise }; for (const auto& c : cases) { // The accuracy_level 4 cases need a looser bound, and not because of the accumulator. The dp4a // kernels quantize A to int8 before the dot product and the CPU reference does not, so at // K = 4096 it is that quantization which sets the error floor: on the D3D12 lanes the spread // against the reference reaches ~0.08 with the option off and ~0.08 with it on, which is the // point, since an accumulator effect would not be symmetric like that. Upstream // Float16_Large already allows 0.1 at this K for the easier accuracy_level 0 case. How closely // the dp4a path tracks the reference is Float16_4b_Accuracy4's job; what these two cases are // here for is to catch a variant that fails to compile or a cache hint that cannot tell the two // apart, and that does not depend on the tolerance. const bool is_dp4a_shape = (c.accuracy_level == 4); const float abs_error = is_dp4a_shape ? 0.15f : 0.055f; const float rel_error = is_dp4a_shape ? 0.03f : 0.02f; for (const char* acc_f32 : {webgpu::options::kEnableMatmulFp32Accumulation_OFF, webgpu::options::kEnableMatmulFp32Accumulation_ON}) { SCOPED_TRACE(std::string{"enableMatmulFp32Accumulation:"} + acc_f32); TestOptions opts{}; opts.M = c.M; opts.N = c.N; opts.K = c.K; opts.block_size = c.block_size; opts.accuracy_level = c.accuracy_level; opts.has_zero_point = false; opts.has_bias = c.has_bias; opts.output_abs_error = abs_error; opts.output_rel_error = rel_error; ConfigOptions config_options{}; ORT_ENFORCE(config_options.AddConfigEntry(webgpu::options::kEnableMatmulFp32Accumulation, acc_f32) .IsOK()); auto ep = WebGpuExecutionProviderWithOptions(config_options); if (!ep) { GTEST_SKIP() << "WebGPU EP unavailable in this build."; } std::vector> execution_providers; execution_providers.push_back(std::move(ep)); RunTest(opts, std::move(execution_providers)); } } } #endif #ifdef USE_CUDA TEST(MatMulNBits, PrepackedOptionalInputsCuda) { #if !USE_FPA_INTB_GEMM GTEST_SKIP() << "Requires fpA_intB kernels"; #else if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Requires SM80+"; } enum class OptionalInputs { Omitted, Empty, Bias, PackedZeroPoints, FloatZeroPoints }; for (auto inputs : {OptionalInputs::Omitted, OptionalInputs::Empty, OptionalInputs::Bias, OptionalInputs::PackedZeroPoints, OptionalInputs::FloatZeroPoints}) { #if USE_COMPACT_FPA_INTB_GEMM if (inputs != OptionalInputs::Omitted && inputs != OptionalInputs::Empty) { continue; // Compact kernels do not support bias or zero points. } #endif const bool has_bias = inputs == OptionalInputs::Bias || inputs == OptionalInputs::PackedZeroPoints || inputs == OptionalInputs::FloatZeroPoints; const bool has_zero_points = inputs == OptionalInputs::PackedZeroPoints || inputs == OptionalInputs::FloatZeroPoints; for (int64_t m : {1, 32}) { SCOPED_TRACE(testing::Message() << "inputs=" << static_cast(inputs) << ", M=" << m); auto cuda_ep = DefaultCudaExecutionProvider(); if (!cuda_ep) { GTEST_SKIP() << "CUDA execution provider is unavailable"; } constexpr int64_t n = 128, k = 128, block_size = 32; constexpr int64_t k_blocks = k / block_size; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", k); test.AddAttribute("N", n); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", 4); // Prepacked weights require fpA_intB, so incorrect presence flags cannot silently select a fallback. test.AddAttribute("weight_prepacked", 1); test.AddInput("A", {m, k}, std::vector(m * k, MLFloat16(1.0f))); // Uniform nibbles are unchanged by the SM80 layout permutations. Code 9 represents signed weight 1. test.AddInput("B", {n, k_blocks, block_size / 2}, std::vector(n * k / 2, 0x99), true); test.AddInput("scales", {n, k_blocks}, std::vector(n * k_blocks, MLFloat16(0.5f)), true); if (inputs != OptionalInputs::Omitted) { if (inputs == OptionalInputs::PackedZeroPoints) { test.AddInput("zero_points", {n, k_blocks / 2}, std::vector(n * k_blocks / 2, 0xaa), true); } else if (inputs == OptionalInputs::FloatZeroPoints) { test.AddInput("zero_points", {n, k_blocks}, std::vector(n * k_blocks, MLFloat16(10.0f)), true); } else { test.AddOptionalInputEdge(); } test.AddOptionalInputEdge(); if (has_bias) { test.AddInput("bias", {n}, std::vector(n, MLFloat16(2.0f))); } else { test.AddOptionalInputEdge(); } } const float expected = k * (9.0f - (has_zero_points ? 10.0f : 8.0f)) * 0.5f + (has_bias ? 2.0f : 0.0f); test.AddOutput("Y", {m, n}, std::vector(m * n, MLFloat16(expected))); test.SetOutputAbsErr("Y", 0.0f); test.SetOutputRelErr("Y", 0.0f); SessionOptions session_options; session_options.use_per_session_threads = false; ASSERT_STATUS_OK(session_options.config_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1")); test.Config(session_options); test.ConfigEp(std::move(cuda_ep)); test.RunWithConfig(); } } #endif } TEST(MatMulNBits, Fp16_Int4_Int4ZeroPoint) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = true; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } TEST(MatMulNBits, Fp16_Int4_Fp16ZeroPoint) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = false; constexpr bool has_zeropoint = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } TEST(MatMulNBits, BFloat16_Int4_Int4ZeroPoint) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = true; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } TEST(MatMulNBits, BFloat16_Int4_BFloat16ZeroPoint) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 8-bit MatMul tests on CUDA < 8.0"; } constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = false; constexpr bool has_zeropoint = true; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } TEST(MatMulNBits, Fp16_Int4_NoZeroPoint) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } // block_size=32 with the fpA_intB path. Production rc2/rc3 int4 models are quantized with // block_size=32. The fpA_intB kernels support group_size=32: the GEMV select_gs dispatches // GroupSize==32, and the SM80/Ampere fine-grained CUTLASS GEMM uses kMinFinegrainedGroupSize=32 // (two scale rows per 64-element K tile). Exercises M=1 (GEMV) and M=32 (CUTLASS), with and // without zero-points, for fp16 and bf16. TEST(MatMulNBits, Fp16_Int4_BlockSize32_FpAIntB) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto has_zeropoint : {false, true}) { RunTest(1, 256, 1024, 32, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, 32, has_zeropoint, zp_is_4bit, abs_error); } } TEST(MatMulNBits, BFloat16_Int4_BlockSize32_FpAIntB) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 MatMul tests on CUDA < 8.0"; } constexpr float abs_error = 0.5f; constexpr bool zp_is_4bit = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto has_zeropoint : {false, true}) { RunTest(1, 256, 1024, 32, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, 32, has_zeropoint, zp_is_4bit, abs_error); } } // fpA_intB with M chunking: M=100 in 32-row chunks runs three CUTLASS chunks and a 4-row trailing // chunk on the GEMV; 8-row chunks run the GEMV only. The shape is below the chunking size gate, so // ORT_MATMULNBITS_FORCE_CHUNKED bypasses it. TEST(MatMulNBits, Fp16_Int4_BlockSize32_FpAIntB_MChunked) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; for (const char* chunk : {"8", "32"}) { ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}, {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_M_CHUNK_SIZE", chunk}}}; RunTest(100, 1024, 2048, 32, has_zeropoint, zp_is_4bit, abs_error); } } // Fused bias with the fpA_intB path. Exercises both the GEMV path (M=1) and the CUTLASS GEMM path // (M=32), for fp16 and bf16, with block_size 64/128. This is the gpt-oss qkv_proj/o_proj scenario // where MatMulNBitsFusion folds the Add(bias) into MatMulNBits input[5]. TEST(MatMulNBits, Fp16_Int4_NoZeroPoint_Bias) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; constexpr bool has_g_idx = false; constexpr bool has_bias = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error, has_g_idx, has_bias); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error, has_g_idx, has_bias); } } TEST(MatMulNBits, BFloat16_Int4_NoZeroPoint_Bias) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 MatMul tests on CUDA < 8.0"; } constexpr float abs_error = 0.5f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; constexpr bool has_g_idx = false; constexpr bool has_bias = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error, has_g_idx, has_bias); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error, has_g_idx, has_bias); } } TEST(MatMulNBits, Fp16_Int4_NoZeroPoint_Bias_Prepacked) { ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; auto cuda_ep = DefaultCudaExecutionProvider(); if (!cuda_ep) { GTEST_SKIP() << "CUDA execution provider is unavailable"; } // Bias-bearing node with runtime prepacking (weight_prepacked=0): the kernel's PrePack transforms // the raw weight into the fpA_intB layout at session init and the fused bias flows through the // CUTLASS/GEMV epilogue. Offline weight_prepacked=1 parity for bias is covered by the Python test // test_op_matmulnbits_prepacked_cuda.py. TestOptions opts{}; opts.M = 32, opts.N = 1024, opts.K = 2048; opts.block_size = 64; opts.has_zero_point = false; opts.has_bias = true; opts.output_abs_error = 0.1f; opts.output_rel_error = 0.02f; std::vector> eps; eps.push_back(std::move(cuda_ep)); RunTest(opts, std::move(eps)); } // A prepacked weight (weight_prepacked!=0) forces the fpA_intB path on regardless of the enable // flag, and the constructor ORT_ENFORCEs that the path is actually supported for the node. Here the // block_size (256) is outside the fpA_intB-supported set, so kernel construction is rejected up front // with a build-specific diagnostic even though ORT_FPA_INTB_GEMM is enabled. TEST(MatMulNBits, Fp16_Int4_PrepackedWeightRejectedWhenFpAIntBUnsupported) { ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; auto cuda_ep = DefaultCudaExecutionProvider(); if (!cuda_ep) { GTEST_SKIP() << "CUDA execution provider is unavailable"; } TestOptions opts{}; opts.M = 1, opts.N = 256, opts.K = 1024; opts.block_size = 256; opts.disable_cpu_ep_fallback = true; opts.weight_prepacked = 1; #if USE_COMPACT_FPA_INTB_GEMM opts.expected_failure = "This compact fpA_intB build supports"; #else opts.expected_failure = "weight_prepacked requires"; #endif std::vector> eps; eps.push_back(std::move(cuda_ep)); RunTest(opts, std::move(eps)); } // weight_prepacked=2 selects the native SM90 (Hopper) mixed-GEMM layout. It is rejected up front // unless the device is SM90 and block_size is 64 or 128 (the SM90 TMA kernel requires group_size to // be a multiple of the 64-element Hopper K tile, so block_size=32 uses the non-Hopper kernel). When // the fpA_intB path is compiled in, all rejection messages begin with "weight_prepacked=2 (SM90 layout)", so the // assertion is stable across machine/build combinations: non-Hopper hits the compute-capability // guard, SM90 without native TMA support hits the build-support guard, and SM90 with native TMA // support hits the block_size guard. In a build without onnxruntime_USE_FPA_INTB_GEMM the kernel // rejects any weight_prepacked!=0 up front with a different ("weight_prepacked requires ...") message. TEST(MatMulNBits, Fp16_Int4_PrepackedSm90BlockSize32Rejected) { ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; auto cuda_ep = DefaultCudaExecutionProvider(); if (!cuda_ep) { GTEST_SKIP() << "CUDA execution provider is unavailable"; } TestOptions opts{}; opts.M = 1, opts.N = 256, opts.K = 1024; opts.block_size = 32; opts.disable_cpu_ep_fallback = true; opts.weight_prepacked = 2; #if USE_FPA_INTB_GEMM opts.expected_failure = "weight_prepacked=2 (SM90 layout)"; #else opts.expected_failure = "weight_prepacked requires"; #endif std::vector> eps; eps.push_back(std::move(cuda_ep)); RunTest(opts, std::move(eps)); } // This GTEST_SKIPs without a CUDA device, so it cannot cover the "build without the native SM90 // kernel" throw on a real Hopper GPU (the only hardware/build combination that reaches it). That // throw is instead covered GPU-free, with synthetic (sm, block_size) values, by // MatMulNBitsSm90ValidationTest in test/contrib_ops/cuda_kernels/matmul_nbits_sm90_validation_test.cc // (see the comment there for why that coverage lives in a separate translation unit). // Exercises the CUDA small-M batched GEMV tiles: CtaM in {2,4,8,16} (with M values that are not a // multiple of CtaM so the row-skip path runs) and CtaN in {1,2} (N divisible / not divisible by 16). TEST(MatMulNBits, Fp16_Int4_SmallMBatchedTiles) { constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; for (auto block_size : {32, 128}) { for (auto m : {3, 4, 5, 8, 12, 16}) { for (auto has_zeropoint : {false, true}) { RunTest(m, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); // N % 16 == 0 -> CtaN=2 RunTest(m, 24, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); // N % 16 != 0 -> CtaN=1 } } } } TEST(MatMulNBits, BFloat16_Int4_SmallMBatchedTiles) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 tests on CUDA < 8.0"; } constexpr float abs_error = 0.1f; for (auto block_size : {32, 128}) { for (auto m : {3, 4, 5, 8, 12, 16}) { for (auto n : {256, 24}) { // N=256 -> CtaN=2, N=24 -> CtaN=1 for (auto has_zeropoint : {false, true}) { TestOptions opts{}; opts.M = m, opts.N = n, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = true; opts.output_abs_error = abs_error; opts.output_rel_error = 0.02f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } } } } TEST(MatMulNBits, Fp16_Int4_GptOssRouterShapeNoZeroPoint) { constexpr float abs_error = 0.1f; // IsSupportedRouterGemvShape enables the specialization for block_size 32 and 64, so exercise both // to keep the MatMulFloatInt4RouterKernel and instantiations covered. for (auto block_size : {32, 64}) { TestOptions opts{}; opts.M = 1, opts.N = 32, opts.K = 2880; opts.block_size = block_size; opts.has_zero_point = false; opts.zp_is_4bit = true; opts.output_abs_error = abs_error; opts.output_rel_error = 0.02f; { ScopedEnvironmentVariables scoped_env_vars{ EnvVarMap{{"ORT_DISABLE_QMOE_ROUTER_GEMV_SPECIALIZATION", std::optional{}}}}; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } { ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_DISABLE_QMOE_ROUTER_GEMV_SPECIALIZATION", "1"}}}; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } { opts.has_bias = true; ScopedEnvironmentVariables scoped_env_vars{ EnvVarMap{{"ORT_DISABLE_QMOE_ROUTER_GEMV_SPECIALIZATION", std::optional{}}}}; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } } TEST(MatMulNBits, BFloat16_Int4_NoZeroPoint) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 8-bit MatMul tests on CUDA < 8.0"; } constexpr float abs_error = 0.5f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = false; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}}; for (auto block_size : {64, 128}) { RunTest(1, 256, 1024, block_size, has_zeropoint, zp_is_4bit, abs_error); RunTest(32, 1024, 2048, block_size, has_zeropoint, zp_is_4bit, abs_error); } } // Chunked dequant+GEMM path tests. // Force the chunked path with a small chunk size to exercise per-chunk pointer // arithmetic (blob, scales, zero_points offsets) and strided cuBLAS output // with manageable tensor sizes. TEST(MatMulNBits, Fp16_Int4_Chunked_Uint8ZeroPoint) { constexpr float abs_error = 0.1f; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{ {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}}; for (auto block_size : {32, 64, 128}) { for (auto M : {1, 2}) { TestOptions opts{}; opts.M = M, opts.N = 256, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = true; opts.zp_is_4bit = true; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } // Odd blocks_per_col (K=96, block_size=32 → blocks_per_col=3) exercises the // (blocks_per_col + 1) / 2 rounding in the 4-bit packed ZP offset. { TestOptions opts{}; opts.M = 1, opts.N = 256, opts.K = 96; opts.block_size = 32; opts.has_zero_point = true; opts.zp_is_4bit = true; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } TEST(MatMulNBits, Fp16_Int4_Chunked_Fp16ZeroPoint) { constexpr float abs_error = 0.1f; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{ {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}}; for (auto block_size : {32, 64, 128}) { for (auto M : {1, 2}) { TestOptions opts{}; opts.M = M, opts.N = 256, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = true; opts.zp_is_4bit = false; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } } TEST(MatMulNBits, Fp16_Int4_Chunked_NoZeroPoint) { constexpr float abs_error = 0.1f; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{ {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}}; for (auto block_size : {32, 64, 128}) { for (auto M : {1, 2}) { TestOptions opts{}; opts.M = M, opts.N = 256, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = false; opts.zp_is_4bit = true; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } } TEST(MatMulNBits, BFloat16_Int4_Chunked_Uint8ZeroPoint) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 tests on CUDA < 8.0"; } constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = true; constexpr bool has_zeropoint = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{ {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}}; for (auto block_size : {32, 64, 128}) { for (auto M : {1, 2}) { TestOptions opts{}; opts.M = M, opts.N = 256, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = zp_is_4bit; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } // Odd blocks_per_col (K=96, block_size=32 → blocks_per_col=3) exercises the // (blocks_per_col + 1) / 2 rounding in the 4-bit packed ZP offset. { TestOptions opts{}; opts.M = 1, opts.N = 256, opts.K = 96; opts.block_size = 32; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = zp_is_4bit; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } TEST(MatMulNBits, BFloat16_Int4_Chunked_BFloat16ZeroPoint) { if (!HasCudaEnvironment(800)) { GTEST_SKIP() << "Skipping BFloat16 tests on CUDA < 8.0"; } constexpr float abs_error = 0.1f; constexpr bool zp_is_4bit = false; constexpr bool has_zeropoint = true; ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{ {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"}, {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}}; for (auto block_size : {32, 64, 128}) { for (auto M : {1, 2}) { TestOptions opts{}; opts.M = M, opts.N = 256, opts.K = 1024; opts.block_size = block_size; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = zp_is_4bit; opts.output_abs_error = abs_error; opts.output_rel_error = 0.001f; std::vector> eps; eps.push_back(DefaultCudaExecutionProvider()); RunTest(opts, std::move(eps)); } } } #endif #endif // defined(USE_CUDA) || defined(USE_DML) #if defined(USE_QNN) && defined(_M_ARM64) namespace { // QNN-EP Test Function // This has too many parameters of the same type that must be specified in the correct order. // Consider using the overload with a TestOptions parameter. void RunQnnEpTest(int64_t M, int64_t N, int64_t K, bool has_zeropoint = true, float abs_error = 0.05f) { TestOptions opts{}; opts.M = M; opts.N = N; opts.K = K; opts.block_size = 32; opts.accuracy_level = 4; opts.has_zero_point = has_zeropoint; opts.zp_is_4bit = true; opts.has_g_idx = false; opts.has_bias = false; if (abs_error > 0.f) { opts.output_abs_error = abs_error; } std::vector> execution_providers; ProviderOptions provider_options; provider_options["backend_type"] = "gpu"; provider_options["offload_graph_io_quantization"] = "0"; execution_providers.push_back(QnnExecutionProviderWithOptions(provider_options)); RunTest(opts, std::move(execution_providers)); } } // namespace // QNN GPU Only support FP16 activations and Q4_0 weights, with zero_points = 8 // Accumulation with larger channel accumulates more error. Set higher abs_error with respect to K. TEST(MatMulNBits, Basic_M1_N128_K512_withZp) { constexpr float abs_error = 0.05f; RunQnnEpTest(1, 128, 512, true, abs_error); } TEST(MatMulNBits, Basic_M1_N128_K512) { constexpr float abs_error = 0.05f; RunQnnEpTest(1, 128, 512, false, abs_error); } TEST(MatMulNBits, Basic_M10_N128_K512_withZp) { constexpr float abs_error = 0.05f; RunQnnEpTest(10, 128, 512, true, abs_error); } TEST(MatMulNBits, Basic_M10_N128_K512) { constexpr float abs_error = 0.05f; RunQnnEpTest(10, 128, 512, false, abs_error); } #endif // Test that out-of-range g_idx values are rejected with INVALID_ARGUMENT. // CUDA EP is excluded from these tests, so no risk of hitting CUDA_KERNEL_ASSERT. TEST(MatMulNBits, InvalidGIdx_OutOfRange) { constexpr int64_t M = 2, N = 4, K = 32, block_size = 16; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; // 2 constexpr int64_t blob_size = block_size * QBits / 8; // 8 OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); // A: [M, K] std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); // B: [N, k_blocks, blob_size] std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); // scales: [N, k_blocks] std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); // zero_points: optional (skip) test.AddOptionalInputEdge(); // g_idx with out-of-range values (valid range is [0, k_blocks) = [0, 2)) std::vector g_idx(K); for (int64_t i = 0; i < K; i++) { g_idx[i] = 99999; // way out of range } test.AddInput("g_idx", {K}, g_idx, true); // bias: optional (skip) test.AddOptionalInputEdge(); // Output placeholder (won't actually be compared since we expect failure) std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); test.Run(OpTester::ExpectResult::kExpectFailure, "group_index value", {kCudaExecutionProvider, kCudaNHWCExecutionProvider, kDmlExecutionProvider, kWebGpuExecutionProvider, kOpenVINOExecutionProvider}); } // Test that negative g_idx values are rejected. TEST(MatMulNBits, InvalidGIdx_Negative) { constexpr int64_t M = 2, N = 4, K = 32, block_size = 16; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); test.AddOptionalInputEdge(); // g_idx with negative values std::vector g_idx(K); for (int64_t i = 0; i < K; i++) { g_idx[i] = -1; } test.AddInput("g_idx", {K}, g_idx, true); test.AddOptionalInputEdge(); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); test.Run(OpTester::ExpectResult::kExpectFailure, "group_index value", {kCudaExecutionProvider, kCudaNHWCExecutionProvider, kDmlExecutionProvider, kWebGpuExecutionProvider, kOpenVINOExecutionProvider}); } // Test that block_size=512 (unsupported) is rejected at kernel creation. TEST(MatMulNBits, UnsupportedBlockSize_512) { constexpr int64_t M = 1, N = 1, K = 512, block_size = 512; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("bits", int64_t{QBits}); test.AddAttribute("block_size", block_size); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectFailure, "Only block sizes 16, 32, 64, 128, and 256 are supported", {}, nullptr, &execution_providers); } // The following tests cover the shape-validation guard added at the top of // MatMulNBits::PrePack. The guard rejects initializer shapes that do not // match the attribute-derived shape so that a crafted model whose (N, K, bits, // block_size) attributes overstate the real tensor extents cannot trigger an // out-of-bounds READ inside the MLAS pack routines during session // initialization. Each test passes a B/scales/zero_points initializer whose // declared shape (and matching data buffer size) is inconsistent with the // attribute-derived shape, and expects session creation to fail with // "MatMulNBits PrePack:" (i.e. before Compute() is ever invoked). // B shape mismatches the (N, k_blocks, blob_size) shape derived from attributes. TEST(MatMulNBits, PrePack_InvalidBShape_RejectsAtSessionInit) { constexpr int64_t M = 1, N = 4, K = 32, block_size = 32; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; // 1 constexpr int64_t blob_size = block_size * QBits / 8; // 16 OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); // Declare B with one fewer row than attributes claim. The data buffer matches // the smaller declared shape, exactly mirroring the crafted-model scenario in // which the attributes overstate the tensor's real extent. constexpr int64_t bad_N = N - 1; std::vector b_data(bad_N * k_blocks * blob_size, 0); test.AddInput("B", {bad_N, k_blocks, blob_size}, b_data, true); std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectFailure, "MatMulNBits PrePack: B initializer shape", {}, nullptr, &execution_providers); } // B shape has the wrong rank (2D instead of (N, k_blocks, blob_size)). TEST(MatMulNBits, PrePack_InvalidBRank_RejectsAtSessionInit) { constexpr int64_t M = 1, N = 4, K = 32, block_size = 32; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); // Flatten the trailing k_blocks/blob_size dims into a single dimension. // The total element count still matches, but the rank differs from the // attribute-derived (N, k_blocks, blob_size) shape. std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks * blob_size}, b_data, true); std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectFailure, "MatMulNBits PrePack: B initializer shape", {}, nullptr, &execution_providers); } // scales shape does not match either of the accepted layouts // ([N * k_blocks] or [N, k_blocks]). TEST(MatMulNBits, PrePack_InvalidScalesShape_RejectsAtSessionInit) { constexpr int64_t M = 1, N = 4, K = 32, block_size = 32; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); // Declare scales with one fewer row than the attribute-derived layout. constexpr int64_t bad_N = N - 1; std::vector scales(bad_N * k_blocks, 1.0f); test.AddInput("scales", {bad_N, k_blocks}, scales, true); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectFailure, "MatMulNBits PrePack: scales initializer shape", {}, nullptr, &execution_providers); } // uint8 (packed) zero_points shape does not match the // [N * zp_blob_size] / [N, zp_blob_size] layout derived from attributes. TEST(MatMulNBits, PrePack_InvalidUInt8ZeroPointsShape_RejectsAtSessionInit) { constexpr int64_t M = 1, N = 4, K = 32, block_size = 32; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; constexpr int64_t zp_blob_size = (k_blocks * QBits + 7) / 8; OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); std::vector a_data(M * K, 1.0f); test.AddInput("A", {M, K}, a_data, false); std::vector b_data(N * k_blocks * blob_size, 0); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); std::vector scales(N * k_blocks, 1.0f); test.AddInput("scales", {N, k_blocks}, scales, true); // Declare uint8 zero_points with one fewer row than the attribute-derived // layout. zp_blob_size==1 here, so this is also distinguishable from any // legacy 1D layout that would otherwise be accepted. constexpr int64_t bad_N = N - 1; std::vector zp(bad_N * zp_blob_size, 0); test.AddInput("zero_points", {bad_N, zp_blob_size}, zp, true); std::vector y_data(M * N, 0.0f); test.AddOutput("Y", {M, N}, y_data); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectFailure, "MatMulNBits PrePack: zero_points initializer shape", {}, nullptr, &execution_providers); } // Sanity check: the legacy 1D layouts for scales and uint8 zero_points are // still accepted by the new shape validation guard (i.e. the guard only // rejects truly mismatched shapes and does not regress backward // compatibility for existing models). TEST(MatMulNBits, PrePack_LegacyFlattenedShapes_Accepted) { constexpr int64_t M = 1, N = 4, K = 32, block_size = 32; constexpr int64_t k_blocks = (K + block_size - 1) / block_size; constexpr int64_t blob_size = block_size * QBits / 8; constexpr int64_t zp_blob_size = (k_blocks * QBits + 7) / 8; RandomValueGenerator random{1234}; std::vector a_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f)); std::vector b_f_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f)); std::vector b_data(N * k_blocks * blob_size); std::vector scales(N * k_blocks); std::vector zp(N * zp_blob_size); QuantizeDequantize(b_f_vals, b_data, scales, &zp, static_cast(N), static_cast(K), static_cast(block_size)); std::vector expected(M * N); 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) { sum += a_vals[m * K + k] * b_f_vals[n * K + k]; } expected[m * N + n] = sum; } } OpTester test("MatMulNBits", 1, kMSDomain); test.AddAttribute("K", K); test.AddAttribute("N", N); test.AddAttribute("block_size", block_size); test.AddAttribute("bits", QBits); test.AddAttribute("accuracy_level", int64_t{0}); test.AddInput("A", {M, K}, a_vals, false); test.AddInput("B", {N, k_blocks, blob_size}, b_data, true); // Legacy flattened 1D layouts for scales and zero_points. test.AddInput("scales", {N * k_blocks}, scales, true); test.AddInput("zero_points", {N * zp_blob_size}, zp, true); test.AddOutput("Y", {M, N}, expected); test.SetOutputAbsErr("Y", 0.1f); std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); test.Run(OpTester::ExpectResult::kExpectSuccess, "", {}, nullptr, &execution_providers); } // Regression test for https://github.com/microsoft/onnxruntime/issues/31137 // MatMulNBits inside an If subgraph where B and scales are parent-graph initializers. // On ARM64 with accuracy_level=4 (KleidiAI path) this triggered a segfault during // session initialization because TryGetConstantInput could not find parent-scope // constants when building the kernel's OpKernelInfo. TEST(MatMulNBits, SubgraphParentScopeInitializers) { #if !defined(MLAS_TARGET_ARM64) GTEST_SKIP() << "This test targets the Arm64 KleidiAI path."; #else if (!MlasQNBitGemmScalesPacked(64, QBits, 32, SQNBIT_CompInt8, true, nullptr)) { GTEST_SKIP() << "KleidiAI Q4 packed-scales path is not active."; } #endif constexpr int64_t M = 4, K = 64, N = 64, BLK = 32, BITS = 4; constexpr int64_t nblk = K / BLK; constexpr int64_t blob = BLK * BITS / 8; // Generate quantized B and scales. std::vector b_f(static_cast(N * K), 0.1f); std::vector b_quant(static_cast(N * nblk * blob)); std::vector scales(static_cast(N * nblk)); QuantizeDequantize(b_f, b_quant, scales, nullptr, static_cast(N), static_cast(K), static_cast(BLK)); // Build the If-branch subgraph containing a MatMulNBits node. // The branch consumes A, Bq, Bs from outer scope and outputs Y. auto build_branch = [&](const std::string& branch_name) -> ONNX_NAMESPACE::GraphProto { ONNX_NAMESPACE::GraphProto g; g.set_name(branch_name); auto* out_vi = g.add_output(); out_vi->set_name("Y"); auto* out_type = out_vi->mutable_type()->mutable_tensor_type(); out_type->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); auto* out_shape = out_type->mutable_shape(); out_shape->add_dim()->set_dim_value(M); out_shape->add_dim()->set_dim_value(N); auto* node = g.add_node(); node->set_op_type("MatMulNBits"); node->set_domain("com.microsoft"); node->set_name(branch_name + "_mmn"); node->add_input("A"); node->add_input("Bq"); node->add_input("Bs"); node->add_output("Y"); auto add_int_attr = [&](const std::string& attr_name, int64_t val) { auto* attr = node->add_attribute(); attr->set_name(attr_name); attr->set_type(ONNX_NAMESPACE::AttributeProto_AttributeType_INT); attr->set_i(val); }; add_int_attr("K", K); add_int_attr("N", N); add_int_attr("bits", BITS); add_int_attr("block_size", BLK); // accuracy_level=4 triggers the KleidiAI / high-accuracy prepack path on ARM64 // that asserts scales != nullptr; this is the crashing case in the bug report. add_int_attr("accuracy_level", 4); return g; }; // Build the parent model: cond + A as inputs, Bq + Bs as parent-graph initializers, // an If node that dispatches to MatMulNBits in both branches. ONNX_NAMESPACE::ModelProto model; model.set_ir_version(9); auto* opset_default = model.add_opset_import(); opset_default->set_version(17); auto* opset_ms = model.add_opset_import(); opset_ms->set_domain("com.microsoft"); opset_ms->set_version(1); auto* graph = model.mutable_graph(); graph->set_name("main"); // Graph inputs. { auto* cond_vi = graph->add_input(); cond_vi->set_name("cond"); cond_vi->mutable_type()->mutable_tensor_type()->set_elem_type( ONNX_NAMESPACE::TensorProto_DataType_BOOL); auto* a_vi = graph->add_input(); a_vi->set_name("A"); auto* a_type = a_vi->mutable_type()->mutable_tensor_type(); a_type->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); auto* a_shape = a_type->mutable_shape(); a_shape->add_dim()->set_dim_value(M); a_shape->add_dim()->set_dim_value(K); } // Parent-graph initializers (Bq and Bs live here, NOT inside the subgraph). { auto* bq_init = graph->add_initializer(); bq_init->set_name("Bq"); bq_init->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_UINT8); bq_init->add_dims(N); bq_init->add_dims(nblk); bq_init->add_dims(blob); bq_init->set_raw_data(b_quant.data(), b_quant.size() * sizeof(uint8_t)); auto* bs_init = graph->add_initializer(); bs_init->set_name("Bs"); bs_init->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); bs_init->add_dims(N * nblk); bs_init->set_raw_data(scales.data(), scales.size() * sizeof(float)); } // Graph output. { auto* out_vi = graph->add_output(); out_vi->set_name("Yout"); auto* out_type = out_vi->mutable_type()->mutable_tensor_type(); out_type->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); auto* out_shape = out_type->mutable_shape(); out_shape->add_dim()->set_dim_value(M); out_shape->add_dim()->set_dim_value(N); } // If node referencing Bq/Bs from parent scope inside both branches. { auto* if_node = graph->add_node(); if_node->set_op_type("If"); if_node->set_name("if0"); if_node->add_input("cond"); if_node->add_output("Yout"); auto* then_attr = if_node->add_attribute(); then_attr->set_name("then_branch"); then_attr->set_type(ONNX_NAMESPACE::AttributeProto_AttributeType_GRAPH); *then_attr->mutable_g() = build_branch("then"); auto* else_attr = if_node->add_attribute(); else_attr->set_name("else_branch"); else_attr->set_type(ONNX_NAMESPACE::AttributeProto_AttributeType_GRAPH); *else_attr->mutable_g() = build_branch("else"); } std::string model_str; ASSERT_TRUE(model.SerializeToString(&model_str)); // Session initialization must not crash/segfault. SessionOptions so; so.session_logid = "MatMulNBitsSubgraphTest"; InferenceSession session{so, GetEnvironment()}; std::istringstream model_stream(model_str); ASSERT_STATUS_OK(session.Load(model_stream)); ASSERT_STATUS_OK(session.Initialize()); // Run inference and verify output shape is correct. std::vector a_vals(static_cast(M * K), 1.0f); OrtValue a_val; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {M, K}, a_vals, &a_val); OrtValue cond_val; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {}, {true}, &cond_val); NameMLValMap feeds = {{"A", a_val}, {"cond", cond_val}}; std::vector output_names = {"Yout"}; std::vector fetches; RunOptions run_options; ASSERT_STATUS_OK(session.Run(run_options, feeds, output_names, &fetches)); ASSERT_EQ(fetches.size(), 1u); const auto& result = fetches[0].Get(); EXPECT_EQ(result.Shape()[0], M); EXPECT_EQ(result.Shape()[1], N); } } // namespace test } // namespace onnxruntime #endif // ORT_MINIMAL_BUILD