// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/common/safeint.h" #include "core/framework/op_kernel.h" #include "core/providers/cpu/math/matmul_helper.h" #include "core/providers/common.h" #include "core/providers/cpu/mlas_backend_kernel_selector_config_utils.h" #include "dequantize_blockwise_bnb4.h" #include "core/mlas/inc/mlas.h" namespace onnxruntime { namespace contrib { class MatMulBnb4 final : public OpKernel { public: MatMulBnb4(const OpKernelInfo& info) : OpKernel(info) { ORT_ENFORCE(Status::OK() == info.GetAttr("K", &K_)); ORT_ENFORCE(Status::OK() == info.GetAttr("N", &N_)); ORT_ENFORCE(Status::OK() == info.GetAttr("block_size", &block_size_)); ORT_ENFORCE(Status::OK() == info.GetAttr("quant_type", &quant_type_)); ORT_ENFORCE(K_ > 0, "K must be positive, got ", K_); ORT_ENFORCE(N_ > 0, "N must be positive, got ", N_); ORT_ENFORCE(block_size_ > 0, "block_size must be positive, got ", block_size_); ORT_ENFORCE( quant_type_ == FP4 || quant_type_ == NF4, "Invalid quant_type, only 0 (FP4) and 1 (NF4) are supported."); is_training_mode_ = static_cast(info.GetAttrOrDefault("training_mode", static_cast(0))); transB_ = static_cast(info.GetAttrOrDefault("transB", static_cast(1))); SetupMlasBackendKernelSelectorFromConfigOptions(mlas_backend_kernel_selector_config_, info.GetConfigOptions()); } Status Compute(OpKernelContext* context) const override; private: MLAS_BACKEND_KERNEL_SELECTOR_CONFIG mlas_backend_kernel_selector_config_; int64_t K_; int64_t N_; int64_t block_size_; int64_t quant_type_; bool is_training_mode_; bool transB_; }; Status MatMulBnb4::Compute(OpKernelContext* ctx) const { concurrency::ThreadPool* thread_pool = ctx->GetOperatorThreadPool(); const Tensor* a = ctx->Input(0); const Tensor* b_quant = ctx->Input(1); const Tensor* absmax = ctx->Input(2); const float* a_data = a->Data(); const uint8_t* b_quant_data = b_quant->Data(); const float* absmax_data = absmax->Data(); // Overflow-safe computation of expected tensor sizes. // K_, N_, block_size_ are validated > 0 in the constructor. if (K_ > std::numeric_limits::max() / N_) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Overflow computing K * N for K=", K_, ", N=", N_, "."); } const int64_t numel = K_ * N_; // Overflow-safe ceiling division: rewrite (a + b - 1) / b as ((a - 1) / b) + 1. // Safe because numel > 0 (K_ > 0 and N_ > 0 validated in constructor). const int64_t expected_b_quant_size = ((numel - 1) / 2) + 1; const int64_t expected_absmax_size = ((numel - 1) / block_size_) + 1; if (b_quant->Shape().Size() < expected_b_quant_size) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "b_quant tensor size (", b_quant->Shape().Size(), ") is too small for K=", K_, " and N=", N_, ". Expected at least ", expected_b_quant_size, " elements."); } if (absmax->Shape().Size() < expected_absmax_size) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "absmax tensor size (", absmax->Shape().Size(), ") is too small for K=", K_, ", N=", N_, ", block_size=", block_size_, ". Expected at least ", expected_absmax_size, " elements."); } AllocatorPtr allocator; auto status = ctx->GetTempSpaceAllocator(&allocator); ORT_RETURN_IF_ERROR(status); auto tmp_b_data_ptr = IAllocator::MakeUniquePtr(allocator, SafeInt(K_) * N_); DequantizeBlockwiseBnb4( tmp_b_data_ptr.get(), b_quant_data, absmax_data, static_cast(block_size_), static_cast(quant_type_), static_cast(N_), static_cast(K_), thread_pool); constexpr bool transa = false; const bool transb = transB_; TensorShape b_shape({N_, K_}); MatMulComputeHelper helper; ORT_RETURN_IF_ERROR(helper.Compute(a->Shape(), b_shape, transa, transb)); Tensor* y = ctx->Output(0, helper.OutputShape()); // Bail out early if the output is going to be empty if (y->Shape().Size() == 0) return Status::OK(); auto* y_data = y->MutableData(); const size_t max_len = helper.OutputOffsets().size(); const size_t M = static_cast(helper.M()); const size_t N = static_cast(helper.N()); const size_t K = static_cast(helper.K()); const size_t lda = helper.Lda(transa); const size_t ldb = helper.Ldb(transb); // TODO: implement with native kernel std::vector data(max_len); for (size_t i = 0; i < max_len; i++) { data[i].BIsPacked = false; data[i].A = a_data + helper.LeftOffsets()[i]; data[i].lda = lda; data[i].B = tmp_b_data_ptr.get() + helper.RightOffsets()[i]; data[i].ldb = ldb; data[i].C = y_data + helper.OutputOffsets()[i]; data[i].ldc = N; data[i].alpha = 1.f; data[i].beta = 0.0f; } MlasGemmBatch(CblasNoTrans, CblasTrans, M, N, K, data.data(), max_len, thread_pool, &mlas_backend_kernel_selector_config_); return Status::OK(); } ONNX_OPERATOR_KERNEL_EX( MatMulBnb4, kMSDomain, 1, kCpuExecutionProvider, KernelDefBuilder() .TypeConstraint("T1", DataTypeImpl::GetTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()), MatMulBnb4); } // namespace contrib } // namespace onnxruntime