Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
edit | blame | history | raw
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#ifndef ORT_MINIMAL_BUILD

#include 
#include 
#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/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 "core/session/onnxruntime_session_options_config_keys.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/unittest_util/graph_transform_test_builder.h"
#include "test/util/include/default_providers.h"
#include "test/util/include/scoped_env_vars.h"
#include "core/session/onnxruntime_cxx_api.h"
#include "core/session/ort_env.h"
#include "core/util/qmath.h"
#include "core/graph/model.h"
#include "test/util/include/inference_session_wrapper.h"
#include "test/util/include/test/test_environment.h"
#include "core/providers/webgpu/webgpu_provider_options.h"
#ifdef USE_WEBGPU
#include "contrib_ops/webgpu/quantization/matmul_nbits_common.h"
#endif

extern std::unique_ptr ort_env;

namespace onnxruntime {

namespace test {

namespace {

constexpr int QBits = 2;

struct TestOptions2Bits {
  int64_t M{1};
  int64_t N{1};
  int64_t K{1};
  int64_t block_size{32};
  int64_t accuracy_level{0};

  bool has_zero_point{false};
  bool has_typed_zero_point{false};
  bool has_g_idx{false};
  bool has_bias{false};

  // Run the node on the CUDA EP instead of the default (CPU / WebGPU) set.
  bool use_cuda{false};

  std::optional output_abs_error{};
  std::optional output_rel_error{};
  std::optional expected_failure{};
};

[[maybe_unused]] std::ostream& operator<<(std::ostream& os, const TestOptions2Bits& opts) {
  return os << "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
            << ", has_typed_zero_point:" << opts.has_typed_zero_point
            << ", has_g_idx:" << opts.has_g_idx
            << ", has_bias:" << opts.has_bias
            << ", use_cuda:" << opts.use_cuda;
}

template 
void RunTest2Bits(const TestOptions2Bits& opts) {
  SCOPED_TRACE(opts);
  ASSERT_FALSE(opts.has_typed_zero_point && !opts.has_zero_point);

  const int64_t M = opts.M,
                K = opts.K,
                N = opts.N;

  RandomValueGenerator random{1234};
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(opts.block_size), /* columnwise */ true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);

  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(opts.block_size), /* columnwise */ true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);
  std::vector zp(q_zp_size_in_bytes);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(),
      scales.data(),
      opts.has_zero_point && !opts.has_typed_zero_point ? zp.data() : nullptr,
      input1_fp32_vals.data(),
      static_cast(opts.block_size),
      true,
      static_cast(K),
      static_cast(N),
      static_cast(N),
      tp);

  // Note that raw_vals is NxK after dequant
  MlasDequantizeBlockwise(
      input1_fp32_vals.data(),
      input1_vals.data(),
      scales.data(),
      opts.has_zero_point && !opts.has_typed_zero_point ? zp.data() : nullptr,
      static_cast(opts.block_size),
      true,
      static_cast(K),
      static_cast(N),
      tp);

  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(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[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 constexpr (std::is_same::value) {
    test.AddInput("A", {M, K}, input0_fp32_vals, false);
  } else if constexpr (std::is_same::value) {
    test.AddInput("A", {M, K}, FloatsToMLFloat16s(input0_fp32_vals), false);
  } else if constexpr (std::is_same::value) {
    test.AddInput("A", {M, K}, FloatsToBFloat16s(input0_fp32_vals), false);
  }

  int64_t k_blocks = (K + opts.block_size - 1) / opts.block_size;
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);

  if constexpr (std::is_same::value) {
    test.AddInput("scales", {N, static_cast(q_scale_size) / N}, scales, true);
  } else if constexpr (std::is_same::value) {
    test.AddInput("scales", {N, static_cast(q_scale_size) / N}, FloatsToMLFloat16s(scales), true);
  } else if constexpr (std::is_same::value) {
    test.AddInput("scales", {N, static_cast(q_scale_size) / N}, FloatsToBFloat16s(scales), true);
  }

  if (opts.has_zero_point) {
    if (opts.has_typed_zero_point) {
      const std::vector typed_zp(q_scale_size, 2.0f);
      if constexpr (std::is_same::value) {
        test.AddInput("zero_points", {N, static_cast(q_scale_size) / N}, typed_zp, true);
      } else if constexpr (std::is_same::value) {
        test.AddInput("zero_points", {N, static_cast(q_scale_size) / N},
                          FloatsToMLFloat16s(typed_zp), true);
      } else if constexpr (std::is_same::value) {
        test.AddInput("zero_points", {N, static_cast(q_scale_size) / N},
                          FloatsToBFloat16s(typed_zp), true);
      }
    } else {
      test.AddInput("zero_points", {N, static_cast(q_zp_size_in_bytes) / N}, zp, true);
    }
  } else {
    test.AddOptionalInputEdge();
  }

  if (opts.has_g_idx) {
    test.AddInput("g_idx", {K}, std::vector(static_cast(K), 0), false);
  } 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", {M, N}, expected_vals);
  } else if constexpr (std::is_same::value) {
    test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(expected_vals));
  } else if constexpr (std::is_same::value) {
    test.AddOutput("Y", {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);
  }

  std::vector> execution_providers;
  if (opts.use_cuda) {
#ifdef USE_CUDA
    execution_providers.emplace_back(DefaultCudaExecutionProvider());
    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.ConfigEps(std::move(execution_providers));
    if (opts.expected_failure.has_value()) {
      test.Config(OpTester::ExpectResult::kExpectFailure, *opts.expected_failure);
    }
    test.RunWithConfig();
#endif
    return;
  }

  if constexpr (std::is_same::value) {
#ifdef USE_WEBGPU
    execution_providers.push_back(DefaultWebGpuExecutionProvider());
#endif
    execution_providers.emplace_back(DefaultCpuExecutionProvider());
    test.ConfigEps(std::move(execution_providers));
    test.RunWithConfig();
  }
}

template 
void TestMatMul2BitsTyped(float abs_error = 0.1f, float rel_error = 0.02f) {
  TestOptions2Bits 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.output_abs_error = abs_error;
  base_opts.output_rel_error = rel_error;

  {
    TestOptions2Bits opts = base_opts;
    opts.has_zero_point = false;
    opts.has_bias = false;
    RunTest2Bits(opts);
  }

  {
    TestOptions2Bits opts = base_opts;
    opts.has_zero_point = true;
    opts.has_bias = false;
    RunTest2Bits(opts);
  }

  {
    TestOptions2Bits opts = base_opts;
    opts.has_zero_point = false;
    opts.has_bias = true;
    RunTest2Bits(opts);
  }

  {
    TestOptions2Bits opts = base_opts;
    opts.has_zero_point = true;
    opts.has_bias = true;
    RunTest2Bits(opts);
  }
}

}  // namespace

