← Back to Pull requests

fix(hdbscan): four dense-path fixes plus the GPU brute_force size ceiling #3811

Closed
unknown closed this pull request without merging on Oct 05, 2026 08:52 UTC
View on GitHub
unknown unknown commented on Sep 24, 2026 09:13 UTC
Author

What

Six HDBSCAN fixes: four on the CPU dense path, two on the GPU brute_force
path. This PR is the union of the union-find race fix and the work previously in
#3750 — that PR is superseded and its commits are here, rebased.

1. Data race in the Boruvka union-find component refresh

UnionFind::find() in cpp/daal/src/algorithms/hdbscan/hdbscan_boruvka_utils.h
is declared const, but it path-halves into parent[]:

DAAL_INT find(DAAL_INT x) const
{
    while (parent[x] != x)
    {
        parent[x] = parent[parent[x]];   // <-- writes through a const member function
        x         = parent[x];
    }
    return x;
}

Phase 4 of every Boruvka round calls it from every thread of a threader_for
over one shared instance, for all three CPU backends (brute-force, kd-tree,
ball-tree):

daal::threader_for(nRows, nRows, [&](size_t i) { componentOf[i] = uf.find(i); });

So nRows threads compress the same paths concurrently with no synchronization.
Every value a racing write can store is still a valid ancestor of x, so the
component ids come out correct — this is not a results bug, and it is not why
anything is failing today. But the write itself is a data race, i.e. undefined
behaviour, and it is the kind of thing ThreadSanitizer and a stricter compiler
are entitled to act on. The GPU backend's equivalent walk
(hdbscan/backend/gpu/kernel_impl.hpp) is already a non-compressing read-only
walk for exactly this reason.

Fix. Split the two finds:

find() — pure read-only walk, no writes. Used by the parallel phase 4.
findCompress() — the path-halving one, non-const. Used only by
mergeComponentsEmitEdges (phase 3), which is a serial loop over component
slots and holds the forest exclusively.

Then recover the compression that phase 4 was doing, without the race.
refreshComponentIds becomes two parallel passes: read the roots into
componentOf (reads only), then flatten parent from that result (every thread
writes only its own index). The next round still resolves every root in a single
indirection, which is what the discarded path halving bought. Cost is one extra
O(N) write pass per round, against a forest that is now fully flat for the
following round's phase 1.

2. max_cluster_size ignored for leaf clusters

runEomSelection skipped every leaf cluster outright, on the grounds that a leaf
has no children and so can never lose the stability comparison. True of the
comparison, not of the size cap: an oversized leaf stayed selected and
max_cluster_size was silently ignored whenever the offending cluster happened
to be a leaf. A leaf now takes the same children-win outcome as an oversized
internal cluster — unselected, propagated stability set to the empty child sum of
zero. The GPU kernel gets the same treatment, keeping the two implementations in
agreement.

3. Serial finalize on the shared Euclidean distance primitive

EuclideanDistances::finalize() applied its max(0, .) clamp and batched vSqrt
in a plain serial loop, and declared a SafeStatus it never used. That is fine
for bf_knn, which finalizes one nTest k block from inside a
threader_for. HDBSCAN's dense path finalizes the entire N x N matrix —
6.25e8 entries at 25000 rows, roughly 40% of the euclidean fit spent on one
thread.

Threaded in 32k-entry tasks, gated on there being more than one task so the small
nested callers keep the behaviour they were tuned for and do not gain a nested
parallel region inside their own:

| Dataset | Metric | n | d | dtype | Speedup | Before vs sklearn | After vs sklearn |
|---|---|---|---|---|---|---|---|
| skin_segmentation | euclidean | 30000 | 3 | float64 | 1.99x | 3.84x | 7.66x |
| skin_segmentation | euclidean | 30000 | 3 | float32 | 1.96x | 6.01x | 11.79x |
| make_blobs | euclidean | 25000 | 64 | float64 | 1.94x | 3.96x | 7.67x |
| sensit | euclidean | 25000 | 100 | float64 | 1.90x | 3.29x | 6.25x |
| make_blobs | euclidean | 25000 | 256 | float64 | 1.88x | 3.16x | 5.93x |
| make_blobs | euclidean | 25000 | 1024 | float64 | 1.80x | 3.25x | 5.84x |
| cifar | euclidean | 15000 | 3072 | float64 | 1.39x | 2.90x | 4.03x |
| make_blobs | cosine | 25000 | 64 | float64 | 1.05x | 6.89x | 7.23x |
| make_blobs | manhattan | 25000 | 64 | float64 | 1.04x | 5.77x | 5.98x |
| make_blobs | chebyshev | 25000 | 64 | float64 | 1.00x | 5.91x | 5.94x |

Geomean 1.54x over the ten cases, median 1.84x; restricted to euclidean the
brute-force geomean against scikit-learn moves from 3.67x to 6.70x. The three
non-euclidean cases never enter the code that changed and are flat
(1.00x–1.05x), so they act as a control. Cluster counts and Davies-Bouldin
scores are identical before and after in all ten cases — this is a pure
scheduling change.

4. Unstable MST edge sort

sortMstEdges used the introsort in qSort. Every mutual-reachability edge
shorter than both of its endpoints' core distances collapses onto
max(core_i, core_j), so ties are dense, and their order decides
tie-degenerate splits — an unstable sort made the labels depend on the thread
schedule. It now sorts an index permutation with std::sort under an explicit
NaN-last total order on (weight, index) and gathers, which also matches the GPU
backend's stable radix sort. qSort stays as the fallback if any of the four
scratch allocations fails.

Also on the dense path

Core distances use a bounded max-heap select-k instead of nth_element on a
full copy of the row, dropping the per-thread scratch from nRows to
minSamples + 1 entries. A memory win, not a time win, and reported as such.
Boruvka now returns an error instead of handing sortMstAndExtractClusters a
truncated MST. The MRD graph over a dense matrix is complete, so a round can
only fail to find a candidate on non-finite input — in which case the tail of
mstFrom / mstTo / mstWeights was never written and got read as tree
nodes.

5. GPU brute_force could not run past n = 46340

Three launches on the GPU brute_force path size themselves off the n x n
matrix, so once n^2 leaves int32 the runtime rejects the range outright:

Provided range and/or offset does not fit in int.
Pass '-fno-sycl-id-queries-fit-in-int' to remove this limit.

46341 is the first n whose square passes 2^31 - 1, and every larger input
failed there regardless of how much device memory was free. The three sites:

ndarray<Float, 2>::zeros filled the matrix through a cgh.fill over n^2
elements. This one was dead work to begin with —
compute_distance_matrix writes every entry — so it becomes an empty(),
which also drops an O(n^2) memset from the fit.
scatter_2d in the shared squared-L2 primitive scattered the norms over a
single range<2>(n_samples1, n_samples2).
compute_mrd_matrix walked the matrix as one range<2>(n, n).

The last two now walk the matrix in row blocks sized by a new shared
bk::max_range_2d_rows helper. Blocking along the first dimension keeps the 2D
shape, and with it the coalescing, while staying under the limit; the blocks
touch disjoint rows and depend only on deps, so they remain free to overlap
and a single-block launch is returned directly rather than joined.

The fix is in the shared primitive, so it is worth noting what else uses it:
scatter_2d is reached by every squared-L2 consumer (knn, dbscan,
kmeans). None of them could hit the limit — they block their own work — and
the distance, knn and dbscan suites confirm no behaviour change.

6. An n x n matrix larger than device memory aborted or threw bad_alloc

Past the range limit the next failure was a bare std::bad_alloc from inside
the allocator, which tells the caller neither what was too large nor that
kd_tree and ball_tree would have worked on the same input.
check_mrd_matrix_fits_on_device now rejects those row counts up front, before
any device allocation, with an actionable domain_error naming the two methods
that do not materialize the matrix.

The budget deliberately stops short of the full global memory size: a
malloc_device past the physically available memory succeeds and then faults
on first access, which aborts the process rather than raising, so a check
against the reported size would not catch it. On a 48 GiB card an n x n
float64 matrix still ran at 28.6 GiB and faulted at 32.5 GiB. Half of global
memory stays clear of that edge and leaves room for the GEMM scratch, the
driver's own reservations and the rest of the pipeline. kmeans guards its own
device buffers the same way, at a quarter.

