Skip to content

[BUG] Cluster metrics fail above 46,340 distinct labels: int32 overflow in the contingency matrix size and index #3231

Backlog

Description

@jpintar

Describe the bug

Two int overflows limit the dense contingency matrix to 46,340 labels ($46{,}341^2 > 2^{31} - 1$):

  1. raft::stats::mutual_info_score computes the size of the matrix as numUniqueClasses * numUniqueClasses in int. With 46,341 labels the product wraps to a negative value, and the allocation fails with Requested size overflows device_uvector storage. homogeneity_score, completeness_score and v_measure are built on mutual_info_score and fail with it.

  2. raft::stats::contingency_matrix computes the element index (gt - outIdxOffset) * outMatWidth + pd - outIdxOffset in the label type. With int labels it overflows for the largest labels, and the kernel writes out of bounds. The same call succeeds with int64_t labels.

Steps/Code to reproduce bug

repro.cu (needs about 8 GiB of GPU memory):

#include <raft/core/device_mdarray.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/core/resources.hpp>
#include <raft/stats/contingency_matrix.cuh>
#include <raft/stats/mutual_info_score.cuh>
#include <raft/util/cudart_utils.hpp>

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <numeric>
#include <string>
#include <vector>

std::string first_line(const std::exception& e)
{
  std::string message = e.what();
  return message.substr(0, message.find('\n'));
}

int main()
{
  raft::resources handle;
  auto stream = raft::resource::get_cuda_stream(handle);

  for (int n_labels : {46340, 46341}) {
    // every sample has its own label
    std::vector<int> host_labels(n_labels);
    std::iota(host_labels.begin(), host_labels.end(), 0);
    auto labels = raft::make_device_vector<int, int64_t>(handle, n_labels);
    raft::update_device(labels.data_handle(), host_labels.data(), n_labels, stream);
    auto view = raft::make_const_mdspan(labels.view());

    try {
      double mi = raft::stats::mutual_info_score(handle, view, view, 0, n_labels - 1);
      std::printf("n_labels=%d: mutual_info_score = %.6f (expected %.6f)\n",
                  n_labels, mi, std::log(n_labels));
    } catch (const std::exception& e) {
      std::printf("n_labels=%d: mutual_info_score failed: %s\n", n_labels, first_line(e).c_str());
    }

    try {
      auto matrix = raft::make_device_matrix<int, int64_t>(handle, n_labels, n_labels);
      raft::stats::contingency_matrix(handle, view, view, matrix.view());
      int last = 0;
      raft::update_host(&last, matrix.data_handle() + matrix.size() - 1, 1, stream);
      raft::resource::sync_stream(handle);
      std::printf("n_labels=%d: contingency_matrix: last diagonal entry = %d (expected 1)\n",
                  n_labels, last);
    } catch (const std::exception& e) {
      std::printf("n_labels=%d: contingency_matrix failed: %s\n", n_labels, first_line(e).c_str());
    }
  }
  return 0;
}

Built in a conda environment with the nightly libraft-headers:

nvcc -std=c++20 -arch=native --extended-lambda --expt-relaxed-constexpr \
  -I"$CONDA_PREFIX/include" repro.cu -o repro \
  -L"$CONDA_PREFIX/lib" -lrmm -lrapids_logger -Xlinker=-rpath,"$CONDA_PREFIX/lib"
./repro

Output:

n_labels=46340: mutual_info_score = 10.743761 (expected 10.743761)
n_labels=46340: contingency_matrix: last diagonal entry = 1 (expected 1)
n_labels=46341: mutual_info_score failed: RMM failure at: .../include/rmm/device_uvector.hpp:628: Requested size overflows device_uvector storage.
n_labels=46341: contingency_matrix failed: CUDA error encountered at: file=.../include/raft/util/cudart_utils.hpp line=138 function=void raft::copy(Type*, const Type*, size_t, cuda::__4::stream_ref) [with Type = int; size_t = long unsigned int]: call='cudaMemcpyAsync(dst, src, len * sizeof(Type), cudaMemcpyDefault, stream.get())', Reason=cudaErrorIllegalAddress:an illegal memory access was encountered

Expected behavior

The mutual information of a labeling with itself is its entropy, here $\ln(46{,}341) ≈ 10.743782$, and the last diagonal entry of its contingency matrix is 1. If label counts this large are not meant to be supported, a clear error would be preferable to a wrapped allocation size or an out-of-bounds write.

Environment details (please complete the following information):

  • Environment location: Docker (RAPIDS devcontainer, cuda13.4-conda)
  • Method of RAFT install: conda (libraft-headers 27.02.00a17 nightly, commit b74966f; librmm 27.02.00a9). The output is the same with the headers of a source checkout at that commit.
  • CUDA 13.4 (nvcc 13.4.92, GCC 14.4), Ubuntu 24.04, NVIDIA RTX PRO 4000 Blackwell (24 GB), driver 595.99.02

Additional context

  • I found this through cuML, whose mutual_info_score, homogeneity_score, completeness_score and v_measure_score all work at 46,340 labels and fail at 46,341. There the first overflow was reported as std::bad_alloc: out_of_memory: CUDA error (failed to allocate 18446744065119635556 bytes), which is the wrapped size multiplied by 4 bytes and converted to size_t.
  • adjusted_rand_index<int, unsigned long long, int64_t> returns 1.0 for 46,340 labels with two samples each, and fails with cudaErrorIllegalAddress for 46,341. With math_t = int it fails with cudaErrorInvalidValue in mapThenReduceImpl instead; nUniqClasses * nUniqClasses is evaluated in math_t there.
  • This is separate from [BUG] mutual_info_score overflows int32 when multiplying marginal counts #3220, which concerns the product of two marginal counts inside the kernel and affects large clusters; this one concerns the number of labels. The fix proposed in [REVIEW] Fix int32 overflow in mutual_info_score and clip negative results #3221 does not affect the lines above.
  • Removing the overflows would raise the limit but not remove it, since the contingency matrix is dense: its size grows with the square of the number of labels (40 GB for 100,000 labels).

Drafted with Claude Code (Fable 5.2), reproduced manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions