Skip to content

Add scipy.sparse.linalg.cg benchmark - #239

Draft
AJ0070 wants to merge 2 commits into
SparseArrayProgrammingSuite:mainfrom
AJ0070:scipy-cg-benchmark
Draft

AJ0070 wants to merge 2 commits into
SparseArrayProgrammingSuite:mainfrom
AJ0070:scipy-cg-benchmark

Conversation

@AJ0070

@AJ0070 AJ0070 commented Sep 20, 2026

Copy link
Copy Markdown

Draft, following up on scipy/scipy#26217.

Adds SciPyCGBenchmark, which runs scipy.sparse.linalg.cg on the same datasets as the existing cg benchmark so the two can be compared directly. It reuses CGTestGenerator and CGGenerator, and delegates check to CGBenchmark.

It subclasses Benchmark rather than CGBenchmark, so that it doesn't also inherit the generated time_cg_solver entry point.

The tolerances map directly: scipy stops on norm(b - A @ x) <= max(rtol*norm(b), atol) and the SAPS cg uses max(rel_tol*norm(b), abs_tol), so rtol=rel_tol, atol=abs_tol, maxiter=max_iter, with no pre-processing needed. On the six SPD matrices I tried the two produce bit-identical solutions, so they are taking the same iterations and any timing difference is implementation overhead rather than different amounts of work.

On those matrices, 24,696 to 74,752 rows, medians over 25 repeats, the two come out within a few percent of each other in both directions. Numbers are in scipy/scipy#26217.

Not included here: metadata.json needs regenerating before the benchmark is discovered, but doing that locally rewrote every freshness hash, 52k lines, since they cover installed dependency versions. Happy to add it if you would rather have it in.

@lucascolley

Copy link
Copy Markdown

cool! I'll try to play around with this at some point.

@willow-ahrens @kylebd99 just copying over these notes from scipy/scipy#26217 in case you can help:

Two things tripped me up getting there, in case they are known:

  • the committed saps.conf.json sets environment_type: existing:same, but run_benchmark.py only takes the existing-environment path when --trace-statistics or --cache-datasets is passed. On the plain invocation from the README it goes through get_environments instead, and for existing:same the resulting environment does not apply env_nobuild, so SAPS_FRAMEWORK never gets set and every case fails with Benchmark.setup must bind a framework before run. CI only ever uses those two flags, so that path looks uncovered.

  • switching to saps.conf.json.example fixes the binding, but its matrix.req has no array-api-compat, which frameworks/saps_scipy.py imports, so scipy and sparse fail while numpy passes. Dropping the matrix key and letting the runner's built-in default apply works.

One practical thing: a new benchmark isn't discovered until bin/generate_metadata.py is run, but regenerating metadata.json rewrote every freshness hash, 52k changed lines for 4 lines of new content. They are computed over installed dependency versions (dependency_versions, via src/saps/freshness.py), so the file ends up environment specific. How do you expect contributors to handle that? I have left mine uncommitted for now.

@kylebd99

Copy link
Copy Markdown
Collaborator

Hey, thanks for contributing! Also, thanks for the PRs over on Finch.jl :)

For the benchmarks in SAPS, the goal is to show how different array frameworks (e.g. pydata/sparse, scipy.sparse, pytorch.sparse, etc.) perform across various workloads leveraging the array API. So, what happens when different framework's arrays are input into scipy_spla? Does it internally use their functionality or does it just translate to a scipy array then call scipy's internal cg function?

The latter wouldn't be a great fit as a benchmark in this suite because it wouldn't be able to demonstrate a difference between frameworks and any errors would either be in scipy or in compatibility with scipy.

@kylebd99

Copy link
Copy Markdown
Collaborator

Thank you for the notes on usability btw. These are super helpful for us as we refine the (framework/benchmark) contributor process. The freshness tests have been a bit tricky for us to nail down. We'd like to ensure that the data and the code come as a coherent pair, but the current setup may be too restrictive. In the end, we will likely move that check to the release process instead of CI.

@lucascolley

lucascolley commented Sep 20, 2026 •

Copy link
Copy Markdown

For the benchmarks in SAPS, the goal is to show how different array frameworks (e.g. pydata/sparse, scipy.sparse, pytorch.sparse, etc.) perform across various workloads leveraging the array API. So, what happens when different framework's arrays are input into scipy_spla? Does it internally use their functionality or does it just translate to a scipy array then call scipy's internal cg function?

Currently, inputs are wrapped with https://scipy.github.io/devdocs/reference/generated/scipy.sparse.linalg.aslinearoperator.html#scipy.sparse.linalg.aslinearoperator. In addition to what is mentioned in that documentation, pydata sparse arrays are also special-cased. The cg implementation assumes that whatever the underlying data structure, it is compatible with dense numpy arrays for the bookkeeping.

My open PR scipy/scipy#24450 switches this to an array API native implementation. The idea is that any sparse array backend which works with the current SAPS benchmarks should also be able to run through the scipy.sparse.linalg.cg on my branch.

That part is I suppose largely to test correctness / interoperability / check that we aren't butchering performance with I/O. A follow-up could look at adding batched benchmarks here, which is the novel part of my cg work.

@lucascolley

Copy link
Copy Markdown

it is admittedly extremely confusing that functions which work with more-than-just-scipy.sparse-arrays are in a sub-namespace of the namespace holding the scipy.sparse data structures 😅

@AJ0070

AJ0070 commented Sep 20, 2026

Copy link
Copy Markdown
Author

Confirming that empirically since it is easy to check: aslinearoperator keeps the pydata/sparse array as it is, giving a MatrixLinearOperator holding a COO, and the matvecs go through COO.dot (38 calls on GHS_psdef/obstclae, no __matmul__). So the framework's own kernel does the work rather than scipy converting to its own format.

It does show up in the numbers too. On Cunningham/qa8fm, scipy.sparse.linalg.cg takes 49 ms under the scipy framework and 1019 ms under pydata/sparse, so the framework choice dominates by about 20x, while scipy's cg and the SAPS cg stay within a few percent of each other under both.

@lucascolley

Copy link
Copy Markdown

yeah, in my rather rudimentary benchmarking of pydata/sparse GCXS arrays with the numba backend through scipy.sparse.linalg.cg a few months ago, I got these numbers:

[100.00%] ··· sparse_linalg_solve.Bench.time_solve                                                                        ok
[100.00%] ··· ======= ============= ============
              --        solver / pydata_sparse
              ------- --------------------------
               (n,n)    cg / False   cg / True
              ======= ============= ============
                 4      86.7±0.5μs   8.34±0.2ms
                 6       151±9μs     16.4±0.5ms
                 10      298±7μs     37.3±0.3ms
                 16      501±30μs     73.5±3ms
                 25      873±20μs     119±3ms
                 40    1.61±0.02ms    248±6ms
                 64     3.69±0.1ms    682±30ms
                100    9.83±0.02ms   2.03±0.01s
              ======= ============= ============

ref. https://discord.com/channels/786703927705862175/1301155724646289420/1476247207886979225 (#pydata-sparse in the Scientific Python discord)

@AJ0070

AJ0070 commented Sep 20, 2026

Copy link
Copy Markdown
Author