Measured on an Intel GPU, the usable brute_force ceiling moves from a hard
failure at n = 46340 to roughly 56k in float64 and 80k in float32, with a
clean error above that. n = 50000 float64 agrees with kd_tree at ARI
1.0000, and at that size brute_force is now the faster of the two.

The evaluation report

The four fixes came out of an evaluation report, which is not committed — it
is attached to this PR as a comment below instead. It covers the 45 paired
scikit-learn_bench cases, the evidence that the dense path's cost is in the
passes over the N x N matrix rather than in the GEMM, clustering agreement with
scikit-learn including the tie-degeneracy analysis, and a run of scikit-learn's
own sklearn/cluster/tests/test_hdbscan.py under patching (140 passed, 8
deselected with a reason).

Section 4 lists seven defects with location, severity and status — the four fixed
here and three left open, each with a fix sketch and why it is not in this PR:
the clusterSelectionEpsilon ancestor/descendant overlap, the missing
single-cluster lambda threshold in labelling (surfaced by the conformance run,
not reachable from the benchmark set, and needs the same change in the GPU
labelling kernel), and the weaker-than-documented kd_tree far-child pruning.

Sections 5 and 6 record two optimizations that were implemented, measured and
rejected, so they are not retried blind: Prim's over the materialized matrix
(24% slower than Boruvka despite doing strictly less work — Boruvka's per-round
query is one threader_for over independent rows, Prim's is N barriers over N
candidate slots) and a per-point cache of the k smallest MRD neighbours (exactly
label-preserving, but only 1.03x because Boruvka converges in few rounds and
building the cache costs one of them).

Performance figures are relative throughout.

Validation

bazel test --config=host //cpp/oneapi/dal/algo/hdbscan:tests — pass.
bazel test //cpp/oneapi/dal/backend/primitives/distance:tests
//cpp/oneapi/dal/algo/knn:tests //cpp/oneapi/dal/algo/dbscan:tests
//cpp/oneapi/dal/algo/hdbscan:tests
— 26/26 pass. This is the blast-radius
check for the scatter_2d blocking, which is shared with every squared-L2
consumer.
brute_force, kd_tree and ball_tree on GPU all match scikit-learn at ARI
1.0000 in both float32 and float64, through scikit-learn-intelex with
target_offload="gpu".
The sizing arithmetic is split into a pure mrd_matrix_fits_on_device so its
boundaries can be asserted against synthetic limits instead of whatever GPU
the test happens to run on; the row-blocking helper gets a test that pins the
46341 crossover and checks that every block stays under 2^31 - 1. Both
guard row counts whose matrix is tens of gigabytes, so neither is reachable
through dal::compute in a test.
//cpp/oneapi/dal/algo/knn:tests and //cpp/oneapi/dal/algo/dbscan:tests —
pass; service_kernel_math.h is shared with bf_knn, so these are the
blast-radius check for the finalize change.
cpp/oneapi/dal/algo/hdbscan/test/batch.cpp gains cases for the
max_cluster_size leaf-cluster cap and for run-to-run label stability (the
regression test for the MST sort: a single configuration clustered repeatedly
must produce identical labels).

  • The union-find change is behaviour-preserving by construction — the component

  • ids were already correct under the race, so the existing tests can only
    confirm that they still are. There is no ThreadSanitizer configuration in the
    repo to assert the absence of the race itself.

    ---

    <details>
    <summary>Checklist:</summary>

    Completeness and readability

  • I have commented my code, particularly in hard-to-understand areas.

  • I have updated the documentation to reflect the changes or created a separate PR with updates and provided its number in the description, if necessary.

  • Git commit message contains an appropriate signed-off-by string _(see CONTRIBUTING.md for details)_.

  • I have resolved any merge conflicts that might occur with the base branch.
  • Testing

  • I have run it locally and tested the changes extensively.

  • All CI jobs are green or I have provided justification why they aren't.

  • I have extended testing suite if new functionality was introduced in this PR.
  • Performance

  • I have measured performance for affected algorithms using scikit-learn_bench and provided at least a summary table with measured data, if performance change is expected.

  • I have provided justification why performance and/or quality metrics have changed or why changes are not expected.

  • I have extended the benchmarking suite and provided a corresponding scikit-learn_bench PR if new measurable functionality was introduced in this PR.
  • </details>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: avolkov-intel Review duration: 15818m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #3811"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%