// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "contrib_ops/cuda/quantization/matmul_nbits.h" #include #include #include #include #include "core/common/status.h" #include "core/common/float16.h" #include "core/providers/cpu/math/matmul_helper.h" #include "core/providers/cuda/cuda_type_conversion.h" #include "contrib_ops/cuda/utils/dump_cuda_tensor.h" #include "contrib_ops/cpu/utils/dump_tensor.h" #include "contrib_ops/cuda/quantization/matmul_nbits.cuh" #include "contrib_ops/cuda/quantization/dequantize_blockwise.cuh" #if USE_FPA_INTB_GEMM #include "contrib_ops/cuda/llm/fpA_intB_gemm/fpA_intB_gemm.h" #include "contrib_ops/cuda/llm/fpA_intB_gemm_adaptor.h" #include "contrib_ops/cuda/llm/fpA_intB_gemm_preprocessors.h" #include "contrib_ops/cuda/llm/common/cuda_runtime_utils.h" #include "contrib_ops/cuda/quantization/matmul_nbits_sm90_validation.h" #endif #include "contrib_ops/cuda/llm/common/logger.h" #include "contrib_ops/cpu/quantization/matmul_nbits_helper.h" constexpr int MatMulNBits_Input_B = 1; constexpr int MatMulNBits_Input_Scale = 2; constexpr int MatMulNBits_Input_ZeroPoint = 3; namespace onnxruntime { namespace contrib { namespace cuda { using namespace onnxruntime::cuda; namespace { Status ValidateGroupIndexRange(const Tensor* group_index, int64_t k_blocks, cudaStream_t stream) { if (group_index == nullptr) { return Status::OK(); } const size_t g_idx_size = static_cast(group_index->Shape().Size()); const int32_t* g_idx_data = group_index->Data(); std::vector g_idx_host; if (group_index->Location().device.Type() != OrtDevice::CPU) { cudaStreamCaptureStatus capture_status{}; CUDA_RETURN_IF_ERROR(cudaStreamIsCapturing(stream, &capture_status)); ORT_RETURN_IF_NOT(capture_status == cudaStreamCaptureStatusNone, "MatMulNBits group_index validation cannot run during CUDA graph capture; " "constant initializers require one warmup inference before capture, and runtime group_index " "inputs are not supported during capture."); g_idx_host.resize(g_idx_size); CUDA_RETURN_IF_ERROR(cudaMemcpyAsync(g_idx_host.data(), g_idx_data, g_idx_size * sizeof(int32_t), cudaMemcpyDeviceToHost, stream)); CUDA_RETURN_IF_ERROR(cudaStreamSynchronize(stream)); g_idx_data = g_idx_host.data(); } for (size_t i = 0; i < g_idx_size; ++i) { if (g_idx_data[i] < 0 || g_idx_data[i] >= k_blocks) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "group_index value at index ", i, " is ", g_idx_data[i], ", which is out of valid range [0, ", k_blocks, ")"); } } return Status::OK(); } } // namespace template Status MatMulNBits::PrePack(const Tensor& tensor, int input_idx, AllocatorPtr alloc, /*out*/ bool& is_packed, /*out*/ PrePackedWeights* /*prepacked_weights*/) { is_packed = false; constexpr int kInputIndexGroupIndex = 4; if (input_idx == kInputIndexGroupIndex) { const int64_t k_blocks = K_ / block_size_ + (K_ % block_size_ != 0); ORT_RETURN_IF_ERROR(ValidateGroupIndexRange(&tensor, k_blocks, cudaStreamLegacy)); is_group_index_validated_.store(true, std::memory_order_release); return Status::OK(); } #if USE_FPA_INTB_GEMM if constexpr (std::is_same_v || std::is_same_v) { if (has_fpA_intB_gemm_) { cudaStream_t stream = cudaStreamLegacy; if (input_idx == MatMulNBits_Input_B) { ORT_RETURN_IF_ERROR(PrePack_B(tensor, alloc, stream, is_packed)); is_prepacked_weight_ = is_packed; } else if (input_idx == MatMulNBits_Input_Scale) { ORT_RETURN_IF_ERROR(PrePack_Scale(tensor, alloc, stream)); is_prepacked_scale_ = true; is_packed = true; } else if (input_idx == MatMulNBits_Input_ZeroPoint && has_zero_points_) { ORT_RETURN_IF_ERROR(PrePack_ZeroPoint(tensor, alloc, stream)); is_prepacked_zero_point_ = true; is_packed = true; } } } #else ORT_UNUSED_PARAMETER(alloc); #endif return Status::OK(); } #if USE_FPA_INTB_GEMM using onnxruntime::llm::kernels::weight_only::GemmPluginProfilerManager; using onnxruntime::llm::kernels::weight_only::WeightOnlyGroupwiseQuantGemmPluginProfiler; using onnxruntime::llm::kernels::weight_only::WeightTypeId; static GemmPluginProfilerManager s_profilerManager; constexpr auto kScaleAndZeros = cutlass::WeightOnlyQuantOp::FINEGRAINED_SCALE_AND_ZEROS; constexpr auto kScaleOnly = cutlass::WeightOnlyQuantOp::FINEGRAINED_SCALE_ONLY; // Single source of truth for the fpA_intB / CUTLASS weight-only-GEMM eligibility decision. See the // declaration in matmul_nbits.h. Kept in lockstep with the MatMulNBits constructor's path selection. bool CheckFpAIntBEligibility(int32_t input0_elem_type, int64_t N, int64_t K, int64_t nbits, int64_t block_size, int64_t weight_prepacked, bool has_zero_points, bool has_g_idx, bool has_bias, int device_sm, int fpa_intb_option) { #if USE_COMPACT_FPA_INTB_GEMM const bool dtype_ok = input0_elem_type == ONNX_NAMESPACE::TensorProto_DataType_FLOAT16 || input0_elem_type == ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16; #else ORT_UNUSED_PARAMETER(has_zero_points); ORT_UNUSED_PARAMETER(has_bias); // The fpA_intB path consumes FP16 or BF16 input A only. CUDA also registers an FP32 MatMulNBits // variant that must never be reported as fpA_intB-eligible. const bool dtype_ok = (input0_elem_type == ONNX_NAMESPACE::TensorProto_DataType_FLOAT16 || input0_elem_type == ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16); #endif if (!dtype_ok) { return false; } if (input0_elem_type == ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16 && device_sm < 80) { return false; } // A prepacked weight is already stored in the fpA_intB layout, so the path cannot be turned off // by the option; an unprepacked weight requires the option to be enabled. const bool prepacked = weight_prepacked != kMatMulNBitsWeightNotPrepacked; const bool enable_fpa_intb = prepacked || (fpa_intb_option != 0); if (!enable_fpa_intb) { return false; } // weight_prepacked must be one of the three known formats. if (weight_prepacked != kMatMulNBitsWeightNotPrepacked && weight_prepacked != kMatMulNBitsWeightPrepackedSm80 && weight_prepacked != kMatMulNBitsWeightPrepackedSm90) { return false; } #if USE_COMPACT_FPA_INTB_GEMM // 2-bit needs block_size >= 64 (one B fragment spans a whole 64-element K tile), so the // compact set carries block_size 64 for it where 4/8-bit carry 32. const bool base_ok = (nbits == 2 ? block_size == 64 : block_size == 32) && (nbits == 2 || nbits == 4 || nbits == 8) && !has_zero_points && !has_g_idx && !has_bias && weight_prepacked != kMatMulNBitsWeightPrepackedSm90 && N % (nbits == 8 ? 32 : (nbits == 4 ? 64 : 128)) == 0 && K % block_size == 0 && device_sm >= 75; #else // block_size in {32,64,128} already guarantees block_size != 0, so K % block_size is well-defined. // 2-bit shares the SM80 column-interleaved layout but has no native SM90 kernel, so the Hopper // prepacked layout is rejected for it below. const bool base_ok = (block_size == 32 || block_size == 64 || block_size == 128) && (nbits == 2 || nbits == 4 || nbits == 8) && !has_g_idx && N % (nbits == 8 ? 32 : (nbits == 4 ? 64 : 128)) == 0 && K % block_size == 0 && device_sm >= 75; #endif if (!base_ok) { return false; } // 2-bit weights have no native SM90 (Hopper) mixed-GEMM kernel; they always use the SM80 layout. if (nbits == 2 && weight_prepacked == kMatMulNBitsWeightPrepackedSm90) { return false; } // At 2 bits one B fragment (one ldsm.x4 per warp) spans a whole 64-element K tile and the GEMV // applies one scale to each thread's 64-element run, so a quantization group cannot be smaller // than 64. if (nbits == 2 && block_size < 64) { return false; } // The native SM90 (Hopper) prepacked layout requires an SM90 device and block_size 64 or 128. if (weight_prepacked == kMatMulNBitsWeightPrepackedSm90 && !(device_sm == 90 && (block_size == 64 || block_size == 128))) { return false; } return true; } std::optional ComputeMatMulNBitsLeadingDimProduct(gsl::span input_a_shape) { if (input_a_shape.empty()) { return std::nullopt; } // Establish a known-empty output before rejecting unknown dimensions or doing arithmetic. // This also avoids reporting overflow for a huge prefix whose later leading dimension is zero. for (size_t i = 0; i + 1 < input_a_shape.size(); ++i) { if (input_a_shape[i] == 0) { return 0; } } SafeInt m(1); try { for (size_t i = 0; i + 1 < input_a_shape.size(); ++i) { if (input_a_shape[i] < 0) { return std::nullopt; } m *= input_a_shape[i]; } } catch (const OnnxRuntimeException&) { return std::nullopt; } return static_cast(m); } // Product of all leading (non-K) dimensions of input A, i.e. the GEMM "m". Returns nullopt when the // shape is missing or any non-zero leading dimension is not statically known. static std::optional StaticLeadingDimProduct(const NodeArg* input_a) { if (input_a == nullptr) { return std::nullopt; } const ONNX_NAMESPACE::TensorShapeProto* shape = input_a->Shape(); if (shape == nullptr || shape->dim_size() < 1) { return std::nullopt; } TensorShapeVector dimensions; dimensions.reserve(static_cast(shape->dim_size())); for (const auto& dimension : shape->dim()) { if (!dimension.has_dim_value()) { dimensions.push_back(-1); } else { dimensions.push_back(dimension.dim_value()); } } return ComputeMatMulNBitsLeadingDimProduct(dimensions); } static std::optional EstimateMatMulNBitsMemoryImpl( const Node& node, const cudaDeviceProp& device_prop, std::optional m, MatMulNBitsMemoryEstimateOptions options) { auto get_attr = [&node](const std::string& name, int64_t default_value) -> int64_t { // Iterate rather than use attrs.find(): in the provider-bridge (shared library) build, // NodeAttributes exposes bridged iterators (IteratorHolder) that do not support find()/ // operator== or iter->second, but range iteration with attr.first/attr.second works. This // matches how CUDAExecutionProvider reads node attributes elsewhere. const auto& attrs = node.GetAttributes(); for (const auto& attr : attrs) { if (attr.first == name) { return attr.second.i(); } } return default_value; }; const auto& input_defs = node.InputDefs(); if (input_defs.empty() || input_defs[0] == nullptr) { return std::nullopt; } const NodeArg* input_a = input_defs[0]; const auto* type_proto = input_a->TypeAsProto(); if (type_proto == nullptr || !type_proto->has_tensor_type()) { return std::nullopt; } const int32_t input0_elem_type = type_proto->tensor_type().elem_type(); const int64_t N = get_attr("N", 0); const int64_t K = get_attr("K", 0); const int64_t nbits = get_attr("bits", 0); const int64_t block_size = get_attr("block_size", 0); const int64_t weight_prepacked = get_attr("weight_prepacked", kMatMulNBitsWeightNotPrepacked); constexpr int kInputIndexGroupIndex = 4; constexpr int kInputIndexZeroPoints = 3; constexpr int kInputIndexBias = 5; const bool has_zero_points = input_defs.size() > kInputIndexZeroPoints && input_defs[kInputIndexZeroPoints] != nullptr && input_defs[kInputIndexZeroPoints]->Exists(); const bool has_g_idx = input_defs.size() > kInputIndexGroupIndex && input_defs[kInputIndexGroupIndex] != nullptr && input_defs[kInputIndexGroupIndex]->Exists(); const bool has_bias = input_defs.size() > kInputIndexBias && input_defs[kInputIndexBias] != nullptr && input_defs[kInputIndexBias]->Exists(); const int device_sm = device_prop.major * 10 + device_prop.minor; const std::string fpa_intb_gemm = options.fpa_intb_gemm.has_value() ? std::string{*options.fpa_intb_gemm} : ParseEnvironmentVariableWithDefault(kFpAIntBGemmOption, ""); const int fpa_intb_option = ParseFpAIntBEnabled(fpa_intb_gemm) ? 1 : 0; const bool fpa_intb_eligible = CheckFpAIntBEligibility( input0_elem_type, N, K, nbits, block_size, weight_prepacked, has_zero_points, has_g_idx, has_bias, device_sm, fpa_intb_option); if (!fpa_intb_eligible) { return std::nullopt; } auto estimate = ComputeMatMulNBitsPrepackMemoryEstimate( N, K, nbits, block_size, weight_prepacked, has_zero_points); if (!estimate.has_value()) { return std::nullopt; } try { const std::string profile_m_value = options.profile_m.has_value() ? std::string{*options.profile_m} : ParseEnvironmentVariableWithDefault( onnxruntime::llm::kernels::weight_only::kEnvProfileM, ""); const std::vector profile_m = WeightOnlyGroupwiseQuantGemmPluginProfiler::ParseProfileMList( profile_m_value); const int requested_constructor_profile_max_m = profile_m.empty() ? onnxruntime::llm::kernels::weight_only::kDefaultProfileMaxM : profile_m.back(); const int constructor_profile_max_m = onnxruntime::llm::kernels::weight_only::RoundUpProfileM( requested_constructor_profile_max_m, onnxruntime::llm::kernels::weight_only::kMaxProfileM); const int sm = EffectiveFpAIntBWorkspaceSm(device_sm, weight_prepacked); const int packing_ratio = onnxruntime::llm::kernels::weight_only::FP16_BITS / SafeInt(nbits); const int packed_n = SafeInt(N) / packing_ratio; const int original_n = packed_n * packing_ratio; const auto compute_profiler_scratch = [&](int profile_bucket_m) -> std::optional { const auto profiler_runner_workspace = onnxruntime::llm::kernels::cutlass_kernels::ComputeFpAIntBGemmWorkspaceSize( profile_bucket_m, original_n, SafeInt(K), sm, device_prop.multiProcessorCount); if (!profiler_runner_workspace.has_value()) { return std::nullopt; } return onnxruntime::llm::kernels::weight_only::ComputeWeightOnlyGemmProfilerScratchSize( profile_bucket_m, SafeInt(packed_n), SafeInt(K), SafeInt(nbits), SafeInt(block_size), *profiler_runner_workspace); }; const auto constructor_profile_scratch = compute_profiler_scratch(constructor_profile_max_m); if (!constructor_profile_scratch.has_value()) { return std::nullopt; } // Kernel construction profiling and PrePack_B conversion happen sequentially. estimate->initialization_scratch_bytes = std::max(estimate->initialization_scratch_bytes, *constructor_profile_scratch); if (m.has_value()) { estimate->runtime_workspace_bytes = onnxruntime::llm::kernels::cutlass_kernels::ComputeFpAIntBGemmWorkspaceSize( SafeInt(*m), original_n, SafeInt(K), sm, device_prop.multiProcessorCount); } std::optional lazy_profile_m; if (!m.has_value()) { // A dynamic M can request any rounded bucket at runtime. lazy_profile_m = onnxruntime::llm::kernels::weight_only::kMaxProfileM; } else if (*m > 0) { const auto initial_profile_m = WeightOnlyGroupwiseQuantGemmPluginProfiler::GetInitialProfileMBuckets( 1, constructor_profile_max_m, profile_m); if (options.input_shape_is_upper_bound) { const int maximum_runtime_profile_m = onnxruntime::llm::kernels::weight_only::RoundUpProfileM( SafeInt(*m), onnxruntime::llm::kernels::weight_only::kMaxProfileM); for (int candidate_m = 1; candidate_m <= maximum_runtime_profile_m; candidate_m *= 2) { if (std::find(initial_profile_m.begin(), initial_profile_m.end(), candidate_m) == initial_profile_m.end()) { lazy_profile_m = candidate_m; } if (candidate_m == maximum_runtime_profile_m) { break; } } } else { const int runtime_profile_m = onnxruntime::llm::kernels::weight_only::RoundUpProfileM( SafeInt(*m), onnxruntime::llm::kernels::weight_only::kMaxProfileM); const bool initially_profiled = std::find(initial_profile_m.begin(), initial_profile_m.end(), *m) != initial_profile_m.end() || std::find(initial_profile_m.begin(), initial_profile_m.end(), runtime_profile_m) != initial_profile_m.end(); if (!initially_profiled) { lazy_profile_m = runtime_profile_m; } } } if (lazy_profile_m.has_value()) { const auto lazy_profile_scratch = compute_profiler_scratch(*lazy_profile_m); if (!lazy_profile_scratch.has_value()) { return std::nullopt; } // Lazy profiling occurs during Run() before the ordinary GEMM. The two allocations do not // overlap, so the accountant peaks them rather than summing them. estimate->runtime_transient_bytes = *lazy_profile_scratch; } return estimate; } catch (const OnnxRuntimeException&) { // Treat invalid or overflowing model-derived sizes as not estimable. return std::nullopt; } } std::optional EstimateMatMulNBitsMemory( const Node& node, const cudaDeviceProp& device_prop, MatMulNBitsMemoryEstimateOptions options) { const auto& input_defs = node.InputDefs(); const NodeArg* input_a = input_defs.empty() ? nullptr : input_defs[0]; return EstimateMatMulNBitsMemoryImpl( node, device_prop, StaticLeadingDimProduct(input_a), options); } std::optional EstimateMatMulNBitsMemory( const Node& node, gsl::span input_a_shape, const cudaDeviceProp& device_prop, MatMulNBitsMemoryEstimateOptions options) { const auto& input_defs = node.InputDefs(); const NodeArg* input_a = input_defs.empty() ? nullptr : input_defs[0]; options.input_shape_is_upper_bound = options.input_shape_is_upper_bound && !StaticLeadingDimProduct(input_a).has_value(); return EstimateMatMulNBitsMemoryImpl( node, device_prop, ComputeMatMulNBitsLeadingDimProduct(input_a_shape), options); } std::optional EstimateMatMulNBitsWorkspace( const Node& node, const cudaDeviceProp& device_prop) { const auto estimate = EstimateMatMulNBitsMemory(node, device_prop); return estimate.has_value() ? estimate->runtime_workspace_bytes : std::nullopt; } std::optional EstimateMatMulNBitsWorkspace( const Node& node, gsl::span input_a_shape, const cudaDeviceProp& device_prop) { const auto estimate = EstimateMatMulNBitsMemory(node, input_a_shape, device_prop); return estimate.has_value() ? estimate->runtime_workspace_bytes : std::nullopt; } template int MatMulNBits::FpAIntBPackingSmForKernel() const { // Select the native SM90 (Hopper) mixed-weight layout only when the weights were prepacked for it // (weight_prepacked_ == 2) AND the device is SM90. Otherwise use the SM80 layout, which is also // used as the SM90 compatibility path for runtime-prepacked (or SM80-prepacked) weights. // // Delegates to the shared EffectiveFpAIntBWorkspaceSm() (matmul_nbits.h) so the compiler - not a // comment - enforces that this (Level 2 / runtime) and the Level-1 workspace estimate resolve the // effective arch identically. Both must stay a single expression. return EffectiveFpAIntBWorkspaceSm(sm_, weight_prepacked_); } template int64_t MatMulNBits::RequiredWeightPrepackedFormat() const { return FpAIntBPackingSmForKernel() == 90 ? kMatMulNBitsWeightPrepackedSm90 : kMatMulNBitsWeightPrepackedSm80; } // See matmul_nbits_sm90_validation.h for why these two functions are declared there but defined // here (non-inline, single definition, inside the CUDA EP translation unit that observes // COMPILE_HOPPER_TMA_GEMMS). bool IsNativeSm90FpAIntBGemmCompiled() { #if defined(COMPILE_HOPPER_TMA_GEMMS) && !defined(USE_COMPACT_FPA_INTB_GEMM) return true; #else return false; #endif } void ValidateSm90PrepackedWeightSupport(int sm, int64_t block_size) { // The native SM90 (Hopper TMA/WGMMA) mixed-GEMM kernel requires a compute-capability 9.0 // device and a block_size that is a multiple of the Hopper K tile (128 / sizeof(half) = 64). // block_size=32 is only supported by the non-Hopper kernel + GEMV path. ORT_ENFORCE(sm == 90, "weight_prepacked=2 (SM90 layout) requires a compute capability 9.0 (Hopper) device, but got sm ", sm); #if !defined(COMPILE_HOPPER_TMA_GEMMS) || defined(USE_COMPACT_FPA_INTB_GEMM) // The native SM90 (Hopper) fpA_intB TMA/WGMMA kernel is not compiled in this build (for // example Windows/MSVC, where CUDA 13 NVCC host stubs hit MSVC C2719 with over-aligned TMA // parameters; see docs/contrib_ops/cuda/moe_qmoe.md section 14.1). The SM90 weight layout // cannot be consumed by the SM80 kernel, so fail early here with a clear message instead of // dispatching to the throwing launcher stub during tactic profiling. ORT_THROW( "weight_prepacked=2 (SM90 layout) is not supported by this ONNX Runtime build " "(the native SM90 Hopper fpA_intB kernel is unavailable, e.g. on Windows/MSVC). " "Re-export the model with weight_prepacked=0 or 1 to use the SM80-compatible fpA_intB layout."); #endif ORT_ENFORCE(block_size == 64 || block_size == 128, "weight_prepacked=2 (SM90 layout) supports block_size 64 or 128 only, but got ", block_size); } template void MatMulNBits::InitGemmProfiler(int sm) { gemmProfiler_ = s_profilerManager.createGemmPluginProfiler(/*inference*/ false); using onnxruntime::llm::kernels::fpA_intB_gemv::KernelType; KernelType cuda_kernel_type; #if USE_COMPACT_FPA_INTB_GEMM if constexpr (std::is_same_v) { ORT_ENFORCE((nbits_ == 2 || nbits_ == 4 || nbits_ == 8) && block_size_ == (nbits_ == 2 ? 64 : 32) && !has_zero_points_ && !has_bias_); if (nbits_ == 8) { cuda_kernel_type = KernelType::FP16Int8Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { cuda_kernel_type = KernelType::FP16Int4Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } else { cuda_kernel_type = KernelType::FP16Int2Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } } else if constexpr (std::is_same_v) { ORT_ENFORCE((nbits_ == 2 || nbits_ == 4 || nbits_ == 8) && block_size_ == (nbits_ == 2 ? 64 : 32) && !has_zero_points_ && !has_bias_); if (nbits_ == 8) { cuda_kernel_type = KernelType::BF16Int8Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { cuda_kernel_type = KernelType::BF16Int4Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } else { cuda_kernel_type = KernelType::BF16Int2Groupwise; weightOnlyGemmRunner_ = std::make_shared>(); } } else { ORT_THROW("Compact fpA_intB GEMM only supports FP16/BF16 activations"); } #else if constexpr (std::is_same_v) { cuda_kernel_type = nbits_ == 8 ? KernelType::FP16Int8Groupwise : nbits_ == 4 ? KernelType::FP16Int4Groupwise : KernelType::FP16Int2Groupwise; if (has_zero_points_) { if (nbits_ == 8) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 2) { weightOnlyGemmRunner_ = std::make_shared>(); } } else { if (nbits_ == 8) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 2) { weightOnlyGemmRunner_ = std::make_shared>(); } } } else if constexpr (std::is_same_v) { cuda_kernel_type = nbits_ == 8 ? KernelType::BF16Int8Groupwise : nbits_ == 4 ? KernelType::BF16Int4Groupwise : KernelType::BF16Int2Groupwise; if (has_zero_points_) { if (nbits_ == 8) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 2) { weightOnlyGemmRunner_ = std::make_shared>(); } } else { if (nbits_ == 8) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 4) { weightOnlyGemmRunner_ = std::make_shared>(); } else if (nbits_ == 2) { weightOnlyGemmRunner_ = std::make_shared>(); } } } #endif // The half/bf16 weight-only path can run either the native Hopper (SM90 TMA/WGMMA) kernel or the // non-Hopper mixed-GEMM kernels. // - Native SM90 (sm == 90): keep the runner targeting SM90 so getConfigs() enumerates Hopper // tactics (tile_config_sm90) and getWorkspaceSize() reserves the stream-K workspace; opt in to // the native kernel via setUseSm90Native(true). // - Non-Hopper compact mode: target SM75 below Ampere, SM89 on Ada, and the SM80 compatibility // kernel otherwise. Full mode retains its existing device-specific selection, except that an // SM90 device using the SM80 weight layout is forced to the SM80 compatibility path. #if USE_COMPACT_FPA_INTB_GEMM const int runner_sm = sm_ < 80 ? sm_ : (sm_ == 89 ? 89 : 80); weightOnlyGemmRunner_->setArch(runner_sm); #else if (sm == 90) { weightOnlyGemmRunner_->setUseSm90Native(true); } else if (sm_ == 90) { weightOnlyGemmRunner_->setArch(sm); } #endif gemmProfiler_->setCudaKernelType(cuda_kernel_type, sm); gemmProfiler_->setWaveAwareGemv(wave_aware_gemv_); gemmProfiler_->setL2CacheBytes(static_cast(this->GetDeviceProp().l2CacheSize)); gemmProfiler_->setQuant(static_cast(nbits_), has_bias_, has_zero_points_); gemmProfiler_->setGroupSize(static_cast(block_size_)); auto allocator = this->Info().GetAllocator(OrtMemType::OrtMemTypeDefault); gemmProfiler_->setAllocator(allocator); } template void MatMulNBits::RunGemmProfile(bool hasWeightOnlyCudaKernel, int min_m, int max_m) { // Number of 16-bit elements after casting int2/int4/int8 to fp16. int n_16b = static_cast(N_ / (16 / nbits_)); // Include the packing/kernel SM in the GEMM id so the SM80-compatibility and native SM90 kernels // (which need different tactics) do not share profiled configs for the same (N, K, dtype). const int kernel_sm = FpAIntBPackingSmForKernel(); // The tag keeps profiled results with and without the optional paired-K tactic apart. const int tactic_set_tag = paired_gemv_mode_; if constexpr (std::is_same_v) { gemmId_ = GemmIdCore(n_16b, static_cast(K_), onnxruntime::llm::nvinfer::DataType::kHALF, kernel_sm, wave_aware_gemv_, tactic_set_tag); } else if constexpr (std::is_same_v) { gemmId_ = GemmIdCore(n_16b, static_cast(K_), onnxruntime::llm::nvinfer::DataType::kBF16, kernel_sm, wave_aware_gemv_, tactic_set_tag); } GemmDims dims = {min_m, max_m, n_16b, K_}; gemmProfiler_->profileTactics(weightOnlyGemmRunner_, gemmId_.dtype, dims, gemmId_, hasWeightOnlyCudaKernel); } template Status MatMulNBits::PrePack_B([[maybe_unused]] const Tensor& tensor, [[maybe_unused]] AllocatorPtr alloc, [[maybe_unused]] cudaStream_t stream, [[maybe_unused]] bool& is_packed) { if constexpr (std::is_same_v || std::is_same_v) { size_t n = static_cast(N_); size_t k = static_cast(K_); size_t packed_weight_bytes = n * k / (8 / nbits_); const uint8_t* blob_data = tensor.Data(); if (weight_prepacked_ != kMatMulNBitsWeightNotPrepacked) { ORT_ENFORCE(tensor.SizeInBytes() == packed_weight_bytes, "Prepacked MatMulNBits weight size mismatch. Expected ", packed_weight_bytes, " bytes, got ", tensor.SizeInBytes()); // Keep device-resident prepacked weights as the original input to avoid a second GPU copy. if (tensor.Location().device.Type() == OrtDevice::GPU) { is_packed = false; return Status::OK(); } fpA_intB_weight_buffer_ = IAllocator::MakeUniquePtr(alloc, packed_weight_bytes, true); int8_t* preprocessed_weight = reinterpret_cast(fpA_intB_weight_buffer_.get()); CUDA_RETURN_IF_ERROR(cudaMemcpyAsync(preprocessed_weight, blob_data, packed_weight_bytes, cudaMemcpyDefault, stream)); CUDA_RETURN_IF_ERROR(cudaStreamSynchronize(stream)); DUMP_TENSOR_INIT(); DUMP_TENSOR_D("preprocessed_weight", reinterpret_cast(preprocessed_weight), k, n * nbits_ / 8); is_packed = true; return Status::OK(); } // uint8 does not need to be packed so we do not need to allocate extra space. IAllocatorUniquePtr packed_transposed_weight_space = this->GetTransientScratchBuffer(packed_weight_bytes); int8_t* packed_transposed_weight = reinterpret_cast(packed_transposed_weight_space.get()); fpA_intB_weight_buffer_ = IAllocator::MakeUniquePtr(alloc, packed_weight_bytes, true); int8_t* preprocessed_weight = reinterpret_cast(fpA_intB_weight_buffer_.get()); if (nbits_ == 4) { // Transpose the weight and add default zero point. onnxruntime::llm::kernels::fpA_intB_gemv::unpack_uint4_transposed_to_int8_direct_cuda( stream, packed_transposed_weight, blob_data, static_cast(n), static_cast(k)); } else if (nbits_ == 2) { onnxruntime::llm::kernels::fpA_intB_gemv::unpack_uint2_transposed_to_int8_direct_cuda( stream, packed_transposed_weight, blob_data, static_cast(n), static_cast(k)); } else { onnxruntime::llm::kernels::fpA_intB_gemv::transpose_uint8_matrix_and_convert_to_int8( stream, packed_transposed_weight, blob_data, static_cast(n), static_cast(k)); } using onnxruntime::llm::kernels::weight_only::QuantType; QuantType quant_type = nbits_ == 4 ? QuantType::W4_A16 : (nbits_ == 2 ? QuantType::W2_A16 : QuantType::W8_A16); // The LDSM row-permutation tile is 8 * kInterleave rows: 16 for 8-bit, 32 for 4-bit, 64 for 2-bit. auto permutation_map_buffer = this->GetTransientScratchBuffer(64); onnxruntime::llm::kernels::weight_only::preprocess_weights_for_mixed_gemm_cuda( stream, FpAIntBPackingSmForKernel(), preprocessed_weight, packed_transposed_weight, permutation_map_buffer.get(), {static_cast(k), static_cast(n)}, quant_type); CUDA_RETURN_IF_ERROR(cudaStreamSynchronize(stream)); DUMP_TENSOR_INIT(); DUMP_TENSOR_D("packed transposed_weight in GPU", packed_transposed_weight, k, n * nbits_ / 8); DUMP_TENSOR_D("preprocessed_weight", reinterpret_cast(preprocessed_weight), k, n * nbits_ / 8); is_packed = true; } return Status::OK(); } template Status MatMulNBits::PrePack_Scale([[maybe_unused]] const Tensor& tensor, [[maybe_unused]] AllocatorPtr alloc, [[maybe_unused]] cudaStream_t stream) { if constexpr (std::is_same_v || std::is_same_v) { size_t n = static_cast(N_); size_t k = static_cast(K_); size_t k_blocks = (k + block_size_ - 1) / block_size_; size_t scale_bytes = n * k_blocks * sizeof(T); fpA_intB_scale_buffer_ = IAllocator::MakeUniquePtr(alloc, scale_bytes, true); // Transient buffer. typedef typename onnxruntime::cuda::OrtToCudaType::type CudaT; CudaT* transposed_scales = reinterpret_cast(fpA_intB_scale_buffer_.get()); onnxruntime::llm::kernels::fpA_intB_gemv::launch_transpose_scale_kernel( stream, reinterpret_cast(tensor.Data()), transposed_scales, static_cast(n), static_cast(k_blocks)); CUDA_RETURN_IF_ERROR(cudaStreamSynchronize(stream)); DUMP_TENSOR_INIT(); DUMP_TENSOR_D("transposed_scales", transposed_scales, static_cast(k_blocks), static_cast(n)); } return Status::OK(); } template Status MatMulNBits::PrePack_ZeroPoint([[maybe_unused]] const Tensor& tensor, [[maybe_unused]] AllocatorPtr alloc, [[maybe_unused]] cudaStream_t stream) { if constexpr (std::is_same_v || std::is_same_v) { size_t n = static_cast(N_); size_t k = static_cast(K_); size_t k_blocks = (k + block_size_ - 1) / block_size_; size_t scale_bytes = n * k_blocks * sizeof(T); typedef typename onnxruntime::cuda::OrtToCudaType::type CudaT; const CudaT* transposed_scales = reinterpret_cast(fpA_intB_scale_buffer_.get()); fpA_intB_zero_buffer_ = IAllocator::MakeUniquePtr(alloc, scale_bytes, true); // Transient buffer. CudaT* scaled_zero_points = reinterpret_cast(fpA_intB_zero_buffer_.get()); constexpr float kDefaultZeroPoint2Bit = 2.0f; constexpr float kDefaultZeroPoint4Bit = 8.0f; constexpr float kDefaultZeroPoint8Bit = 128.0f; const float default_zero_point = nbits_ == 4 ? kDefaultZeroPoint4Bit : (nbits_ == 2 ? kDefaultZeroPoint2Bit : kDefaultZeroPoint8Bit); const auto* zero_points_data = tensor.DataRaw(); // The scaled zero point will be zero for the default zero point, so there is no need to scale when it is nullptr. if (!tensor.IsDataType()) { // zero point is uint8_t type if (nbits_ == 4) { onnxruntime::llm::kernels::fpA_intB_gemv::launch_scaled_zero_point_kernel<4, CudaT, uint8_t>( stream, reinterpret_cast(zero_points_data), transposed_scales, scaled_zero_points, static_cast(n), static_cast(k_blocks), default_zero_point); } else if (nbits_ == 2) { onnxruntime::llm::kernels::fpA_intB_gemv::launch_scaled_zero_point_kernel<2, CudaT, uint8_t>( stream, reinterpret_cast(zero_points_data), transposed_scales, scaled_zero_points, static_cast(n), static_cast(k_blocks), default_zero_point); } else { onnxruntime::llm::kernels::fpA_intB_gemv::launch_scaled_zero_point_kernel<0, CudaT, uint8_t>( stream, reinterpret_cast(zero_points_data), transposed_scales, scaled_zero_points, static_cast(n), static_cast(k_blocks), default_zero_point); } } else { // zero point is not uint8_t type onnxruntime::llm::kernels::fpA_intB_gemv::launch_scaled_zero_point_kernel<0, CudaT, CudaT>( stream, reinterpret_cast(zero_points_data), transposed_scales, scaled_zero_points, static_cast(n), static_cast(k_blocks), default_zero_point); } CUDA_RETURN_IF_ERROR(cudaStreamSynchronize(stream)); DUMP_TENSOR_INIT(); DUMP_TENSOR_D("scaled_zero_points", scaled_zero_points, static_cast(k_blocks), static_cast(n)); } return Status::OK(); } #endif #if USE_FPA_INTB_GEMM && !defined(BUILD_CUDA_EP_AS_PLUGIN) // Level 2 (Phase-A memory roadmap, issue microsoft/onnxruntime#29775). Uses the constructed runner // state and effective arch from ComputeInternal(). The size is exact for its CUTLASS GEMM branch. // Runtime may instead select the CUDA GEMV tactic, which requests no workspace; in that case this is // a safe upper bound. Unknown/negative dimensions and arithmetic overflow use dynamic fallback. // The shared formula returns zero for empty output; a zero-sized requirement is omitted. template Status MatMulNBits::DeclareWorkspaceRequirements( gsl::span input_shapes, /*out*/ InlinedVector& requirements) const { requirements.clear(); if (!has_fpA_intB_gemm_ || weightOnlyGemmRunner_ == nullptr) { return Status::OK(); } // Input A is the only input needed for this estimate. Missing or unknown unrelated optional // inputs do not suppress declaration. const TensorShape* a_shape = GetWorkspaceInputShape(input_shapes, 0).GetShape(); if (a_shape == nullptr) { return Status::OK(); } // Input A is the same tensor as ctx->Input(0) in Compute(). m = product of all its dims except // the last (K), which comes from the kernel attribute and may remain unknown here. const std::optional m64 = ComputeMatMulNBitsLeadingDimProduct(a_shape->GetDims()); if (!m64.has_value()) { return Status::OK(); } // ComputeInternal sizes the workspace for one M chunk. const int64_t workspace_m = FpAIntBRowsPerLaunch(*m64); // Feed the SAME effective arch the runner resolved after setArch() - not the raw sm_ member. const int effective_sm = FpAIntBPackingSmForKernel(); std::optional ws; try { ws = onnxruntime::llm::kernels::cutlass_kernels::ComputeFpAIntBGemmWorkspaceSize( SafeInt(workspace_m), SafeInt(N_), SafeInt(K_), effective_sm, this->GetDeviceProp().multiProcessorCount); } catch (const OnnxRuntimeException&) { return Status::OK(); } if (!ws.has_value() || *ws == 0) { return Status::OK(); } requirements.push_back(WorkspaceRequirement{*ws, /*slot_id=*/0, /*alignment_bytes=*/0}); return Status::OK(); } #endif template Status MatMulNBits::ComputeInternal(OpKernelContext* ctx) const { #if USE_FPA_INTB_GEMM // TEST verification hook only. Record every invocation, including validation failures, empty // outputs, and GEMV/non-fpA_intB paths, so the value always describes the latest call. last_compute_workspace_bytes_.store(0, std::memory_order_relaxed); #endif if constexpr (std::is_same_v) { if (sm_ < 80) { return ORT_MAKE_STATUS(ONNXRUNTIME, NOT_IMPLEMENTED, "BFloat16 MatMulNBits is not supported on cuda device with compute capability < 8.0"); } } const Tensor* a = ctx->Input(0); const Tensor* reorder_idx = ctx->Input(4); const Tensor* bias = ctx->Input(5); #if USE_FPA_INTB_GEMM const Tensor* b = is_prepacked_weight_ ? nullptr : ctx->Input(1); const Tensor* scales = is_prepacked_scale_ ? nullptr : ctx->Input(2); const Tensor* zero_points = is_prepacked_zero_point_ ? nullptr : ctx->Input(3); const uint8_t* blob_data = is_prepacked_weight_ ? nullptr : b->Data(); const auto* scales_data = is_prepacked_scale_ ? nullptr : scales->Data(); const auto* zero_points_data = (is_prepacked_zero_point_ || zero_points == nullptr) ? nullptr : zero_points->DataRaw(); #else const Tensor* b = ctx->Input(1); const Tensor* scales = ctx->Input(2); const Tensor* zero_points = ctx->Input(3); const uint8_t* blob_data = b->Data(); const auto* scales_data = scales->Data(); const auto* zero_points_data = zero_points == nullptr ? nullptr : zero_points->DataRaw(); #endif const auto* bias_data = bias == nullptr ? nullptr : bias->Data(); ORT_RETURN_IF_ERROR(matmul_nbits_helper::CheckInputs( a, b, scales, zero_points, reorder_idx, bias, N_, K_, block_size_, nbits_)); ORT_RETURN_IF(nbits_ == 2 && reorder_idx != nullptr, "CUDA MatMulNBits does not support g_idx (reorder_idx) for 2-bit weights."); const auto* a_data = a->Data(); const auto* reorder_idx_data = reorder_idx == nullptr ? nullptr : reorder_idx->Data(); constexpr bool transa = false; constexpr bool transb = true; MatMulComputeHelper helper; TensorShape b_shape({N_, K_}); ORT_RETURN_IF_ERROR(helper.Compute(a->Shape(), b_shape, transa, transb)); Tensor* Y = ctx->Output(0, helper.OutputShape()); // Empty input (M == 0) produces an empty output; nothing reads the weights or g_idx. if (Y->Shape().Size() == 0) { return Status::OK(); } cudaStream_t stream = this->Stream(ctx); if (reorder_idx != nullptr) { const int64_t k_blocks = K_ / block_size_ + (K_ % block_size_ != 0); if (!group_index_is_initializer_) { ORT_RETURN_IF_ERROR(ValidateGroupIndexRange(reorder_idx, k_blocks, stream)); } else if (!is_group_index_validated_.load(std::memory_order_acquire)) { std::lock_guard lock(group_index_validation_mutex_); if (!is_group_index_validated_.load(std::memory_order_relaxed)) { ORT_RETURN_IF_ERROR(ValidateGroupIndexRange(reorder_idx, k_blocks, stream)); is_group_index_validated_.store(true, std::memory_order_release); } } } typedef typename onnxruntime::cuda::OrtToCudaType::type CudaT; int m = SafeInt(helper.M()); int n = SafeInt(helper.N()); int k = SafeInt(helper.K()); DUMP_TENSOR_INIT(); #if USE_FPA_INTB_GEMM CudaT* out_data = reinterpret_cast(Y->MutableData()); if constexpr (std::is_same::value || std::is_same::value) { if (has_fpA_intB_gemm_) { // We expect weight/scale/zero_point(optional) inputs are initializers and have been prepacked. // A non-prepacked node can opt out by setting session config ep.cuda.fpa_intb_gemm=0 (or env // ORT_FPA_INTB_GEMM=0) if those tensors cannot be prepacked (it is rare). const bool has_fpA_intB_weight = is_prepacked_weight_ || weight_prepacked_ != kMatMulNBitsWeightNotPrepacked; ORT_ENFORCE(has_fpA_intB_weight && is_prepacked_scale_ && (is_prepacked_zero_point_ || !has_zero_points_), "To use fpA_intB_gemm, prepacking must be done on weight, scale and zero point."); const void* fpA_intB_weight = is_prepacked_weight_ ? fpA_intB_weight_buffer_.get() : static_cast(blob_data); // During CUDA graph capture we must not lazily profile: profiling launches kernels, records // and synchronizes events, and allocates/frees scratch, all of which are illegal while the // compute stream is being captured. Fall back to a lookup of an already-profiled bucket // (warmup runs before capture populate these); only outside capture do we allow lazy // single-bucket profiling. Note: a null cudaStream_t is the default stream (a valid capture // target under per-thread default streams), so query the capture status unconditionally. const bool stream_is_capturing = onnxruntime::llm::common::isCapturing(stream); // Env-gated diagnostics (ORT_FPA_INTB_DEBUG=1): dump the selected tactic, the kernel path // (GEMV CUDA kernel vs CUTLASS GEMM), the weight format, and the device/packing SM so that // SM90 layout-selection issues can be traced. static const bool fpA_intB_debug = ParseEnvironmentVariableWithDefault("ORT_FPA_INTB_DEBUG", 0) != 0; using onnxruntime::llm::kernels::fpA_intB_gemv::KernelType; KernelType cuda_kernel_type; if constexpr (std::is_same::value) { cuda_kernel_type = nbits_ == 8 ? KernelType::FP16Int8Groupwise : nbits_ == 4 ? KernelType::FP16Int4Groupwise : KernelType::FP16Int2Groupwise; } else if constexpr (std::is_same::value) { cuda_kernel_type = nbits_ == 8 ? KernelType::BF16Int8Groupwise : nbits_ == 4 ? KernelType::BF16Int4Groupwise : KernelType::BF16Int2Groupwise; } // Rows of A are independent, so a large M runs as row chunks. The workspace and any lazily // profiled M bucket are then bounded by the chunk instead of the full M. const int chunk_m = static_cast(FpAIntBRowsPerLaunch(m)); decltype(gemmProfiler_->getBestConfig(m, gemmId_)) bestTactic; int tactic_m = 0; IAllocatorUniquePtr workspace_buffer; size_t workspace_size = 0; bool workspace_allocated = false; for (int row_start = 0; row_start < m; row_start += chunk_m) { const int rows = std::min(chunk_m, m - row_start); // Only a trailing partial chunk can change rows, so this looks up at most two tactics. if (rows != tactic_m) { bestTactic = stream_is_capturing ? gemmProfiler_->getBestConfig(rows, gemmId_) : gemmProfiler_->getBestConfigOrProfile(rows, gemmId_); if (!bestTactic.has_value()) { return ORT_MAKE_STATUS( ONNXRUNTIME, FAIL, "No valid fpA_intB MatMulNBits tactic for M=", rows, ", N=", n, ", K=", k, stream_is_capturing ? ". The M bucket was not profiled before CUDA graph capture; run a warmup inference outside capture first." : ""); } tactic_m = rows; if (fpA_intB_debug) { const char* weight_fmt = is_prepacked_weight_ ? "runtime-prepacked(SM80 layout)" : (weight_prepacked_ == kMatMulNBitsWeightPrepackedSm80 ? "offline-prepacked-SM80" : (weight_prepacked_ == kMatMulNBitsWeightPrepackedSm90 ? "offline-prepacked-SM90" : "raw")); std::cout << "[fpA_intB_debug] M=" << m << " chunk_M=" << rows << " N=" << n << " K=" << k << " nbits=" << nbits_ << " block_size=" << block_size_ << " device_sm=" << sm_ << " packing_sm=" << FpAIntBPackingSmForKernel() << " has_bias=" << (bias_data != nullptr ? 1 : 0) << " has_zero_points=" << (has_zero_points_ ? 1 : 0) << " weight_format=" << weight_fmt << " kernel=" << (bestTactic->enableCudaKernel ? "GEMV(cuda)" : (FpAIntBPackingSmForKernel() == 90 ? "CUTLASS(hopper gemm)" : "CUTLASS(non-hopper gemm)")) << " tactic=" << bestTactic->toString() << std::endl; } #if ORT_LLM_VERBOSE > 1 std::cout << "Best tactic for m=" << rows << ", n=" << n << ", k=" << k << "group_size=" << block_size_ << " is: " << bestTactic->toString() << std::endl; #endif } const T* chunk_a_data = a_data + static_cast(row_start) * static_cast(k); CudaT* chunk_out_data = out_data + static_cast(row_start) * static_cast(n); if (bestTactic->enableCudaKernel) { void const* pre_quant_scale_ptr = nullptr; bool apply_alpha_in_advance = false; float alpha = 1.0f; onnxruntime::llm::kernels::fpA_intB_gemv::Params params( chunk_a_data, pre_quant_scale_ptr, fpA_intB_weight, fpA_intB_scale_buffer_.get(), has_zero_points_ ? fpA_intB_zero_buffer_.get() : nullptr, bias_data, chunk_out_data, alpha, rows, n, k, static_cast(block_size_), cuda_kernel_type, apply_alpha_in_advance); params.paired_k = bestTactic->cudaKernelVariant == 1; params.wave_aware = wave_aware_gemv_; params.debug = fpA_intB_debug; // Launch the GEMV with the arch the weights were PACKED for (FpAIntBPackingSmForKernel), // not the raw device SM. The GEMV interleave layout is arch-dependent: arch in [90,100) // uses ColumnMajorInterleavedForHopper while the SM80 packing uses ColumnMajorInterleaved. // PrePack_B packs the SM80 layout, and the tactic profiler also profiles with the packing // arch, so passing the device SM (e.g. 90) here would read the SM80-packed weights with the // Hopper interleave and produce wrong results. onnxruntime::llm::kernels::fpA_intB_gemv::kernel_launcher(FpAIntBPackingSmForKernel(), params, stream); } else { if (!workspace_allocated) { // Sized for a full chunk; the workspace size is non-decreasing in M, so it also covers // a smaller trailing chunk. workspace_size = weightOnlyGemmRunner_->getWorkspaceSize(chunk_m, n, k); workspace_buffer = this->template GetScratchBuffer(workspace_size, this->GetComputeStream(ctx)); workspace_allocated = true; // TEST verification hook only. Relaxed ordering is sufficient: the pilot's single-threaded // tests only read this after the compute call has returned, so no cross-thread happens-before // relationship needs to be established here. last_compute_workspace_bytes_.store(workspace_size, std::memory_order_relaxed); } weightOnlyGemmRunner_->gemm( chunk_a_data, fpA_intB_weight, fpA_intB_scale_buffer_.get(), has_zero_points_ ? fpA_intB_zero_buffer_.get() : nullptr, bias_data, 1.f, chunk_out_data, rows, n, k, static_cast(block_size_), *bestTactic, reinterpret_cast(workspace_buffer.get()), workspace_size, stream); } } return Status::OK(); } } #endif if ((reorder_idx_data == nullptr) && (!zero_points || !zero_points->IsDataType())) { // First, try the fused fast path. It handles bias only for the GPT-OSS router GEMV // specialization; for other shapes it fails when bias is present. if (TryMatMulNBits( static_cast(nbits_), reinterpret_cast(Y->MutableData()), reinterpret_cast(a_data), blob_data, reinterpret_cast(scales_data), static_cast(zero_points_data), reinterpret_cast(bias_data), m, n, k, SafeInt(block_size_), GetDeviceProp().sharedMemPerBlock, stream, sm_)) { return Status::OK(); } // If bias prevented the fused path from running, retry the fast path without bias and // add the bias with a separate kernel. This keeps the lightweight GEMV path for cases // (e.g. 8-bit, or 4-bit non-router shapes) where only the bias was unsupported. if (bias_data != nullptr && TryMatMulNBits( static_cast(nbits_), reinterpret_cast(Y->MutableData()), reinterpret_cast(a_data), blob_data, reinterpret_cast(scales_data), static_cast(zero_points_data), /*bias_data*/ static_cast(nullptr), m, n, k, SafeInt(block_size_), GetDeviceProp().sharedMemPerBlock, stream, sm_)) { LaunchMatMulNBitsBiasAdd( reinterpret_cast(Y->MutableData()), reinterpret_cast(bias_data), m, n, stream); return Status::OK(); } } // When bias is present but the fused router GEMV specialization above did not apply, // fall back to the generic dequantize + GEMM path (which ignores bias) and add the // bias with a separate kernel after the GEMM completes. int64_t K_padded = (K_ + block_size_ - 1) / block_size_ * block_size_; // Chunked dequant+GEMM trades peak scratch memory for repeated kernel launches. // Thresholds: // 256 MB – scratch budget; above this the full N*K_padded buffer would dominate // device memory and risk OOM on consumer GPUs (8–12 GB). // N > 2*chunk_target_rows (default 65536) – ensures at least two chunks so the // overhead of per-chunk cuBLAS calls is amortised. // chunk_target_rows (default 32768) – chosen so that each dequant+GEMM tile is // large enough to saturate SMs while keeping scratch ≤ ~128 MB. // Only column-wise quantization without reorder_idx is supported; row-wise layouts // interleave K blocks across N and cannot be sliced along the N axis. const int64_t chunk_target_rows = chunk_target_rows_; const int64_t scratch_bytes = N_ * K_padded * static_cast(sizeof(T)); const bool will_use_chunked = column_wise_quant_blk_ && (reorder_idx_data == nullptr) && (force_chunked_ || ((scratch_bytes > 256 * 1024 * 1024) && (N_ > chunk_target_rows * 2))); // Allocate scratch: full size normally, chunk size if chunked path will be used const int64_t scratch_n = will_use_chunked ? chunk_target_rows : N_; IAllocatorUniquePtr b_data_ptr = this->template GetScratchBuffer(scratch_n * K_padded, this->GetComputeStream(ctx)); auto* b_data = b_data_ptr.get(); // Column-wise dequant helper: dispatches 8/4/2-bit x typed / uint8 zero-points. // Used by both the full-N and chunked paths so the offset math stays in one place. const int64_t blocks_per_col = K_padded / block_size_; auto dequant_column_wise = [&](const uint8_t* chunk_blob, const CudaT* chunk_scales, const void* chunk_zp, const int32_t* chunk_reorder_idx, int n_rows) -> Status { const bool typed_zero_points = zero_points && zero_points->IsDataType(); if (typed_zero_points) { return DequantizeNBits( SafeInt(nbits_), reinterpret_cast(b_data), chunk_blob, chunk_scales, static_cast(chunk_zp), chunk_reorder_idx, SafeInt(K_padded), n_rows, SafeInt(block_size_), stream); } return DequantizeNBits( SafeInt(nbits_), reinterpret_cast(b_data), chunk_blob, chunk_scales, static_cast(chunk_zp), chunk_reorder_idx, SafeInt(K_padded), n_rows, SafeInt(block_size_), stream); }; // Skip full dequant when chunked path will handle it in the GEMM loop if (!will_use_chunked) { if (column_wise_quant_blk_) { if (reorder_idx) { ORT_ENFORCE(K_padded == reorder_idx->Shape()[0], "K_padded != g_idx->Shape()[0]"); } ORT_RETURN_IF_ERROR(dequant_column_wise( blob_data, reinterpret_cast(scales_data), zero_points_data, reorder_idx_data, SafeInt(N_))); } else if (nbits_ == 8) { // row-wise block (8-bit) ORT_RETURN_IF_ERROR(DequantizeBlockwise8b( reinterpret_cast(b_data), blob_data, reinterpret_cast(scales_data), (const uint8_t*)zero_points_data, SafeInt(block_size_), column_wise_quant_blk_, SafeInt(K_), SafeInt(N_), stream)); } else { // row-wise block (4-bit) ORT_RETURN_IF_NOT(nbits_ == 4, "CUDA MatMulNBits row-wise quantization blocks are only implemented for bits = 4 or 8, but got bits = ", nbits_); K_padded = K_; ORT_RETURN_IF_ERROR(DequantizeBlockwise4b( reinterpret_cast(b_data), blob_data, reinterpret_cast(scales_data), (const uint8_t*)zero_points_data, SafeInt(block_size_), column_wise_quant_blk_, SafeInt(K_), SafeInt(N_), stream)); } } // end if (!will_use_chunked) if (!will_use_chunked) { DUMP_TENSOR_D("DeQuantized", b_data, static_cast(N_), static_cast(K_padded)); } const CudaT alpha = onnxruntime::cuda::OrtToCudaType::FromFloat(1.f); const CudaT zero = onnxruntime::cuda::OrtToCudaType::FromFloat(0.f); if (helper.OutputOffsets().size() == 1) { if (will_use_chunked) { // Chunked dequant+GEMM: scratch buffer is already sized for one chunk. const int64_t chunk_n = chunk_target_rows; auto* chunk_out_data = reinterpret_cast(Y->MutableData()); for (int64_t n_start = 0; n_start < N_; n_start += chunk_n) { const int64_t n_end = std::min(n_start + chunk_n, N_); const int this_chunk = static_cast(n_end - n_start); // Dequantize this chunk of N rows // column_wise_quant_blk_ is guaranteed by will_use_chunked; assert to prevent // silent use of uninitialized b_data if the outer guard is ever relaxed. ORT_ENFORCE(column_wise_quant_blk_, "Chunked path requires column-wise quantization blocks"); // Compute per-chunk pointers into the column-wise-packed weight, scale, and ZP arrays. const int64_t elements_per_byte = 8 / nbits_; const uint8_t* chunk_blob = blob_data + n_start * (K_padded / elements_per_byte); const auto* chunk_scales = reinterpret_cast(scales_data) + n_start * blocks_per_col; const void* chunk_zp = nullptr; if (zero_points_data) { if (zero_points && zero_points->IsDataType()) { chunk_zp = reinterpret_cast(zero_points_data) + n_start * blocks_per_col; } else { // uint8 ZP rows are bit-packed: ceil(blocks_per_col / elements_per_byte) bytes per output channel. chunk_zp = static_cast(zero_points_data) + n_start * ((blocks_per_col + elements_per_byte - 1) / elements_per_byte); } } ORT_RETURN_IF_ERROR(dequant_column_wise( chunk_blob, chunk_scales, chunk_zp, nullptr, // no reorder_idx for chunked path this_chunk)); DUMP_TENSOR_D("DeQuantized_chunk", b_data, this_chunk, static_cast(K_padded)); // GEMM for this chunk: C[:, n_start:n_end] = A[M,K] @ B_chunk[chunk_n, K]^T CUBLAS_RETURN_IF_ERROR(cublasGemmHelper( GetCublasHandle(ctx), CUBLAS_OP_T, CUBLAS_OP_N, this_chunk, // n (output columns for this chunk) SafeInt(helper.M()), // m SafeInt(helper.K()), // k &alpha, reinterpret_cast(b_data), // B_chunk [chunk_n, K_padded] SafeInt(K_padded), reinterpret_cast(a_data), // A [M, K] helper.Lda(transa), &zero, chunk_out_data + n_start, // C[:, n_start] — strided output SafeInt(helper.Ldc()), // ldc = N (full output stride) GetDeviceProp(), UseTF32())); } } else { // Original non-chunked path for small N CUBLAS_RETURN_IF_ERROR(cublasGemmHelper( GetCublasHandle(ctx), CUBLAS_OP_T, CUBLAS_OP_N, SafeInt(helper.N()), SafeInt(helper.M()), SafeInt(helper.K()), &alpha, reinterpret_cast(b_data), SafeInt(K_padded), reinterpret_cast(a_data), helper.Lda(transa), &zero, reinterpret_cast(Y->MutableData()), helper.Ldc(), GetDeviceProp(), UseTF32())); } // Fallback bias handling: the generic dequant + GEMM path above ignores bias, so add it here. if (bias_data != nullptr) { LaunchMatMulNBitsBiasAdd( reinterpret_cast(Y->MutableData()), reinterpret_cast(bias_data), m, n, stream); } } return Status::OK(); } ONNX_OPERATOR_TYPED_KERNEL_EX( MatMulNBits, kMSDomain, 1, float, kCudaExecutionProvider, (*KernelDefBuilder::Create()) .TypeConstraint("T1", DataTypeImpl::GetTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()) .TypeConstraint("T3", {DataTypeImpl::GetTensorType(), DataTypeImpl::GetTensorType()}), MatMulNBits); ONNX_OPERATOR_TYPED_KERNEL_EX( MatMulNBits, kMSDomain, 1, MLFloat16, kCudaExecutionProvider, (*KernelDefBuilder::Create()) .TypeConstraint("T1", DataTypeImpl::GetTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()) .TypeConstraint("T3", {DataTypeImpl::GetTensorType(), DataTypeImpl::GetTensorType()}), MatMulNBits); ONNX_OPERATOR_TYPED_KERNEL_EX( MatMulNBits, kMSDomain, 1, BFloat16, kCudaExecutionProvider, (*KernelDefBuilder::Create()) .TypeConstraint("T1", DataTypeImpl::GetTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()) .TypeConstraint("T3", {DataTypeImpl::GetTensorType(), DataTypeImpl::GetTensorType()}), MatMulNBits); } // namespace cuda } // namespace contrib } // namespace onnxruntime