@lucascolley I am not able to open that discord link :(, Do I need an invite link to the channel first?

@lucascolley

Copy link
Copy Markdown

@lucascolley I am not able to open that discord link :(, Do I need an invite link to the channel first?

Try clicking the discord logo in the footer of https://scientific-python.org/

@AJ0070

AJ0070 commented Sep 20, 2026

Copy link
Copy Markdown
Author

Got in, Thanks!

@kylebd99

Copy link
Copy Markdown
Collaborator

Ah, very cool that this supports any array-api compatible backend. My gut intuition is to add this benchmark in with an "experimental" suite tag, just because the benchmark function is subject to change based on your PR/the status of scipy.sparse.linalg. Fortunately, the scipy version is pinned in the repo, so there should be no variation in the benchmark function within a single version of SAPS.

Going forward, we'll likely be refining the notion of benchmark suites, and we will move it out of experimental and into something like 'solvers'.

@willow-ahrens @JoelMathewC thoughts?

@kylebd99

Copy link
Copy Markdown
Collaborator

Also, @AJ0070, we're doing a series of interviews with people in the sparse ecosystem, would you be open to finding a time to chat https://calendly.com/d/dv9p-7b9-96m/pose-interview ?

@lucascolley

Copy link
Copy Markdown

My gut intuition is to add this benchmark in with an "experimental" suite tag, just because the benchmark function is subject to change based on your PR/the status of scipy.sparse.linalg. Fortunately, the scipy version is pinned in the repo, so there should be no variation in the benchmark function within a single version of SAPS.

Yeah, at least from my side there is no rush for anything to actually be merged into SAPS, as long as there is a branch that is usable. Hopefully this helps drive the design though :)

@AJ0070

AJ0070 commented Sep 20, 2026

Copy link
Copy Markdown
Author

Also, @AJ0070, we're doing a series of interviews with people in the sparse ecosystem, would you be open to finding a time to chat https://calendly.com/d/dv9p-7b9-96m/pose-interview ?

@kylebd99 Thanks for the offer! Bit stretched for time at the moment, but I am happy to keep helping here, so do ping me whenever something comes up.

@willow-ahrens

willow-ahrens commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

A few notes:

  1. If we merge this, scipy would need to be loaded whenever we run the benchmark suite, since it would be in the benchmark definition. Currently, as far as I know, scipy is not required to run the benchmarks.
  2. We would need to pin the scipy version, as kyle mentioned, or be very careful about which scipy version is used. I'd push for the scipy load to be dynamic here, so as not to disrupt other benchmark environments. I'd also push for an "external" tag to be added, just so we know to be extra careful.
  3. Thank you for catching those environment bugs, I'm raising a separate issue for those and I'll be sure to fix them in the next saps version: environment issues #240
  4. No worries about metadata regeneration/etc. I usually handle that, and I think main is stale from other changes currently. we only fix metadata when we release a version.

@lucascolley

Copy link
Copy Markdown

Perhaps we should start thinking about how to include benchmarking against a development version of scipy. I'm not sure how to do that with Poetry, as one will need to take care to have the system-level dependencies needed to install SciPy.

It would be a one-line change with Pixi, but I realise that switching this repo from poetry to Pixi would potentially be quite a large task. Maybe worth it though if there may be other use-cases for benchmarking dev versions of packages?

@AJ0070

AJ0070 commented Oct 3, 2026

Copy link
Copy Markdown
Author

Done: the scipy import now happens inside benchmark, and the benchmark is tagged experimental and external, since you each suggested one. Happy to drop either.

cg.py already imports scipy.sparse at module level, so scipy itself still loads with the suite, but scipy.sparse.linalg now doesn't load until the benchmark runs. The import inside the timed region costs about 200 ns against solves of 7 ms and up, so it doesn't affect the numbers.

Main has moved on since I branched, so I checked against current main too. The benchmark passes under numpy, scipy and pydata/sparse, but fails under the new smart framework: scipy.sparse.linalg.cg raises TypeError: type not understood from aslinearoperator, because the WrappedArray it gets has shape and @ but no matvec. The array-API CGBenchmark is fine under smart. That's a limitation in scipy, not something to fix in the benchmark, and it's the kind of input @lucascolley's branch is meant to handle, but it means test_benchmark_check would fail for smart once this is merged with main. How would you like benchmarks that only support some frameworks to be handled?

@lucascolley

Copy link
Copy Markdown

hi @willow-ahrens @kylebd99, just checking in here — any way I can help on the framework-side? Would be great to progress this

@willow-ahrens

willow-ahrens commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

@AJ0070 Eventually, we hope to remove the smart framework, but we don't yet have an external framework capable of executing all of the suite. The point of the smart framework was to be a place where we contain any hacks we need to get frameworks to run, so we can just hack it until it runs this one too.

@lucascolley On the framework side, our goal is to eventually remove "Framework" from the saps suite altogether by putting as much of it as possible in array api extra. If you have any suggestions for how to work towards this I would be on board! Overall, I think this PR is ready for me to take a look at and merge, I can take it from here. It would be great to see more PRs like this one for other solvers in Scipy!

@lucascolley

Copy link
Copy Markdown

@lucascolley On the framework side, our goal is to eventually remove "Framework" from the saps suite altogether by putting as much of it as possible in array api extra. If you have any suggestions for how to work towards this I would be on board! Overall, I think this PR is ready for me to take a look at and merge, I can take it from here. It would be great to see more PRs like this one for other solvers in Scipy!

let me review data-apis/array-api-extra#1072 now and we can move from there 👍

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.

4 participants