diff --git a/modelopt/torch/kernels/quantization/ggml/choice_search.cu b/modelopt/torch/kernels/quantization/ggml/choice_search.cu new file mode 100644 index 00000000000..a12e24898aa --- /dev/null +++ b/modelopt/torch/kernels/quantization/ggml/choice_search.cu @@ -0,0 +1,161 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// modelopt.torch.quantization.ggml.choice_search's Hessian-weighted choice search, one CUDA block +// per row of a 256-column GGML block. H is read by column, so a warp's reads are coalesced. + +#include "common.cuh" + +namespace { + +using namespace modelopt::ggml; + +constexpr int kMaxChoices = 16; +constexpr int kMaxGroups = 16; +static_assert(kThreads == kBlockSize, "each thread owns one column of the block"); + +// Sum of value over each aligned run of width lanes (a power of two up to 32), on every lane. +__device__ __forceinline__ float segment_sum(float value, int width) { + for (int offset = width / 2; offset > 0; offset /= 2) + value += __shfl_xor_sync(0xffffffff, value, offset); + return value; +} + +__global__ void search(const float *errors, const float *hessian, int64_t rows, int choices, + int groups, int sweeps, int64_t *picks) { + __shared__ float error[kMaxChoices][kBlockSize]; + __shared__ float current[kBlockSize]; + __shared__ float gradient[kBlockSize]; + __shared__ float score[kMaxChoices][kMaxGroups]; + __shared__ int pick[kMaxGroups]; + + const int tid = threadIdx.x; + const int64_t row = blockIdx.x; + const int group_size = kBlockSize / groups; + const int lane_in_group = tid % group_size; + + for (int c = 0; c < choices; ++c) + error[c][tid] = errors[(c * rows + row) * kBlockSize + tid]; + __syncthreads(); + + // Each group's error under each choice: sum over i, j in the group of e_i H_ij e_j. Thread tid + // owns column tid, so a choice's groups are aligned runs of group_size threads. + const int own_group = tid / group_size; + const int group_start = own_group * group_size; + for (int c = 0; c < choices; ++c) { + float projected = 0.0f; + for (int j = 0; j < group_size; ++j) + projected = + fmaf(hessian[(group_start + j) * kBlockSize + tid], error[c][group_start + j], projected); + const float total = segment_sum(error[c][tid] * projected, group_size); + if (lane_in_group == 0) + score[c][own_group] = total; + } + __syncthreads(); + if (tid < groups) { + int best = 0; + for (int c = 1; c < choices; ++c) + best = score[c][tid] < score[best][tid] ? c : best; + pick[tid] = best; + } + __syncthreads(); + current[tid] = error[pick[own_group]][tid]; + __syncthreads(); + float grad = 0.0f; + for (int i = 0; i < kBlockSize; ++i) + grad = fmaf(current[i], hessian[i * kBlockSize + tid], grad); + gradient[tid] = grad; + __syncthreads(); + + // Switching group g by delta changes e H e^T by delta . (2 gradient_g + H_gg delta). Items are + // (choice, column of g) pairs, group_size threads per choice, so the segment sums apply. + const int pairs = choices * group_size; + for (int sweep = 0; sweep < sweeps; ++sweep) { + for (int g = 0; g < groups; ++g) { + const int start = g * group_size; + for (int base = 0; base < pairs; base += kThreads) { + const int item = base + tid; + const bool active = item < pairs; + const int c = active ? item / group_size : 0; + const int i = start + lane_in_group; + float value = 0.0f; + if (active) { + float projected = 0.0f; + for (int j = 0; j < group_size; ++j) + projected = fmaf(hessian[(start + j) * kBlockSize + i], + error[c][start + j] - current[start + j], projected); + value = (error[c][i] - current[i]) * (2.0f * gradient[i] + projected); + } + value = segment_sum(value, group_size); + if (active && lane_in_group == 0) + score[c][g] = value; + } + __syncthreads(); + if (tid == 0) { + int best = 0; + for (int c = 1; c < choices; ++c) + best = score[c][g] < score[best][g] ? c : best; + pick[g] = best; + } + __syncthreads(); + float update = 0.0f; + for (int j = 0; j < group_size; ++j) + update = fmaf(error[pick[g]][start + j] - current[start + j], + hessian[(start + j) * kBlockSize + tid], update); + __syncthreads(); + gradient[tid] += update; + if (tid >= start && tid < start + group_size) + current[tid] = error[pick[g]][tid]; + __syncthreads(); + } + } + if (tid < groups) + picks[row * groups + tid] = pick[tid]; +} + +} // namespace + +at::Tensor search_choices_cuda(at::Tensor errors, at::Tensor hessian, int64_t groups, + int64_t sweeps) { + TORCH_CHECK(errors.is_cuda() && errors.scalar_type() == at::kFloat && errors.dim() == 3 && + errors.size(2) == kBlockSize, + "errors must be a float32 CUDA [choices, rows, 256] tensor"); + TORCH_CHECK(errors.size(0) >= 1 && errors.size(0) <= kMaxChoices, "at most ", kMaxChoices, + " choices are supported"); + TORCH_CHECK(hessian.is_cuda() && hessian.get_device() == errors.get_device() && + hessian.scalar_type() == at::kFloat && hessian.dim() == 2 && + hessian.size(0) == kBlockSize && hessian.size(1) == kBlockSize, + "hessian must be a float32 [256, 256] tensor on the errors' device"); + TORCH_CHECK(groups >= kBlockSize / 32 && groups <= kMaxGroups && kBlockSize % groups == 0 && + ((kBlockSize / groups) & (kBlockSize / groups - 1)) == 0, + "groups must split 256 columns into power-of-two runs of at most 32"); + TORCH_CHECK(sweeps >= 0, "sweeps must be non-negative"); + TORCH_CHECK(errors.size(1) <= std::numeric_limits::max(), "CUDA grid is too large"); + const auto error_values = errors.contiguous(); + const auto hessian_values = hessian.contiguous(); + c10::cuda::CUDAGuard guard(error_values.device()); + const int64_t rows = error_values.size(1); + at::Tensor picks = at::empty({rows, groups}, error_values.options().dtype(at::kLong)); + if (rows == 0) + return picks; + search<<(rows), kThreads, 0, c10::cuda::getCurrentCUDAStream()>>>( + error_values.data_ptr(), hessian_values.data_ptr(), rows, + static_cast(error_values.size(0)), static_cast(groups), static_cast(sweeps), + picks.data_ptr()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return picks; +} diff --git a/modelopt/torch/kernels/quantization/ggml/ggml.cpp b/modelopt/torch/kernels/quantization/ggml/ggml.cpp index eca70a8a217..5885d5fafd6 100644 --- a/modelopt/torch/kernels/quantization/ggml/ggml.cpp +++ b/modelopt/torch/kernels/quantization/ggml/ggml.cpp @@ -38,6 +38,8 @@ at::Tensor iq1_m_pack_cuda(at::Tensor input, at::Tensor grid, at::Tensor scales, std::optional importance, std::optional choices, bool every_choice); at::Tensor q8_0_pack_cuda(at::Tensor input); +at::Tensor search_choices_cuda(at::Tensor errors, at::Tensor hessian, int64_t groups, + int64_t sweeps); at::Tensor iq1_s_unpack_cuda(at::Tensor packed, at::Tensor grid, at::ScalarType dtype); at::Tensor iq1_m_unpack_cuda(at::Tensor packed, at::Tensor grid, at::ScalarType dtype); at::Tensor iq2_xxs_unpack_cuda(at::Tensor packed, at::Tensor grid, at::ScalarType dtype); @@ -128,6 +130,13 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { pybind11::arg("input"), pybind11::arg("grid"), pybind11::arg("scales"), pybind11::arg("importance") = pybind11::none(), pybind11::arg("choices") = pybind11::none(), pybind11::arg("every_choice") = false); + module.def("search_choices", &search_choices_cuda, + "Each group's choice minimizing e H e^T for every row of one 256-column block, given " + "every choice's float32 decoding error [choices, rows, 256] and the symmetric float32 " + "[256, 256] H: the least-error choice per group under its diagonal block of H, then " + "sweeps passes revisiting the groups in turn. Returns int64 [rows, groups].", + pybind11::arg("errors"), pybind11::arg("hessian"), pybind11::arg("groups"), + pybind11::arg("sweeps")); module.def("q8_0_pack", &q8_0_pack, "Pack a non-empty float32, float64, float16, or bfloat16 CUDA tensor whose innermost " "dimension is a multiple of 32. Returns uint8 [numel / 32, 34] on the input device. " diff --git a/modelopt/torch/quantization/extensions.py b/modelopt/torch/quantization/extensions.py index d839ad1ad8c..429c960b4a4 100644 --- a/modelopt/torch/quantization/extensions.py +++ b/modelopt/torch/quantization/extensions.py @@ -86,7 +86,8 @@ def get_cuda_ext_ggml(raise_if_failed: bool = False): build as a single extension: ``iq1_s_pack(input, grid, scales, importance=None, choices=None, every_choice=False)``, the same for ``iq1_m_pack``, ``iq2_xs_pack``, ``iq2_xxs_pack`` and ``iq2_s_pack``, and - ``q8_0_pack(input)``. Each IQ format also has ``_unpack(payload, grid, dtype)``. + ``q8_0_pack(input)``. Each IQ format also has ``_unpack(payload, grid, dtype)``, and + ``search_choices(errors, hessian, groups, sweeps)`` runs the local-Hessian choice search. """ if not hasattr(get_cuda_ext_ggml, "extension") or ( raise_if_failed and get_cuda_ext_ggml.extension is None @@ -101,6 +102,7 @@ def get_cuda_ext_ggml(raise_if_failed: bool = False): kernels_ggml / "iq2_s.cu", kernels_ggml / "iq1_m.cu", kernels_ggml / "q8_0.cu", + kernels_ggml / "choice_search.cu", ], cuda_version_specifiers=">=11.8", fail_msg="GGML IQ CUDA packing extension is unavailable.", diff --git a/modelopt/torch/quantization/ggml/choice_search.py b/modelopt/torch/quantization/ggml/choice_search.py index a06e2a9a3be..18f081a78a7 100644 --- a/modelopt/torch/quantization/ggml/choice_search.py +++ b/modelopt/torch/quantization/ggml/choice_search.py @@ -17,6 +17,7 @@ import torch +from ..extensions import get_cuda_ext_ggml from .common import GGML_BLOCK_SIZE, GGMLFormat __all__ = ["search_choices", "search_scratch"] @@ -42,7 +43,8 @@ def search_choices( for every group, its codebook entries searched as the encoder does (weighted by ``importance``). In each block, each group first takes the choice with the least error under its own diagonal block of the Hessian; groups are then revisited in turn, each taking the choice that most lowers - the block's error with the others held. + the block's error with the others held, an update that needs each block's Hessian symmetric. + With the CUDA extension, the search after the encode runs as one kernel per block. """ rows = weight.reshape(-1, weight.shape[-1]) blocks, groups = weight.shape[-1] // GGML_BLOCK_SIZE, ggml_format.choice_groups @@ -74,12 +76,12 @@ def _rows_per_chunk(ggml_format: GGMLFormat) -> int: def search_scratch(ggml_format: GGMLFormat, rows: int) -> int: """Bytes :func:`search_choices` holds at once on ``rows`` rows, as measured with the CUDA codecs. - For each chunk of rows, every choice's payload and float32 errors, and two einsum temporaries - as large as the errors. + For each chunk of rows, every choice's payload and float32 errors, and the block's float32 + reference and contiguous copy; the fused search kernel needs nothing as large besides. """ chunk = min(rows, _rows_per_chunk(ggml_format)) - candidates = ggml_format.num_choices * chunk - return candidates * (3 * 4 * GGML_BLOCK_SIZE + ggml_format.block_bytes) + candidates = ggml_format.num_choices * chunk * (4 * GGML_BLOCK_SIZE + ggml_format.block_bytes) + return candidates + chunk * 8 * GGML_BLOCK_SIZE def _search_block(ggml_format, block, hessian, importance, chunk_args, decode_args): @@ -97,6 +99,8 @@ def _search_block(ggml_format, block, hessian, importance, chunk_args, decode_ar **decode_args, ).reshape(ggml_format.num_choices, rows, GGML_BLOCK_SIZE) errors -= reference + if block.is_cuda and (extension := get_cuda_ext_ggml()) is not None: + return extension.search_choices(errors, hessian, groups, _REFINE_SWEEPS) errors = errors.reshape(ggml_format.num_choices, rows, groups, group_size) group_rows = hessian.reshape(groups, group_size, GGML_BLOCK_SIZE) diff --git a/modelopt/torch/quantization/ggml/local_hessian.py b/modelopt/torch/quantization/ggml/local_hessian.py index 88cdfe15d4e..c26a42f866d 100644 --- a/modelopt/torch/quantization/ggml/local_hessian.py +++ b/modelopt/torch/quantization/ggml/local_hessian.py @@ -75,7 +75,7 @@ class GGMLLocalHessianEncoder(LocalHessianEncoder): if ggml_format.weighted: kwargs["importance"] = moments.sqrt().to(weight.device) hessian = hessian.to(device=weight.device, dtype=torch.float32) - # Symmetrized, as the CUDA search reads each block by column. + # Symmetrized, as the search's refinement update assumes. hessian = (hessian + hessian.transpose(1, 2)) / 2 ridge = perc_damp * hessian.diagonal(dim1=1, dim2=2).mean() hessian.diagonal(dim1=1, dim2=2).add_(ridge) diff --git a/tests/gpu/torch/quantization/test_ggml_gptq_cuda.py b/tests/gpu/torch/quantization/test_ggml_gptq_cuda.py index e522b37152d..da511378d03 100644 --- a/tests/gpu/torch/quantization/test_ggml_gptq_cuda.py +++ b/tests/gpu/torch/quantization/test_ggml_gptq_cuda.py @@ -21,8 +21,11 @@ import torch import modelopt.torch.opt as mto import modelopt.torch.quantization as mtq -from modelopt.torch.quantization.ggml import GGML_FORMAT_REGISTRY +from modelopt.torch.quantization.extensions import get_cuda_ext_ggml +from modelopt.torch.quantization.ggml import GGML_FORMAT_REGISTRY, choice_search from modelopt.torch.quantization.ggml.common import pinned_packed_weight +from modelopt.torch.quantization.ggml.gptq import compensated_block_hessian +from modelopt.torch.quantization.utils.calib_utils import compute_hessian_inverse def _iq1_s_config(algorithm): @@ -132,3 +135,18 @@ def test_auto_quantize_refuses_gptq_on_native_fp8_weights_and_hands_back_the_mod assert torch.equal(param, original) # The same model searches again with a calibration that leaves its weights alone. search("max") + + +@pytest.mark.parametrize("num_bits", ["iq2_xxs", "iq2_xs", "iq2_s", "iq1_s", "iq1_m"]) +def test_fused_choice_search_matches_the_pytorch_search(monkeypatch, num_bits): + get_cuda_ext_ggml(raise_if_failed=True) # without it, both searches would be the PyTorch one + ggml_format = GGML_FORMAT_REGISTRY[num_bits] + inputs = _correlated_inputs() + weight = torch.randn(64, 512, generator=torch.Generator().manual_seed(1)).cuda() + h_inv = compute_hessian_inverse(inputs.T @ inputs / len(inputs), weight, 0.3) + hessian = compensated_block_hessian(h_inv, slice(256, 512))[None] + block = weight[:, 256:].contiguous() + + fused = choice_search.search_choices(ggml_format, block, hessian) + monkeypatch.setattr(choice_search, "get_cuda_ext_ggml", lambda: None) + assert torch.equal(fused, choice_search.search_choices(ggml_format, block, hessian))