Skip to content

Accept spectra as padded peak arrays, and return scores as a device tensor - #11

Closed
BioGeek wants to merge 3 commits into
PangeAI:mainfrom
BioGeek:feat/peak-array-input
Closed

BioGeek wants to merge 3 commits into
PangeAI:mainfrom
BioGeek:feat/peak-array-input

Conversation

@BioGeek

@BioGeek BioGeek commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

CudaCosineGreedy.matrix and CudaModifiedCosine.matrix currently need lists of matchms Spectrum objects. They copy each spectrum's peaks into padded arrays on every call, and then copy the full score matrix back to the host. This PR adds two opt-in paths around that, without changing the existing API:

  • PeakArrays input. A small frozen dataclass of zero-padded m/z and intensity arrays, per-spectrum peak counts, and optional precursor m/z. Both matrix() methods accept it wherever they accept a list of Spectrum objects. Data already in arrays (NumPy, Parquet, HDF5) reaches the GPU without building Spectrum objects, and the per-call conversion becomes a slice.
  • array_type="torch" output. Returns the (3, R, Q) float32 tensor of scores, matched peaks and overflow flags that matrix() already builds on the device. The host copy and record-array construction of "numpy" are skipped, so callers can filter or reduce on the GPU (best match per query, a mask on another criterion) before copying anything.

Motivation

I used SimMS to compare ~100k query spectra with every reference spectrum of matching precursor mass in a corpus of ~170M spectra stored in Parquet. The spectra already sit in arrays, so building Spectrum objects only to have _spectra_peaks_to_tensor copy their peaks back into arrays was pure overhead. Each call also only needed the best-scoring reference per query among candidates within a precursor tolerance, a reduction that is cheap on the GPU. The "numpy" output instead copies the whole matrix to the host and builds a record array first. I worked around both by subclassing, this PR makes the workaround unnecessary.

Changes

  • New simms/peaks.py: PeakArrays, exported as simms.PeakArrays.
    • It validates shapes, supports slicing (used by the existing batching), and has to_width(width), which pads or truncates to the kernel's n_max_peaks.
    • Constructors: from_peak_lists(mz, intensities, precursor_mz=None, n_max_peaks=None), and from_spectra(spectra, with_precursor_mz=False) to convert Spectrum objects once for reuse across calls.
  • CudaCosineGreedy, CudaModifiedCosine:
    • _spectra_peaks_to_tensor takes the arrays directly when given a PeakArrays. CudaModifiedCosine raises a clear error if precursor_mz is missing.
    • matrix() accepts PeakArrays for references and queries, and array_type="torch".
    • Truncation is unchanged: a spectrum with more than n_max_peaks peaks keeps its first n_max_peaks, as for Spectrum input.
  • README: a FAQ entry with an example.
  • CudaFingerprintSimilarity: unchanged, it works on fingerprints, not peaks.

Tests

New tests/similarity/test_peak_arrays.py, 9 tests, run with NUMBA_ENABLE_CUDASIM=1:

  • PeakArrays padding, truncation, slicing and validation;
  • from_spectra keeps peaks and precursor m/z;
  • CudaCosineGreedy and CudaModifiedCosine: PeakArrays input gives the same scores and matches as Spectrum input, including when n_max_peaks truncates spectra, and across several batches;
  • CudaModifiedCosine rejects PeakArrays without precursor m/z;
  • array_type="torch" matches "numpy" for both classes.

The PeakArrays doctest passes, and the existing tests/similarity/test_cosine_greedy.py and test_modified_cosine.py still pass (14 tests). The CI job's steps pass too: flake8's strict selection (E9,F63,F7,F82), and pytest -m github_ci with the CUDA simulator (24 passed). Run on Python 3.12, with numba 0.60.0, matchms 0.29.0 and torch 2.15.0.

