Skip to content

ENH check t-SNE input are all finite - #32041

Closed
Tokasumi wants to merge 1 commit into
scikit-learn:mainfrom
Tokasumi:tsne_valid_check
Closed

Tokasumi wants to merge 1 commit into
scikit-learn:mainfrom
Tokasumi:tsne_valid_check

Conversation

@Tokasumi

Copy link
Copy Markdown

Reference Issues/PRs

#28368 reports crashes caused by t-SNE on Windows.

#29127 reports crashes on Mac.

What does this implement/fix? Explain your changes.

Before calling _tsne(), check the initialization array X_embedded to be all finite.

Any other comments?

In sklearn.manifold._t_sne.TSNE._fit:

        if isinstance(self.init, np.ndarray):
            X_embedded = self.init
        elif self.init == "pca":
            pca = PCA(
                n_components=self.n_components,
                svd_solver="randomized",
                random_state=random_state,
            )
            # Always output a numpy array, no matter what is configured globally
            pca.set_output(transform="default")
            X_embedded = pca.fit_transform(X).astype(np.float32, copy=False)
            # PCA is rescaled so that PC1 has standard deviation 1e-4 which is
            # the default value for random initialization. See issue #18018.
            X_embedded = X_embedded / np.std(X_embedded[:, 0]) * 1e-4
        elif self.init == "random":
            # The embedding is initialized with iid samples from Gaussians with
            # standard deviation 1e-4.
            X_embedded = 1e-4 * random_state.standard_normal(
                size=(n_samples, self.n_components)
            ).astype(np.float32)

