Repository navigation
Conversation
…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.
…ores match Spectrum input
Collaborator
|
Thank you for designing and benchmarking |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
CudaCosineGreedy.matrixandCudaModifiedCosine.matrixcurrently need lists of matchmsSpectrumobjects. 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:PeakArraysinput. A small frozen dataclass of zero-padded m/z and intensity arrays, per-spectrum peak counts, and optional precursor m/z. Bothmatrix()methods accept it wherever they accept a list ofSpectrumobjects. Data already in arrays (NumPy, Parquet, HDF5) reaches the GPU without buildingSpectrumobjects, 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 thatmatrix()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
Spectrumobjects only to have_spectra_peaks_to_tensorcopy 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
simms/peaks.py:PeakArrays, exported assimms.PeakArrays.to_width(width), which pads or truncates to the kernel'sn_max_peaks.from_peak_lists(mz, intensities, precursor_mz=None, n_max_peaks=None), andfrom_spectra(spectra, with_precursor_mz=False)to convertSpectrumobjects once for reuse across calls.CudaCosineGreedy,CudaModifiedCosine:_spectra_peaks_to_tensortakes the arrays directly when given aPeakArrays.CudaModifiedCosineraises a clear error ifprecursor_mzis missing.matrix()acceptsPeakArraysforreferencesandqueries, andarray_type="torch".n_max_peakspeaks keeps its firstn_max_peaks, as forSpectruminput.CudaFingerprintSimilarity: unchanged, it works on fingerprints, not peaks.Tests
New
tests/similarity/test_peak_arrays.py, 9 tests, run withNUMBA_ENABLE_CUDASIM=1:PeakArrayspadding, truncation, slicing and validation;from_spectrakeeps peaks and precursor m/z;CudaCosineGreedyandCudaModifiedCosine:PeakArraysinput gives the same scores and matches asSpectruminput, including whenn_max_peakstruncates spectra, and across several batches;CudaModifiedCosinerejectsPeakArrayswithout precursor m/z;array_type="torch"matches"numpy"for both classes.The
PeakArraysdoctest passes, and the existingtests/similarity/test_cosine_greedy.pyandtest_modified_cosine.pystill pass (14 tests). The CI job's steps pass too: flake8's strict selection (E9,F63,F7,F82), andpytest -m github_ciwith 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:
tests/similarityandtests/usecasegive 40 passed.test_matchms_compatibility.pyis left out, because it imports matchms' renamedModifiedCosine, which the dependency update fixes;tests/stress.Host-side cost
CPU only, no kernel. 100,000 random spectra of 75–225 peaks,
n_max_peaks=150,batch_size=2048, withNUMBA_ENABLE_CUDASIM=1 python benchmark.py 100000 150(script below).Spectrumobjects from arrays_get_batcheson theSpectrumlist (everymatrix()call)PeakArrays.from_peak_listson the same arrays (once)_get_batcheson thePeakArrays(every call)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.pyOn the GPU
matrix()on an H100, with random spectra of 75–225 peaks,n_max_peaks=150,batch_size=2048and tolerance 0.05. Each time is the best of three runs after a warm-up call, synchronised before and after.Spectrum→ numpyPeakArrays→ numpyPeakArrays→ torchCudaCosineGreedyCudaModifiedCosineCudaCosineGreedyCudaModifiedCosineSpectrumobjects for the 100,000 × 2,048 case took 3.31 s;PeakArrays.from_peak_liststook 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 forCudaCosineGreedyand 26% forCudaModifiedCosine.Spectruminput with numpy output toPeakArrayswith torch output is about 2× for cosine at the larger size.Spectruminput, for every pair and both classes.CudaCosineGreedy. ForCudaModifiedCosineit 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
Spectrumlists, and the"numpy"and"sparse"outputs, behave as before.PeakArraysstores m/z and intensities as float64 by default, as matchmsSpectrumobjects do, and precursor m/z always as float64. Both classes then give exactly the scores they give forSpectruminput.dtype=np.float32halves the memory and stays exact forCudaCosineGreedy, which computes in float32. ForCudaModifiedCosine, 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.calculate_scores()still goes throughSpectrumobjects.PeakArraysis for callingmatrix()directly.