Skip to content

Enable config setting sparse_interface to control sparray and spmatrix creation - #31177

Merged
lesteve merged 35 commits into
scikit-learn:mainfrom
dschult:impl_as_sparse_function
Mar 11, 2026
Merged

lesteve merged 35 commits into
scikit-learn:mainfrom
dschult:impl_as_sparse_function

Conversation

@dschult

@dschult dschult commented Apr 11, 2025

Copy link
Copy Markdown
Contributor

This PR sets up a config parameter sparse_interface to indicate "sparray" or "spmatrix" outputs, as suggested in #26418.

The first commit sets everything up and implements the system for a few modules. Please take a look and provide feedback for whether this is the way to proceed. The next commit(s) will implement these same style of changes throughout the library. If you would prefer they be in separate PRs let me know. (I'll keep Draft status until there is feedback and the full library is convered.)

More specifically, this PR does the following:

  • adds sparse_interface to the config parameters. (I think this name is better than sparse_format because "format" means csr/coo/lil, etc in the sparse world.) The values it can hold are "sparray" or "spmatrix". Update config tests accordingly.
  • adds utils._sparse.py with (private) helper functions. The difference is how much checking is done. Tests added too.
    • _as_sparse(x_sparse), raises unless sparse input. converts to interface chosen by config.
    • _select_interface_if_sparse(x), allows dense input with no action, sparse input uses _as_sparse.
    • one-line convenience functions: _convert_from_spmatrix_to_sparray(x) and _convert_from_sparray_to_spmatrix(x)
  • updates the following modules to use this helper utility to return or store newly created sparse objects.
    • sklearn/feature_selection/text.py and adapts tests.
    • sklearn/linear_model/_coordinate_descent.py no tests change needed.
    • sklearn/manifold/_locally_linear.py no tests change needed.

@thomasjpfan can you see if this does what you had in mind? I tried to pick modules that cover returning sparse, setting estimators to hold sparse, and transforming to sparse, so you can see how this would work.

Let me know if you think _as_sparse should be a public function, and if my approach aligns with how you want it. The next steps for this PR are to repeat these type of changes throughout the library.

@github-actions

github-actions Bot commented Apr 11, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

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

Generated for commit: 511b41d. Link to the linter CI: here

@dschult

dschult commented Apr 11, 2025

Copy link
Copy Markdown
Contributor Author

Another note:
The new sparse construction function eye_array(n) which is the sparray version of eye(n) was released in SciPy v1.12 along with other construction functions like diags_array. So they will not work with the oldest supported version being v1.8.

We can work around it for now with e.g. _as_sparse(eye(n)), but it will need to be updated later (before spmatrix is removed).

The recent features for sparse by version are:

  • v1.12 added construction function e.g. eye_array, diags_array, etc
  • v1.14 added 1D sparray support
  • v1.15 added indexing for sparray which returns 1D objects (like numpy.array does), e.g. A[3,:] -> 1D array
    goals: v1.16 nD support, v1.17 broadcasting of binary operations.

This info might help us decide when to support which versions. I think the construction functions are all that is currently needed. If/when we start using indexing code for both sparse and dense, we will likely want 1.15. If/when we want nD sparse we will need v1.16, and broadcasting binary operations in v1.17. But for now, 1.8 leaves out only construction functions from current code.

@dschult

dschult commented May 4, 2025

Copy link
Copy Markdown
Contributor Author

It sounds like the community has decided to convert to SciPy sparray using the config parameter. This PR is a start toward that. I've removed the "Draft status" from the PR. I am ready to implement this approach in other parts of the library.

I have two questions:

  • should I put the changes for other parts of the library in a different PR?
  • Is there a timeline for bumping up the minimum version dependence on scipy? I will likely want to add a few functions to fixes.py and knowing their expected lifetime would give context to that effort. If it isn't known, that's a fine answer too.

@dschult
dschult marked this pull request as ready for review May 4, 2025 03:35

@thomasjpfan thomasjpfan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, this is basically what I had in mind.

Comment thread sklearn/utils/_sparse.py Resolved
@dschult
dschult force-pushed the impl_as_sparse_function branch 3 times, most recently from 5e3d3cd to 511de76 Compare May 8, 2025 03:29
@dschult

dschult commented May 8, 2025

Copy link
Copy Markdown
Contributor Author

I've updated the name and example code -- and I added a commit that implements (with a utils shim function for SciPy versions older than 1.12) the 4 sparray construction functions. I've named them _sparse_eye, _sparse_diags, _sparse_random and _sparse_block. They call eye_array, diags_array, random_array and block_array on recent versions of SciPy.

These changes are largely orthogonal to the return sparse interface issue we've been focusing on here. But it is a needed step that would be easier to get feedback on here before this gets any bigger. If you'd prefer this in a different PR let me know. And if it'd be good to put further changes in a separate PR let me know. The further changes are mostly switching csr_matrix calls to csr_array with _align_api_if_sparse at the end of the function if it will be returned or stored somewhere.

Do my choices for function names that bridge the old versions of SciPy look ok?
Thanks!

@dschult
dschult force-pushed the impl_as_sparse_function branch 3 times, most recently from 8b58511 to a802f12 Compare July 19, 2025 17:04
@dschult
dschult force-pushed the impl_as_sparse_function branch 3 times, most recently from 05da23c to 6fbaae6 Compare July 25, 2025 17:50
@dschult
dschult force-pushed the impl_as_sparse_function branch 2 times, most recently from 8994094 to 220e7f1 Compare July 26, 2025 17:32
@dschult
dschult force-pushed the impl_as_sparse_function branch 2 times, most recently from 5d190f2 to 2d71b2c Compare August 3, 2025 16:37
@dschult

dschult commented Aug 4, 2025 •

Copy link
Copy Markdown
Contributor Author

Okay, I think this is finally ready for review. I've implemented a config to determine the type of sparse matrix to return (sparray or spmatrix). Both kinds can be used for sparse inputs.

New helper functions in utils._sparse.py:

  • _align_api_if_sparse(X) changes the sparse type if needed
  • _sparse_random, _sparse_eye_array, _sparse_diags (sparse construction functions across versions 1.8->1.12-> 1.15+)
  • _ensure_sparse_index_int32(X) sets index dtype for sparse X to be int32 if safe to do so. Raise if not. Useful when using libraries that only support int32 index arrays.
  • safely_cast_index_arrays local version of scipy.sparse._sputils.safely_cast_index_arrays that works across SciPy versions.

New Scipy Version bool flags to ease indexing code that depends on SciPy version (mostly index that make 1D arrays):

  • SCIPY_VERSION_BELOW_1_12
  • SCIPY_VERSION_BELOW_1_15

All internal constructors are switched to sparray, e.g. csr_array, csc_array, etc.
Return values are converted to the interface specified in config 'sparse_interface'.
code, docs, rst files, doc_strings, benchmarks are all updated.

If you want me to separate this into smaller PRs, let me know.

CC: @thomasjpfan , @lorentzenchr, @jjerphan, #26418

@lorentzenchr lorentzenchr added this to the 1.8 milestone Aug 6, 2025
@lorentzenchr

Copy link
Copy Markdown
Member

@scikit-learn/core-devs ping for visibility

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems pretty straightforward to me.

Comment thread sklearn/_config.py
Comment on lines +203 to +204
- `"sparray"`: Return sparse as SciPy sparse array
- `"spmatrix"`: Return sparse as SciPy sparse matrix

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we changing this default at some point? Should we introducing a deprecation cycle at the same time?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I propose to start a deprecation in a different PR because we first need to find a consensus as per when we do that.

Comment thread sklearn/_config.py Resolved
Comment thread sklearn/manifold/_isomap.py Resolved
@dschult

dschult commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor Author

I'm going to resolve conflicts with main once again here.

I think we need to decide what's going to happen with this PR. We are about midway between releases so if we wait much longer we won't have time to let people try it on the pre-release level. We are close to completion, but I don't think we have a way to know how many changes are left. I've tried hard to find everything -- and I like the spirit of the 80-20 effort approach that @lorentzenchr put forward. We get rid of most of the problems here and we pay close attention after it is merged and respond fully and quickly when issues arise. I think we have experience with the types of problems and how to approach fixing them.

I can offer some intensive attention over the next 2-3 months on Issues and PRs that tag me. And again after the next release. I can also offer attention over the next 3 years. Beyond that it is hard to forecast. :)

I'm hearing conflicting suggestions, so I'd like to ask some questions here about what needs to be done to this before it gets merged.

  • Testing new code additions for spmatrix: I added code to conftest.py that can be turned on for a CI run and makes new code and tests fail if they use improper spmatrix operations (like * for matmul or ** for matrix_power). This is not configured to actually have a CI run with it. Should I leave it in? It could be used locally I suppose. Or it could be turned into a CI path via a later PR.

  • Protecting estimator attributes: I think the config parameter should protect people from surprises. If they keep the setting for spmatrix they should be able to use the old spmatrix code they've made to work with the attributes of the estimators. If/when they flip the config switch to sparray, they might have issues, but can go back to their working code by flipping back again.

  • I've looked for code additions since the start of this PR that assume spmatrix (as of two weeks ago). So we should be pretty good at this point.

Can you guys put this PR on the agenda for a meeting and hopefully decide on a path forward for it? I'll resolve conflicts and merge with main in the meantime. Thanks!!

@jeremiedbb jeremiedbb moved this from Todo to In progress in Labs Feb 16, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

@scikit-learn/core-devs @thomasjpfan @lesteve @adrinjalali I intent to merge this by the end of February because it is a pain to keep this PR up to date. If you disagree on the approach of this PR, please tell so.

@thomasjpfan thomasjpfan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm +1 on moving forward with this before the next release. High level thoughts:

  1. I suspect there will be unexpected side effects from this PR that we will uncover when it's released.
  2. It'll be easy to miss the _align_api_if_sparse for future functions.

Comment thread sklearn/conftest.py
if not PARALLEL_RUN_AVAILABLE:
parser.addini("thread_unsafe_fixtures", "list of stuff")
parser.addoption(
"--check_spmatrix",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the plan to run this in CI at some point?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@adrinjalali requested a CI run dedicated to this kind of thing. It is currently set up to work at the command line. It could be put into CI in a follow-up PR. I don't think it should be in this PR.

assert not hasattr(clustering, "distances_")


@pytest.mark.no_check_spmatrix # pickle breaks check_spmatrix

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How will a contributor know to add the no_check_spmatrix marker?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They will need to add the no_check_spmatrix mark for tests that require the on-disk code files. This currently only occurs for tests using pickle on spmatrix objects and tests that look for the __module__ attribute of the class.

That is hard to teach a contributor -- and it is too detailed to include in a contributor guide. I also don't think we can anticipate all the ways they could use an in-memory coded class as if it is written in a file in the repo.

I guess that's a reason for not doing this kind of test -- that is, we could remove the code in this PR's conftest.py. I'd be fine with that.

Even more than a contributor not knowing how to handle it, will the reviewers remember how to handle it? If they remember that spmatrix stuff should tag @dschult that'd be enough, but I'm not sure all reviewers would know that.

Without this check_spmatrix stuff, contributors need to know that their code should work for sparray and spmatrix (so they can't use * when they mean @). And shapes might be 1D (or nD) with sparray and always 2D with spmatrix. More importantly reviewers will need to know that any sparse code coming in will need to work for both spmatrix and sparray -- at least until spmatrix is no longer supported.

@lesteve

lesteve commented Feb 23, 2026

Copy link
Copy Markdown
Member

Can you guys put this PR on the agenda for a meeting and hopefully decide on a path forward for it? I'll resolve conflicts and merge with main in the meantime. Thanks!!

Thanks a lot for your continued efforts on this @dschult 🙏. I have added this point to the monthly meeting today.

@lesteve

lesteve commented Feb 25, 2026

Copy link
Copy Markdown
Member

So this PR was mentioned at the meeting, the summary was:

  • there was no objections on the general approach
  • it would be nice to have a second reviewer make a detailed review. I will try to a detailed review next week, do ping me if you don't hear back from me!

@dschult

dschult commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

Sounds great -- I merged with main. I'll watch for review questions -- :)

@dschult

dschult commented Mar 6, 2026

Copy link
Copy Markdown
Contributor Author

I will try to a detailed review next week, do ping me if you don't hear back from me!

Hi @lesteve! Just a quick ping to remind you about the detailed review of this PR. Happy March!

@adrinjalali
adrinjalali enabled auto-merge (squash) March 9, 2026 15:43
@lesteve
lesteve disabled auto-merge March 9, 2026 15:54

@lesteve lesteve left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the promised detailed review (better late than never 😅)! Below are the comments that may make sense to tackle before this PR is merged.

I may have a few other comments, but they can likely be done in follow-up PRs. The hope would be to merge this PR and iterate if follow-up PRs if needed.

Comment thread sklearn/datasets/_rcv1.py
# reorder categories in lexicographic order
order = np.argsort(categories)
categories = categories[order]
y = sp.csr_matrix(y[:, order])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would use _align_api_if_sparse on y as well since we are using it on X.

prefer_skip_nested_validation=True,
)
def img_to_graph(img, *, mask=None, return_as=sparse.coo_matrix, dtype=None):
def img_to_graph(img, *, mask=None, return_as=sparse.coo_array, dtype=None):

@lesteve lesteve Mar 9, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I originally thought this was changing the output type of a public function, which would have been a problem. Actually it's not the case, since this calls _to_graph which uses the config.

This is potentially a teeny bit misleading if for example you pass return_as=sparse.csc_array and it gets overriden by the config, and you get a csc_matrix out.

My gut feeling is that it is fine because it is a multi-level edge case:

  • this is not really a core functionality of scikit-learn
  • probably most users use the default return_as value, which still has the same behaviour (returns a coo_matrix)
  • even then most users will not care about the difference between sparray and spmatrix

Comment thread sklearn/utils/_sparse.py Outdated
# Fundamental code to switch to sparray in any format
return getattr(sp.sparse, X.format + "_array")(X)
return X
else: # config is spmatrix

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this can be set by the user, it would be nicer if there is an error if it's neither sparray nor spmatrix?

Comment thread sklearn/utils/_testing.py Outdated
if constructor_name in ("sparse", "sparse_csr"):
# sparse and sparse_csr are equivalent for legacy reasons
return sp.sparse.csr_matrix(container, dtype=dtype)
return _align_api_if_sparse(sp.sparse.csr_array(container, dtype=dtype))

@lesteve lesteve Mar 9, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels like we should mostly not change this code since this is some utils for testing when you want to test with multiple inputs, in particular both sparray and spmatrix. In other words _convert_container should give you what you specify and not use the config.

Maybe the only thing you could change is that sparse means csr_array rather than csr_matrix? Not even sure TBH. I would not change it in this PR but leave it for later.

Comment thread sklearn/utils/fixes.py Outdated
# TODO: Replace when Scipy 1.12 is the minimum supported version
# fixes for transitioning scipy.sparse function names
if not SCIPY_VERSION_BELOW_1_12:
_sparse_eye = scipy.sparse.eye_array

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bit weird to have different return types depending on the scipy version.

I would rather have these helper functions be called _sparse_eye_array and _sparse_diags_array and always return sparrays?

Maybe I am missing some subtlety here? In case it matters, our minimum scipy version is currently 1.10.0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I renamed the helper functions _sparse_eye_array, _sparse_diags_array and _sparse_random_array.

Also, note that there is also already a sklearn function named _sparse_random_matrix defined in sklearn/random_projection.py. That is a long existing function in sklearn and not related to the scipy sparse functions. So I don't think there is any confusion between these names.

@dschult

dschult commented Mar 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @lesteve for the helpful review comments!

And yes, it is likely this will require follow-up PRs. Thanks for noting some cases that are likely to need that.

The requested changes are in and we've got green checks for CI.

@lorentzenchr

Copy link
Copy Markdown
Member

@lesteve I looked up codecov and it‘s fine for me. For instance, I can live with the missing lines in fixes. Those will be removed in the future anyway. The others don‘t seem so important.

@lesteve

lesteve commented Mar 11, 2026

Copy link
Copy Markdown
Member

Thanks a lot for your continued effort on this @dschult!

Let's merge this one and iterate in further PRs. I'll try to clean up my other comments/questions and do another review here or open an issue, whatever seems more convenient.

@lesteve
lesteve merged commit 0169f83 into scikit-learn:main Mar 11, 2026
31 of 32 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in Labs Mar 11, 2026
@lesteve

lesteve commented Mar 11, 2026 •

Copy link
Copy Markdown
Member

First follow-up PR (aka merger's remorse 😉) on #31177 (comment): what I was suggesting was to return sparray from _sparse_random_array for all scipy versions (as well as similar _sparse_ helper functions. In other words something like:

if not SCIPY_VERSION_BELOW_1_12:
    ...
else:

    def _sparse_eye_array(m, n=None, *, k=0, dtype=float, format=None):
        mat = scipy.sparse.eye(m, n, k=k, dtype=dtype, format=format)
        return scipy.sparse.dia_array(mat)

Do you see a downside with this?

@lesteve

lesteve commented Mar 11, 2026

Copy link
Copy Markdown
Member

Another follow-up it seems like this PR breaks one example related to 32 bit indices:

    Unexpected failing examples (1):
    
        ../examples/preprocessing/plot_discretization_classification.py failed leaving traceback:
    
        Traceback (most recent call last):
          File "/home/circleci/project/examples/preprocessing/plot_discretization_classification.py", line 168, in <module>
            clf.fit(X_train, y_train)
          File "/home/circleci/project/sklearn/base.py", line 1385, in wrapper
            return fit_method(estimator, *args, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/model_selection/_search.py", line 1053, in fit
            self._run_search(evaluate_candidates)
          File "/home/circleci/project/sklearn/model_selection/_search.py", line 1613, in _run_search
            evaluate_candidates(ParameterGrid(self.param_grid))
          File "/home/circleci/project/sklearn/model_selection/_search.py", line 1030, in evaluate_candidates
            _warn_or_raise_about_fit_failures(out, self.error_score)
          File "/home/circleci/project/sklearn/model_selection/_validation.py", line 479, in _warn_or_raise_about_fit_failures
            raise ValueError(all_fits_failed_message)
        ValueError: 
        All the 45 fits failed.
        It is very likely that your model is misconfigured.
        You can try to debug the error by setting error_score='raise'.
    
        Below are more details about the failures:
        --------------------------------------------------------------------------------
        45 fits failed with the following error:
        Traceback (most recent call last):
          File "/home/circleci/project/sklearn/model_selection/_validation.py", line 833, in _fit_and_score
            estimator.fit(X_train, y_train, **fit_params)
          File "/home/circleci/project/sklearn/base.py", line 1385, in wrapper
            return fit_method(estimator, *args, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/pipeline.py", line 628, in fit
            self._final_estimator.fit(Xt, y, **last_step_params["fit"])
          File "/home/circleci/project/sklearn/base.py", line 1385, in wrapper
            return fit_method(estimator, *args, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/svm/_classes.py", line 314, in fit
            X, y = validate_data(
                   ^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/utils/validation.py", line 2933, in validate_data
            X, y = check_X_y(X, y, **check_params)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/utils/validation.py", line 1318, in check_X_y
            X = check_array(
                ^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/utils/validation.py", line 985, in check_array
            array = _ensure_sparse_format(
                    ^^^^^^^^^^^^^^^^^^^^^^
          File "/home/circleci/project/sklearn/utils/validation.py", line 602, in _ensure_sparse_format
            _check_large_sparse(sparse_container, accept_large_sparse)
          File "/home/circleci/project/sklearn/utils/validation.py", line 1165, in _check_large_sparse
            raise ValueError(
        ValueError: Only sparse matrices with 32-bit integer indices are accepted. Got int64 indices. Please do report a minimal reproducer on scikit-learn issue tracker so that support for your use-case can be studied by maintainers. See: https://scikit-learn.org/dev/developers/minimal_reproducer.html
    
    
    -------------------------------------------------------------------------------

See build log for more details.

@dschult

dschult commented Mar 11, 2026

Copy link
Copy Markdown
Contributor Author

what I was suggesting was to return sparray from _sparse_random_array for all scipy versions (as well as similar sparse helper functions.
Do you see a downside with this?

I see what you mean now -- and I don't see any problem with making these always return sparray because these are private and we convert any results to spmatrix in the publicly facing functions.

I'll put something together.

Another follow-up it seems like this PR breaks one example related to 32 bit indices:

It looks like one of the datasets is creating sparse arrays with int64 index arrays. Hard for me to tell which dataset right away. I've recreated it locally, so should be able to track it down. traveling today so hopefully solution tonight.

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.

5 participants