template 
void TestMatMul2BitsLutGemm(int64_t M, int64_t N, int64_t K, int64_t block_size,
                            bool has_zero_point, bool has_bias = false,
                            float abs_error = 0.15f, float rel_error = 0.05f) {
  if (K % 32 != 0 || N % 128 != 0 || block_size % 32 != 0) {
    GTEST_SKIP() << "LUT GEMM requires K multiple of 32, N multiple of 128, block_size multiple of 32";
  }

  if (!MlasIsLutGemmAvailable(static_cast(N), static_cast(K), 2, static_cast(block_size))) {
    GTEST_SKIP() << "LUT GEMM not available on this platform";
  }

  RandomValueGenerator random{1234};
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), /* columnwise */ true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);

  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), /* columnwise */ true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);
  std::vector zp(q_zp_size_in_bytes);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(),
      scales.data(),
      has_zero_point ? zp.data() : nullptr,
      input1_fp32_vals.data(),
      static_cast(block_size),
      true,
      static_cast(K),
      static_cast(N),
      static_cast(N),
      tp);

  // Dequantize for reference computation
  MlasDequantizeBlockwise(
      input1_fp32_vals.data(),
      input1_vals.data(),
      scales.data(),
      has_zero_point ? zp.data() : nullptr,
      static_cast(block_size),
      true,
      static_cast(K),
      static_cast(N),
      tp);

  // Optional per-output-feature bias with non-trivial variation across N so any stride/transpose
  // bug in the fused bias add (inside MlasLutGemm) is observable.
  std::vector bias;
  if (has_bias) {
    bias.resize(static_cast(N));
    for (int64_t n = 0; n < N; ++n) {
      bias[static_cast(n)] =
          0.125f + 0.5f * static_cast(n % 7) - 0.25f * static_cast(n % 11);
    }
  }

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      if (has_bias) {
        sum += bias[static_cast(n)];
      }
      expected_vals[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", static_cast(0));

  if constexpr (std::is_same::value) {
    test.AddInput("A", {M, K}, input0_fp32_vals, false);
  }

  int64_t k_blocks = (K + block_size - 1) / block_size;
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);

  if constexpr (std::is_same::value) {
    test.AddInput("scales", {N, static_cast(q_scale_size) / N}, scales, true);
  }

  if (has_zero_point) {
    test.AddInput("zero_points", {N, static_cast(q_zp_size_in_bytes) / N}, zp, true);
  } else {
    test.AddOptionalInputEdge();
  }

  test.AddOptionalInputEdge();

  if (has_bias) {
    if constexpr (std::is_same::value) {
      test.AddInput("bias", {N}, bias, true);
    } else {
      test.AddOptionalInputEdge();
    }
  } else {
    test.AddOptionalInputEdge();
  }

  if constexpr (std::is_same::value) {
    test.AddOutput("Y", {M, N}, expected_vals);
  }

  test.SetOutputAbsErr("Y", abs_error);
  test.SetOutputRelErr("Y", rel_error);

  SessionOptions so;
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1"));

  test.Config(so)
      .ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_128x128) {
  TestMatMul2BitsLutGemm(1, 128, 128, 32, false);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_128x128) {
  TestMatMul2BitsLutGemm(1, 128, 128, 32, true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_256x256) {
  TestMatMul2BitsLutGemm(1, 256, 256, 32, false);
}

// This test was previously disabled due to accuracy issues related to non-deterministic
// gather operations. It is now re-enabled after replacing gather with deterministic
// load+shuffle operations to improve determinism and stability.
TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_256x256) {
  TestMatMul2BitsLutGemm(1, 256, 256, 32, true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_256x256_BlkLen64) {
  TestMatMul2BitsLutGemm(1, 256, 256, 64, false);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_256x256_BlkLen64) {
  TestMatMul2BitsLutGemm(1, 256, 256, 64, true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_128x256_BlkLen128) {
  TestMatMul2BitsLutGemm(1, 128, 256, 128, false);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_128x256_BlkLen128) {
  TestMatMul2BitsLutGemm(1, 128, 256, 128, true);
}

// Batch tests (M > 1)
TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_Batch32_128x128) {
  TestMatMul2BitsLutGemm(32, 128, 128, 32, false);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_Batch32_256x256) {
  TestMatMul2BitsLutGemm(32, 256, 256, 32, true);
}

// Fused-bias tests — verify the Bias parameter to MlasLutGemm is broadcast-added correctly.
// These are the regression tests for the bug where the LUT path silently dropped the optional
// `bias` input of MatMulNBits.
TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_128x128_Bias) {
  TestMatMul2BitsLutGemm(1, 128, 128, 32, /*has_zero_point=*/false, /*has_bias=*/true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_128x128_Bias) {
  TestMatMul2BitsLutGemm(1, 128, 128, 32, /*has_zero_point=*/true, /*has_bias=*/true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_256x256_BlkLen64_Bias) {
  TestMatMul2BitsLutGemm(1, 256, 256, 64, /*has_zero_point=*/false, /*has_bias=*/true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_256x256_BlkLen64_Bias) {
  TestMatMul2BitsLutGemm(1, 256, 256, 64, /*has_zero_point=*/true, /*has_bias=*/true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_128x256_BlkLen128_Bias) {
  TestMatMul2BitsLutGemm(1, 128, 256, 128, /*has_zero_point=*/true, /*has_bias=*/true);
}

// Batched (M>1) bias tests — exercise the per-row bias broadcast across many activation rows.
TEST(MatMulNBitsLutGemm, Float32_2Bits_Symmetric_Batch32_128x128_Bias) {
  TestMatMul2BitsLutGemm(32, 128, 128, 32, /*has_zero_point=*/false, /*has_bias=*/true);
}

TEST(MatMulNBitsLutGemm, Float32_2Bits_Asymmetric_Batch32_256x256_Bias) {
  TestMatMul2BitsLutGemm(32, 256, 256, 32, /*has_zero_point=*/true, /*has_bias=*/true);
}

// Regression test for the LUT GEMM pre-pack + prepacked-save path. A 2-bit MatMulNBits node pre-packed
// via the LUT path must record its packed B buffer exactly once. A prior bug appended packed_b_ twice
// on the LUT path (inside the LUT branch and again in the shared append at the end of the B block), so
// the second entry was a moved-from/null buffer paired with a non-zero packed_b_size_. The pre-packed
// content hash skips null buffers, so cross-session sharing appeared to work, but saving pre-packed
// initializers iterates every recorded buffer and writes buffer_sizes_[i] bytes from buffers_[i].get(),
// dereferencing the null pointer when mlas.use_lut_gemm=1. This drives mlas.use_lut_gemm=1 together with
// session.save_external_prepacked_constant_initializers=1 and a non-empty optimized_model_filepath, and
// asserts that initialization (which performs the save) and a subsequent run both succeed.
TEST(MatMulNBitsLutGemm, Float32_2Bits_PrepackSaveDoesNotCrash) {
  constexpr int64_t M = 1, N = 128, K = 128, block_size = 32;
  if (!MlasIsLutGemmAvailable(static_cast(N), static_cast(K), 2, static_cast(block_size))) {
    GTEST_SKIP() << "LUT GEMM not available on this platform";
  }

  // Quantize random weights into valid 2-bit MatMulNBits B/scales/zero_points initializers.
  RandomValueGenerator random{1234};
  std::vector b_fp32(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows = 0, q_cols = 0;
  MlasBlockwiseQuantizedShape(static_cast(block_size), /*columnwise*/ true,
                                            static_cast(K), static_cast(N), q_rows, q_cols);
  size_t q_data_size_in_bytes = 0, q_scale_size = 0, q_zp_size_in_bytes = 0;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), /*columnwise*/ true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector b_data(q_data_size_in_bytes);
  std::vector scales(q_scale_size);
  std::vector zp(q_zp_size_in_bytes);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();
  MlasQuantizeBlockwise(b_data.data(), scales.data(), zp.data(), b_fp32.data(),
                                      static_cast(block_size), /*columnwise*/ true,
                                      static_cast(K), static_cast(N),
                                      static_cast(N), tp);

  // Single-node MatMulNBits model: A is a runtime input; B/scales/zero_points are constant initializers
  // (so they are pre-packed at session initialization).
  const int64_t k_blocks = (K + block_size - 1) / block_size;
  const std::unordered_map domain_to_version{{"", 21}, {kMSDomain, 1}};
  Model model("matmul_2bits_lut_prepack_save", false, ModelMetaData(), PathString(),
              IOnnxRuntimeOpSchemaRegistryList(), domain_to_version,
              std::vector(), DefaultLoggingManager().DefaultLogger());
  Graph& graph = model.MainGraph();
  ModelTestBuilder builder(graph);

  ONNX_NAMESPACE::TypeProto float_2d;
  float_2d.mutable_tensor_type()->set_elem_type(utils::ToTensorProtoElementType());
  float_2d.mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(M);
  float_2d.mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(K);
  NodeArg* A = &graph.GetOrCreateNodeArg("A", &float_2d);
  NodeArg* Y = &graph.GetOrCreateNodeArg("Y", nullptr);

  NodeArg* B = builder.MakeInitializer(
      {static_cast(q_cols), k_blocks, static_cast(q_rows) / k_blocks}, b_data);
  NodeArg* scales_arg = builder.MakeInitializer({N, static_cast(q_scale_size) / N}, scales);
  NodeArg* zero_points =
      builder.MakeInitializer({N, static_cast(q_zp_size_in_bytes) / N}, zp);

  Node& node = builder.AddNode("MatMulNBits", {A, B, scales_arg, zero_points}, {Y}, 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));

  graph.SetOutputs(std::vector{Y});
  ASSERT_STATUS_OK(graph.Resolve());

  std::string model_bytes;
  ASSERT_TRUE(model.ToProto().SerializeToString(&model_bytes));

  // Save the optimized model + pre-packed initializers into a unique temp dir. Writing the prepacked
  // initializers is the path that dereferenced the duplicate null buffer before the fix.
  namespace fs = std::filesystem;
  const fs::path tmp_dir = fs::temp_directory_path() / "ort_matmul2bits_lut_prepack_save_test";
  std::error_code ec;
  fs::remove_all(tmp_dir, ec);
  ASSERT_TRUE(fs::create_directories(tmp_dir, ec)) << ec.message();
  const fs::path optimized_model_path = tmp_dir / "optimized.onnx";

  SessionOptions so;
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1"));
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsSavePrePackedConstantInitializers, "1"));
  so.optimized_model_filepath = optimized_model_path.native();

  std::vector fetches;
  {
    InferenceSessionWrapper session{so, GetEnvironment()};
    ASSERT_STATUS_OK(session.Load(model_bytes.data(), static_cast(model_bytes.size())));
    // Initialization performs the LUT pre-pack and writes the optimized model with external
    // pre-packed initializers. Before the fix this dereferenced the duplicate null packed buffer.
    ASSERT_STATUS_OK(session.Initialize());

    auto cpu_allocator = TestCPUExecutionProvider()->CreatePreferredAllocators()[0];
    std::vector a_data = random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f);
    OrtValue a_value;
    CreateMLValue(cpu_allocator, AsSpan({M, K}), a_data, &a_value);
    NameMLValMap feeds{{"A", a_value}};

    ASSERT_STATUS_OK(session.Run(RunOptions{}, feeds, std::vector{"Y"}, &fetches));
  }

  ASSERT_EQ(fetches.size(), static_cast(1));
  EXPECT_TRUE(fs::exists(optimized_model_path));

  fs::remove_all(tmp_dir, ec);
}

