Skip to content
Prev Previous commit
Next Next commit
Cut precision_score peak memory from O(L^2) to O(n+L)
The per-class counts were built by materializing the full
label-by-label confusion matrix on device even though only its
diagonal and the row and column sums of the selected labels are ever
read. Three weighted cupy.bincount reductions over the samples produce
identical values, so float-heavy or otherwise high-cardinality label
sets no longer allocate quadratically in the label count. The
now-unused cupyx import is dropped along with it.

Test Plan:
  python -m pytest tests/test_metrics.py -k "precision"
  -> 77 passed, 9 skipped, 886 deselected (RAPIDS container, RTX 5060 Ti)
  python -m pytest tests/test_metrics.py -k "(accuracy or confusion or
    log_loss or hinge) and not precision" -> 147 passed
  ruff check / format --check / isort --check-only on the changed file
  • Loading branch information
VaggelisGian committed Aug 27, 2026
commit 30c290d0e9449f4bb776fc39046fd1539f5cb41b
21 changes: 12 additions & 9 deletions python/cuml/cuml/metrics/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import cudf
import cupy as cp
import cupyx
import numpy as np
from sklearn.exceptions import UndefinedMetricWarning

Expand Down Expand Up @@ -346,14 +345,18 @@ def precision_score(
else sample_weight.astype(cp.float64, copy=False)
)

cm = cupyx.scipy.sparse.coo_matrix(
(weights, (true_idx, pred_idx)),
shape=(n_labels_total, n_labels_total),
).toarray()

tp_sum = cm[pos, pos]
pred_sum = cm[:, pos].sum(axis=0)
true_sum = cm[pos, :].sum(axis=1)
diag_mask = true_idx == pred_idx
tp_sum = cp.bincount(
true_idx[diag_mask],
weights=weights[diag_mask],
minlength=n_labels_total,
)[pos]
pred_sum = cp.bincount(
pred_idx, weights=weights, minlength=n_labels_total
)[pos]
true_sum = cp.bincount(
true_idx, weights=weights, minlength=n_labels_total
)[pos]

empty = pred_sum == 0
per_class = cp.where(
Expand Down
Loading