fix(hdbscan): four dense-path fixes plus the GPU brute_force size ceiling #3811
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
avolkov-intel
What
Six HDBSCAN fixes: four on the CPU dense path, two on the GPU
brute_forcepath. 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()incpp/daal/src/algorithms/hdbscan/hdbscan_boruvka_utils.his declared
const, but it path-halves intoparent[]:Phase 4 of every Boruvka round calls it from every thread of a
threader_forover one shared instance, for all three CPU backends (brute-force, kd-tree,
ball-tree):
So
nRowsthreads compress the same paths concurrently with no synchronization.Every value a racing write can store is still a valid ancestor of
x, so thecomponent 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-onlywalk 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 bymergeComponentsEmitEdges(phase 3), which is a serial loop over componentslots and holds the forest exclusively.
Then recover the compression that phase 4 was doing, without the race.
refreshComponentIdsbecomes two parallel passes: read the roots intocomponentOf(reads only), then flattenparentfrom that result (every threadwrites 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 thefollowing round's phase 1.
2.
max_cluster_sizeignored for leaf clustersrunEomSelectionskipped every leaf cluster outright, on the grounds that a leafhas 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_sizewas silently ignored whenever the offending cluster happenedto 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
finalizeon the shared Euclidean distance primitiveEuclideanDistances::finalize()applied itsmax(0, .)clamp and batchedvSqrtin a plain serial loop, and declared a
SafeStatusit never used. That is finefor
bf_knn, which finalizes onenTest kblock from inside athreader_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
sortMstEdgesused the introsort inqSort. Every mutual-reachability edgeshorter than both of its endpoints' core distances collapses onto
max(core_i, core_j), so ties are dense, and their order decidestie-degenerate splits — an unstable sort made the labels depend on the thread
schedule. It now sorts an index permutation with
std::sortunder an explicitNaN-last total order on
(weight, index)and gathers, which also matches the GPUbackend's stable radix sort.
qSortstays as the fallback if any of the fourscratch allocations fails.
Also on the dense path
Core distances use a bounded max-heap select-k instead of
nth_elementon afull copy of the row, dropping the per-thread scratch from
nRowstominSamples + 1entries. A memory win, not a time win, and reported as such.Boruvka now returns an error instead of handing
sortMstAndExtractClustersatruncated 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/mstWeightswas never written and got read as treenodes.
5. GPU
brute_forcecould not run past n = 46340Three launches on the GPU
brute_forcepath size themselves off then x nmatrix, so once
n^2leaves int32 the runtime rejects the range outright:46341 is the first
nwhose square passes2^31 - 1, and every larger inputfailed there regardless of how much device memory was free. The three sites:
ndarray<Float, 2>::zerosfilled the matrix through acgh.fillovern^2elements. This one was dead work to begin with —
compute_distance_matrixwrites every entry — so it becomes anempty(),which also drops an
O(n^2)memset from the fit.scatter_2din the shared squared-L2 primitive scattered the norms over asingle
range<2>(n_samples1, n_samples2).compute_mrd_matrixwalked the matrix as onerange<2>(n, n).The last two now walk the matrix in row blocks sized by a new shared
bk::max_range_2d_rowshelper. Blocking along the first dimension keeps the 2Dshape, 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 overlapand 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_2dis reached by every squared-L2 consumer (knn,dbscan,kmeans). None of them could hit the limit — they block their own work — andthe distance, knn and dbscan suites confirm no behaviour change.
6. An
n x nmatrix larger than device memory aborted or threwbad_allocPast the range limit the next failure was a bare
std::bad_allocfrom insidethe allocator, which tells the caller neither what was too large nor that
kd_treeandball_treewould have worked on the same input.check_mrd_matrix_fits_on_devicenow rejects those row counts up front, beforeany device allocation, with an actionable
domain_errornaming the two methodsthat do not materialize the matrix.
The budget deliberately stops short of the full global memory size: a
malloc_devicepast the physically available memory succeeds and then faultson 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 nfloat64matrix still ran at 28.6 GiB and faulted at 32.5 GiB. Half of globalmemory stays clear of that edge and leaves room for the GEMM scratch, the
driver's own reservations and the rest of the pipeline.
kmeansguards its owndevice buffers the same way, at a quarter.
Measured on an Intel GPU, the usable
brute_forceceiling moves from a hardfailure at n = 46340 to roughly 56k in
float64and 80k infloat32, with aclean error above that. n = 50000
float64agrees withkd_treeat ARI1.0000, and at that size
brute_forceis 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.pyunder patching (140 passed, 8deselected 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
clusterSelectionEpsilonancestor/descendant overlap, the missingsingle-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_treefar-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_forover independent rows, Prim's is N barriers over Ncandidate 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— 26/26 pass. This is the blast-radius//cpp/oneapi/dal/algo/knn:tests //cpp/oneapi/dal/algo/dbscan:tests
//cpp/oneapi/dal/algo/hdbscan:tests
check for the
scatter_2dblocking, which is shared with every squared-L2consumer.
brute_force,kd_treeandball_treeon GPU all match scikit-learn at ARI1.0000 in both
float32andfloat64, through scikit-learn-intelex withtarget_offload="gpu".The sizing arithmetic is split into a pure
mrd_matrix_fits_on_deviceso itsboundaries 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. Bothguard row counts whose matrix is tens of gigabytes, so neither is reachable
through
dal::computein a test.//cpp/oneapi/dal/algo/knn:testsand//cpp/oneapi/dal/algo/dbscan:tests—pass;
service_kernel_math.his shared withbf_knn, so these are theblast-radius check for the
finalizechange.cpp/oneapi/dal/algo/hdbscan/test/batch.cppgains cases for themax_cluster_sizeleaf-cluster cap and for run-to-run label stability (theregression test for the MST sort: a single configuration clustered repeatedly
must produce identical labels).
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
Testing
Performance
</details>