// Float zero point tests — directed QAD scenario (zp=1.5)
void RunTest2BitsFloatZP(int64_t M, int64_t N, int64_t K, int64_t block_size, float zp_value) {
  RandomValueGenerator random{1234};
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);

  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  // Quantize symmetrically
  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  // Create float ZP: one per quantization group
  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(N * k_blocks, zp_value);

  // Dequantize with float ZP for reference
  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[n * k_blocks + blk];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[packed_idx] >> bit_offset) & 0x3;
      input1_fp32_vals[n * K + k] = (static_cast(q) - zp_value) * scale;
    }
  }

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[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", static_cast(0));

  test.AddInput("A", {M, K}, input0_fp32_vals, false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, scales, true);
  test.AddInput("zero_points", {N, k_blocks}, float_zp, true);

  test.AddOutput("Y", {M, N}, expected_vals);
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  SessionOptions so;
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1"));

  test.Config(so)
      .ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

TEST(MatMul2Bits, Float32_2b_FloatZP_QAD) {
  if (!MlasIsLutGemmAvailable(128, 128, 2, 32)) {
    GTEST_SKIP() << "LUT GEMM not available on this platform";
  }
  // QAD scenario: zp=1.5 maps {0,1,2,3} to {-1, -1/3, 1/3, 1} * scale
  RunTest2BitsFloatZP(1, 128, 128, 32, 1.5f);
  RunTest2BitsFloatZP(1, 256, 256, 64, 1.5f);
  RunTest2BitsFloatZP(1, 128, 128, 32, 0.0f);
  RunTest2BitsFloatZP(1, 128, 128, 32, 2.0f);
  RunTest2BitsFloatZP(1, 128, 128, 32, 3.0f);
}

// Varying per-block float ZP — uses a unique ZP per (N, k_blocks) element so that
// packer layout/stride bugs in PackScalesAndZeroPoints become observable.
TEST(MatMul2Bits, Float32_2b_FloatZP_VaryingPerBlock) {
  const int64_t M = 1, N = 128, K = 128, block_size = 32;
  if (!MlasIsLutGemmAvailable(static_cast(N), static_cast(K), 2,
                              static_cast(block_size))) {
    GTEST_SKIP() << "LUT GEMM not available on this platform";
  }

  RandomValueGenerator random{1234};
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(static_cast(N * k_blocks));
  for (int64_t n = 0; n < N; n++) {
    for (int64_t blk = 0; blk < k_blocks; blk++) {
      // Strong variation in both dimensions so stride/transpose bugs are observable
      float_zp[static_cast(n * k_blocks + blk)] =
          0.25f + 0.5f * static_cast(blk) + 0.01f * static_cast(n % 17);
    }
  }

  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[static_cast(n * k_blocks + blk)];
      float zp = float_zp[static_cast(n * k_blocks + blk)];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[static_cast(packed_idx)] >> bit_offset) & 0x3;
      input1_fp32_vals[static_cast(n * K + k)] =
          (static_cast(q) - zp) * scale;
    }
  }

  std::vector expected_vals(static_cast(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 += input0_fp32_vals[static_cast(m * K + k)] *
               input1_fp32_vals[static_cast(n * K + k)];
      }
      expected_vals[static_cast(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", static_cast(0));

  test.AddInput("A", {M, K}, input0_fp32_vals, false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, scales, true);
  test.AddInput("zero_points", {N, k_blocks}, float_zp, true);

  test.AddOutput("Y", {M, N}, expected_vals);
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  SessionOptions so;
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1"));

  test.Config(so)
      .ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// Dynamic (non-constant) ZP test — verifies that the PrePack dynamic-ZP guard
// (prefer_lut_gemm_ && has_zp_arg_ && !has_zp_input_) correctly falls back to
// the unpacked dequant path instead of silently ignoring the zero points.
TEST(MatMul2Bits, Float32_2b_FloatZP_DynamicZP) {
  const int64_t M = 1, N = 128, K = 128, block_size = 32;
  if (!MlasIsLutGemmAvailable(static_cast(N), static_cast(K), 2,
                              static_cast(block_size))) {
    GTEST_SKIP() << "LUT GEMM not available on this platform";
  }

  RandomValueGenerator random{1234};
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(static_cast(N * k_blocks));
  for (int64_t n = 0; n < N; n++) {
    for (int64_t blk = 0; blk < k_blocks; blk++) {
      float_zp[static_cast(n * k_blocks + blk)] =
          0.25f + 0.5f * static_cast(blk) + 0.01f * static_cast(n % 17);
    }
  }

  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[static_cast(n * k_blocks + blk)];
      float zp = float_zp[static_cast(n * k_blocks + blk)];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[static_cast(packed_idx)] >> bit_offset) & 0x3;
      input1_fp32_vals[static_cast(n * K + k)] =
          (static_cast(q) - zp) * scale;
    }
  }

  std::vector expected_vals(static_cast(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 += input0_fp32_vals[static_cast(m * K + k)] *
               input1_fp32_vals[static_cast(n * K + k)];
      }
      expected_vals[static_cast(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", static_cast(0));

  test.AddInput("A", {M, K}, input0_fp32_vals, false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, scales, true);
  // is_initializer=false: ZP is a dynamic runtime input, not a constant
  test.AddInput("zero_points", {N, k_blocks}, float_zp, false);

  test.AddOutput("Y", {M, N}, expected_vals);
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  // LUT GEMM enabled, but ZP is dynamic — PrePack should skip LUT packing
  // and fall through to the unpacked dequant path at Compute() time.
  SessionOptions so;
  ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsMlasLutGemm, "1"));

  test.Config(so)
      .ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// Float ZP fallback test — exercises the non-LUT dequant path by NOT enabling the LUT session option
TEST(MatMul2Bits, Float32_2b_FloatZP_Fallback) {
  RandomValueGenerator random{1234};
  const int64_t M = 1, N = 32, K = 32, block_size = 16;
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  const float zp_value = 1.5f;
  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(N * k_blocks, zp_value);

  // Reference dequant with correct packed stride
  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[n * k_blocks + blk];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[packed_idx] >> bit_offset) & 0x3;
      input1_fp32_vals[n * K + k] = (static_cast(q) - zp_value) * scale;
    }
  }

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[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", static_cast(0));

  test.AddInput("A", {M, K}, input0_fp32_vals, false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, scales, true);
  test.AddInput("zero_points", {N, k_blocks}, float_zp, true);

  test.AddOutput("Y", {M, N}, expected_vals);
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  // No LUT session option — forces fallback dequant path
  test.ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// Non-aligned K fallback test — K=48 is not a multiple of block_size=32, exercises padded stride
TEST(MatMul2Bits, Float32_2b_FloatZP_Fallback_NonAlignedK) {
  RandomValueGenerator random{1234};
  const int64_t M = 1, N = 32, K = 48, block_size = 32;
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  const float zp_value = 1.5f;
  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(N * k_blocks, zp_value);

  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[n * k_blocks + blk];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[packed_idx] >> bit_offset) & 0x3;
      input1_fp32_vals[n * K + k] = (static_cast(q) - zp_value) * scale;
    }
  }

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[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", static_cast(0));

  test.AddInput("A", {M, K}, input0_fp32_vals, false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, scales, true);
  test.AddInput("zero_points", {N, k_blocks}, float_zp, true);

  test.AddOutput("Y", {M, N}, expected_vals);
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  test.ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// MLFloat16 activation + MLFloat16 zero point fallback test
// Exercises ComputeBUnpacked 2-bit fp16-ZP dequant path
TEST(MatMul2Bits, MLFloat16_2b_MLFloat16ZP_Fallback) {
  RandomValueGenerator random{1234};
  const int64_t M = 1, N = 32, K = 32, block_size = 16;
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), nullptr,
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  const float zp_value = 1.5f;
  int64_t k_blocks = (K + block_size - 1) / block_size;
  std::vector float_zp(N * k_blocks, zp_value);

  // Reference dequant with float ZP
  int64_t packed_k = k_blocks * block_size;
  int64_t bytes_per_col = packed_k / 4;
  for (int64_t n = 0; n < N; n++) {
    for (int64_t k = 0; k < K; k++) {
      int64_t blk = k / block_size;
      float scale = scales[n * k_blocks + blk];
      int64_t packed_idx = n * bytes_per_col + k / 4;
      int bit_offset = static_cast((k % 4) * 2);
      uint8_t q = (input1_vals[packed_idx] >> bit_offset) & 0x3;
      input1_fp32_vals[n * K + k] = (static_cast(q) - zp_value) * scale;
    }
  }

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[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", static_cast(0));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(input0_fp32_vals), false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, FloatsToMLFloat16s(scales), true);
  test.AddInput("zero_points", {N, k_blocks}, FloatsToMLFloat16s(float_zp), true);

  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(expected_vals));
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  // No LUT session option — forces fallback dequant path
  test.ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// MLFloat16 activation + uint8 zero point fallback test.
// Exercises the nbits_ == 2 arm of MatMulNBits::ComputeBUnpacked
// (MlasDequantizeBlockwise) for the uint8-ZP path.
TEST(MatMul2Bits, MLFloat16_2b_Uint8ZP_Fallback) {
  RandomValueGenerator random{1234};
  const int64_t M = 1, N = 32, K = 32, block_size = 16;
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);
  std::vector zero_points(q_zp_size_in_bytes);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), zero_points.data(),
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  // Reference dequant via MLAS (matches the kernel's MlasDequantizeBlockwise arm).
  MlasDequantizeBlockwise(
      input1_fp32_vals.data(), input1_vals.data(), scales.data(), zero_points.data(),
      static_cast(block_size), true,
      static_cast(K), static_cast(N), tp);

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[m * N + n] = sum;
    }
  }

  int64_t k_blocks = (K + block_size - 1) / block_size;

  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", static_cast(0));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(input0_fp32_vals), false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, FloatsToMLFloat16s(scales), true);
  test.AddInput("zero_points",
                         {N, static_cast(q_zp_size_in_bytes) / N}, zero_points, true);

  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(expected_vals));
  test.SetOutputAbsErr("Y", 0.1f);
  test.SetOutputRelErr("Y", 0.02f);

  test.ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

// MLFloat16 activation + Uint8 ZP with accuracy_level=4 -- exercises the native MLAS W2
// CompInt8 path with PrePack of constant scales/ZPs. On ARM64 with f16 intrinsics this
// goes through GetComputeType = HQNBIT_CompInt8 which redirects pack/compute
// through SQNBIT_CompInt8. The bug being guarded: the HQNBIT_CompInt8 PrePack branch
// originally only forwarded scales to the packer (zptr=nullptr), and the 3-call ZP
// follow-up was gated on compute_type_ == SQNBIT_CompInt8 (so it did not fire here).
// QuantBBlkSum then baked in the symmetric default ZP=2 for every block, giving wrong
// outputs whenever the model's real ZPs != 2. Shape: M=1, N=32, K=128, block_size=64
// (K%BlkLen==0, BlkLen in {32,64,128}); large/varied uint8 ZPs.
TEST(MatMul2Bits, MLFloat16_2b_Uint8ZP_Accuracy4) {
  RandomValueGenerator random{1234};
  const int64_t M = 1, N = 32, K = 128, block_size = 64;
  std::vector input0_fp32_vals(random.Gaussian(AsSpan({M, K}), 0.0f, 0.25f));
  std::vector input1_fp32_vals(random.Gaussian(AsSpan({K, N}), 0.0f, 0.25f));

  int q_rows, q_cols;
  MlasBlockwiseQuantizedShape(static_cast(block_size), true,
                                            static_cast(K), static_cast(N),
                                            q_rows, q_cols);
  size_t q_data_size_in_bytes, q_scale_size, q_zp_size_in_bytes;
  MlasBlockwiseQuantizedBufferSizes(static_cast(block_size), true,
                                           static_cast(K), static_cast(N),
                                           q_data_size_in_bytes, q_scale_size, &q_zp_size_in_bytes);

  std::vector input1_vals(q_data_size_in_bytes);
  std::vector scales(q_scale_size);
  std::vector zero_points(q_zp_size_in_bytes);

  auto& ortenv = **ort_env.get();
  onnxruntime::concurrency::ThreadPool* tp = ortenv.GetEnvironment().GetIntraOpThreadPool();

  MlasQuantizeBlockwise(
      input1_vals.data(), scales.data(), zero_points.data(),
      input1_fp32_vals.data(), static_cast(block_size),
      true, static_cast(K), static_cast(N),
      static_cast(N), tp);

  // Force non-symmetric ZPs so the bug actually surfaces. With all ZPs == 2 the
  // missing-ZP code path coincidentally produces correct results; varying ZPs
  // (1 / 2 / 3 packed two-per-byte) make the QuantBBlkSum correction non-trivial.
  for (size_t i = 0; i < zero_points.size(); ++i) {
    const uint8_t lo = static_cast(((i * 3) % 4));      // 0,3,2,1,0,3,...
    const uint8_t hi = static_cast(((i * 5 + 1) % 4));  // 1,2,3,0,1,2,...
    zero_points[i] = static_cast((hi << 4) | (lo & 0x0F));
  }

  // Reference dequant via MLAS using the same (varied) ZPs so the expected matmul
  // uses the same B values that the kernel sees post-pack.
  MlasDequantizeBlockwise(
      input1_fp32_vals.data(), input1_vals.data(), scales.data(), zero_points.data(),
      static_cast(block_size), true,
      static_cast(K), static_cast(N), tp);

  std::vector expected_vals(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 += input0_fp32_vals[m * K + k] * input1_fp32_vals[n * K + k];
      }
      expected_vals[m * N + n] = sum;
    }
  }

  int64_t k_blocks = (K + block_size - 1) / block_size;

  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", static_cast(4));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(input0_fp32_vals), false);
  test.AddInput("B", {q_cols, k_blocks, q_rows / k_blocks}, input1_vals, true);
  test.AddInput("scales", {N, k_blocks}, FloatsToMLFloat16s(scales), true);
  test.AddInput("zero_points",
                         {N, static_cast(q_zp_size_in_bytes) / N}, zero_points, true);

  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(expected_vals));
  test.SetOutputAbsErr("Y", 0.15f);
  test.SetOutputRelErr("Y", 0.03f);

  test.ConfigEp(DefaultCpuExecutionProvider())
      .RunWithConfig();
}

