[Enhancement] Native PyTorch Implementation for `SpearmanRankCorrelation`
Description
The current implementation of SpearmanRankCorrelation in ignite.metrics.regression is a wrapper around scipy.stats.spearmanr and inherits from EpochMetric. This introduces several limitations:
Hard Dependency:
It requires scipy to be installed. As shown in the reproduction below, the metric cannot even be initialized in a pure PyTorch environment.
Memory Inefficiency:
As an EpochMetric, it stores all predictions and targets in a list (O(n) memory complexity), which can lead to Out-Of-Memory (OOM) issues on large datasets.
Performance Bottleneck:
Data must be moved to the CPU and converted to NumPy/Scipy, preventing the metric from running natively on accelerators such as GPU/TPU.
Steps to Reproduce (In Environment Without SciPy)
import torch
from ignite.metrics.regression import SpearmanRankCorrelation
# This raises ModuleNotFoundError immediately
metric = SpearmanRankCorrelation()
Actual Output
ModuleNotFoundError: This module requires scipy to be installed.
Proposed Improvement
I propose a Native PyTorch implementation of SpearmanRankCorrelation that:
Remove the SciPy Dependency
Use torch.argsort or a unique/cumsum-based ranking logic to compute ranks directly in PyTorch.
Use Streaming Accumulation
Instead of relying on EpochMetric, accumulate the necessary sums for the Pearson correlation of ranks incrementally.
This reduces memory complexity from:
O(n) → O(1)
(or O(batch) depending on the ranking approach).
Device Agnostic
Keep all computations on the original device (CPU/GPU) so the metric can run efficiently on accelerators.
Hi @vfdev-5, I'd like to work on refactoring this as part of my GSoC contributions. I believe making this PyTorch-native will significantly improve the portability and performance of Ignite's regression suite. Waiting for your thoughts! 😊.
Okay? Well what are you proposing writing the metric calculation in pytorch? Or using pytorch metrics?
Hi @aaishwarymishra, thanks for the quick response!
I am proposing writing the metric calculation natively in PyTorch within Ignite, rather than wrapping an external library. My plan is to:
- Implement Native Ranking: Use
torch.uniqueandtorch.cumsum(ortorch.argsort) to calculate ranks. This allows us to handle tied ranks (the 'average' method used by SciPy) without leaving the GPU/accelerator - Streaming Pearson Logic: Once we have the ranks, we can use the same stable accumulation logic used in
PearsonCorrelation(addressing the $O(1)$ memory goal). 3.Remove Scipy: This removes theModuleNotFoundErrorfor users without SciPy and keeps the data on the original device.
I've already benchmarked the memory growth of the current EpochMetric implementation, and I'm happy to share a draft of the native ranking logic if you'd like to see the approach!
@vfdev-5 what do you think? I think few metrics can be optimized.
Yes, we can rewrite some metrics computation in online way etc. I think this is not a priority, especially, that we should 1) make sure about the correctness of the implementation and 2) code maintenance. However, if someone who needs this for their project and would like to give a hand with points 1 and 2, the contributions are welcome.
Hi @vfdev-5, thanks for the feedback!
I just wanted to give a quick update. My mid-semester exams are currently ongoing, so progress on the implementation may be a bit slower for the next couple of weeks. That said, I am actively working on the design and validating the ranking logic to ensure correctness before submitting a PR.
I'll share an update or draft implementation as soon as I have a stable version ready. Thanks for the guidance!
@Prathamesh8989 what does your PR: O(n) or O(1) ?
Hi @vfdev-5, to be precise, the current PR is O(n) because it inherits from EpochMetric to ensure correct global ranking across the entire dataset.
However, it achieves two of the primary goals:
Zero-Dependency: It removes the SciPy requirement.
Accelerator Native: Computation stays on the GPU/TPU instead of forcing a move to CPU/NumPy.
A true O(1) implementation for Spearman is mathematically challenging because ranking is a global operation. I'm focusing on getting the native PyTorch logic correct first. Do you prefer that I stick with this native EpochMetric approach, or should I explore an approximation for O(1)?
@Prathamesh8989 your plan here already speaks about O(1) and not O(n): https://github.com/pytorch/ignite/issues/3663#issuecomment-4025562288 I have an impression that you use an AI bot to write these descriptions and they diverge with the code your provide.
To move forward with your PR, we have to ensure that we cover all parameters that scikit-learn covers and also ensure the correctness and edge cases. If you can help to make these checks more transparent.
Hi @vfdev-5, thanks for pointing that out — that’s fair.
You're right that my initial proposal mentioned an O(1) streaming approach, but after looking deeper into the problem, I realize that exact Spearman correlation requires global ranking, so a true O(1) implementation isn't practical without approximation.
I think this is where my initial description and the realistic implementation direction diverged — I’ll make sure to keep the proposal aligned more clearly going forward.
For now, I’d like to focus on a more concrete improvement:
- Native PyTorch implementation (removing SciPy dependency)
- Device-agnostic execution (CPU/GPU)
- Ensuring correctness by matching scipy.stats.spearmanr (including ties and edge cases)
I can also make the validation more transparent by:
- Adding comparison tests against SciPy / scikit-learn
- Clearly documenting assumptions and complexity (O(n))
Please let me know if this direction sounds good, or if you'd prefer exploring approximation-based approaches separately.