Merged with the dependency update (#10), the same tests pass on Python 3.12 with numba 0.68.1, numba-cuda, matchms 0.34.0 and torch 2.15.0.

On an H100 (driver 580.105.08; PyTorch 2.4.1+cu124, numba 0.68.1, numba-cuda 0.30.4, matchms 0.34.0), without the simulator:

  • this branch: tests/similarity and tests/usecase give 40 passed. test_matchms_compatibility.py is left out, because it imports matchms' renamed ModifiedCosine, which the dependency update fixes;
  • merged with the dependency update: 45 passed, plus 8 passed in tests/stress.

Host-side cost

CPU only, no kernel. 100,000 random spectra of 75–225 peaks, n_max_peaks=150, batch_size=2048, with NUMBA_ENABLE_CUDASIM=1 python benchmark.py 100000 150 (script below).

Step Time
Create matchms Spectrum objects from arrays 1.54 s
_get_batches on the Spectrum list (every matrix() call) 0.67 s
PeakArrays.from_peak_lists on the same arrays (once) 0.15 s
_get_batches on the PeakArrays (every call) 0.03 s

That is about 12× less host time to get the data in, and 22× less per call. For a 100M-spectrum reference set, that is roughly 35 minutes of single-threaded host work before the kernel starts, against about 3 minutes.

benchmark.py
"""Host-side cost of feeding SimMS: matchms Spectrum objects vs PeakArrays (CPU only, no kernel).

Times, for N random spectra of ~P peaks:
1. creating matchms Spectrum objects from arrays (what a caller with Parquet/NumPy data must do today);
2. CudaCosineGreedy._get_batches on those Spectrum objects (matrix() does this on every call);
3. PeakArrays.from_peak_lists on the same arrays;
4. CudaCosineGreedy._get_batches on the PeakArrays.
Run with NUMBA_ENABLE_CUDASIM=1 so the class can be built without a GPU.
"""
import sys
import time

import numpy as np
from matchms import Spectrum

from simms.peaks import PeakArrays
from simms.similarity import CudaCosineGreedy

n, p = int(sys.argv[1]), int(sys.argv[2])
rng = np.random.default_rng(0)
mz = [np.sort(rng.uniform(100, 2000, int(rng.integers(p // 2, p * 3 // 2)))) for _ in range(n)]
it = [rng.uniform(0, 1, len(m)) for m in mz]
sim = CudaCosineGreedy(n_max_peaks=p, batch_size=2048)


def timed(label, f):
    t = time.perf_counter()
    out = f()
    print(f"{label:<55} {time.perf_counter() - t:8.2f} s")
    return out


spectra = timed("1. create matchms Spectrum objects", lambda: [Spectrum(mz=m, intensities=x, metadata={"precursor_mz": 500.0}) for m, x in zip(mz, it)])
timed("2. _get_batches(Spectrum list, 1 query batch)", lambda: sim._get_batches(spectra, spectra[:2048]))
peaks = timed("3. PeakArrays.from_peak_lists", lambda: PeakArrays.from_peak_lists(mz, it))
timed("4. _get_batches(PeakArrays, 1 query batch)", lambda: sim._get_batches(peaks, peaks[:2048]))

On the GPU

matrix() on an H100, with random spectra of 75–225 peaks, n_max_peaks=150, batch_size=2048 and tolerance 0.05. Each time is the best of three runs after a warm-up call, synchronised before and after.

References × queries Class Spectrum → numpy PeakArrays → numpy PeakArrays → torch
20,000 × 2,048 CudaCosineGreedy 1.80 s 1.67 s 0.99 s
20,000 × 2,048 CudaModifiedCosine 2.41 s 2.34 s 1.64 s
100,000 × 2,048 CudaCosineGreedy 9.85 s 7.91 s 4.70 s
100,000 × 2,048 CudaModifiedCosine 12.52 s 9.88 s 7.32 s
  • Building the input: Spectrum objects for the 100,000 × 2,048 case took 3.31 s; PeakArrays.from_peak_lists took 0.26 s.
  • array_type="torch" against "numpy": it saves the device-to-host copy of the (3, R, Q) matrix (12·R·Q bytes) and the record-array construction. Here that is 41% of the call for CudaCosineGreedy and 26% for CudaModifiedCosine.
  • End to end: from Spectrum input with numpy output to PeakArrays with torch output is about 2× for cosine at the larger size.
  • Scores: every timing above uses the float64 default. It gives exactly the same scores and match counts as Spectrum input, for every pair and both classes.
  • float32 storage: speeds and results are unchanged for CudaCosineGreedy. For CudaModifiedCosine it changed the score or match count of 68,404 of 41M pairs at 20,000 × 2,048, and 339,300 of 205M at 100,000 × 2,048, where rounded m/z moved a match across the tolerance.

Notes for review

  • The change is additive: callers passing Spectrum lists, and the "numpy" and "sparse" outputs, behave as before.
  • PeakArrays stores m/z and intensities as float64 by default, as matchms Spectrum objects do, and precursor m/z always as float64. Both classes then give exactly the scores they give for Spectrum input. dtype=np.float32 halves the memory and stays exact for CudaCosineGreedy, which computes in float32. For CudaModifiedCosine, which computes in float64 by default, it changed up to 0.17% of pairs in the GPU benchmark above, where rounded m/z moved a match across the tolerance. A test pins this case.
  • matchms-style calculate_scores() still goes through Spectrum objects. PeakArrays is for calling matrix() directly.
  • CI fails at 'Set up Python 3.9' because GitHub's runners no longer provide Python 3.9. Support Python 3.11–3.14, numba ≥ 0.61 with numba-cuda, and matchms 0.34 #10 moves the matrix to 3.11–3.14. Once Support Python 3.11–3.14, numba ≥ 0.61 with numba-cuda, and matchms 0.34 #10 is merged I'll rebase this PR onto main and CI will run on the new matrix.

…vice tensor

PeakArrays holds spectra as zero-padded m/z and intensity arrays with per-spectrum peak counts (and
precursor m/z for the modified cosine). CudaCosineGreedy.matrix and CudaModifiedCosine.matrix accept it
in place of a list of matchms Spectrum objects, so data already in arrays reaches the GPU without
building Spectrum objects and without the per-spectrum conversion every matrix() call does.

array_type="torch" returns the (3, R, Q) score, matches and overflow tensor on the device, without the
host copy and record-array construction of the "numpy" output.
@tornikeo

tornikeo commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Thank you for designing and benchmarking PeakArrays and GPU-resident array_type="torch" outputs, @BioGeek! We incorporated this into #12 (v1.0.0) with additional input validation, zeroed padding safety, direct matchms.SpectraCollection support, and CI coverage across all scorers, and credited you in CHANGELOG.md.

@tornikeo tornikeo closed this Dec 2, 2026
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.

2 participants