The line X_embedded = X_embedded / np.std(X_embedded[:, 0]) * 1e-4 would leads to all-NaN entries. This could happen if np.std(X_embedded[:, 0]) evaluates to zero (The #29127 case) if the first principal component has zero standard deviation.

By user input, the line X_embedded = self.init would include NaN or Inf entries. The crash caused by sklearn.manifold.TSNE can be reproduced by inserting a NaN or Inf entry to the initial X_embedded:

x = np.random.random(size=(5, 7))

init_x_embeddings = np.random.random(size=(5, 2))  # user-defined initials

init_x_embeddings[1, 1] = np.nan  # <<<<<<<<<< insert a nan here

tsne = TSNE(n_components=2, perplexity=3, verbose=5, init=init_x_embeddings)
embeddings = tsne.fit_transform(x)
print(embeddings)

The code runs into Segmentation fault

[t-SNE] Computing 4 nearest neighbors...
[t-SNE] Indexed 5 samples in 0.000s...
[t-SNE] Computed neighbors for 5 samples in 0.014s...
[t-SNE] Computed conditional probabilities for sample 5 / 5
[t-SNE] Mean sigma: 0.610483
[t-SNE] Computed conditional probabilities in 0.001s
Segmentation fault (core dumped)

Or run with gdb

Thread 1 "python" received signal SIGSEGV, Segmentation fault.
0x00007fff4bf46d59 in __pyx_f_7sklearn_9neighbors_10_quad_tree_9_QuadTree__insert_point_in_new_child ()
   from /home/tokai/dev/sklearn_tsne/scikit-learn/build/cp312/sklearn/neighbors/_quad_tree.cpython-312-x86_64-linux-gnu.so

Same outcome if Inf or -Inf is inserted to the embeddings, and same happens on Windows.

go further...

The _QuadTree is used by _kl_divergence_bh to calculate KL-divergence. The _QuadTree.build_tree() is recursive.

import numpy as np
from sklearn.neighbors._quad_tree import _QuadTree

Y = np.array([[np.nan, np.nan], [np.nan, np.nan]], dtype=np.float32)
print(Y)

tree = _QuadTree(n_dimensions=2, verbose=0)
tree.verbose = 500
tree.build_tree(Y)

Result of above snippet:

[QuadTree] inserted point 0 in new child 32713
[QuadTree] Inserting depth 32712
[QuadTree] selected child 32713
[QuadTree] Inserting depth 32713
[QuadTree] inserted point 0 in new child 32714
[QuadTree] Inserting depth 32713
[QuadTree] selected child 32714
[QuadTree] Inserting depth 32714
[QuadTree] inserted point 0 in new child 32715
[QuadTree] Inserting depth 32714
[QuadTree] selected child 32715
[QuadTree] Inserting depth 32715
[QuadTree] inserted point 0 in new child 32716
[QuadTree] Inserting depth 32715
[QuadTree] selected child 32716
[QuadTree] Inserting depth 32716
[QuadTree] inserted point 0 in new child 32717
[QuadTree] Inserting depth 32716
[QuadTree] selected child 32717
[QuadTree] Inserting depth 32717
Segmentation fault (core dumped)

The cause of the crash is highly suspected to be stack overflow caused by infinite recursion.

@github-actions

github-actions Bot commented Aug 28, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: dc779c3. Link to the linter CI: here

@dkobak

dkobak commented Sep 20, 2025 •

Copy link
Copy Markdown
Contributor

There are actually two issues here.

One is that PCA initialization cannot be scaled to have std 1e-4 if all input points are identical (as in #28368) and PCA has zero variance:

data = np.zeros((91, 3))

Another issue is that Barnes--Hut can cause problems if some points overlap exactly, as reported in #28368:

Note that it also happens when only a relative small proportion of points are equal (but only sometimes?), this is just the easiest way to show it.

This will happen in PCA initialization if some input points are identical.

A simple workaround to prevent both issues is to add a small amount of random noise to the PCA initialization. This is what is done in the openTSNE library: https://github.com/pavlin-policar/openTSNE/blob/master/openTSNE/initialization.py#L139, and was introduced there to get rid of similar Barnes--Hut-related issues.

For example:

X_embedded = X_embedded / np.std(X_embedded[:, 0]) * 1e-4
X_embedded += 1e-6 * random_state.standard_normal(
                size=(n_samples, self.n_components)
            ).astype(np.float32)

This should fix the reported issues.

I don't think we necessarily need to remove nans/infs from the user-provided init... If a user explicitly provides a broken initialization, then it's their problem.

@dkobak dkobak mentioned this pull request Sep 20, 2025
@adrinjalali

Copy link
Copy Markdown
Member

I think we also need good tests to see how each solution's dealing with the issue and which one's really necessary.

@dkobak do you have good reproducers at hand?

@dkobak

dkobak commented Oct 6, 2025

Copy link
Copy Markdown
Contributor

I think we also need good tests to see how each solution's dealing with the issue and which one's really necessary.

I agree.

@dkobak do you have good reproducers at hand?

No, not really. But I now tried the following:

X, _ = load_iris(return_X_y=True)
X = np.concatenate((X, X, X, X, X, X, X, X, X, X))
Z = TSNE(verbose=2, init="pca").fit_transform(X)

and while this does not crash, it reports negative Kullback-Leibler divergence, which is clearly mathematically impossible:

[t-SNE] Iteration 1000: error = -1.2604096, gradient norm = 0.0000791 (50 iterations in 0.164s)

Running the same code with init="random" does not lead to negative KL values:

[t-SNE] Iteration 1000: error = 0.0397266, gradient norm = 0.0000866 (50 iterations in 0.146s)

I am pretty sure that the negative KL values are due to points exactly overlapping at initialization, and consequently Barnes--Hut experiencing weird issues (which apparently can sometimes lead to a crash). Adding a small amount of noise to the PCA initialization should fix this.

@adrinjalali adrinjalali added the Closing candidate indicating we might close this one soon / at a later review label Oct 7, 2025
@adrinjalali

Copy link
Copy Markdown
Member

Marking as "Closing candidate" to come back to this in case @Tokasumi doesn't respond here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Closing candidate indicating we might close this one soon / at a later review module:manifold

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants