feat(dbscan): add manhattan, minkowski, chebyshev and cosine distance metrics #3815
Returning 1 makes a zero row a neighbor of every point, including itself, whenever epsilon >= 1; it can then become a core point despite the documented rule that zero rows are never neighbors. This also disagrees with the full-matrix CPU path, whose zero-norm division yields NaN and is rejected by the cutoff. Use a representation that is outside every accepted radius and make the CPU batch and GPU implementations follow the same policy.
A zero row is assigned distance 1, so at epsilon >= 1 the GPU includes it in neighborhoods and may mark it core. That contradicts the stated rule that a zero row is maximally distant and never a neighbor, and 1 is not the maximum cosine distance (2). Align this sentinel and the accepted epsilon range with both CPU paths.
NaN passes this check because every ordered comparison with it is false, so set_degree(NaN) violates the documented degree > 0 invariant and later turns Minkowski thresholds and distances into NaNs. Reject unordered values by expressing the invariant directly; add a matching bad-argument case.
Cosine distance ranges from 0 to 2; orthogonal vectors have distance 1, while opposite vectors reach the maximum 2. Calling one the maximum conflicts with the metric documentation and obscures the zero-row boundary bug.
This issue also appears on line 450 of the same file.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Zero-vector cosine handling violates its documented contract across backends, and NaN Minkowski degrees bypass validation.
<details open>
<summary><strong>4 open findings</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adds configurable DBSCAN distance metrics across the public API, CPU/GPU backends, tests, and documentation.
Changes:
| File | Description |
| ---- | ----------- |
| docs/source/onedal/algorithms/clustering/dbscan.rst | Documents supported metrics. |
| docs/source/api/algorithms/clustering/dbscan.rst | Exposes the metric enum. |
| cpp/oneapi/dal/algo/dbscan/test/fixture.hpp | Adds metric test helpers. |
| cpp/oneapi/dal/algo/dbscan/test/batch.cpp | Adds metric behavior tests. |
| cpp/oneapi/dal/algo/dbscan/test/badarg.cpp | Adds argument validation tests. |
| cpp/oneapi/dal/algo/dbscan/common.hpp | Adds the public metric API. |
| cpp/oneapi/dal/algo/dbscan/common.cpp | Stores and validates metric settings. |
| cpp/oneapi/dal/algo/dbscan/backend/gpu/kernels_fp.hpp | Templates GPU kernels by metric. |
| cpp/oneapi/dal/algo/dbscan/backend/gpu/kernel_fp_impl.hpp | Applies metric operations in GPU kernels. |
| cpp/oneapi/dal/algo/dbscan/backend/gpu/distance_metric_op.hpp | Implements GPU metric operations. |
| cpp/oneapi/dal/algo/dbscan/backend/gpu/compute_kernel_brute_force_dpc.cpp | Dispatches GPU computation by metric. |
| cpp/oneapi/dal/algo/dbscan/backend/cpu/compute_kernel_common.hpp | Maps public metrics to DAAL types. |
| cpp/oneapi/dal/algo/dbscan/backend/cpu/compute_kernel_brute_force.cpp | Passes metric settings to CPU kernels. |
| cpp/daal/src/algorithms/dbscan/dbscan_utils.h | Implements CPU metric neighborhood searches. |
| cpp/daal/src/algorithms/dbscan/dbscan_kernel.h | Extends internal kernel arguments. |
| cpp/daal/src/algorithms/dbscan/dbscan_dense_default_batch_impl.i | Configures CPU engines with metrics. |
</details>
🧠 Review effort: Balanced
---
💡 <a href="/uxlfoundation/oneDAL/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
Agreed the paths disagreed, but I matched scikit-learn rather than making zero rows never neighbours. sklearn's cosine_distances puts a zero row at distance 1 from every other row and 0 from itself, so at eps >= 1 it is a neighbour and can be core. Fixed in e8493e3f1: every path now gives 1 against a non-zero row and 0 against a zero row. The full-matrix path overwrites the 0/0 entries from CosineDistances, which HDBSCAN and KNN share, so they are untouched. The docs now state this.
Same fix in e8493e3f1: the GPU op now matches both CPU paths and scikit-learn (1 against a non-zero row, 0 against a zero row). epsilon is unchanged; any value is valid, and eps >= 2 simply makes every pair a neighbour.
Fixed in e8493e3f1: the check is now !(value > 0.0), and the bad-argument test covers NaN.
Fixed in e8493e3f1: the comment now says orthogonal rows are at cosine distance one. The zero-row test also covers eps = 1 and min_observations = 1 now.
<!-- coderabbit-ai-generated:v1 -->
<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- review_stack_entry_start -->
<a href="https://app.coderabbit.ai/change-stack/uxlfoundation/oneDAL/pull/3815?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a>
<!-- review_stack_entry_end -->
<!-- This is an auto-generated comment: review paused by coderabbit.ai -->
[!NOTE]
## Reviews paused
> It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.> - Last reviewed commit: 5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930
- Latest commit, not reviewed: 6c1dd474b32a71ad80d797cb16766d5ef302449b
> Use the following commands to manage reviews:
- @coderabbitai resume to resume automatic reviews.- @coderabbitai review to trigger a single review.> Use the checkboxes below for quick actions:
- [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> Resume reviews
- [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> Trigger review
<!-- end of auto-generated comment: review paused by coderabbit.ai -->
<!-- recent_review_status_start -->
No actionable comments were generated in the recent review.
<!-- recent_review_status_end -->
<!-- walkthrough_start -->
<details>
<summary><strong>Summary</strong></summary>
<dl>
<dd>
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
Summary by CodeRabbit
New Features
DBSCAN supports Euclidean, Manhattan, Minkowski, Chebyshev, and cosine distance metrics on CPU and GPU, in both memory modes.
Choose a distance metric and, for Minkowski, configure its degree. The neighborhood radius is interpreted in the selected metric’s units. Cosine distance also handles zero-valued observations.
Documentation
Added guidance and C++ and SYCL examples for running DBSCAN with different distance metrics.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
DBSCAN adds Euclidean, Manhattan, Minkowski, Chebyshev, and cosine distance options, with configurable Minkowski degree. CPU and GPU paths use metric-specific distances and thresholds. The change adds reference-based tests, documentation, examples, and shared pairwise-distance utilities used by HDBSCAN.
Changes: DBSCAN distance metrics
|Layer / File(s)|Summary|
|:---|:---|
|Metric API and descriptor <br> cpp/oneapi/dal/algo/dbscan/common.hpp, cpp/oneapi/dal/algo/dbscan/common.cpp|The descriptor exposes five distance metrics and a degree. It defaults to Euclidean and 2.0. It rejects degrees that are non-positive or non-finite.|
|CPU neighborhood distance execution <br> cpp/daal/src/algorithms/dbscan/, cpp/oneapi/dal/algo/dbscan/backend/cpu/, cpp/daal/src/algorithms/service_kernel_math.h, cpp/daal/src/algorithms/hdbscan/hdbscan_centers_impl.i, cpp/oneapi/dal/algo/dbscan/BUILD|The CPU backend passes the selected metric and degree to DBSCAN. The neighborhood engine dispatches distance queries by metric and transforms epsilon for comparisons. Shared pairwise-distance utilities provide metric implementations for DBSCAN and HDBSCAN medoid computation.|
|GPU neighborhood distance execution <br> cpp/oneapi/dal/algo/dbscan/backend/gpu/|GPU core-search and queue-update kernels accumulate distances according to the selected metric and compare them with a transformed threshold. Cosine distance calculations use normalized input rows.|
|Metric tests, documentation, and examples <br> cpp/oneapi/dal/algo/dbscan/test/, docs/source/api/algorithms/clustering/dbscan.rst, docs/source/onedal/algorithms/clustering/dbscan.rst, docs/source/includes/clustering/dbscan-examples.rst, examples/oneapi/cpp/source/dbscan/, examples/oneapi/dpc/source/dbscan/|Tests compare DBSCAN results with reference distances and cover cosine inputs with zero rows. Documentation and C++ and DPC++ examples describe and exercise the supported metrics.|
Possibly related issues
#3815 extends shared HDBSCAN distance functors and identifies HDBSCAN degree validation as a remaining gap. The changes reuse shared pairwise-distance creation but do not change HDBSCAN degree validation.</dd>
</dl>
</details>
<!-- walkthrough_end -->
<!-- change_assessment_start -->
<!-- change_assessment_commit:"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930" -->
<!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} -->
<!-- change_assessment_end -->
<details>
<summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · previous review <code>5df38</code></summary>
<dl>
<dd>
<!-- final_review_risk_start -->
<!-- final_review_risk_label
Merge Risk: 🔵 Low · up to 5df38
-->
<!-- final_review_risk_coverage:{"sourceCommitId":"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930","coveredCommitId":"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930","kind":"reviewed"} -->
Memory-saving Minkowski DBSCAN may fault for some row widths on Intel AVX-512 builds. The concern is limited to that configuration and has already been reported; the other inspected metric paths are consistent.
<!-- final_review_risk_end -->
</dd>
</dl>
</details>
<details>
<summary><strong>Security architecture risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · up to <code>c10c2</code></summary>
<dl>
<dd>
<!-- architecture_review_start -->
<!-- architecture_review_label
Security Architecture Review
Security architecture risk: 🔵 Low · up to c10c2
-->
The change broadens DBSCAN’s numeric API within its existing execution paths. No introduced security flaw was identified, although distributed failure behavior was assessed from source rather than runtime fault testing.
Retained concerns
No architecture-level concerns identified.
<details>
<summary><strong>Security review details</strong></summary>
<dl>
<dd>
Security Blast Radius
Trust Boundaries and Controls
</dd>
</dl>
</details>
<!-- architecture_review_end -->
</dd>
</dl>
</details>
<!-- pre_merge_checks_walkthrough_start -->
<details>
<summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary>
<dl>
<dd>
| Check name | Status | Explanation |
| :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Title check | !Passed | The title clearly and concisely identifies the primary change: adding Manhattan, Minkowski, Chebyshev, and cosine distance metrics to DBSCAN. |
| Linked Issues check | !Passed | Issue #3623 is closed and provides historical context only. No active directly linked issue remains. No linked-issue coding requirements apply. |
| Out of Scope Changes check | !Passed | The changes match the current DBSCAN metric objective. They add metric and degree accessors, implement the metrics in CPU, GPU, memory-saving, and SPMD paths, add validation and tests, and update docu… |
| Description check | !Passed | The description covers the required structure well. It gives a full summary of the change, with a usage example for set_metric and set_degree and a 'How it works' section for the CPU and GPU paths. It… |
<details>
<summary><strong>Full details: Out of Scope Changes check</strong></summary>
<dl>
<dd>
Explanation
The changes match the current DBSCAN metric objective. They add metric and degree accessors, implement the metrics in CPU, GPU, memory-saving, and SPMD paths, add validation and tests, and update documentation and examples. The shared distance-primitives and HDBSCAN factory changes support this implementation. No unrelated change is demonstrated.
</dd>
</dl>
</details>
<details>
<summary><strong>Full details: Description check</strong></summary>
<dl>
<dd>
Explanation
The description covers the required structure well. It gives a full summary of the change, with a usage example for set_metric and set_degree and a 'How it works' section for the CPU and GPU paths. It lists tests (metrics, degrees, dimensions, weights, memory modes, float and double, GPU SPMD, cosine zero rows vs. scikit-learn, bad arguments), documentation updates (developer guide section, API reference enum, new batch examples), and an API/ABI and breaking-change statement. The template's checklist is not filled in. Its items cover commenting, documentation, signed-off-by commit message, merge conflicts, local testing, green CI, extended tests, and performance measurements. The description does not mark these items or justify any unchecked ones. It also does not state whether the PR is still a draft, and it does not list a scikit-learn_bench PR or performance measurements for the affected DBSCAN path. The PR objectives say the author reports passing host tests on a specific commit, but the description does not mention CI status. The description is mostly complete, so the check passes. The missing checklist and performance information are non-critical for this assessment.
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<!-- pre_merge_checks_walkthrough_end -->
<!-- finishing_touch_checkbox_start -->
<details>
<summary><strong>Finishing Touches</strong></summary>
<dl>
<dd>
<details open>
<summary><strong>Simplify code</strong></summary>
<dl>
<dd>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<!-- finishing_touch_checkbox_end -->
<!-- autopilot:start -->
<!-- autopilot:end -->
<!-- announcements_start -->
[!TIP]
<details>
<summary><strong>🎯 Customize your risk assessments</strong></summary>
<dl>
<dd>
> Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.
> </dd>
</dl>
</details>
> <details>
<summary><strong>✅ Automatic approvals, with your rules</strong></summary>
<dl>
<dd>
> Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.
> </dd>
</dl>
</details>
<!-- announcements_end -->
<!-- tips_start -->
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
<details>
<summary><strong>Share</strong></summary>
<dl>
<dd>
</dd>
</dl>
</details>
<!-- tips_end -->
<!-- verify_invitation_start -->
CodeRabbit Verify
<!-- verify_invitation_end -->
<!-- recent_review_start -->
<h6>
<details>
<summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Recent review info</strong></summary>
<dl>
<dd>
<!-- review_info_content -->
<details>
<summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary>
<dl>
<dd>
138b3f73-6760-4bc4-8c24-b4185d1c6fe6</dd>
</dl>
</details>
<details>
<summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</strong></summary>
<dl>
<dd>
Reviewing files that changed from the base of the PR and between a452c2bb47d61749d071e302efa852c707f87710 and 5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930.
</dd>
</dl>
</details>
<details>
<summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 6</strong></summary>
<dl>
<dd>
cpp/daal/src/algorithms/dbscan/dbscan_utils.h
cpp/daal/src/algorithms/service_kernel_math.h
cpp/oneapi/dal/algo/dbscan/backend/cpu/compute_kernel_brute_force.cpp
cpp/oneapi/dal/algo/dbscan/common.cpp
cpp/oneapi/dal/algo/dbscan/common.hpp
cpp/oneapi/dal/algo/dbscan/test/fixture.hpp</dd>
</dl>
</details>
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.
</dd>
</dl>
</details>
</h6>
<!-- recent_review_end -->
Thanks for the metric additions. The shared poweredEpsilon and the memory-mode tests read well.
Question, the one item to settle before approval: the self-diagonal is forced to zero on CPU (queryFullImpl, queryImpl) and on GPU (j == wg_id). For a zero row under cosine, that puts the row in its own neighborhood even when eps < 1. The test handles zero rows like scikit-learn expects {0,1,2,2} for eps 0.1, min_observations 1. Could you confirm that against sklearn.cluster.DBSCAN(eps=0.1, min_samples=1, metric="cosine") on the same 4x2 fixture? I have not run sklearn here. If sklearn labels those zero rows as noise, zero rows need an exception to the self-inclusion rule, or the test comment needs correcting.
Nit: set_degree validates even for non-Minkowski metrics, but the doc says the degree is ignored. Please align them.
@napetrov thanks, checked both points.
Zero rows under cosine. Confirmed against scikit-learn 1.9.1 with DBSCAN(eps, min_samples, metric="cosine") on the test's fixtures, the 4x2 and the 4x5 one (the wide one gives the same labels):
| eps | min_samples | sklearn labels | test expects |
|---|---|---|---|
| 0.1 | 1 | [0 1 2 2] | {0, 1, 2, 2} |
| 0.1 | 2 | [-1 -1 0 0] | {-1, -1, 0, 0} |
| 1.0 | 4 | [0 0 0 0] | {0, 0, 0, 0} |
Mechanism: sklearn.metrics.pairwise.cosine_distances(X, Y) sets the diagonal to 0 when X is Y, so a zero row is its own neighbor (self-distance 0 <= eps) even though its distance to the other zero row is 1. With min_samples=1 it is therefore a core point and gets its own cluster, which is what the test expects, and it also matches the DBSCAN definition (the eps-neighborhood contains the point itself; sklearn's min_samples doc says "including the point itself").
One caveat for the record: when pairwise_distances_chunked splits the rows into chunks (roughly above 11k rows with the default working_memory), sklearn does not zero the diagonal and the same zero rows come out as noise (-1); I reproduced that on 20002 rows. So sklearn is inconsistent across input sizes there, and forcing the self-distance to 0 is the consistent choice. The test comment now names the path it reproduces.
set_degree vs. doc. Kept the eager validation, like the other setters (set_epsilon, set_min_observations), and aligned the doc: the degree must be positive and finite for every metric and only the Minkowski metric reads it. Both common.hpp and docs/source/onedal/algorithms/clustering/dbscan.rst say so now. Commit 7b0f6ea29, after a merge of current main; //cpp/oneapi/dal/algo/dbscan:tests (host) passes.
Maybe I've missed this during a HDBSCAN review, but now I have questions:
Why distances support here is done differently than in KNN? In KNN distance type is provided as part of the descriptor's template, and here it is a runtime information.
Is it possible now not to duplicate those kind of enums. I.e. HDBSCAN has the same enum. It would be better to have a shared enum defining distance types and just implement checks on descriptor's set methods in case some algorithm does not provide support for some distance types.
To make it more readable:
// A row is always in its own neighborhood.
const size_t kStart = max(i1, j1);
const size_t kEnd = min(i2, j2);
for (size_t k = kStart; k < kEnd; k++) local[(k - i1) * jSize + (k - j1)] = FPType(0);
HDBSCAN's createPairwiseDistances code can be reused here with minor modifications allowing to provide two tables as input arguments instead of one.
I still do not get, why do we need a separate implementation of the distances (MinkowskiDist, etc) laying in HDBSCAN?
Can we just add those pointDist functions into already existing implementations of pairwise distances in service_kernel_math.h and use those in all the algorithms?
memset?
Should there be some tolerance? i.e. fabs(aNorms[i]) < tol?
It is better to move this definition to the place where CosineDistances is defined.
<!-- coderabbit-ai-generated:v1 -->
<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major · Stability & Availability · Quick win
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary>
<dl>
<dd>
Script executed:
printf '%s\n' '--- service_kernel_math.h ---'
nl -ba cpp/daal/src/algorithms/service_kernel_math.h | sed -n '715,810p'
printf '%s\n' '--- dbscan_utils.h indexed query ---'
nl -ba cpp/daal/src/algorithms/dbscan/dbscan_utils.h | sed -n '450,480p;635,670p'
Repository: uxlfoundation/oneDAL
Length of output: 6979
---
</dd>
</dl>
</details>
Use unaligned loads for AVX-512 Minkowski inputs.
The indexed path passes &outData[j outDim] to MinkowskiDistances::computeDistance. A valid 17-float row advances by 68 bytes, so later rows can be unaligned. The AVX-512 specialization dereferences those rows through __m512 or __m512d*, which can cause undefined behavior or a fault. Use _mm512_loadu_ps and _mm512_loadu_pd for every input vector load.
<details>
<summary>Suggested fix</summary>
<dl>
<dd>
- const __m512 * ptr512x = (__m512 *)x;
- const __m512 * ptr512y = (__m512 *)y;
-
...
- d += _mm512_reduce_add_ps(_mm512_abs_ps(_mm512_sub_ps(ptr512x[i], ptr512y[i])));
+ d += _mm512_reduce_add_ps(
+ _mm512_abs_ps(_mm512_sub_ps(_mm512_loadu_ps(x + i * vecSize), _mm512_loadu_ps(y + i * vecSize))));
...
- _mm512_storeu_ps(tmp, _mm512_abs_ps(_mm512_sub_ps(ptr512x[i], ptr512y[i])));
+ _mm512_storeu_ps(tmp, _mm512_abs_ps(
+ _mm512_sub_ps(_mm512_loadu_ps(x + i * vecSize), _mm512_loadu_ps(y + i * vecSize))));
...
- const __m512d * ptr512x = (__m512d *)x;
- const __m512d * ptr512y = (__m512d *)y;
-
...
- d += _mm512_reduce_add_pd(_mm512_abs_pd(_mm512_sub_pd(ptr512x[i], ptr512y[i])));
+ d += _mm512_reduce_add_pd(
+ _mm512_abs_pd(_mm512_sub_pd(_mm512_loadu_pd(x + i * vecSize), _mm512_loadu_pd(y + i * vecSize))));
...
- _mm512_storeu_pd(tmp, _mm512_abs_pd(_mm512_sub_pd(ptr512x[i], ptr512y[i])));
+ _mm512_storeu_pd(tmp, _mm512_abs_pd(
+ _mm512_sub_pd(_mm512_loadu_pd(x + i * vecSize), _mm512_loadu_pd(y + i * vecSize))));
</dd>
</dl>
</details>
<!-- fingerprinting:phantom:medusa:wombat -->
<!-- cr-indicator-types:potential_issue -->
<!-- cr-comment:v1:315dbcd7476e276a79cd9632 -->
<!-- This is an auto-generated reply by CodeRabbit -->
✅ Addressed in commit 104d229
<!-- coderabbit-ai-generated:v1 -->
<!-- This is an auto-generated comment by CodeRabbit for review status -->
<!-- coderabbit-ai-generated:v1 -->
<!-- This is an auto-generated comment by CodeRabbit for review status -->
<!-- coderabbit-review-publication v1 publication=4ed2ec0a-fbed-487b-8ace-f79b17d919f4 attempt=c262714a-b29c-4a05-babc-aa1d72bb38e7 batch=1/1 -->
done
done
done
done
KNN takes the distance as a template because it is a whole separate algorithm (minkowski_distance::descriptor) with its own kernels. In DBSCAN the metric only picks a small distance functor inside one kernel, with degree as the only extra parameter. A runtime enum is simpler here: it matches sklearn's metric= argument, the HDBSCAN descriptor, and the DAAL kernel, which already switches at runtime.
I agree one shared enum is better. I can't do it in this PR, though: HDBSCAN's distance_metric is already part of the public ABI since 2026.2.0, can be changed in major release.
Fixed
No tolerance on purpose: a norm is exactly zero only when the row has no direction at all. Any row with a non-zero norm has a valid cosine, so a tolerance would just drop good rows
/intelci: run
In my understanding his switch could be also replaced with something like:
services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
DAAL_CHECK_MALLOC(metric.get());
return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs, doReset);
@Alexandr-Solovev I think coderabbitai is right here. I'd only add values for x + i vecSize and y + i vecSize in order not to calculate those multiple times.
Done in 104d229f1: PairwiseDistances now has a virtual computeDistance for one pair of rows, so query builds its engine with createPairwiseDistances exactly like queryFull. The batch loops of MinkowskiDistances and ChebyshevDistances call it by qualified name, so they keep inlining it.
Done in 104d229f1: both specializations use _mm512_loadu_ps/_mm512_loadu_pd with the row pointers hoisted into xi/yi.
@Vika-F thanks for the review. Both remaining inline items are in 104d229f1; //cpp/oneapi/dal/algo/{dbscan,hdbscan,knn}:tests pass on host with all ISAs compiled.
On the duplicated enum: agreed, and I would like to converge on one oneapi::dal::distance_metric. hdbscan::distance_metric shipped in 2026.2.0, so turning it into an alias of a shared enum changes the mangled name of set_metric_impl and is an ABI break, which has to wait for 2027.0. That is a follow-up: a shared enum with deprecated aliases in both algorithms. DBSCAN's values and order here are identical to HDBSCAN's so that switch stays mechanical.
On DAAL vs oneDAL: the public DAAL dbscan::Parameter is intentionally unchanged, so DAAL users keep the same API and defaults. The metric only travels from the oneAPI descriptor into the internal kernel, the way HDBSCAN works without any DAAL interface at all. I agree that retiring the DAAL API for algorithms with a oneDAL counterpart is the right direction; that is a deprecation discussion of its own, so I would keep it out of this PR.
<!-- coderabbit-ai-generated:v1 -->
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
<!-- This is an auto-generated mute comment by CodeRabbit -->
/intelci: run
Should there be a zero check?
return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
norm = MathInst<FPType, cpu>::sSqrt(xx * yy);
/intelci: run
/intelci: run
/intelci: run
/intelci: run
Alexandr-Solovev
Description
DBSCAN is hardcoded to the squared Euclidean distance. This PR exposes the neighborhood metric through the descriptor, with the same API as HDBSCAN:
distance_metriciseuclidean(default, unchanged),manhattan,minkowski(degree> 0),chebyshevorcosine, on CPU and GPU, in both memory modes and through GPU SPMD.epsilonis in the units of the selected metric.How it works
Each metric is compared in a form monotone in the true distance: Euclidean squared, Minkowski raised to p, the rest as is;
epsilonis mapped into that form once.service_kernel_math.hengines (EuclideanDistances,MinkowskiDistances,ChebyshevDistances,CosineDistanceswith the zero-row fix-up).ManhattanDist,ChebyshevDist, andMinkowskiDist::poweredPointDist, new and wrapped bypointDist),distancePow2for Euclidean.neighborhood_metric{kind, degree, threshold}, and the accumulation is selected at compile time through onedispatch_distance_kindhelper, so the Euclidean kernel is the same code as before. Kernel signatures stay non-template. Cosine runs on rows normalized once withcompute_squared_l2_norms, so it accumulates a negated dot product and zero rows sit at distance 1. No distance matrix is built.Notes
set_degreerejects non-positive and NaN values (domain_error); an unknown metric throwsinvalid_argument.API/ABI
New public enum
dbscan::distance_metricand descriptor accessorsset/get_metric,set/get_degree(new exported symbols; the descriptor is pimpl, so no layout change). DAALParameteris unchanged; metric and degree are internal kernel arguments.Tests
epsilonplaced in a wide gap between pairwise distances.sklearn.cluster.DBSCAN(metric="cosine").Documentation
epsilonin the units of the selected metric, and the cosine zero-row rule... onedal_enumclass:: oneapi::dal::dbscan::distance_metric.dbscan_brute_force_metrics_batch.cpp(oneAPI C++ and DPC++) run every metric onhdbscan_dense.csv, each with its ownepsilon, and are listed in the DBSCAN examples page.Breaking changes
None.
euclideanstays the default. The only change to the Euclidean path: a row counts in its own neighborhood by index, so round-off can no longer push its self-distance aboveepsilonwhenepsilonis close to zero.Replaces the closed #3623.
🤖 Generated with Claude Code