def spearman_formula(predictions, labels, mask=None):
    """
    This function is spearman formula from:
        https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
    """
    if mask is not None:
        predictions = predictions * mask
        labels = labels * mask

    # if all number of a set is same, return np.nan
    if len(torch.unique(predictions)) == 1 or len(torch.unique(labels)) == 1:
        return float("NaN")

    len_pre = len(predictions)

    predictions = [(k, v) for k, v in enumerate(predictions)]
    predictions.sort(key=lambda x: x[1], reverse=True)
    predictions = [(k, v) for k, v in enumerate(predictions)]
    predictions.sort(key=lambda x: x[1][0])

    labels = [(k, v) for k, v in enumerate(labels)]
    labels.sort(key=lambda x: x[1], reverse=True)
    labels = [(k, v) for k, v in enumerate(labels)]
    labels.sort(key=lambda x: x[1][0])

    total = 0
    for i in range(len_pre):
        total += (predictions[i][0] - labels[i][0]) ** 2
    expected_spearman_correlation = 1 - 6 * total / (len_pre * (len_pre**2 - 1))

    return expected_spearman_correlation
This function is spearman formula from:
https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
tests/training/metrics/spearman_correlation_test.py