TEST(MatMul2Bits, Float32_2b_Accuracy0) {
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

TEST(MatMul2Bits, Float32_2b_Accuracy4) {
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

// NOTE on host-coverage of the new W2 op-level tests below.
// These tests run unconditionally on DefaultCpuExecutionProvider() and compute
// the expected output via dequant + matmul (see TestOptions2Bits / RunTest2Bits).
// The new native AVX-512(+VNNI) W2 kernel is dispatched only on hosts where
// GetMlasPlatform().Avx512Supported_ is true; on other hosts the op falls back
// to dequant + SGEMM and the same correctness check still passes. So these
// tests guard correctness everywhere and exercise the new SIMD path on
// AVX-512(+VNNI) CI machines and dev boxes.

// MatMulNBits operator-level coverage for the native AVX-512 W2 CPU kernel.
// The kernel is gated on (BlkBitWidth=2, BlkLen=64, ComputeType=SQNBIT_CompInt8)
// and is reachable through the public MatMulNBits op when accuracy_level=4 and
// block_size=64 (so the platform dispatcher picks the CompInt8 path on AVX-512
// hosts). On non-AVX-512 hosts the path is unavailable and the op falls back
// to LUT or scalar -- the OpTester correctness check still passes because the
// expected output is computed via dequantize-and-matmul.
//
// The K-values are chosen to exercise:
//   * Single block (BlockCountK=1)         -> K=64
//   * BlockCountK=2,3 not multiple of 4    -> K=128, K=192 (K-tail handler)
//   * Exact block-group multiples          -> K=256, K=512, K=1024
//   * BlockCountK=6 (1 full + 2 tail)      -> K=384  (non-aligned tail case)
// and combinations of M ∈ {1 (decode), 2, 4, 100 (prefill)} and
// N ∈ {16 (N-tail R1xC1/R2xC1), 32, 288, 1024 (kNCols4 multiples)}.
//
// TestMatMul2BitsTyped fans each shape out to 4 sub-tests: ±has_zero_point
// crossed with ±has_bias.
TEST(MatMul2Bits, Float32_2b_BlkLen64_Accuracy4) {
  // Single-block K (K = BlkLen = 64).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // BlockCountK=2,3 -- exercises K-tail handler (BlockCountK not a multiple
  // of kBlockGroupBlks=4).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // Exact block-group multiples (BlockCountK = 4, 8, 16; no K-tail).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // Realistic-shape proportion: BlockCountK=6 = 1 full block-group + 2-block tail.
  TestMatMul2BitsTyped();

  // Larger M (multiple R2 tile iterations) and representative K=1024.
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

// Same BlkLen=64 grid at accuracy_level=0. accuracy_level=0 lets the runtime
// pick the best path; for BlkBitWidth=2 + BlkLen=64 it still routes to the
// native W2 CompInt8 kernel on AVX-512 hosts. This catches any dispatch-table
// wiring bug that only manifests when accuracy_level isn't explicitly 4.
TEST(MatMul2Bits, Float32_2b_BlkLen64_Accuracy0) {
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

// MatMulNBits op-level coverage for the BlkLen=128 path. Same coverage matrix
// as the BlkLen=64 tests above, adjusted so that K is always a multiple of
// 128 (BlkLen=128 constraint). Exercises:
//   * Single-block K (BlockCountK=1)         -> K=128
//   * BlockCountK=2,3 not multiple of 4      -> K=256, K=384 (K-tail handler)
//   * Exact block-group multiples            -> K=512, K=1024, K=2048
//   * BlockCountK=6 (1 full + 2 tail)        -> K=768
// and the same M/N combinations as BlkLen=64.
TEST(MatMul2Bits, Float32_2b_BlkLen128_Accuracy4) {
  // Single-block K (K = BlkLen = 128).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // BlockCountK=2,3 -- exercises K-tail handler.
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // Exact block-group multiples (BlockCountK = 4, 8, 16).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // BlockCountK=6 = 1 full block-group + 2-block tail.
  TestMatMul2BitsTyped();

  // Larger M (multi-iter R2 tile) at representative-shape proportions.
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

TEST(MatMul2Bits, Float32_2b_BlkLen128_Accuracy0) {
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

// MatMulNBits op-level coverage for the BlkLen=32 path. K multiples of 32.
// Same coverage matrix as BlkLen=64/128 (single-block, K-tail, exact group
// multiples, representative-shape proportions, single-row decode, M=100 prefill).
TEST(MatMul2Bits, Float32_2b_BlkLen32_Accuracy4) {
  // Single-block K (K = BlkLen = 32).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // BlockCountK=2,3 -- K-tail handler (BlockCountK not a multiple of 4).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // Exact block-group multiples (BlockCountK = 4, 8, 16).
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  // BlockCountK=6 = 1 full block-group + 2-block tail.
  TestMatMul2BitsTyped();

  // Larger M.
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

TEST(MatMul2Bits, Float32_2b_BlkLen32_Accuracy0) {
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();

  TestMatMul2BitsTyped();
  TestMatMul2BitsTyped();
}

#if defined(USE_WEBGPU) && !defined(ORT_USE_EP_API_ADAPTERS)

namespace {

// Runs a 2-bit MatMulNBits test on WebGPU EP with CPU as baseline.
// The test quantizes random weights to 2 bits, dequantizes to compute
// expected output via matmul on CPU, then compares WebGPU output.
template 
void RunWebGpu2BitsTest(int64_t M, int64_t N, int64_t K, int64_t block_size,
                        bool has_zero_point, float abs_error = 0.1f, float rel_error = 0.02f) {
  TestOptions2Bits opts{};
  opts.M = M;
  opts.N = N;
  opts.K = K;
  opts.block_size = block_size;
  opts.has_zero_point = has_zero_point;
  opts.output_abs_error = abs_error;
  opts.output_rel_error = rel_error;

  RunTest2Bits(opts);
}

}  // namespace

// WebGPU 2-bit tests: symmetric (no zero points)
TEST(MatMul2BitsWebGpu, Float32_Symmetric_Small) {
  RunWebGpu2BitsTest(1, 32, 32, 16, false);
  RunWebGpu2BitsTest(1, 32, 32, 32, false);
  RunWebGpu2BitsTest(1, 32, 16, 16, false);
}

TEST(MatMul2BitsWebGpu, Float32_Symmetric_Medium) {
  RunWebGpu2BitsTest(1, 288, 16, 16, false);
  RunWebGpu2BitsTest(4, 32, 32, 16, false);
  RunWebGpu2BitsTest(4, 288, 16, 16, false);
  RunWebGpu2BitsTest(100, 32, 32, 16, false);
  RunWebGpu2BitsTest(100, 288, 16, 16, false);
}

// WebGPU 2-bit tests: asymmetric (with zero points) — the primary accuracy concern
TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_Small) {
  RunWebGpu2BitsTest(1, 1, 16, 16, true);
  RunWebGpu2BitsTest(1, 2, 16, 16, true);
  RunWebGpu2BitsTest(1, 32, 16, 16, true);
  RunWebGpu2BitsTest(1, 32, 32, 16, true);
  RunWebGpu2BitsTest(1, 32, 32, 32, true);
}

TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_Medium) {
  RunWebGpu2BitsTest(1, 288, 16, 16, true);
  RunWebGpu2BitsTest(4, 32, 32, 16, true);
  RunWebGpu2BitsTest(4, 288, 16, 16, true);
  RunWebGpu2BitsTest(100, 32, 32, 16, true);
  RunWebGpu2BitsTest(100, 288, 16, 16, true);
}

TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_BlockSize32) {
  // blockSize=32 triggers the Intel Gen12 optimized path on matching hardware.
  RunWebGpu2BitsTest(1, 32, 32, 32, true);
  RunWebGpu2BitsTest(4, 32, 32, 32, true);
  RunWebGpu2BitsTest(100, 32, 32, 32, true);
}

TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_BlockSize128) {
  RunWebGpu2BitsTest(1, 32, 16, 128, true);
  RunWebGpu2BitsTest(4, 32, 16, 128, true);
  RunWebGpu2BitsTest(100, 32, 16, 128, true);
}

// BlockSize=64 tests — covers nBlocksPerCol not a multiple of 4 (padding edge case).
// These match configurations found in real 2-bit quantized transformer models.
TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_BlockSize64) {
  RunWebGpu2BitsTest(1, 32, 64, 64, true);
  RunWebGpu2BitsTest(1, 32, 128, 64, true);
  RunWebGpu2BitsTest(1, 192, 384, 64, true, 0.3f, 0.05f);
  RunWebGpu2BitsTest(1, 384, 1024, 64, true, 0.5f, 0.05f);
}

TEST(MatMul2BitsWebGpu, Float32_Symmetric_BlockSize64) {
  RunWebGpu2BitsTest(1, 32, 64, 64, false);
  RunWebGpu2BitsTest(1, 32, 128, 64, false);
  RunWebGpu2BitsTest(1, 192, 384, 64, false, 0.3f, 0.05f);
}

// Larger K tests — exercises multi-word (multiple u32) extraction per block,
// verifying the Q2 nibble-spread and A-offset tracking across passes.
TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_LargerK) {
  RunWebGpu2BitsTest(1, 32, 64, 32, true);
  RunWebGpu2BitsTest(1, 32, 128, 32, true);
  RunWebGpu2BitsTest(1, 32, 256, 32, true, 0.3f, 0.05f);
}

// DP4A path tests (accuracy_level=4) — exercises the 1024-entry LUT / dequantization
// path for 2-bit weights with zero_points.
// DP4A constraints: accuracy_level==4, block_size%32==0, K%128==0, N%16==0.
// Skipped when the adapter lacks Subgroups support or is Apple (Metal),
// because the DP4A kernel would silently fall back to the default path.
TEST(MatMul2BitsWebGpu, Float32_ZeroPoint_DP4A) {
  // Ensure the WebGPU context is initialized so we can query adapter capabilities.
  auto ep = DefaultWebGpuExecutionProvider();
  if (!contrib::webgpu::HasDP4ADeviceSupport(ep->GetDeviceId())) {
    GTEST_SKIP() << "DP4A requires Subgroups support on a non-Apple adapter";
  }

  TestOptions2Bits opts{};
  opts.accuracy_level = 4;
  opts.has_zero_point = true;
  opts.output_abs_error = 0.1f;
  opts.output_rel_error = 0.02f;

  // M=1, N=16, K=128, block_size=32 — minimal DP4A-eligible shape
  opts.M = 1;
  opts.N = 16;
  opts.K = 128;
  opts.block_size = 32;
  RunTest2Bits(opts);

  // M=1, N=32, K=256, block_size=32 — larger K
  opts.M = 1;
  opts.N = 32;
  opts.K = 256;
  opts.block_size = 32;
  opts.output_abs_error = 0.3f;
  opts.output_rel_error = 0.05f;
  RunTest2Bits(opts);

  // M=4 (rows), N=32, K=128, block_size=32
  opts.M = 4;
  opts.N = 32;
  opts.K = 128;
  opts.block_size = 32;
  opts.output_abs_error = 0.1f;
  opts.output_rel_error = 0.02f;
  RunTest2Bits(opts);

  // M=1, N=16, K=128, block_size=128 — full-block
  opts.M = 1;
  opts.N = 16;
  opts.K = 128;
  opts.block_size = 128;
  RunTest2Bits(opts);
}

#endif  // defined(USE_WEBGPU) && !defined(ORT_USE_EP_API_ADAPTERS)

#ifdef USE_CUDA

namespace {

// The 2-bit CUDA kernels need at least Pascal-era half support; the GEMV path uses half2 FMA.
bool SkipIfNo2BitCudaDevice() {
  return !HasCudaEnvironment(530);
}

template 
void RunCuda2BitsShapes(int64_t block_size, float abs_error, float rel_error) {
  // M = 1 exercises the GEMV kernel, 3 the register-tiled small-M kernel with a partially filled
  // row tile, 8 a full row tile, and 128 the dequantize + cuBLAS fallback. N = 24 is not a multiple
  // of two warp tiles so it also covers the CtaN = 1 dispatch.
  constexpr int64_t kRows[] = {1, 3, 8, 128};
  constexpr int64_t kShapes[][2] = {{32, 256}, {64, 512}, {24, 1024}};
  for (int64_t m : kRows) {
    for (bool has_zero_point : {false, true}) {
      for (const auto& nk : kShapes) {
        TestOptions2Bits opts{};
        opts.M = m;
        opts.N = nk[0];
        opts.K = nk[1];
        opts.block_size = block_size;
        opts.has_zero_point = has_zero_point;
        opts.use_cuda = true;
        opts.output_abs_error = abs_error;
        opts.output_rel_error = rel_error;
        RunTest2Bits(opts);
      }
    }
  }
}

}  // namespace

TEST(MatMul2BitsCuda, Float16_BlkLen16) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(16, 0.1f, 0.02f);
}

