[4/4] Run the local-Hessian choice search as one CUDA kernel (#3218)

### What does this PR do?

Type of change: new feature (performance)

**[4/4]** of the GGML local-Hessian series. [1/4] #3158, [2/4] #3159 and
[3/4] #3209 are merged, so this is based on `main`. Merge order: #3158 →
#3159 → #3209 → #3218.

After the one-pass encode, `search_choices` scores every choice of every
group under the block Hessian and refines the groups in two sweeps. In
PyTorch that is a few small kernels per group and sweep, for every
256-column block: `local_hessian` searches every block of every weight,
and GPTQ with `local_hessian_scales` searches one block at a time. On
MoE models, with thousands of small expert weights, launch overhead
dominated calibration.

`choice_search.cu` runs the whole search for one block in a single
launch:
- **Layout:** one CUDA block per row, one thread per column.
- **Shared memory:** the candidate errors, current errors and gradient.
- **The Hessian:** read from L2 by column. It is symmetric by
construction (`U_gg⁻¹ U_gg⁻ᵀ`).
- **Reductions:** per-group sums are warp-segment shuffles.

Its picks match the PyTorch search, which remains the CPU path.

**Per 256-column block on a GB300:**

| Rows | Format | [2/4] | this PR |
|---|---|---|---|
| 512 | IQ2_XXS | 4.8 ms | 0.8 ms |
| 512 | IQ2_S | 9.1 ms | 0.8 ms |
| 512 | IQ1_S | 4.4 ms | 0.7 ms |
| 4096 | IQ2_XXS | 4.8 ms | 3.0 ms |
| 4096 | IQ2_S | 9.0 ms | 3.1 ms |
| 4096 | IQ1_S | 5.3 ms | 4.0 ms |

At 4,096 rows the one-pass encode is now the larger part: about 2 ms,
against about 1 ms for the search kernel.

**End to end**, GPTQ with `local_hessian_scales` relative to plain GPTQ:

| Workload | [1/4] search | [2/4] | this PR |
|---|---|---|---|
| 16 expert-sized 1536×4096 weights | 7.0× | 2.9× | **1.6×** |

On the real models (4× GB300, 1,024 samples), calibration with
`local_hessian_scales`:

| Model | plain GPTQ | [2/4] | this PR |
|---|---|---|---|
| GLM-5.3-Flash | 25.4 min | 108 min | **28.1 min** |
| Qwen3.8-Flash-Next | 9.8 min | 50 min | **15.5 min** |

KL against BF16 is unchanged within noise: GLM 0.625 vs 0.624,
Flash-Next 0.249 vs 0.247.

`local_hessian` on GLM-5.3-Flash, whose earlier PyTorch search already
batched every block of a weight together, also gets faster: encode 9.1
min vs 11.1 min, calibration 18.6 min vs 20.8 min. KL is unchanged at
0.720.

**Memory.** The kernel scores the candidate errors in place, without
[3/4]'s einsum temporaries. So `search_scratch`, which `_update_room`
adds for an update GPTQ may move to another GPU, now counts only the
candidate errors and payloads, plus the block's float32 reference and
contiguous copy. Peak memory of one IQ2_XXS update moved to a second
GB200, with the option on:

| Weight `[out, in]` | [3/4] | this PR (room) |
|---|---:|---:|
| 4096×2048 | 329 MiB | 199 MiB (360) |
| 16384×2048 | 1,123 MiB | 604 MiB (865) |
| 17408×5120 | 1,675 MiB | 1,125 MiB (2,089) |
| 65536×256 | 3,431 MiB | 1,355 MiB (1,636) |

### Testing

-
`tests/gpu/torch/quantization/test_ggml_gptq_cuda.py::test_fused_choice_search_matches_the_pytorch_search`:
on a compensated GPTQ block Hessian, the fused picks equal the PyTorch
search's on all five formats. It fails when the kernel skips its
refinement sweeps.
- Fused and PyTorch picks are also identical on 8,192 rows per format
over four random 256-column blocks.
- `test_gptq.py::test_an_update_that_may_move_fits_its_room`,
parametrized by `local_hessian_scales` in [3/4], passes with the lowered
estimate.
- I ran the GGML unit and GPU suites, `test_autoquant.py` and the GPU
`test_gptq.py` on this branch on GB200 (oci-jhb) in the calibration
container: 46 + 367 + 96 passed.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅ (internal speedup; picks
unchanged)
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A (speedup of 1/4 and 3/4, same release)
- Did you get Claude approval on this PR?: ❌ (pending)

### Additional Information

Series (#3157, fixed per-group choices, is merged): [1/4] #3158
local_hessian for GGML IQ · [2/4] #3159 one-pass every-choice encode ·
[3/4] #3209 GPTQ local-Hessian scale picks · [4/4] this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Added CUDA-accelerated choice refinement for GGML quantization. When
available, the accelerated search produces the same results as the
PyTorch implementation.
* Documented the symmetric Hessian requirement for group-by-group
refinement and updated memory estimates for the search.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chenjie Luo <chenjiel@nvidia.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chenjie Luo
2026-11-09 15:50:23 -08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 55979033f0
commit 914e9abcb4
6 changed files with 202 additions and 8 deletions
@@ -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<int>::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<<<static_cast<int>(rows), kThreads, 0, c10::cuda::getCurrentCUDAStream()>>>(
error_values.data_ptr<float>(), hessian_values.data_ptr<float>(), rows,
static_cast<int>(error_values.size(0)), static_cast<int>(groups), static_cast<int>(sweeps),
picks.data_ptr<int64_t>());
C10_CUDA_KERNEL_LAUNCH_CHECK();
return picks;
}
@@ -38,6 +38,8 @@ at::Tensor iq1_m_pack_cuda(at::Tensor input, at::Tensor grid, at::Tensor scales,
std::optional<at::Tensor> importance, std::optional<at::Tensor> 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. "
+3 -1
View File
@@ -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 ``<format>_unpack(payload, grid, dtype)``.
``q8_0_pack(input)``. Each IQ format also has ``<format>_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.",
@@ -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)
@@ -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)
@@ -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))