Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## v1.2.0

- Added `backend="cpu"` and `backend="auto"` to `CudaMyopicMCES`. CUDA remains the default. Both CPU and CUDA use the same exact verifier and support finite inclusive thresholds and unrestricted distances.
- Added a histogram screen for exact-hit queries, staged PDHG refinement, integer dual certificates, and ring-edge disjunctions before HiGHS. Dense scoring preserves the v1.1 neighborhood bounds. The default DFS budget is 8,192 frames.
- Reduced local scratch for greedy spectral cosine by using its bounded global workspace above 512 candidates.
- One million GNPS pairs at threshold 10 returned all 11,245 exact hits in 4.62 s on an RTX 4060 Laptop GPU and 11.01 s on eight CPU cores (warm medians). [Measurements](benchmarks/myopic_mces_v1_2_rtx4060.json)

## v1.1.0

- Added `CudaMyopicMCES` and the cached `MolecularGraphs` container for exact thresholded (`threshold=10.0`) and unrestricted (`threshold=None`) Myopic MCES molecular distances on CUDA with automatic in-process SciPy HiGHS (`scipy.optimize.milp`) fallback and zero new required dependencies.
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ SimMS compares tandem mass spectra on an NVIDIA GPU using the scoring algorithms

## Installation

The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14, an NVIDIA driver compatible with your CUDA runtime and a CUDA-enabled build of PyTorch for that runtime. Choose the matching wheel with the [PyTorch installation selector](https://pytorch.org/get-started/locally/).
The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14. GPU scoring requires an NVIDIA driver and a CUDA-enabled build of PyTorch for the chosen runtime. For CPU molecular scoring, install the base package and select `backend="cpu"`. Choose the matching wheel with the [PyTorch installation selector](https://pytorch.org/get-started/locally/).

```bash
# CUDA 12, in an environment with a matching CUDA 12 PyTorch build
Expand Down Expand Up @@ -68,15 +68,17 @@ The default cosine tensor has shape `(2, n_refs, n_queries)`, with score and mat
| `CudaModifiedCosineLinear` | `ModifiedCosineLinear` | Linear matching with a precursor shift and conflict resolution |
| `CudaBinnedEmbeddingSimilarity` | `BinnedEmbeddingSimilarity` | Cosine or Euclidean similarity of binned intensities |
| `CudaFingerprintSimilarity` | `FingerprintSimilarity` | Tanimoto or cosine over molecular fingerprints |
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (GPU bounds + bounded graph search + SciPy HiGHS fallback) |
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (Numba CPU or CUDA, with SciPy HiGHS fallback) |

`CudaModifiedCosine` is an alias for `CudaModifiedCosineGreedy`. Fingerprint matrices are indexed by valid unique compounds, in matchms `Fingerprints.inchikeys` order on each axis. Use a chemap-compatible generator with valid InChIKey and SMILES or InChI metadata, or pass prepared containers as `fingerprints_1` and `fingerprints_2`. A precursor mask for fingerprint scoring must use those same compound axes. A spectrum-level mask is directly reusable when each spectrum represents a different valid compound on its axis. RDKit generators with JSON support can be exported through `to_dict()` and reconstructed from the saved parameters. Embedding, entropy and fingerprint scorers return a single score field.

Binned embeddings and precomputed fingerprints also run on CPU. The six spectral CUDA scorers require a CUDA device or the Numba simulator. For simulator tests, set `NUMBA_ENABLE_CUDASIM=1` before starting Python.

## Myopic MCES (`CudaMyopicMCES`)

`CudaMyopicMCES` computes exact thresholded (`threshold=10.0`) or unrestricted (`threshold=None`) weighted Maximum Common Edge Subgraph distances matching `myopic-mces 2.3.0`, with zero extra dependencies beyond SimMS's core install (`numba-cuda`, `rdkit`, and SciPy's in-process HiGHS `scipy.optimize.milp`). Duplicate SMILES/structures are deduplicated automatically and pairs exceeding `max_frames` or `max_gpu_atoms` fall back to exact in-process HiGHS before returning or sparse filtering.
`CudaMyopicMCES` computes weighted molecular common-edge distances on CUDA (default) or a multicore CPU. Use `backend="auto"` to select an available device. All three modes accept the same prepared graphs, spectra, SMILES, and RDKit molecules. The package ships one pure-Python wheel. Numba compiles the kernels at runtime.

A finite threshold includes exact hits at the boundary. Use `exact_only=True` for hit retrieval. With the default `always_stronger_bound=True`, dense scores retain upstream's neighborhood bound (`filter2`) when it exceeds the threshold. Other rejections return the threshold with `exact=False`. With `always_stronger_bound=False`, every rejection returns that capped score. Set `threshold=None` for unrestricted exact distances.

```python
from simms import MolecularGraphs
Expand All @@ -88,11 +90,9 @@ scores = mces.matrix(graphs)
close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
```

On the RTX 4060 Laptop GPU (`2,240/2,240` exact oracle parity vs `myopic-mces 2.3.0`, max diff `1.66e-12`; [benchmarks/myopic_mces_rtx4060.json](benchmarks/myopic_mces_rtx4060.json)):
Exact-hit queries start with a histogram screen. A Hungarian assignment, local swaps and capped graph search resolve easy pairs. The remaining pairs use a primal-dual relaxation, integer certificates and an oriented-edge HiGHS fallback. `max_frames` defaults to 8,192. Models above `max_gpu_atoms` use CPU refinement. With `backend="cpu"`, Torch output is a CPU tensor.

- **1,000 mixed pairs (`threshold=10`):** `17.9 ms` (`92.2×` vs 8-core upstream HiGHS, `690×` vs 8-core CBC)
- **120 `filter2` survivors (`threshold=10`):** `444 ms` (`4.24×` vs 8-core upstream HiGHS, `24.9×` vs 8-core CBC)
- *(Honest baseline note: an 8-core Numba CPU port of the same graph-native algorithm ran `1.1×–3.6×` faster than Numba CUDA on these 120–1,000 pair laptop batches, showing that most of the speedup over upstream `myopic-mces` comes from replacing generic MILP setup with compact integer graph bounds + in-process HiGHS fallback.)*
On one million prepared GNPS pairs at threshold 10, warm exact-hit retrieval took **4.62 s on CUDA** and **11.01 s on CPU**. Both returned all 11,245 reference hits with identical distances. Dense scoring took 7.82 s and 13.22 s, respectively, and matched every reference score and exact flag. These are three-run medians on an RTX 4060 Laptop GPU and eight i9-14900HX P-cores. [Benchmark results](benchmarks/myopic_mces_v1_2_rtx4060.json) · [Benchmark script](benchmarks/benchmark_mces_matrix.py)

## Transitive alignment

Expand Down
59 changes: 59 additions & 0 deletions benchmarks/benchmark_mces_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# SPDX-License-Identifier: MIT
"""Measure the public MCES API on trusted, prepared graph axes and a structured NumPy oracle.

taskset -c 0,2,4,6,8,10,12,14 python benchmarks/benchmark_mces_matrix.py \
/tmp/bench-mces-1m/axes.pkl /tmp/bench-mces-1m/cpu-full.npy --backend cuda
"""
import argparse
import json
import pickle
from statistics import median
from time import perf_counter

import numpy as np

from simms.similarity import CudaMyopicMCES


def benchmark(left, right, oracle, backend, repeats, dense):
scorer = CudaMyopicMCES(backend=backend)
result = {"backend": backend, "shape": list(oracle.shape)}
expected = np.flatnonzero(oracle["exact"])
for mode in (("sparse", "dense") if dense else ("sparse",)):
times = []
for trial in range(repeats + 1):
start = perf_counter()
if mode == "sparse":
scores = scorer.sparse_matrix(left, right, exact_only=True, progress_bar=False)
else:
scores = scorer.matrix(left, right, array_type="numpy", progress_bar=False)
elapsed = perf_counter() - start
if trial:
times.append(elapsed)
if mode == "sparse":
coo = scores.to_coo("score")
keys = coo.row * len(right) + coo.col
flags = scores.to_coo("exact")
np.testing.assert_array_equal(np.sort(keys), expected)
np.testing.assert_array_equal(flags.data, np.ones(len(keys), bool))
np.testing.assert_array_equal(coo.data, oracle["score"].ravel()[keys])
result["exact_hits"] = len(keys)
else:
for field in oracle.dtype.names:
np.testing.assert_equal(scores[field], oracle[field])
result[mode] = {"seconds": times, "median_seconds": median(times)}
return result


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("axes", type=argparse.FileType("rb"))
parser.add_argument("reference")
parser.add_argument("--backend", choices=["cpu", "cuda"], required=True)
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--dense", action="store_true")
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be positive")
print(json.dumps(benchmark(*pickle.load(args.axes), np.load(args.reference),
args.backend, args.repeats, args.dense), indent=2))
133 changes: 13 additions & 120 deletions benchmarks/benchmark_myopic_mces.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"""
import argparse
from concurrent.futures import ProcessPoolExecutor
from importlib import import_module
from importlib.metadata import version
import json
import os
Expand All @@ -20,7 +19,6 @@
import sys
from tempfile import TemporaryDirectory
from time import perf_counter
from unittest.mock import patch

import numpy as np
from rdkit import Chem, DataStructs, RDLogger
Expand Down Expand Up @@ -124,72 +122,6 @@ def oracle(path):
path.write_text(json.dumps(data))


def cpu_port():
"""Compile the very same bounds and search for CPU, with independent pair workspaces."""
from numba import njit, prange
from simms.similarity import CudaMyopicMCES
from simms.similarity._mces_milp import solve_milp
from simms.similarity._mces_search import _objective_bound, _specialize

bounds, search, _, _ = _specialize(njit)
objective_bound = njit(_objective_bound)

@njit(parallel=True)
def solve(meta, vertices, adjacency, neighbors, pairs, limit, frame_cap, atom_cap):
n = len(pairs)
lower, distance, frames = np.empty(n, np.int32), np.empty(n, np.int32), np.zeros(n, np.int64)
for k in prange(n):
i, j = pairs[k]
a = vertices[meta[i, 0]:meta[i + 1, 0]]
b = vertices[meta[j, 0]:meta[j + 1, 0]]
na = neighbors[meta[i, 2]:meta[i + 1, 2]]
nb = neighbors[meta[j, 2]:meta[j + 1, 2]]
width = max(len(a), len(b))
cost = np.empty((width, width), np.int32)
work = np.empty((7, width + 1), np.int32)
seed = np.empty((3, width), np.int32)
wa, wb = meta[i, 3], meta[j, 3]
lower[k] = bounds(a, b, na, nb, wa + wb, limit, True, cost, work, seed[0], seed[1], seed[2])
distance[k] = lower[k]
if lower[k] <= limit:
distance[k] = -1
if width <= atom_cap:
goal = objective_bound(wa + wb, lower[k], meta[i, 4], meta[j, 4])
if goal > limit:
distance[k], frames[k] = goal, -1
continue
adj = adjacency[meta[j, 1]:meta[j + 1, 1]]
distance[k], frames[k] = search(a, b, na, nb, adj, wa, wb, goal, limit,
frame_cap, seed[0], seed[1], seed[2], work)
return lower, distance, frames

class Cpu(CudaMyopicMCES):
_upload = staticmethod(tuple)

def _solve(self, library, graphs, pairs, width, pool, maximum, only_exact, device_output):
limit = np.inf if self.threshold is None else 2 * self.threshold
lower, distance, frames = solve(*library, np.asarray(pairs, np.int32), limit,
self.max_frames, self.max_gpu_atoms)
exact = distance <= limit
values = np.where(exact | (lower > limit), distance / 2, limit / 2)
pending = np.flatnonzero(distance < 0)

def fallback(k):
i, j = pairs[k]
return solve_milp(graphs[i], graphs[j], self.threshold)

for k, result in zip(pending, pool.map(fallback, pending)):
values[k], exact[k] = result
if self.counts is not None:
self.counts += np.array([np.count_nonzero(lower > limit),
np.count_nonzero((lower <= limit) & (frames == 0)),
np.count_nonzero((frames > 0) & (distance >= 0)),
np.count_nonzero(frames == -1), len(pending)])
return range(len(pairs)), values, exact

return Cpu


def unpack(scores, pairs):
values, flags = scores.to_coo("score"), scores.to_coo("exact")
np.testing.assert_array_equal(flags.row, values.row)
Expand All @@ -203,36 +135,15 @@ def mismatches(values, oracle):


def verify_filters(graphs, pairs, expected):
from numba import cuda
from simms.similarity._mces_search import filter_kernel, pack

indices = np.sort(graphs.index[np.asarray(pairs)], axis=1)
meta, vertices, _, neighbors = pack(graphs.graphs)
n, width = len(pairs), max(len(g.elements) for g in graphs.graphs)
args = [cuda.to_device(arr) for arr in (meta, vertices, neighbors, indices)]
scratch = [cuda.device_array(shape, np.int32) for shape in
((n, width, width), (n, 7, width + 1), (n, 3, width), n)]
for column in (0, 1):
# A limit of -1 forces even a zero filter1 to return in dynamic mode.
filter_kernel[(n + 31) // 32, 32](*args, -1., bool(column), *scratch)
actual = scratch[-1].copy_to_host() / 2
np.testing.assert_array_equal(actual, np.array(expected)[:, column])
seeds = scratch[2].copy_to_host()[:, 0]
seed_certificates = 0
for k, (i, j) in enumerate(indices):
if actual[k] > 10:
continue
a, b = graphs.graphs[i], graphs.graphs[j]
seed = seeds[k, :len(a.elements)]
left = np.flatnonzero(seed >= 0)
right = seed[left]
overlap_twice = np.minimum(a.adjacency[np.ix_(left, left)],
b.adjacency[np.ix_(right, right)]).sum(dtype=np.int64)
distance = (a.weight + b.weight - overlap_twice) / 2
seed_certificates += int(distance == actual[k])
return {"checked_per_filter": n, "filter1_mismatches": 0, "filter2_mismatches": 0,
"threshold_10_survivors": int(np.count_nonzero(actual <= 10)),
"unmodified_assignment_certificates_at_10": seed_certificates}
from simms.similarity._mces_search import front, pack

left, right = graphs.index[np.asarray(pairs)].T
lib, _ = pack(graphs.graphs)
# A negative limit exposes the unrounded filter2 before any search.
actual = front(lib, left, right, -1., 1)[:, 0] / 2
np.testing.assert_array_equal(actual, np.asarray(expected)[:, 1])
return {"checked_per_filter": len(pairs), "filter2_mismatches": 0,
"threshold_10_survivors": int(np.count_nonzero(actual <= 10))}


def device_load():
Expand All @@ -252,7 +163,6 @@ def benchmark(data, repeats):
from simms.similarity import CudaMyopicMCES

set_num_threads(8)
cpu = cpu_port()
start = perf_counter()
graphs = MolecularGraphs.from_smiles(data["smiles"])
preparation = perf_counter() - start
Expand All @@ -268,9 +178,8 @@ def benchmark(data, repeats):
timing="Warm sparse_matrix on prepared MolecularGraphs, including graph packing, host/device transfers, "
"fallback and Scores assembly. CPU graph solver uses identical JIT source and public batch path. "
"Upstream uses MCES on cached RDKit molecules, native C++ filters, one solver thread per process. "
"Pool startup and first call excluded. Speedups use medians of the recorded wall times. GPU lanes partition "
"root choices and share a frame cap. CPU threads handle one complete pair at a time. "
"Routing counts come from an untimed pass. Score tolerance is 1e-7 with exact flag equality.",
"Pool startup and first call excluded. Speedups use medians of the recorded wall times. "
"Score tolerance is 1e-7 with exact flag equality.",
sampling="Distinct unordered pairs. Analogue panel uses three named analogue pairs plus seeded "
"Tanimoto-neighbor selection with 0 < upstream filter2 <= 10. Mixed panel sampled without "
"replacement from molecules with 4-13 atoms to make unrestricted oracle testing practical.",
Expand All @@ -295,9 +204,8 @@ def benchmark(data, repeats):
key = f"HiGHS/8/{threshold or -1}"
oracle_values = data["oracle"][key][panel]["values"]
run = stats["threshold_10" if threshold else "unrestricted"] = {}
for name, cls in (("numba_cpu", cpu), ("cuda", CudaMyopicMCES)):
scorer = cls(threshold=threshold, n_fallback_workers=8)
scorer.counts = None
for name, backend in (("numba_cpu", "cpu"), ("cuda", "cuda")):
scorer = CudaMyopicMCES(threshold=threshold, n_fallback_workers=8, backend=backend)
latencies = []
before = device_load()
for trial in range(repeats + 1):
Expand All @@ -315,21 +223,6 @@ def benchmark(data, repeats):
load_before=before, load_after=device_load(),
exact=sum(e for _, e in values),
max_absolute_error=max(abs(a[0] - b[0]) for a, b in zip(values, oracle_values)))
if name == "numba_cpu":
scorer.counts = np.zeros(5, np.int64)
scorer.sparse_matrix(graphs, graphs, rows, cols, progress_bar=False)
routes = ("filter_rejections", "map_certificates", "search_proofs",
"objective_bound_rejections", "fallbacks")
run[name]["routing"] = dict(zip(routes, scorer.counts.tolist()))
else:
module = import_module("simms.similarity.CudaMyopicMCES")
with patch.object(module, "solve_milp", wraps=module.solve_milp) as fallback:
checked = scorer.sparse_matrix(graphs, graphs, rows, cols, progress_bar=False)
assert not mismatches(unpack(checked, pairs), oracle_values)
routing = run["numba_cpu"]["routing"].copy()
routing["search_proofs"] += routing["fallbacks"] - len(fallback.call_args_list)
routing["fallbacks"] = len(fallback.call_args_list)
run[name]["routing"] = routing
gpu_time = run["cuda"]["median_seconds"]
run["speedup"] = {"numba_cpu_8": run["numba_cpu"]["median_seconds"] / gpu_time,
**{k: v["seconds"] / gpu_time for k, v in times.items()
Expand Down
Loading
Loading