TEST(MatMul2BitsCuda, Float16_BlkLen32) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(32, 0.1f, 0.02f);
}

TEST(MatMul2BitsCuda, Float16_BlkLen64) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(64, 0.1f, 0.02f);
}

TEST(MatMul2BitsCuda, Float16_BlkLen128) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(128, 0.1f, 0.02f);
}

TEST(MatMul2BitsCuda, Float16_BlkLen256) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(256, 0.1f, 0.02f);
}

TEST(MatMul2BitsCuda, Float32_BlkLen32) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(32, 0.05f, 0.01f);
}

TEST(MatMul2BitsCuda, Float32_BlkLen128) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  RunCuda2BitsShapes(128, 0.05f, 0.01f);
}

TEST(MatMul2BitsCuda, BFloat16_BlkLen128) {
  if (!CudaHasBF16Support()) GTEST_SKIP() << "CUDA device does not support BFloat16";
  RunCuda2BitsShapes(128, 0.3f, 0.05f);
}

// A K that is not a multiple of block_size forces the GEMV kernels to decline and the
// dequantize + cuBLAS fallback to handle the padded trailing block.
TEST(MatMul2BitsCuda, Float16_UnalignedK) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  for (int64_t m : {int64_t{1}, int64_t{4}, int64_t{64}}) {
    for (bool has_zero_point : {false, true}) {
      TestOptions2Bits opts{};
      opts.M = m;
      opts.N = 32;
      opts.K = 320;  // 2.5 blocks of 128
      opts.block_size = 128;
      opts.has_zero_point = has_zero_point;
      opts.use_cuda = true;
      opts.output_abs_error = 0.1f;
      opts.output_rel_error = 0.02f;
      RunTest2Bits(opts);
    }
  }
}

