cuml: [BUG] the UMAP implementation much worse than on CPU

Describe the bug

The GPU-accelerated implementation from cuml can give much worse results than the CPU alternative from the package umap on a simple dataset. By visual inspection, we see that the clusters are less separable and there are many outliers. I wonder if the gap could be bridged somehow by non-obvious customization (that my example is missing)? Any help appreciated 🙏

NOTE: I show a toy example to facilitate debugging. I have also seen a complex NLP pipeline with UMAP responsible for dimensionality reduction, where switching from umap to cuml cost as much as 8% in terms of the coherence score.

Steps/Code to reproduce bug

from sklearn.datasets import fetch_openml
import matplotlib.pyplot as plt
%matplotlib inline
import umap
import cuml

X,y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)
y = y.astype(int)

umap_model_1 = umap.UMAP(random_state=42, n_components=2, n_neighbors=12, min_dist=0.0).fit(X)
umap_model_2 = cuml.UMAP(random_state=42, n_components=2, n_neighbors=12, min_dist=0.0).fit(X)

embeds_1 = umap_model_1.transform(X)
embeds_2 = umap_model_2.transform(X)

fig,axs = plt.subplots(1,2)
axs[0].scatter(embeds_1[:,0], embeds_1[:,1], c=y, s=0.1, cmap='Spectral')
axs[1].scatter(embeds_2[:,0], embeds_2[:,1], c=y, s=0.1, cmap='Spectral')
plt.show()

image

Expected behavior

Results should be much closer.

Environment details (please complete the following information):

  • Linux Distro/Architecture: [Ubuntu 20.04 x86_64]
  • GPU Model/Driver: [L4 / GeForce RTX 3090]
  • CUDA: [12.2]
  • Docker by NVIDIA: nvcr.io/nvidia/pytorch:23.09-py3

See also the original discussion on umap gh repo

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 2
  • Comments: 23 (7 by maintainers)

Most upvoted comments

The initialization of UMAP is indeed super important to attain quality in the global structure (https://www.nature.com/articles/s41587-020-00809-z). And cuML seems to have a bug regarding that (see #5782). The random initialization is not a good option according to these, and does not seem to capture the global structure well, at least with the default parameters.

I’ve managed to get better UMAPs by astronomically increasing the number of epochs (to 500000!), the number of neighbors and negative sample rate (corresponding to the repulsive realizations). By doing that I end up with nice results even for large datasets. However this completely undermines the usefulness of a GPU-based method as it can take more time than the CPU implementation to attain a similar quality. I think this is a critical limitation of cuML and a dangerous one for scientific analysis. Libraries for single cell analysis are now providing the option of using cuML to perform UMAP.

Would it be possible (and maybe easier to implement) a way to provide our own initialization as a parameter?

This would allow us to use PCA, for instance, which can lead to higher quality than the current implementation or random initialization. This would also allow us to apply UMAP and resume it afterwards with more iterations.

Good news! Two sets of major fixes have been implemented in the soon-to-be-released 25.04 version, which should resolve the issues discussed in this thread. The first one resolves issues regarding spectral initialization (laplacian matrix fix + lanczos solver fix). The second one is a bug in the transform function.

Please note that the cuML implementation of UMAP does not strictly follow its reference counterpart, which may lead to some numerical instabilities. If you continue to see outliers in projections, please consider increasing the number of epochs (n_epochs). Additionally, adjusting parameters such as negative_sample_rate and repulsion_strength might possibly help mitigate issues like overlapping samples from different classes.

A special thank you to @RaisoLiu for his excellent temporary solution!

If you continue to experience problems, please open a new issue with details. Thanks to everyone for your patience and contributions!

Closing this for now.

Hey everyone,

Sorry for being late to this discussion. I think one of the problems here might be the assumption that cuML’s UMAP will always yield the exact same results as the CPU-based reference implementation for the exact same parameter settings. We did some parallelism magic on the GPU side to speed up the algorithm and as a result, it’s possible that some of the parameters (such as the number of iterations for the solver) might need to be tweaked a bit.

In addition, the underlying GPU-accelerated spectral embedding initialization primitive has gotten fairly old by this point and hasn’t been updated in quite some time so it’s been accumulating little bugs as CUDA versions increase and the code itself becomes more stale. I suggest trying to use the random initialization, along with adjusting the number of neighbors and the number of iterations to see if that improves the quality of your embeddings.

We have an engineer ramping up to fix the spectral clustering initialization and they will also be working to improve the end to end quality of the results. Again, I apology sincerely for the delay in replying to this thread.

Here is my solution before the problem is fixed.

from cuml.manifold.umap import fuzzy_simplicial_set, simplicial_set_embedding
from umap.spectral import spectral_layout
from cuml.manifold.umap_utils import find_ab_params
import numpy as np

class UMAP:
    def __init__(self, n_epochs, n_neighbors, n_components, min_dist=0.1, random_state=np.random.randint(1, 1000), verbose=False):
        self.n_epochs = n_epochs
        self.n_neighbors = n_neighbors
        self.n_components = n_components
        self.min_dist = min_dist
        self.random_state = random_state
        self.verbose = verbose


        
    def fit_transform(self, X):
        graph = fuzzy_simplicial_set(X, 
                                     n_neighbors=self.n_neighbors, 
                                     random_state=self.random_state, 
                                     metric='euclidean', 
                                     verbose=self.verbose)
        
        layout = spectral_layout(X, graph.tocsr().get(), 
                                 dim=self.n_components, 
                                 random_state=self.random_state)
        spread = 1.0
        a, b = find_ab_params(spread, self.min_dist)
        embedding = simplicial_set_embedding(X, graph, 
                                             init=layout,
                                             a=a, b=b,
                                             n_epochs=self.n_epochs,
                                             n_components=self.n_components,
                                             random_state=self.random_state, 
                                             verbose=self.verbose)
        
        return embedding.to_host_array()

Image

Can we get an update on this issue? I also faced it while trying to use cuml.UMAP to speed up BERTopic. I’ve noticed that the problem gets much worse when the number of prediction samples increases relative to the number of training samples.

Building on @maciejskorski’s example above:

from sklearn.datasets import fetch_openml
import matplotlib.pyplot as plt
%matplotlib inline
import umap
import cuml

X,y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)
y = y.astype(int)

