Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Numerical stability fixes for l2 pairwise distance #1319

Merged
merged 4 commits into from
Mar 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion cpp/include/raft/distance/detail/euclidean.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ struct L2ExpandedOp {
__device__ AccT operator()(DataT& aNorm, const DataT& bNorm, DataT& accVal) const noexcept
{
AccT outVal = aNorm + bNorm - DataT(2.0) * accVal;
// outVal could be negative due to numerical instability, especially when
// calculating self distance.
// clamp to 0 to avoid potential NaN in sqrt
outVal = outVal * (outVal > DataT(0.0));
return sqrt ? raft::sqrt(outVal) : outVal;
}

Expand Down Expand Up @@ -122,7 +126,8 @@ void euclideanExpImpl(const DataT* x,
for (int i = 0; i < KPolicy::AccRowsPerTh; ++i) {
#pragma unroll
for (int j = 0; j < KPolicy::AccColsPerTh; ++j) {
acc[i][j] = regxn[i] + regyn[j] - (DataT)2.0 * acc[i][j];
DataT val = regxn[i] + regyn[j] - (DataT)2.0 * acc[i][j];
acc[i][j] = val * (val > DataT(0.0));
}
}
if (sqrt) {
Expand Down