TEST(MatMul2BitsCuda, Float16_Bias) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  for (int64_t m : {int64_t{1}, int64_t{4}, int64_t{64}}) {
    TestOptions2Bits opts{};
    opts.M = m;
    opts.N = 32;
    opts.K = 512;
    opts.block_size = 128;
    opts.has_zero_point = true;
    opts.has_bias = true;
    opts.use_cuda = true;
    opts.output_abs_error = 0.1f;
    opts.output_rel_error = 0.02f;
    RunTest2Bits(opts);
  }
}

TEST(MatMul2BitsCuda, Float16_TypedZeroPointFallback) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  TestOptions2Bits opts{};
  opts.M = 128;
  opts.N = 32;
  opts.K = 256;
  opts.block_size = 128;
  opts.has_zero_point = true;
  opts.has_typed_zero_point = true;
  opts.use_cuda = true;
  opts.output_abs_error = 0.1f;
  opts.output_rel_error = 0.02f;
  RunTest2Bits(opts);
}

TEST(MatMul2BitsCuda, RejectsGroupIndex) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  TestOptions2Bits opts{};
  opts.M = 1;
  opts.N = 32;
  opts.K = 256;
  opts.block_size = 128;
  opts.has_g_idx = true;
  opts.use_cuda = true;
  opts.expected_failure = "does not support g_idx";
  RunTest2Bits(opts);
}

TEST(MatMul2BitsCuda, RejectsOversizedBlock) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";

  constexpr int64_t M = 1, N = 1, K = 512, block_size = 512;
  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", static_cast(QBits));
  test.AddAttribute("accuracy_level", static_cast(0));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(std::vector(M * K, 0.5f)), false);
  test.AddInput("B", {N, k_blocks, block_size / 4},
                         std::vector(static_cast(N * k_blocks * block_size / 4), 0x55), true);
  test.AddInput("scales", {N, k_blocks},
                           FloatsToMLFloat16s(std::vector(static_cast(N * k_blocks), 0.25f)), true);
  test.AddOptionalInputEdge();
  test.AddOptionalInputEdge();
  test.AddOptionalInputEdge();
  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(std::vector(M * N, 0.0f)));

  std::vector> execution_providers;
  execution_providers.emplace_back(DefaultCudaExecutionProvider());
  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.Config(OpTester::ExpectResult::kExpectFailure, "block_size must not exceed 256")
      .ConfigEps(std::move(execution_providers))
      .RunWithConfig();
}

TEST(MatMul2BitsCuda, ChunkedFallback) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";

  ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{
      {"ORT_MATMULNBITS_FORCE_CHUNKED", "1"},
      {"ORT_MATMULNBITS_CHUNK_SIZE", "64"}}};

  for (bool has_zero_point : {false, true}) {
    TestOptions2Bits opts{};
    opts.M = 2;
    opts.N = 130;
    opts.K = 384;
    opts.block_size = 128;
    opts.has_zero_point = has_zero_point;
    opts.use_cuda = true;
    opts.output_abs_error = 0.1f;
    opts.output_rel_error = 0.02f;
    RunTest2Bits(opts);
  }
}

namespace {

// End-to-end cover for the CUTLASS weight-only (fpA_intB) 2-bit path. This is the only test that
// exercises the offline weight transform -- LDSM row permutation (kPerm_W2_A16), sub-byte
// transpose, 8-column interleave and the [e0,e2,..,e14,e1,e3,..,e15] pair-interleave -- against an
// independent dequantize + matmul reference, so a wrong permutation shows up here and nowhere else.
// M = 1 takes the fused GEMV, M = 32 the CUTLASS GEMM. N must be a multiple of 128 for 2 bits.
template 
void RunFpAIntB2BitsShapes(int64_t block_size, float abs_error, float rel_error) {
  for (int64_t m : {int64_t{1}, int64_t{32}}) {
    for (bool has_zero_point : {false, true}) {
      for (const auto& nk : {std::pair{128, 1024},
                             std::pair{256, 2048}}) {
        TestOptions2Bits opts{};
        opts.M = m;
        opts.N = nk.first;
        opts.K = nk.second;
        opts.block_size = block_size;
        opts.has_zero_point = has_zero_point;
        opts.use_cuda = true;
        opts.output_abs_error = abs_error;
        opts.output_rel_error = rel_error;
        RunTest2Bits(opts);
      }
    }
  }
}

}  // namespace

TEST(MatMul2BitsCuda, Float16_FpAIntB) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}};
  for (int64_t block_size : {int64_t{64}, int64_t{128}}) {
    RunFpAIntB2BitsShapes(block_size, 0.1f, 0.02f);
  }
}

TEST(MatMul2BitsCuda, BFloat16_FpAIntB) {
  if (!CudaHasBF16Support()) GTEST_SKIP() << "CUDA device does not support BFloat16";
  ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}};
  for (int64_t block_size : {int64_t{64}, int64_t{128}}) {
    RunFpAIntB2BitsShapes(block_size, 0.3f, 0.05f);
  }
}

// Cover production N/K at small M and the large-M GEMM route with bounded reference work.
TEST(MatMul2BitsCuda, Float16_FpAIntB_ProductionShape) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  ScopedEnvironmentVariables scoped_env_vars{EnvVarMap{{"ORT_FPA_INTB_GEMM", "1"}}};
  for (int64_t m : {int64_t{1}, int64_t{8}}) {
    TestOptions2Bits opts{};
    opts.M = m;
    opts.N = 10240;
    opts.K = 5120;
    opts.block_size = 128;
    opts.has_zero_point = true;
    opts.use_cuda = true;
    opts.output_abs_error = 0.2f;
    opts.output_rel_error = 0.02f;
    RunTest2Bits(opts);
  }

  TestOptions2Bits opts{};
  opts.M = 512;
  opts.N = 128;
  opts.K = 1024;
  opts.block_size = 128;
  opts.has_zero_point = true;
  opts.use_cuda = true;
  opts.output_abs_error = 0.2f;
  opts.output_rel_error = 0.02f;
  RunTest2Bits(opts);
}

namespace {

// Ternary weights {-1, 0, +1} map exactly onto the affine 2-bit ABI as codes {0, 1, 2} with a
// uniform zero point of 1. MlasQuantizeBlockwise never emits that subset, so the node is built by
// hand here and checked against an exact float reference; every quantity is chosen to be
// representable in fp16 so the only error left is accumulation order.
void RunTernary2BitsCudaTest(int64_t M, int64_t N, int64_t K, int64_t block_size,
                             float abs_error = 0.05f, float rel_error = 0.01f) {
  SCOPED_TRACE("ternary M:" + std::to_string(M) + " N:" + std::to_string(N) +
               " K:" + std::to_string(K) + " block_size:" + std::to_string(block_size));
  ASSERT_EQ(K % block_size, 0) << "this helper assumes an aligned K";

  const int64_t k_blocks = K / block_size;
  const int64_t blob_size = block_size / 4;
  const int64_t zp_bytes = (k_blocks * 2 + 7) / 8;

  // Codes cycle through {0, 1, 2} with a stride that is co-prime with the block size so every
  // block sees all three symbols; code 3 never appears, as in a real ternary checkpoint.
  std::vector b_packed(static_cast(N * k_blocks * blob_size), 0);
  std::vector ternary(static_cast(N * K));
  for (int64_t n = 0; n < N; ++n) {
    for (int64_t k = 0; k < K; ++k) {
      const uint8_t code = static_cast((7 * n + 3 * k + (k / 5)) % 3);
      ternary[static_cast(n * K + k)] = static_cast(static_cast(code) - 1);
      const size_t byte_index = static_cast(n * K + k) / 4;
      b_packed[byte_index] |= static_cast(code << (2 * (k % 4)));
    }
  }

  // Powers of two are exact in fp16, so dequantization introduces no error at all.
  constexpr float kScaleTable[] = {0.0625f, 0.03125f, 0.015625f};
  std::vector scales(static_cast(N * k_blocks));
  for (size_t i = 0; i < scales.size(); ++i) {
    scales[i] = kScaleTable[i % 3];
  }

  // Every 2-bit crumb is 1: 0b01010101.
  std::vector zp(static_cast(N * zp_bytes), 0x55);

  // Multiples of 1/64 in [-1, 1) are exact in fp16. The values are zero-mean so the running dot
  // product stays small and fp16 accumulation error cannot masquerade as a kernel bug.
  uint32_t rng = 0x9E3779B9u;
  std::vector a_vals(static_cast(M * K));
  for (size_t i = 0; i < a_vals.size(); ++i) {
    rng = rng * 1664525u + 1013904223u;
    a_vals[i] = static_cast(static_cast((rng >> 16) & 0x7F) - 64) / 64.0f;
  }

  // Dequantize one output channel at a time and reuse it across all M rows: the naive
  // m/n/k triple loop costs an integer division per element and is unusably slow at the
  // 27B prefill shape (N = 10240, K = 5120).
  std::vector expected(static_cast(M * N));
  std::vector w_row(static_cast(K));
  for (int64_t n = 0; n < N; ++n) {
    for (int64_t kb = 0; kb < k_blocks; ++kb) {
      const float s = scales[static_cast(n * k_blocks + kb)];
      for (int64_t j = 0; j < block_size; ++j) {
        const int64_t k = kb * block_size + j;
        w_row[static_cast(k)] = static_cast(ternary[static_cast(n * K + k)]) * s;
      }
    }
    for (int64_t m = 0; m < M; ++m) {
      const float* a_row = a_vals.data() + static_cast(m * K);
      float sum = 0.0f;
      for (int64_t k = 0; k < K; ++k) {
        sum += a_row[k] * w_row[static_cast(k)];
      }
      expected[static_cast(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", static_cast(0));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(a_vals), false);
  test.AddInput("B", {N, k_blocks, blob_size}, b_packed, true);
  test.AddInput("scales", {N, k_blocks}, FloatsToMLFloat16s(scales), true);
  test.AddInput("zero_points", {N, zp_bytes}, zp, true);
  test.AddOptionalInputEdge();
  test.AddOptionalInputEdge();
  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(expected));
  test.SetOutputAbsErr("Y", abs_error);
  test.SetOutputRelErr("Y", rel_error);

  std::vector> execution_providers;
  execution_providers.emplace_back(DefaultCudaExecutionProvider());
  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.ConfigEps(std::move(execution_providers));
  test.RunWithConfig();
}

}  // namespace

TEST(MatMul2BitsCuda, TernaryZeroPointOne) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  for (int64_t block_size : {int64_t{16}, int64_t{32}, int64_t{64}, int64_t{128}}) {
    for (int64_t m : {int64_t{1}, int64_t{2}, int64_t{8}, int64_t{96}}) {
      RunTernary2BitsCudaTest(m, 32, 512, block_size);
    }
  }
  // The shape the ternary 27B model actually runs at decode time, trimmed to keep the test fast.
  RunTernary2BitsCudaTest(1, 512, 5120, 128, 0.2f, 0.02f);
}

// The qkv_proj of the ternary 27B model: N = 10240, K = 5120, block_size = 128. M >= 32 is
// past the small-M kernels and therefore exercises the dequantize-to-fp16 + cuBLAS fallback;
// M = 32 covers the fallback boundary, while M = 1 covers GEMV at the same shape.
TEST(MatMul2BitsCuda, TernaryPrefillQkvProjShape) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";
  for (int64_t m : {int64_t{1}, int64_t{32}}) {
    RunTernary2BitsCudaTest(m, 10240, 5120, 128, 0.2f, 0.02f);
  }
}

// Regression guard for the silent-corruption bug this support was built on top of: an
// unimplemented weight width used to be accepted by the shared validator, fall through to the
// 4-bit dequantize path, and return garbage. It must fail at session initialization instead.
TEST(MatMul2BitsCuda, UnsupportedBitWidthFailsLoudly) {
  if (SkipIfNo2BitCudaDevice()) GTEST_SKIP() << "No CUDA device with the required architecture";

  constexpr int64_t M = 1, N = 32, K = 256, block_size = 128;
  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", static_cast(3));
  test.AddAttribute("accuracy_level", static_cast(0));

  test.AddInput("A", {M, K}, FloatsToMLFloat16s(std::vector(M * K, 0.5f)), false);
  test.AddInput("B", {N, k_blocks, block_size * 3 / 8},
                         std::vector(static_cast(N * k_blocks * block_size * 3 / 8), 0x55), true);
  test.AddInput("scales", {N, k_blocks},
                           FloatsToMLFloat16s(std::vector(static_cast(N * k_blocks), 0.25f)), true);
  test.AddOptionalInputEdge();
  test.AddOptionalInputEdge();
  test.AddOptionalInputEdge();
  test.AddOutput("Y", {M, N}, FloatsToMLFloat16s(std::vector(M * N, 0.0f)));

  std::vector> execution_providers;
  execution_providers.emplace_back(DefaultCudaExecutionProvider());
  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.Config(OpTester::ExpectResult::kExpectFailure, "bits")
      .ConfigEps(std::move(execution_providers))
      .RunWithConfig();
}

#endif  // USE_CUDA

}  // namespace test
}  // namespace onnxruntime

#endif  // ORT_MINIMAL_BUILD