umap_model_1 = umap.UMAP(random_state=42, n_components=2, n_neighbors=12, min_dist=0.0).fit(X[:10000])
umap_model_2 = cuml.UMAP(random_state=42, n_components=2, n_neighbors=12, min_dist=0.0).fit(X[:10000])

embeds_1_small = umap_model_1.transform(X[10000:20000])
embeds_2_small = umap_model_2.transform(X[10000:20000])
embeds_1_large = umap_model_1.transform(X[10000:70000])
embeds_2_large = umap_model_2.transform(X[10000:70000])

fig,axs = plt.subplots(2,2, figsize=(12, 8))
axs[0, 0].scatter(embeds_1_small[:,0], embeds_1_small[:,1], c=y[10000:20000], s=0.1, cmap='Spectral')
axs[0, 0].set_title("CPU, 10k predictions")
axs[0, 1].scatter(embeds_2_small[:,0], embeds_2_small[:,1], c=y[10000:20000], s=0.1, cmap='Spectral')
axs[0, 1].set_title("GPU, 10k predictions")
axs[1, 0].scatter(embeds_1_large[:,0], embeds_1_large[:,1], c=y[10000:70000], s=0.1, cmap='Spectral')
axs[1, 0].set_title("CPU, 60k predictions")
axs[1, 1].scatter(embeds_2_large[:,0], embeds_2_large[:,1], c=y[10000:70000], s=0.1, cmap='Spectral')
axs[1, 1].set_title("GPU, 60k predictions")
plt.show()

image

Also echoing this, in my experience the results from cuML’s UMAP are often unusable, which is a shame as it’s so fast! Funnily enough though I’ve seen the opposite behaviour to @Bougeant; when running transform on ~25k instances, the clusters are fairly well separated when fit is run on a random sample of 1000 instances, but increasing this to 5000 or running fit_transform on the 25k leads to results like the bottom right figure.

Fingers crossed on a fix for this one @dantegd! 🤞🏻

For an update, issues were identified in the algorithm that generates the spectral embedding initialization and work is being done to fix it. Also, with the nightly version you can now provide your own initialization as a parameter to the simplicial_set_embedding function. In order to use this function, you first need to train a fuzzy simplicial set with the appropriate function.

Thanks for the update @cjnolet!

I think it’s quite clear to me that we’re not going to get exactly the same results with cuML’s UMAP and the CPU-based umap.UMAP. However, while in my example above, the CPU and GPU clusters for 10k datapoints are probably of similar quality, the one with 60k datapoints is clearly worse for the GPU generated clusters (even though when we zoom into the ±15 range, the clusters look decent for the GPU case as well).

@MaartenGr, as the author of Bertopic, you might be interested in this.

Thanks for the issue @maciejskorski, and thanks for the great and easy to repro example/code 😃. Can confirm repro’ing on totally different hardware, we’ll be looking into it alongside a few updates we want to do to UMAP. The discrepancies, alongside points between clusters are larger than I would’ve expected. Will update issue as we progress with findings.

Thanks for the thoughtful question @alexwilson1! The quality of embeddings can be evaluated by analyzing the similarity of sample neighborhoods in the projected space compared to the original space. One way to measure this is by using the trustworthiness score. Please ensure that you specify an appropriate value for n_neighbors (as well as the metric) to obtain meaningful results.

That’s a very fun test case of the problem and solution @RaisoLiu 😃

I can confirm on a more complex case that the results are indeed better with the cpu_spectral approach. As a note, to get the embeddings back onto the host as a Numpy array, you can use embeddings.to_output().get()

@KanishkT123 we are still working on getting improvements (contributions from the community reviewed and merged) so thanks for bearing with us here.

Depending on the dataset size, more epochs is not always better. Small precision errors can also accrue much faster with highly parallel implementations of algorithms that use atomics and where mantissas even for very minor arithmatic are drastically different. Unfortunately, I don’t have one answer of suggestion that can solve all of these cases because this is more of a computing problem in specific datasets than it is a global problem. Many datasets can have great results with umap with only minor tweaks to the params. Other datasets unfortunately run into precision errors that accrue across computational steps.

We have fixes to the lanczos solver that make it faster and more stable which should be merged soon (as in, likely within the next few weeks). We have some engineers also looking into other stability problems. I apologize our timeline for these changes has been fairly slow, but we do also accept patches from (and are willing to guide) folks who might be able to provide their own time to help this along as well.

Thanks again for using this algorithm and helping us better characterize the issue.

@Bougeant Yes, the GPU should not look worse than CPU, that’s not expected.

What is expected, though, is that the same parameter settings might yield different results, and that sometimes causes the need for the number of iterations to be tweaked.

If you have a moment to try the init=random, it would be helpful to know if that improves anything for you.