Skip to content

Fix numerical instability in silhouette/distance computation#5

Merged
maarten-devries merged 1 commit into
mainfrom
fix/silhouette-numerical-stability
Mar 23, 2026
Merged

Fix numerical instability in silhouette/distance computation#5
maarten-devries merged 1 commit into
mainfrom
fix/silhouette-numerical-stability

Conversation

@maarten-devries

Copy link
Copy Markdown
Owner

Summary

  • cdist euclidean used the expansion formula (||x||² + ||y||² - 2xy) which suffers from catastrophic cancellation in float32 for nearby points. Switched to the direct formula sqrt(sum((x-y)²)) with sub-chunking over y to manage GPU memory, matching scib-metrics (JAX) behavior.
  • Fixed silhouette denominator: (label_freqs - 1)[labels] instead of cp.maximum(label_freqs[labels] - 1, 1) to match scib-metrics singleton handling.
  • Fixed mean_other mode in _silhouette_reduce to use nan/nansum instead of 0.0/sum.

Impact

Before this fix, benchmarking against scib-metrics showed large discrepancies:

Metric scib-metrics scib-rapids (before) scib-rapids (after)
silhouette_batch (1k) 0.8047 0.7180 0.8047
bras (1k) 0.6793 0.5924 0.6791
isolated_labels (1k) 0.5763 0.8323 0.5763

All metrics now agree to <0.0002 on Tabula Sapiens data (1k and 20k cells).

Test plan

  • Verified equivalence on 1k cell benchmark (all diffs < 0.0002)
  • Verified equivalence on 20k cell benchmark (all diffs < 0.0002)

🤖 Generated with Claude Code

cdist used the expansion formula (||x||²+||y||²-2xy) which suffers from
catastrophic cancellation in float32 for nearby points. Switch to the
direct formula sqrt(sum((x-y)²)) to match scib-metrics (JAX) behavior.

Also fix silhouette denominator handling and mean_other mode to exactly
match scib-metrics. Verified: all metrics now agree to <0.0002 on both
1k and 20k cell Tabula Sapiens benchmarks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@maarten-devries maarten-devries merged commit aab7947 into main Mar 23, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant