diff --git a/CHANGELOG.md b/CHANGELOG.md index 706152b..16e299a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index fbc1888..7b80918 100644 --- a/README.md +++ b/README.md @@ -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 @@ -68,7 +68,7 @@ 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. @@ -76,7 +76,9 @@ Binned embeddings and precomputed fingerprints also run on CPU. The six spectral ## 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 @@ -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 diff --git a/benchmarks/benchmark_mces_matrix.py b/benchmarks/benchmark_mces_matrix.py new file mode 100644 index 0000000..b4c04b3 --- /dev/null +++ b/benchmarks/benchmark_mces_matrix.py @@ -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)) diff --git a/benchmarks/benchmark_myopic_mces.py b/benchmarks/benchmark_myopic_mces.py index d6ccac1..ac5ddc3 100644 --- a/benchmarks/benchmark_myopic_mces.py +++ b/benchmarks/benchmark_myopic_mces.py @@ -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 @@ -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 @@ -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) @@ -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(): @@ -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 @@ -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.", @@ -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): @@ -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() diff --git a/benchmarks/myopic_mces_v1_2_rtx4060.json b/benchmarks/myopic_mces_v1_2_rtx4060.json new file mode 100644 index 0000000..8758bd7 --- /dev/null +++ b/benchmarks/myopic_mces_v1_2_rtx4060.json @@ -0,0 +1,116 @@ +{ + "package": "simms-gpu 1.2.0", + "gpu": "NVIDIA GeForce RTX 4060 Laptop GPU", + "driver": "580.105.08", + "cpu_model": "Intel Core i9-14900HX", + "cpu_affinity": [ + 0, + 2, + 4, + 6, + 8, + 10, + 12, + 14 + ], + "numba_threads": 8, + "versions": { + "numba": "0.68.1", + "numba-cuda": "0.30.4", + "numpy": "2.4.6", + "scipy": "1.18.1", + "rdkit": "2026.3.5", + "torch": "2.15.0", + "matchms": "1.0.0" + }, + "inputs": { + "axes.pkl": "1d1ecce2724098bad5c440fc1f07684b585812a8a512932b95a03053e73facaa", + "cpu-full.npy": "a1b87a0fba0c7fac03316d3d18ecfa1415383cf220c3dd5908a1bff497ce62ef" + }, + "threshold": 10.0, + "always_stronger_bound": true, + "timing": "One untimed full warmup per mode followed by three public calls on prepared graph axes. Each call includes graph packing, transfers, solving, and output assembly. Output validation is outside the timer.", + "cuda": { + "backend": "cuda", + "shape": [ + 1000, + 1000 + ], + "exact_hits": 11245, + "sparse": { + "seconds": [ + 4.513099032003083, + 4.6346951790037565, + 4.616093119002471 + ], + "median_seconds": 4.616093119002471 + }, + "dense": { + "seconds": [ + 7.8544662650019745, + 7.824842872003501, + 7.771347099995182 + ], + "median_seconds": 7.824842872003501 + } + }, + "cpu": { + "backend": "cpu", + "shape": [ + 1000, + 1000 + ], + "exact_hits": 11245, + "sparse": { + "seconds": [ + 12.446466964996944, + 11.006379234000633, + 10.98814214199956 + ], + "median_seconds": 11.006379234000633 + }, + "dense": { + "seconds": [ + 13.507027934996586, + 13.071766080996895, + 13.217113215003337 + ], + "median_seconds": 13.217113215003337 + } + }, + "parity": { + "pairs": 1000000, + "exact_hits": 11245, + "exact_at_threshold": 2312, + "false_positives": 0, + "false_negatives": 0, + "distance_errors": 0, + "duplicates": 0, + "dense_record_errors": 0 + }, + "process_vram_peak_MiB": { + "cpu": 0, + "cuda": 226 + }, + "cuda_kernels": { + "static_shared_bytes": { + "screen_kernel": 0, + "px": 0, + "py": 0 + }, + "survivors": 38487, + "histogram_kernel_ms": [ + 0.45977601408958435, + 0.4546560049057007, + 0.4628480076789856, + 0.45849600434303284, + 0.4546560049057007, + 0.44441598653793335, + 0.447488009929657, + 0.44441598653793335, + 0.44441598653793335, + 0.44441598653793335 + ], + "median_histogram_kernel_ms": 0.45107200741767883 + } +} diff --git a/pyproject.toml b/pyproject.toml index 4797822..a086320 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "simms-gpu" -version = "1.1.0" +version = "1.2.0" description = "Faster Similarity for Mass Spec on GPU" authors = [ {name="Tornike Onoprishvili", email="tornikeonoprishvili@gmail.com"} diff --git a/simms/__version__.py b/simms/__version__.py index 6849410..c68196d 100644 --- a/simms/__version__.py +++ b/simms/__version__.py @@ -1 +1 @@ -__version__ = "1.1.0" +__version__ = "1.2.0" diff --git a/simms/molecules.py b/simms/molecules.py index fba2bb9..cf4060b 100644 --- a/simms/molecules.py +++ b/simms/molecules.py @@ -115,7 +115,7 @@ def _prepare(cls, items, kind): keys, parsed = {}, {} def register(mol): - if mol is None or not mol.GetNumAtoms(): + if mol is None: return -1 try: key = Chem.MolToSmiles(mol, allBondsExplicit=True) diff --git a/simms/similarity/CudaMyopicMCES.py b/simms/similarity/CudaMyopicMCES.py index 5c60179..1375bdb 100644 --- a/simms/similarity/CudaMyopicMCES.py +++ b/simms/similarity/CudaMyopicMCES.py @@ -1,8 +1,7 @@ # SPDX-License-Identifier: MIT -"""Thresholded weighted molecular common-edge distances on CUDA.""" +"""Thresholded weighted molecular common-edge distances on CUDA and CPU.""" from collections import defaultdict from concurrent.futures import ThreadPoolExecutor -from itertools import islice, product from operator import index import numpy as np @@ -15,30 +14,7 @@ from ..molecules import MolecularGraphs from ..utils import get_device from ._base import CudaSimilarity -from ._mces_milp import solve_milp -from ._mces_search import filter_kernel, pack, solve_kernel -from .vector_similarity_functions import kernel_stream, kernel_view - - -@cuda.jit -def _scatter(ids, values, flags, scores, exact): - k = cuda.grid(1) - if k < len(ids): - scores[ids[k]], exact[ids[k]] = values[k], flags[k] - - -@cuda.jit -def _retain(scores, exact, maximum, has_maximum, only_exact, ids, values, flags, count): - k = cuda.grid(1) - if k < len(scores): - if (not has_maximum or scores[k] <= maximum) and (not only_exact or exact[k]): - slot = cuda.atomic.add(count, 0, 1) - ids[slot], values[slot], flags[slot] = k, scores[k], exact[k] - - -def _launch(n): - threads = 32 - return (n + threads - 1) // threads, threads +from ._mces_engine import Engine def _library(left, right): @@ -91,46 +67,45 @@ def __init__(self, a, b, symmetric, row, col): if symmetric: self.requested[key].add((j, i)) - def __iter__(self): + def tiles(self, size): if self.requested is not None: - yield from self.requested + keys = np.asarray(list(self.requested), np.int32).reshape(-1, 2) + for start in range(0, len(keys), size): + yield keys[start:start + size].T return - for i in self.left: - for j in self.right: - if i > j and j in self.left and i in self.right: - continue - yield i, j - - def batches(self, graphs, batch_size): - def split(tile): - width = max((len(graphs[g].elements) for i, j in tile if i >= 0 and j >= 0 and i != j - for g in (i, j)), default=1) - # Bound concurrent LAP scratch without penalizing unrelated small pairs. - if len(tile) > 1 and len(tile) * 4 * width * width > (64 << 20): - mid = len(tile) // 2 - yield from split(tile[:mid]) - yield from split(tile[mid:]) - else: - yield tile, width - - pairs = iter(self) - while tile := list(islice(pairs, batch_size)): - yield from split(tile) - - def expand(self, tile, ids, records, predicate): - for k, pair_id in enumerate(ids): - if predicate is None or predicate(records[k]): - for i, j in self.locations(tile[pair_id]): - yield i, j, k - - def locations(self, pair): + a, b = np.array(list(self.left), np.int32), np.array(list(self.right), np.int32) + for start in range(0, len(a) * len(b), size): + idx = np.arange(start, min(start + size, len(a) * len(b))) + i, j = a[idx // len(b)], b[idx % len(b)] + keep = (i <= j) | ~np.isin(i, b) | ~np.isin(j, a) + yield i[keep], j[keep] + + def locations(self, left, right): if self.requested is not None: - yield from self.requested[pair] + parts = [np.asarray(list(self.requested[i, j]), np.intp) for i, j in zip(left, right)] + coords = np.concatenate(parts) + yield coords[:, 0], coords[:, 1], np.repeat(np.arange(len(parts)), [len(p) for p in parts]) return - i, j = pair - yield from product(self.left[i], self.right[j]) - if i != j and j in self.left and i in self.right: - yield from product(self.left[j], self.right[i]) + unique = all(len(v) == 1 for v in self.left.values()) and all(len(v) == 1 for v in self.right.values()) + for a, b, reverse in ((left, right, False), (right, left, True)): + ids = np.arange(len(a)) + if reverse: + ids = ids[(a != b) & np.isin(a, list(self.left)) & np.isin(b, list(self.right))] + if not len(ids): + continue + if unique: + # Dense lookup also accommodates the missing-structure sentinel via +1. + row = np.empty(max(self.left) + 2, np.intp) + col = np.empty(max(self.right) + 2, np.intp) + for k, v in self.left.items(): + row[k + 1] = v[0] + for k, v in self.right.items(): + col[k + 1] = v[0] + yield row[a[ids] + 1], col[b[ids] + 1], ids + else: + for k in ids: + rows, cols = self.left[a[k]], self.right[b[k]] + yield np.repeat(rows, len(cols)), np.tile(cols, len(rows)), k class CudaMyopicMCES(CudaSimilarity): @@ -148,8 +123,8 @@ class CudaMyopicMCES(CudaSimilarity): score_fields = score_datatype.names def __init__(self, threshold: float | None = 10.0, always_stronger_bound: bool = True, - batch_size: int = 2048, max_frames: int = 50_000, max_gpu_atoms: int = 64, - n_fallback_workers: int | None = None): + batch_size: int = 2048, max_frames: int = 8_192, max_gpu_atoms: int = 64, + n_fallback_workers: int | None = None, backend: str = "cuda"): self.threshold = None if threshold is None else float(threshold) if threshold is not None and (not np.isfinite(self.threshold) or self.threshold < 0): raise ValueError("threshold must be nonnegative and finite, or None") @@ -161,8 +136,20 @@ def __init__(self, threshold: float | None = 10.0, always_stronger_bound: bool = if min(self.batch_size, self.max_frames, self.max_gpu_atoms, 1 if n_fallback_workers is None else self.n_fallback_workers) < 1: raise ValueError("batch_size, max_frames, max_gpu_atoms and n_fallback_workers must be positive") - self.device = get_device(require_cuda=True) - if not cuda.is_available(): + if backend not in ("cuda", "cpu", "auto"): + raise ValueError("backend must be 'cuda', 'cpu' or 'auto'") + self.backend = backend + self.device = None + if backend != "cpu" and cuda.is_available(): + try: + device = get_device(require_cuda=backend == "cuda") + except RuntimeError: + if backend == "cuda": + raise + device = None + if device == "cuda" or cuda.config.ENABLE_CUDASIM: + self.device = device + if backend == "cuda" and self.device is None: raise RuntimeError("MCES requires CUDA or NUMBA_ENABLE_CUDASIM=1") def pair(self, a, b): @@ -175,112 +162,62 @@ def single(item): return self.matrix(single(a), single(b), array_type="numpy", progress_bar=False).reshape(()) - @staticmethod - def _upload(arrays): - return tuple(cuda.to_device(arr) for arr in arrays) - - def _solve(self, library, graphs, pairs, width, pool, maximum, only_exact, device_output): - n = len(pairs) - meta, vertices, adjacency, neighbors = library - device_pairs = cuda.to_device(np.asarray(pairs, np.int32)) - work = cuda.device_array((n, 7, width + 1), np.int32) - costs = cuda.device_array((n, width, width), np.int32) - seeds = cuda.device_array((n, 3, width), np.int32) - lower = cuda.device_array(n, np.int32) - stream = kernel_stream(self.device) if device_output else 0 - if device_output: - planes = (torch.empty(n, device=self.device, dtype=torch.float64), - torch.empty(n, device=self.device, dtype=torch.bool)) - scores, exact = map(kernel_view, planes) - else: - scores, exact = cuda.device_array(n, np.float64), cuda.device_array(n, np.bool_) - pending = cuda.device_array(n, np.int32) - count = cuda.to_device(np.zeros(1, np.int32)) - threshold = np.inf if self.threshold is None else self.threshold - blocks, threads = _launch(n) - filter_kernel[blocks, threads, stream](meta, vertices, neighbors, device_pairs, threshold * 2, - self.always_stronger_bound, costs, work, seeds, lower) - lanes = 1 if cuda.config.ENABLE_CUDASIM else 32 - solve_kernel[n, lanes, stream]( - meta, vertices, adjacency, neighbors, device_pairs, threshold, self.always_stronger_bound, - self.max_gpu_atoms, self.max_frames, lower, seeds, work, scores, exact, pending, count, - ) - if stream: - stream.synchronize() - size = int(count.copy_to_host()[0]) - if size: - ids = pending[:size].copy_to_host() - - def solve(k): - i, j = pairs[k] - return solve_milp(graphs[i], graphs[j], self.threshold) - - values, flags = zip(*pool.map(solve, ids)) - blocks, threads = _launch(size) - _scatter[blocks, threads, stream](pending[:size], cuda.to_device(np.array(values, np.float64)), - cuda.to_device(np.array(flags, bool)), scores, exact) - if device_output: - return range(n), *planes - if maximum is None and not only_exact: - return range(n), scores.copy_to_host(), exact.copy_to_host() - count.copy_to_device(np.zeros(1, np.int32)) - values = cuda.device_array_like(scores) - flags = cuda.device_array_like(exact) - _retain[_launch(n)](scores, exact, 0. if maximum is None else float(maximum), - maximum is not None, only_exact, pending, values, flags, count) - size = int(count.copy_to_host()[0]) - return (pending[:size].copy_to_host(), values[:size].copy_to_host(), flags[:size].copy_to_host()) - def _compute(self, left, right, fields, progress_bar, array_type, row=None, col=None, - predicate=None, maximum=None, only_exact=False): + predicate=None, maximum=None, only_exact=False, is_symmetric=False): symmetric = right is None same = symmetric or left is right left = MolecularGraphs.from_spectra(left) right = left if same else MolecularGraphs.from_spectra(right) shape = (len(left), len(right)) graphs, a, b = _library(left, right) - plan = _Pairs(a, b, symmetric, row, col) + if is_symmetric and not np.array_equal(a[0], b[0]): + raise ValueError("is_symmetric requires identical molecular axes") + plan = _Pairs(a, b, symmetric or is_symmetric, row, col) dtype = np.dtype([(f, self.score_datatype[f]) for f in fields]) sparse = array_type == "sparse" if sparse: chunks = [] elif array_type == "torch": - result = torch.empty((len(fields), *shape), dtype=torch.float64, device=self.device) + result = torch.empty((len(fields), *shape), dtype=torch.float64, device=self.device or "cpu") elif array_type == "scores": result = self._create_dense_result(*shape, fields) else: result = np.empty(shape, dtype) - if graphs: - library = self._upload(pack(graphs)) - else: - # Sentinel-only pairs leave the kernels before graph access. - library = tuple(cuda.to_device(arr) for arr in - (np.zeros((1, 5), np.int64), np.empty((0, 5), np.int32), - np.empty(0, np.uint8), np.empty((0, 3), np.int32))) + fast = self.threshold is not None and ( + only_exact or not self.always_stronger_bound or (maximum is not None and maximum < self.threshold)) + engine = Engine(graphs, self, fast, maximum) if graphs else None with ThreadPoolExecutor(self.n_fallback_workers) as pool, tqdm( desc="Scoring molecular pairs", unit="pair", disable=not progress_bar ) as progress: - for tile, width in plan.batches(graphs, self.batch_size): - ids, values, flags = self._solve(library, graphs, tile, width, pool, maximum, - only_exact, array_type == "torch") - if array_type == "torch": - records = {"score": values, "exact": flags} + for left_ids, right_ids in plan.tiles(min(1 << 20, self.batch_size * 512)): + if engine is None: + values, flags = np.full(len(left_ids), np.nan), np.zeros(len(left_ids), bool) else: - records = np.empty(len(values), self.score_datatype) - records["score"], records["exact"] = values, flags - locations = plan.expand(tile, ids, records, predicate) - while block := list(islice(locations, max(len(tile), 4096))): - i, j, k = np.asarray(block, np.intp).T - if sparse: - chunks.append((i, j, records[k])) - elif array_type == "torch": - i, j, k = (torch.as_tensor(x, device=self.device) for x in (i, j, k)) - for p, field in enumerate(fields): - result[p, i, j] = records[field][k].to(result.dtype) - else: - for field in fields: - result[field][i, j] = records[field][k] - progress.update(len(tile)) + values, flags = engine.solve(left_ids, right_ids, pool) + keep = np.ones(len(values), bool) + if maximum is not None: + keep &= values <= maximum + if only_exact: + keep &= flags + ids = np.flatnonzero(keep) + records = np.empty(len(ids), self.score_datatype) + records["score"], records["exact"] = values[ids], flags[ids] + if predicate is not None: + passed = np.fromiter(map(predicate, records), bool, len(records)) + ids, records = ids[passed], records[passed] + if len(ids): + for i, j, k in plan.locations(left_ids[ids], right_ids[ids]): + if sparse: + chunks.append((i, j, np.broadcast_to(records[k], i.shape))) + elif array_type == "torch": + for plane, field in enumerate(fields): + data = np.ascontiguousarray(records[field][k]) + result[plane, i, j] = torch.as_tensor(data, device=self.device or "cpu", + dtype=result.dtype) + else: + for field in fields: + result[field][i, j] = records[field][k] + progress.update(len(left_ids)) if sparse: if chunks: i, j, values = map(np.concatenate, zip(*chunks)) @@ -290,19 +227,21 @@ def _compute(self, left, right, fields, progress_bar, array_type, row=None, col= return Scores({f: coo_array((values[f], (i, j)), shape=shape) for f in fields}) return Scores(result) if array_type == "scores" else result - def matrix(self, left, right=None, score_fields=None, progress_bar=True, array_type="scores"): + def matrix(self, left, right=None, score_fields=None, progress_bar=True, array_type="scores", *, is_symmetric=False): if array_type not in ("scores", "numpy", "torch"): raise ValueError("array_type must be 'scores', 'numpy' or 'torch'") - return self._compute(left, right, self._fields(score_fields), progress_bar, array_type) + return self._compute(left, right, self._fields(score_fields), progress_bar, array_type, + is_symmetric=is_symmetric) def keep_score(self, score): """Retain all requested distances, including exact zeros and missing values.""" return True def sparse_matrix(self, left, right=None, idx_row=None, idx_col=None, score_fields=None, - score_filter=None, progress_bar=True, max_distance=None, exact_only=False): + score_filter=None, progress_bar=True, max_distance=None, exact_only=False, + *, is_symmetric=False): """Retain inclusive distance/exactness matches, then apply a full-record predicate.""" if score_filter is None and getattr(self.keep_score, "__func__", None) is not CudaMyopicMCES.keep_score: score_filter = self.keep_score return self._compute(left, right, self._fields(score_fields), progress_bar, "sparse", - idx_row, idx_col, score_filter, max_distance, exact_only) + idx_row, idx_col, score_filter, max_distance, exact_only, is_symmetric) diff --git a/simms/similarity/_mces_engine.py b/simms/similarity/_mces_engine.py new file mode 100644 index 0000000..0064d77 --- /dev/null +++ b/simms/similarity/_mces_engine.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: MIT +"""Per-call workspaces and scheduling for the thresholded MCES pipeline.""" +from contextlib import nullcontext + +import numpy as np +from numba import cuda + +from ._mces_milp import solve_milp +from ._mces_model import count_models, pack_models +from ._mces_pdhg import iterate, verify +from ._mces_search import cpu_screen, device_features, front, pack, screen_kernel, simulator_launch + + +class Engine: + def __init__(self, graphs, scorer, fast, maximum): + self.graphs = graphs + self.lib, self.hist = pack(graphs) + self.weights = np.ascontiguousarray(self.lib.meta[:-1, 3]) + self.scorer = scorer + self.fast = fast + threshold = scorer.threshold + self.threshold = threshold + if fast and maximum is not None and maximum < threshold: + threshold = maximum + largest = 2 * int(self.weights.max()) + self.limit = float(largest) if threshold is None or threshold >= largest / 2 else 2 * threshold + self.gpu = scorer.device is not None + # Bound resident screening storage even for chemically diverse libraries. + self.device_hist = None + if fast and self.gpu and self.hist.nbytes < (128 << 20): + features, packed = device_features(self.hist) + self.device_hist = cuda.to_device(self.weights), cuda.to_device(features), packed + + def screen(self, left, right): + if self.device_hist is None: + return cpu_screen(left, right, self.weights, self.hist, self.limit) + keep = cuda.device_array(len(left), np.bool_) + with simulator_launch if cuda.config.ENABLE_CUDASIM else nullcontext(): + screen_kernel[(len(left) + 127) // 128, 128]( + cuda.to_device(left), cuda.to_device(right), *self.device_hist, self.limit, keep) + return keep.copy_to_host() + + def solve(self, left, right, pool): + valid = (left >= 0) & (right >= 0) + exact = valid & (left == right) + scores = np.full(len(left), np.inf if self.threshold is None else self.threshold) + scores[~valid] = np.nan + scores[exact] = 0. + ids = np.flatnonzero(valid & ~exact) + if self.fast and len(ids): + ids = ids[self.screen(left[ids], right[ids])] + if not len(ids): + return scores, exact + a, b = left[ids], right[ids] + states = np.empty((len(ids), 3), np.int64) + batch = self.scorer.batch_size + for start in range(0, len(ids), batch): + chunk = slice(start, start + batch) + states[chunk] = front(self.lib, a[chunk], b[chunk], self.limit, + self.scorer.max_frames) + rejected = states[:, 1] == -2 + if not self.fast: + scores[ids[rejected]] = states[rejected, 0] / 2 + pending = np.flatnonzero((states[:, 1] == -1) & (states[:, 0] <= self.limit)) + tail = {} + if len(pending): + widths = np.diff(self.lib.meta[:, 0]) + on_cuda = self.gpu & (np.maximum(widths[a[pending]], widths[b[pending]]) <= self.scorer.max_gpu_atoms) + for use_gpu in (True, False): + group = pending[on_cuda == use_gpu] + if len(group): + self.refine(a, b, states, group, tail, use_gpu) + solved = (states[:, 1] >= 0) & (states[:, 1] <= self.limit) + scores[ids[solved]] = states[solved, 1] / 2 + exact[ids[solved]] = True + oversize = np.flatnonzero(states[:, 1] == -3) + + def fallback(k): + args = tail.get(k, ()) + # Reduced costs were proved at this call's effective cutoff. + score, flag = solve_milp(self.graphs[a[k]], self.graphs[b[k]], self.limit / 2, *args) + return (score, True) if flag else (self.threshold, False) + + remaining = [*oversize, *tail] + for k, (score, flag) in zip(remaining, pool.map(fallback, remaining)): + scores[ids[k]], exact[ids[k]] = score, flag + return scores, exact + + def refine(self, left, right, state, pending, tail, gpu): + sizes = count_models(self.lib, left[pending], right[pending]) + order = np.argsort(sizes[:, 2], kind="stable") + pending, sizes = pending[order], sizes[order] + # Bound scratch by actual nonzeros. A single exceptionally large model + # goes directly to host HiGHS. No device buffer is shared between calls. + large = sizes[:, 2] > 4_000_000 + state[pending[large], 1] = -3 + pending, sizes = pending[~large], sizes[~large] + for iterations in (96, 384, 768): + if not len(pending): + break + sums = np.append(0, np.cumsum(sizes[:, 2])) + start = 0 + while start < len(pending): + end = min(start + self.scorer.batch_size, + np.searchsorted(sums, sums[start] + 4_000_000, side="right") - 1) + keys = pending[start:end] + a, b = left[keys], right[keys] + model, offsets = pack_models(self.lib, a, b, sizes[start:end]) + x, y = iterate(model, offsets, iterations, gpu) + values = state[keys] + final = iterations == 768 + fix = verify(self.lib, a, b, model, offsets, sizes[start:end, 3], x, y, values, + self.limit, final) + state[keys] = values + if final: + for idx in np.flatnonzero(values[:, 1] == -1): + tail[keys[idx]] = (int(values[idx, 2]), fix[offsets[idx, 0]:offsets[idx + 1, 0]].copy()) + start = end + keep = state[pending, 1] == -1 + pending, sizes = pending[keep], sizes[keep] diff --git a/simms/similarity/_mces_milp.py b/simms/similarity/_mces_milp.py index 175dfbc..5d1b9c0 100644 --- a/simms/similarity/_mces_milp.py +++ b/simms/similarity/_mces_milp.py @@ -1,79 +1,132 @@ # SPDX-License-Identifier: MIT -"""Sparse binary model for the weighted common-edge edit distance (SciPy/HiGHS).""" -from collections import defaultdict +"""Exact oriented-edge HiGHS tail for capped searches and cyclic integrality gaps.""" from warnings import filterwarnings import numpy as np -from scipy.optimize import Bounds, LinearConstraint, milp -from scipy.sparse import csc_matrix +from scipy.optimize import Bounds, LinearConstraint, linprog, milp +from scipy.sparse import csc_matrix, vstack +from ._mces_model import allocate_model, dimensions, fill_model +from ._mces_search import Graph, reverse_edges -# SciPy forwards the native threads option. Scope the warning filter to this -# module: entering/exiting catch_warnings in concurrent workers races on 3.11. -filterwarnings("ignore", message=r"Unrecognized options detected: .*'threads'.*", category=RuntimeWarning, + +filterwarnings("ignore", message=r"Unrecognized options detected: .*'threads'.*", module=r"^simms\.similarity\._mces_milp$") -def solve_milp(a, b, threshold): - """Return the certified optimum, or the threshold after certified infeasibility.""" - # Eliminate the unmatched-edge variables: an edge unused by a match pays - # its weight. A matched edge pair saves twice its smaller weight. - total = a.weight + b.weight - edge_a = list(zip(*np.nonzero(np.triu(a.adjacency, 1)))) - edge_b = list(zip(*np.nonzero(np.triu(b.adjacency, 1)))) - atom_vars = {} - objective = [] - rows = defaultdict(dict) +def _cycle(g): + """Find a fundamental cycle, or certify the entire graph is a forest.""" + parent = np.full(len(g.vertices), -1, np.intp) + depth = np.full(len(parent), -1, np.intp) + shortest = None + for root in range(len(parent)): + if depth[root] >= 0: + continue + depth[root] = 0 + stack = [root] + while stack: + i = stack.pop() + for j in np.flatnonzero(g.adjacency[i]): + if depth[j] < 0: + parent[j], depth[j] = i, depth[i] + 1 + stack.append(j) + elif j != parent[i] and i != parent[j] and i < j: + a, b = i, j + path = [(i, j)] + while a != b: + if depth[a] >= depth[b]: + path.append((a, parent[a])) + a = parent[a] + else: + path.append((b, parent[b])) + b = parent[b] + if shortest is None or len(path) < len(shortest): + shortest = path + return shortest - for i, elem in enumerate(a.elements): - for j in np.flatnonzero(b.elements == elem): - var = len(objective) - atom_vars[i, j] = var - objective.append(0) - rows["atom_a", i][var] = rows["atom_b", j][var] = 1 - for e, (i, h) in enumerate(edge_a): - for f, (j, k) in enumerate(edge_b): - if not (((i, j) in atom_vars and (h, k) in atom_vars) - or ((i, k) in atom_vars and (h, j) in atom_vars)): - continue - var = len(objective) - objective.append(-2 * int(min(a.adjacency[i, h], b.adjacency[j, k]))) - rows["edge_a", e][var] = rows["edge_b", f][var] = 1 - # Incidence consistency, aggregated by (vertex, opposite edge). - for src in (i, h): - row = rows["inc_a", src, f] - row[var] = 1 - for dst in (j, k): - if (src, dst) in atom_vars: - row[atom_vars[src, dst]] = -1 - for dst in (j, k): - row = rows["inc_b", dst, e] - row[var] = 1 - for src in (i, h): - if (src, dst) in atom_vars: - row[atom_vars[src, dst]] = -1 - if len(objective) == len(atom_vars): - score = total / 2 - return (score, True) if threshold is None or score <= threshold else (threshold, False) - if threshold is not None: - rows["limit",] = {i: c for i, c in enumerate(objective) if c} +def _ring_disjunction(a, b, model, atom_count): + rings = _cycle(a), _cycle(b) + if bool(rings[0]) == bool(rings[1]): + return [] + side = 0 if rings[0] else 1 + g = (a, b)[side] + edge_ids = (model.edge_a, model.edge_b)[side][atom_count:] + branches = [] + for i, j in rings[side]: + directions = [] + for u, v in ((i, j), (j, i)): + start, count = g.vertices[u, 3:5] + directions.append(start + np.flatnonzero(g.neighbors[start:start + count, 0] == v)[0]) + branches.append(atom_count + np.flatnonzero(np.isin(edge_ids, directions))) + return branches - ri, ci, values, upper = [], [], [], [] - for r, (key, entries) in enumerate(rows.items()): - ri.extend([r] * len(entries)) - ci.extend(entries) - values.extend(entries.values()) - if key[0] == "limit": - upper.append(np.floor(2 * threshold) - total) + +def solve_model(a, b, threshold, model, atoms, best, fix): + total = a.weight + b.weight + limit = total if threshold is None or threshold >= total / 2 else int(2 * threshold) + step = max(1, 2 * int(np.gcd(a.weight_gcd, b.weight_gcd))) + cutoff = min(limit, best - step) + incumbent = (best / 2, True) if best <= limit else (threshold, False) + if cutoff < 0 or len(model.objective) == atoms: + return incumbent + coefficients = np.ones(len(model.ci), np.int8) + for c in range(atoms): + coefficients[model.cp[c] + 2:model.cp[c + 1]] = -1 + matrix = csc_matrix((coefficients, model.ci, model.cp), shape=(len(model.rhs), len(model.objective))) + lo, hi = (fix > 0).astype(float), (fix >= 0).astype(float) + obj = -model.objective.astype(np.float64) + rhs = model.rhs + branches = _ring_disjunction(a, b, model, atoms) + if branches: + # Every injection of a cycle into a forest omits at least one whole + # edge. Prove each disjunct separately using integer dual bounds. + for indices in branches: + upper = hi.copy() + upper[indices] = 0 + if np.any(lo > upper): + continue + lp = linprog(obj, A_ub=matrix, b_ub=rhs, bounds=np.column_stack((lo, upper)), + method="highs-ipm", options={"threads": 1}) + if lp.status == 2: + continue + if not lp.success: + break + scale = 1 << 20 + q = np.maximum(0, np.rint(-lp.ineqlin.marginals * scale)).astype(np.int64) + reduced = -obj.astype(np.int64) * scale - matrix.T @ q + bound = rhs.astype(np.int64) @ q + np.where(reduced >= 0, upper, lo).astype(np.int64) @ reduced + if bound >= (total - cutoff) * scale: + break else: - upper.append(0 if key[0].startswith("inc") else 1) - matrix = csc_matrix((values, (ri, ci)), shape=(len(upper), len(objective))) - result = milp(np.asarray(objective, float), integrality=np.ones(len(objective), np.uint8), - bounds=Bounds(0, 1), constraints=LinearConstraint(matrix, -np.inf, upper), - options={"mip_rel_gap": 0.0, "threads": 1}) - if result.status == 2 and threshold is not None: - return threshold, False + return incumbent + ring = np.zeros(len(obj)) + ring[np.concatenate(branches)] = 1 + matrix = vstack((matrix, ring), format="csc") + rhs = np.append(rhs, len(branches) - 1) + matrix = vstack((matrix, obj), format="csc") + rhs = np.append(rhs, cutoff - total) + integrality = np.zeros(len(obj), np.uint8) + integrality[:atoms] = 1 + result = milp(obj, integrality=integrality, bounds=Bounds(lo, hi), + constraints=LinearConstraint(matrix, -np.inf, rhs), + options={"mip_rel_gap": 0., "threads": 1}) + if result.status == 2: + return incumbent if not result.success: raise RuntimeError(f"HiGHS could not certify the MCES distance: {result.message}") return (total + round(result.fun)) / 2, True + + +def solve_milp(a, b, threshold, best=None, fix=None): + def local(g): + return Graph(g.vertices, g.neighbors, g.adjacency.ravel(), g.elements, + reverse_edges(g.vertices, g.neighbors), g.weight, g.weight_gcd) + + left, right = local(a), local(b) + cols, rows, nnz, atoms = dimensions(left, right) + model = allocate_model(cols, rows, nnz) + fill_model(left, right, model, np.zeros(3, np.int64), np.array([cols, rows, nnz])) + if fix is None: + fix = np.zeros(cols, np.int8) + return solve_model(a, b, threshold, model, atoms, a.weight + b.weight if best is None else best, fix) diff --git a/simms/similarity/_mces_model.py b/simms/similarity/_mces_model.py new file mode 100644 index 0000000..15891bd --- /dev/null +++ b/simms/similarity/_mces_model.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: MIT +"""Block-diagonal oriented-edge relaxation in CSR and CSC incidence order. + +An atom column selects a compatible vertex pair. An edge column selects two +compatible endpoint pairs in one orientation. For each selected atom, incident +edge matches form a partial bipartite matching between its two neighbor lists. +""" +from collections import namedtuple + +import numpy as np +from numba import njit, prange + +from ._mces_search import graph + + +Model = namedtuple("Model", "cp ci rp ri objective rhs initial edge_a edge_b") + + +@njit(cache=True) +def dimensions(a, b): + atoms = edges = links = 0 + for i in range(len(a.atoms)): + for j in range(len(b.atoms)): + if a.atoms[i, 0] != b.atoms[j, 0]: + continue + atoms += 1 + for e in range(a.atoms[i, 3], a.atoms[i, 3] + a.atoms[i, 4]): + active = False + for f in range(b.atoms[j, 3], b.atoms[j, 3] + b.atoms[j, 4]): + if a.bonds[e, 1] == b.bonds[f, 1]: + active = True + edges += a.bonds[e, 0] > i + links += active + for f in range(b.atoms[j, 3], b.atoms[j, 3] + b.atoms[j, 4]): + for e in range(a.atoms[i, 3], a.atoms[i, 3] + a.atoms[i, 4]): + if a.bonds[e, 1] == b.bonds[f, 1]: + links += 1 + break + return (atoms + edges, len(a.atoms) + len(b.atoms) + links, + 2 * atoms + links + 4 * edges, atoms) + + +@njit(parallel=True, nogil=True, cache=True) +def count_models(lib, left, right): + counts = np.empty((len(left), 4), np.int64) + for k in prange(len(left)): + counts[k] = dimensions(graph(lib, left[k]), graph(lib, right[k])) + return counts + + +@njit(cache=True) +def fill_model(a, b, model, offsets, end): + n, m = len(a.atoms), len(b.atoms) + col, row, pos = offsets[0], offsets[1], offsets[2] + first_row = row + xy = np.full((n, m), -1, model.cp.dtype) + left = np.full((len(a.bonds), m), -1, model.cp.dtype) + right = np.full((n, len(b.bonds)), -1, model.cp.dtype) + for i in range(n): + model.initial[row + i] = a.atoms[i, 1] * 0.5 + for j in range(m): + model.initial[row + n + j] = b.atoms[j, 1] * 0.5 + model.rhs[row:row + n + m] = 1 + row += n + m + for i in range(n): + for j in range(m): + if a.atoms[i, 0] != b.atoms[j, 0]: + continue + xy[i, j] = col + model.cp[col] = pos + model.ci[pos] = first_row + i + model.ci[pos + 1] = first_row + n + j + pos += 2 + for side in range(2): + src, dst = (a, b) if side == 0 else (b, a) + u, v = (i, j) if side == 0 else (j, i) + for e in range(src.atoms[u, 3], src.atoms[u, 3] + src.atoms[u, 4]): + label = src.bonds[e, 1] + for f in range(dst.atoms[v, 3], dst.atoms[v, 3] + dst.atoms[v, 4]): + if dst.bonds[f, 1] == label: + if side == 0: + left[e, j] = row + else: + right[i, e] = row + model.ci[pos] = row + model.initial[row] = src.bonds[e, 2] * 0.5 + pos += 1 + row += 1 + break + col += 1 + for i in range(n): + for e in range(a.atoms[i, 3], a.atoms[i, 3] + a.atoms[i, 4]): + h = a.bonds[e, 0] + if h <= i: + continue + for j in range(m): + if xy[i, j] < 0: + continue + for f in range(b.atoms[j, 3], b.atoms[j, 3] + b.atoms[j, 4]): + k = b.bonds[f, 0] + if xy[h, k] >= 0: + model.cp[col] = pos + model.ci[pos] = left[e, j] + model.ci[pos + 1] = right[i, f] + model.ci[pos + 2] = left[a.reverse[e], k] + model.ci[pos + 3] = right[h, b.reverse[f]] + model.edge_a[col], model.edge_b[col] = e, f + model.objective[col] = 2 * min(a.bonds[e, 2], b.bonds[f, 2]) + pos += 4 + col += 1 + # Counting transpose preserves column order. Every link row starts with + # its negative atom coefficient, followed by positive edge coefficients. + cursor = np.zeros(row - first_row, model.rp.dtype) + for t in range(offsets[2], pos): + cursor[model.ci[t] - first_row] += 1 + start = offsets[2] + for r in range(len(cursor)): + count = cursor[r] + model.rp[first_row + r] = start + cursor[r] = start + start += count + for c in range(offsets[0], col): + stop = model.cp[c + 1] if c + 1 < col else end[2] + for t in range(model.cp[c], stop): + r = model.ci[t] - first_row + model.ri[cursor[r]] = c + cursor[r] += 1 + + +@njit(parallel=True, nogil=True, cache=True) +def fill_models(lib, left, right, model, offsets): + for k in prange(len(left)): + fill_model(graph(lib, left[k]), graph(lib, right[k]), model, offsets[k], offsets[k + 1]) + + +def allocate_model(cols, rows, nnz): + index_type = np.int32 if max(cols, rows, nnz) <= np.iinfo(np.int32).max else np.int64 + model = Model(np.empty(cols + 1, index_type), np.empty(nnz, index_type), + np.empty(rows + 1, index_type), np.empty(nnz, index_type), + np.zeros(cols, np.float32), np.zeros(rows, np.float32), + np.empty(rows, np.float32), np.empty(cols, index_type), np.empty(cols, index_type)) + model.cp[-1] = model.rp[-1] = nnz + return model + + +def pack_models(lib, left, right, sizes): + offsets = np.zeros((len(left) + 1, 3), np.int64) + np.cumsum(sizes[:, :3], axis=0, out=offsets[1:]) + model = allocate_model(*offsets[-1]) + fill_models(lib, left, right, model, offsets) + return model, offsets diff --git a/simms/similarity/_mces_pdhg.py b/simms/similarity/_mces_pdhg.py new file mode 100644 index 0000000..b14a182 --- /dev/null +++ b/simms/similarity/_mces_pdhg.py @@ -0,0 +1,310 @@ +# SPDX-License-Identifier: MIT +"""PDHG iterates propose primal assignments and dual prices; integer checks certify them.""" +from contextlib import nullcontext + +import numpy as np +from numba import cuda, njit, prange + +from ._mces_search import graph, improve, lap, simulator_launch + + +def _x_step(k, cp, ci, objective, tau, x, extra, y): + start = cp[k] + if objective[k] != 0: + value = y[ci[start]] + y[ci[start + 1]] + y[ci[start + 2]] + y[ci[start + 3]] + else: + value = y[ci[start]] + y[ci[start + 1]] + for t in range(start + 2, cp[k + 1]): + value -= y[ci[t]] + new = min(np.float32(1), max(np.float32(0), x[k] + tau[k] * (objective[k] - value))) + extra[k] = np.float32(2) * new - x[k] + x[k] = new + + +def _y_step(k, rp, ri, rhs, sigma, extra, y): + start = rp[k] + value = np.float32(0) + if rhs[k] == 0: + value = -extra[ri[start]] + start += 1 + for t in range(start, rp[k + 1]): + value += extra[ri[t]] + y[k] = max(np.float32(0), y[k] + sigma[k] * (value - rhs[k])) + + +_x_cpu = njit(inline="always")(_x_step) +_y_cpu = njit(inline="always")(_y_step) +_x_gpu = cuda.jit(device=True, inline=True)(_x_step) +_y_gpu = cuda.jit(device=True, inline=True)(_y_step) + + +@cuda.jit +def px(cp, ci, objective, tau, x, extra, y): + for k in range(cuda.grid(1), len(x), cuda.gridsize(1)): + _x_gpu(k, cp, ci, objective, tau, x, extra, y) + + +@cuda.jit +def py(rp, ri, rhs, sigma, extra, y): + for k in range(cuda.grid(1), len(y), cuda.gridsize(1)): + _y_gpu(k, rp, ri, rhs, sigma, extra, y) + + +@njit(parallel=True, nogil=True, cache=True) +def cpu_iterations(offsets, iterations, cp, ci, rp, ri, objective, rhs, tau, sigma, x, extra, y): + for k in prange(len(offsets) - 1): + for _ in range(iterations): + for c in range(offsets[k, 0], offsets[k + 1, 0]): + _x_cpu(c, cp, ci, objective, tau, x, extra, y) + for r in range(offsets[k, 1], offsets[k + 1, 1]): + _y_cpu(r, rp, ri, rhs, sigma, extra, y) + + +def iterate(model, offsets, iterations, gpu): + cp, ci, rp, ri, obj, rhs, initial = model[:7] + tau = (0.95 / np.maximum(1, np.diff(cp))).astype(np.float32) + sigma = (0.95 / np.maximum(1, np.diff(rp))).astype(np.float32) + x = np.zeros(len(obj), np.float32) + if not gpu: + y = initial.copy() + cpu_iterations(offsets, iterations, cp, ci, rp, ri, obj, rhs, tau, sigma, x, np.empty_like(x), y) + return x, y + cp, ci, rp, ri, obj, rhs, tau, sigma, x, y = map( + cuda.to_device, (cp, ci, rp, ri, obj, rhs, tau, sigma, x, initial)) + extra = cuda.device_array_like(x) + block = 128 + nx, ny = (len(x) + block - 1) // block, (len(y) + block - 1) // block + # Grid-stride loops let the simulator run the same kernels and iteration + # counts without creating an OS thread for every row and column. + simulated = cuda.config.ENABLE_CUDASIM + if simulated: + nx = ny = block = 1 + x_launch, y_launch = px[nx, block], py[ny, block] + with simulator_launch if simulated else nullcontext(): + for _ in range(iterations): + x_launch(cp, ci, obj, tau, x, extra, y) + y_launch(rp, ri, rhs, sigma, extra, y) + return x.copy_to_host(), y.copy_to_host() + + +@njit(cache=True) +def star_profits(a, b, prices, domain): + """Assign each pair of incident stars independently under antisymmetric edge prices.""" + profits = np.zeros(domain.shape, np.int64) + weights = np.zeros((4, 4), np.int64) + # A four-neighbor star needs at most 16 subsets for its local matching. + dp = np.empty(16, np.int64) + for i in range(len(a.atoms)): + for j in range(len(b.atoms)): + if not domain[i, j]: + continue + e, f = a.atoms[i, 3], b.atoms[j, 3] + end_e, end_f = e + a.atoms[i, 4], f + b.atoms[j, 4] + while e < end_e and f < end_f: + el, other = a.bonds[e, 1], b.bonds[f, 1] + if el < other: + e += 1 + continue + if other < el: + f += 1 + continue + h, k = e + 1, f + 1 + while h < end_e and a.bonds[h, 1] == el: + h += 1 + while k < end_f and b.bonds[k, 1] == el: + k += 1 + nr, nc = h - e, k - f + value = 0 + for p in range(nr): + best = 0 + for q in range(nc): + x, y = e + p, f + q + w = max(0, 256 * min(a.bonds[x, 2], b.bonds[y, 2]) + prices[x, y]) + if not domain[a.bonds[x, 0], b.bonds[y, 0]]: + w = 0 + if nr <= 4 and nc <= 4: + weights[p, q] = w + best = max(best, w) + value += best + if nr <= 4 and nc <= 4 and nr > 1: + if nc == 1: + value = weights[0, 0] + for p in range(1, nr): + value = max(value, weights[p, 0]) + elif nr == 2 and nc == 2: + value = max(weights[0, 0] + weights[1, 1], weights[0, 1] + weights[1, 0]) + else: + states = 1 << nc + dp[:states] = 0 + for p in range(nr): + for mask in range(states - 1, 0, -1): + for q in range(nc): + if mask & (1 << q): + dp[mask] = max(dp[mask], dp[mask ^ (1 << q)] + weights[p, q]) + value = dp[states - 1] + profits[i, j] += value + e, f = h, k + return profits + + +@njit(cache=True) +def core_search(a, b, prices, domain, primal, lower, best, limit, step, budget): + """Branch on a competing atom assignment using projected LAP reduced costs.""" + stack = [domain] + total = a.weight + b.weight + for node in range(budget): + if len(stack) == 0 or best == lower: + return best, True + active = stack.pop() + overlap, seed, reduced = lap(a, b, star_profits(a, b, prices, active)) + bound = max(lower, total - (overlap // (256 * step)) * step) + cutoff = min(limit, best - step) + if bound > cutoff: + continue + best = min(best, improve(a, b, seed, bound)) + cutoff = min(limit, best - step) + if bound > cutoff: + continue + slack = overlap - (total - cutoff) * 256 + rows = np.zeros(len(a.atoms), np.int32) + cols = np.zeros(len(b.atoms), np.int32) + for i in range(len(rows)): + for j in range(len(cols)): + if reduced[i, j] > slack: + active[i, j] = False + if active[i, j]: + rows[i] += 1 + cols[j] += 1 + priority = -np.inf + src = dst = -1 + for i in range(len(rows)): + for j in range(len(cols)): + if active[i, j] and (rows[i] > 1 or cols[j] > 1): + rank = (4 * (a.atoms[i, 4] + b.atoms[j, 4]) - 24 * abs(0.5 - primal[i, j]) + - 0.2 * (rows[i] + cols[j]) + 2 * (seed[i] == j)) + if rank > priority: + src, dst, priority = i, j, rank + if src < 0: + seed[:] = -1 + for i in range(len(rows)): + for j in range(len(cols)): + if active[i, j]: + seed[i] = j + best = min(best, improve(a, b, seed, lower)) + continue + include = active.copy() + include[src, :] = False + include[:, dst] = False + include[src, dst] = True + active[src, dst] = False + stack.append(active) + stack.append(include) + return best, len(stack) == 0 + + +@njit(cache=True) +def certify(a, b, model, offsets, end, atoms, x, y, lower, best, limit, final, fix): + total = a.weight + b.weight + step = max(1, 2 * np.gcd(a.step, b.step)) + first, row = offsets[:2] + n, m = len(a.atoms), len(b.atoms) + domain = np.empty((n, m), np.bool_) + primal = np.zeros((n, m), np.int32) + c = first + for i in range(n): + for j in range(m): + domain[i, j] = a.atoms[i, 0] == b.atoms[j, 0] + if domain[i, j]: + primal[i, j] = round(65536 * x[c]) + c += 1 + prices = np.zeros((len(a.bonds), len(b.bonds)), np.int64) + for c in range(first + atoms, end[0]): + e, f = model.edge_a[c], model.edge_b[c] + t = model.cp[c] + price = round(128 * (y[model.ci[t]] + y[model.ci[t + 1]] - y[model.ci[t + 2]] - y[model.ci[t + 3]])) + prices[e, f] = price + prices[a.reverse[e], b.reverse[f]] = -price + overlap, dual_seed, _ = lap(a, b, star_profits(a, b, prices, domain)) + lower = max(lower, total - (overlap // (step * 256)) * step) + if lower > limit: + return lower, -2, best + _, seed, _ = lap(a, b, primal) + best = min(best, improve(a, b, seed, lower)) + if best != lower: + best = min(best, improve(a, b, dual_seed, lower)) + if best == lower: + return lower, best, best + + # For Ax <= b and 0 <= x <= 1, b'y + sum(max(c - A'y, 0)) + # bounds the maximum for ANY nonnegative y. Do all certificate arithmetic + # in integers, including the final rounding onto the attainable lattice. + scale = 1 << 20 + q = np.empty(end[1] - row, np.int64) + bound = np.int64(0) + for r in range(len(q)): + q[r] = max(0, round(np.float64(y[row + r]) * scale)) + if model.rhs[row + r]: + bound += q[r] + reduced = np.empty(end[0] - first, np.int64) + for c in range(first, end[0]): + value = int(model.objective[c]) * scale + for t in range(model.cp[c], model.cp[c + 1]): + price = q[model.ci[t] - row] + value += price if c < first + atoms and t >= model.cp[c] + 2 else -price + reduced[c - first] = value + bound += max(0, value) + lower = max(lower, total - (bound // (scale * step)) * step) + if lower > limit or lower == best or not final: + return lower, (-2 if lower > limit else best if lower == best else -1), best + + # Deterministic perturbed 2-opt provides feasible incumbents only. + state = np.uint32(274939) + current = seed.copy() + for attempt in range(96): + if attempt % 8 == 0: + current[:] = seed + for h in range(2 + attempt % 5): + state = np.uint32(1664525 * np.int64(state) + 1013904223) + i = (state >> 8) % n + state = np.uint32(1664525 * np.int64(state) + 1013904223) + j = (state >> 8) % n + if a.atoms[i, 0] == a.atoms[j, 0]: + current[i], current[j] = current[j], current[i] + score = improve(a, b, current, lower) + if score < best: + seed[:] = current + best = score + if lower == best: + return lower, best, best + cutoff = min(int(min(limit, total)), best - step) + slack = bound - (total - cutoff) * scale + for k in range(len(reduced)): + fix[first + k] = 1 if reduced[k] > slack else -1 if reduced[k] < -slack else 0 + c = first + for i in range(n): + for j in range(m): + if a.atoms[i, 0] == b.atoms[j, 0]: + if fix[c] < 0: + domain[i, j] = False + elif fix[c] > 0: + domain[i, :] = False + domain[:, j] = False + domain[i, j] = True + c += 1 + for c in range(first + atoms, end[0]): + if fix[c] < 0: + e, f = model.edge_a[c], model.edge_b[c] + # Deleting a column allows both local copies of that edge match to be omitted. + prices[e, f] = prices[a.reverse[e], b.reverse[f]] = -256 * 255 + best, done = core_search(a, b, prices, domain, primal / 65536., lower, best, limit, step, 256) + return lower, best if done else -1, best + + +@njit(parallel=True, nogil=True, cache=True) +def verify(lib, left, right, model, offsets, atoms, x, y, state, limit, final): + fix = np.zeros(len(x), np.int8) + for k in prange(len(left)): + state[k, 0], state[k, 1], state[k, 2] = certify( + graph(lib, left[k]), graph(lib, right[k]), model, offsets[k], offsets[k + 1], + atoms[k], x, y, state[k, 0], state[k, 2], limit, final, fix) + return fix diff --git a/simms/similarity/_mces_search.py b/simms/similarity/_mces_search.py index f3b1200..7e12ecb 100644 --- a/simms/similarity/_mces_search.py +++ b/simms/similarity/_mces_search.py @@ -1,22 +1,154 @@ # SPDX-License-Identifier: MIT -"""Integer MCES bounds and depth-first search, specialized for CUDA or CPU JIT. +"""Graph-local integer bounds. All weights and distances are in half-bond units.""" +from collections import Counter, namedtuple +from threading import Lock -Weights, lower bounds and distances inside the search use doubled bond order. -An overlapping edge saves its weight in *both* graphs. No connectivity -constraint is imposed on the matched edges. -""" import numpy as np -from numba import cuda +from numba import cuda, njit, prange -def _objective_bound(total, lower, divisor_a, divisor_b): - """Round the search target to an attainable distance, preserving the public LAP bound.""" - while divisor_b: - divisor_a, divisor_b = divisor_b, divisor_a % divisor_b - step = max(1, 2 * divisor_a) - return lower + (total - lower) % step +# Numba's simulator installs one process-wide fake CUDA module during each +# launch. Serialize those launches only. Actual device workspaces are per call. +simulator_launch = Lock() +Graph = namedtuple("Graph", "atoms bonds adjacent signatures reverse weight step") +Library = namedtuple("Library", "meta atoms bonds adjacent signatures reverse table") + +def pack(graphs): + meta = np.zeros((len(graphs) + 1, 5), np.int64) + registry, channels, masks = {}, {}, [] + signatures = [] + for i, g in enumerate(graphs): + meta[i + 1, :3] = meta[i, :3] + (len(g.vertices), len(g.neighbors), g.adjacency.size) + meta[i, 3:] = g.weight, g.weight_gcd + for element, _, _, start, count in g.vertices: + neighbors = g.neighbors[start:start + count, 1:] + key = (element, neighbors.tobytes()) + if key not in registry: + registry[key] = len(registry) + counts = Counter((el, level) for el, weight in neighbors for level in range(1, weight + 1)) + masks.append([channels.setdefault((element, el, level, rank), len(channels)) + for (el, level), degree in counts.items() for rank in range(degree)]) + signatures.append(registry[key]) + signatures = np.asarray(signatures, np.int32) + features = np.zeros((len(masks), len(channels)), np.int32) + for i, indices in enumerate(masks): + features[i, indices] = 1 + # Very diverse libraries can use the direct incident merge in place of a quadratic table. + table = features @ features.T if len(masks)**2 <= 4_000_000 else np.empty((0, 0), np.int32) + hist = np.zeros((len(graphs), len(channels)), np.int32) + for i in range(len(graphs)): + hist[i] = features[signatures[meta[i, 0]:meta[i + 1, 0]]].sum(axis=0) + # Common channels first lets the L1 screen reject most pairs using a prefix. + order = np.argsort(hist.sum(axis=0))[::-1] + count_type = np.min_scalar_type(int(hist.max(initial=0))) + hist = np.ascontiguousarray(hist[:, order], dtype=count_type) + hist = np.pad(hist, ((0, 0), (0, -hist.shape[1] % 4))) + atoms = np.concatenate([g.vertices for g in graphs]) + bonds = np.concatenate([g.neighbors for g in graphs]) + reverse = np.empty(len(bonds), np.int32) + for g, start in zip(graphs, meta[:, 1]): + reverse[start:start + len(g.neighbors)] = reverse_edges(g.vertices, g.neighbors) + return Library(meta, atoms, bonds, np.concatenate([g.adjacency.ravel() for g in graphs]), + signatures, reverse, table), hist + + +@njit(cache=True) +def reverse_edges(atoms, bonds): + reverse = np.empty(len(bonds), np.int32) + for i in range(len(atoms)): + for e in range(atoms[i, 3], atoms[i, 3] + atoms[i, 4]): + j = bonds[e, 0] + for f in range(atoms[j, 3], atoms[j, 3] + atoms[j, 4]): + if bonds[f, 0] == i: + reverse[e] = f + break + return reverse + + +@njit(cache=True, inline="always") +def graph(lib, i): + start, end = lib.meta[i], lib.meta[i + 1] + return Graph(lib.atoms[start[0]:end[0]], lib.bonds[start[1]:end[1]], + lib.adjacent[start[2]:end[2]], lib.signatures[start[0]:end[0]], + lib.reverse[start[1]:end[1]], start[3], start[4]) + + +def _passes(i, j, weights, hist, limit): + if abs(weights[i] - weights[j]) > limit: + return False + # Each undirected edge contributes at both ends, so half the L1 + # difference is the doubled-weight histogram bound. Pad the final group. + difference = 0 + for group in range(hist.shape[1] // 4): + for offset in range(4): + f = group * 4 + offset + difference += abs(np.int64(hist[i, f]) - np.int64(hist[j, f])) + if difference > 2 * limit: + return False + return True + + +_cpu_passes = njit(inline="always")(_passes) +_gpu_passes = cuda.jit(device=True, inline=True)(_passes) + + +@njit(parallel=True, nogil=True, cache=True) +def _unary_words(hist, offsets, words): + result = np.zeros((len(hist), words), np.uint32) + for i in prange(len(hist)): + for f in range(hist.shape[1]): + pos = offsets[f] + stop = pos + np.int64(hist[i, f]) + while pos < stop: + bit = pos % 32 + width = min(32 - bit, stop - pos) + mask = ((np.uint64(1) << width) - np.uint64(1)) << bit + result[i, pos // 32] |= np.uint32(mask) + pos += width + return result + + +def device_features(hist): + """Unary counts turn histogram L1 distance into Hamming distance. + + Reserve one bit per rank up to each observed channel maximum. Keep wide + counts in their original representation when the bitset would be larger. + """ + offsets = np.zeros(hist.shape[1] + 1, np.int64) + np.cumsum(hist.max(axis=0), dtype=np.int64, out=offsets[1:]) + words = (offsets[-1] + 31) // 32 + if 4 * words <= hist.strides[0]: + return _unary_words(hist, offsets, words), True + return hist, False + + +@cuda.jit +def screen_kernel(left, right, weights, features, packed, limit, keep): + k = cuda.grid(1) + if k < len(left): + i, j = left[k], right[k] + if not packed: + keep[k] = _gpu_passes(i, j, weights, features, limit) + elif abs(weights[i] - weights[j]) > limit: + keep[k] = False + else: + difference = 0 + for word in range(features.shape[1]): + difference += cuda.popc(np.uint32(features[i, word] ^ features[j, word])) + keep[k] = difference <= 2 * limit + + +@njit(parallel=True, nogil=True, cache=True) +def cpu_screen(left, right, weights, hist, limit): + keep = np.empty(len(left), np.bool_) + for k in prange(len(left)): + keep[k] = _cpu_passes(left[k], right[k], weights, hist, limit) + return keep + + +@njit(cache=True, inline="always") def _incident(a, b, na, nb, left_after, occupied): """Maximum incident overlap by neighbor element, optionally across a DFS cut.""" p, q = a[3], b[3] @@ -38,6 +170,7 @@ def _incident(a, b, na, nb, left_after, occupied): return value +@njit(cache=True, inline="always") def _move_gain(atom, neighbors, adjacency, size, mapping, old, new, exclude): """Change in conserved weight when moving one end of each incident edge.""" gain = 0 @@ -53,387 +186,254 @@ def _move_gain(atom, neighbors, adjacency, size, mapping, old, new, exclude): return gain -def _assignment(cost, size, w): - """Shortest augmenting path Hungarian LAP. w[2, j] gives row for column j.""" - u, v, owner, parent, slack, used = w[0], w[1], w[2], w[3], w[4], w[5] - for j in range(size + 1): - u[j] = v[j] = owner[j] = 0 - for i in range(1, size + 1): - owner[0] = i - for j in range(size + 1): - slack[j] = 2147483647 - used[j] = 0 - j = 0 - while True: - used[j] = 1 - row = owner[j] - delta, next_j = 2147483647, 0 - for k in range(1, size + 1): - if not used[k]: - reduced = cost[row - 1, k - 1] - u[row] - v[k] - if reduced < slack[k]: - slack[k], parent[k] = reduced, j - if slack[k] < delta: - delta, next_j = slack[k], k - for k in range(size + 1): - if used[k]: - u[owner[k]] += delta - v[k] -= delta - else: - slack[k] -= delta - j = next_j - if owner[j] == 0: - break - while j: - k = parent[j] - owner[j] = owner[k] - j = k - - -def _specialize(compile_fn, gpu=False): - incident = compile_fn(_incident) - assignment = compile_fn(_assignment) - move_gain = compile_fn(_move_gain) - - @compile_fn - def bounds(a, b, na, nb, total, limit, stronger, cost, w, seed, dual_a, dual_b): - # Zipped, degree-descending lists within equal-element groups. - p = q = overlap = 0 - while p < len(a) and q < len(b): - x, y = a[a[p, 2]], b[b[q, 2]] - if x[0] < y[0]: - p += 1 - elif x[0] > y[0]: - q += 1 - else: - overlap += min(x[1], y[1]) - p += 1 - q += 1 - weak = total - overlap - if weak > limit and not stronger: - return weak - for i in range(len(a)): - seed[i] = -1 - dual_a[i] = 0 - for j in range(len(b)): - dual_b[j] = 0 - p = q = overlap = 0 - while p < len(a) and q < len(b): - el, er = a[a[p, 2], 0], b[b[q, 2], 0] - if el < er: - p += 1 - continue - if er < el: - q += 1 - continue - end_p, end_q = p + 1, q + 1 - while end_p < len(a) and a[a[end_p, 2], 0] == el: - end_p += 1 - while end_q < len(b) and b[b[end_q, 2], 0] == el: - end_q += 1 - rows, cols = end_p - p, end_q - q - size = max(rows, cols) - for i in range(size): - for j in range(size): - value = 0 - if i < rows and j < cols: - value = incident(a[a[p + i, 2]], b[b[q + j, 2]], na, nb, -1, w[0]) - cost[i, j] = -value - assignment(cost, size, w) - for i in range(rows): - dual_a[a[p + i, 2]] = -w[0, i + 1] - for j in range(cols): - dual_b[b[q + j, 2]] = -w[1, j + 1] - i = w[2, j + 1] - 1 - if i < rows: - seed[a[p + i, 2]] = b[q + j, 2] - overlap -= cost[i, j] - p, q = end_p, end_q - return total - overlap - - @compile_fn - def feasible(a, b, na, adj_b, total, lower, seed, inverse): - size = len(b) - best = 0 +@njit(cache=True) +def feasible(a, b, na, adj_b, total, lower, seed, inverse): + size = len(b) + best = 0 + for i in range(len(a)): + j = seed[i] + if j >= 0: + for k in range(a[i, 3], a[i, 3] + a[i, 4]): + src = na[k, 0] + dst = seed[src] + if src < i and dst >= 0: + best += min(na[k, 2], int(adj_b[j * size + dst])) + if total - 2 * best == lower: + return best + # Improve the feasible LAP seed by element-preserving swaps, including + # moving into a free target. Strict improvements guarantee termination. + for j in range(size): + inverse[j] = -1 + for i in range(len(a)): + if seed[i] >= 0: + inverse[seed[i]] = i + while True: + gain, src, dst = 0, 0, 0 for i in range(len(a)): - j = seed[i] - if j >= 0: - for k in range(a[i, 3], a[i, 3] + a[i, 4]): - src = na[k, 0] - dst = seed[src] - if src < i and dst >= 0: - best += min(na[k, 2], int(adj_b[j * size + dst])) + old = seed[i] + for j in range(size): + h = inverse[j] + if a[i, 0] != b[j, 0] or (h >= 0 and h <= i and old >= 0): + continue + delta = _move_gain(a[i], na, adj_b, size, seed, old, j, h) + if h >= 0: + delta += _move_gain(a[h], na, adj_b, size, seed, j, old, i) + if delta > gain: + gain, src, dst = delta, i, j + if not gain: + break + old, h = seed[src], inverse[dst] + if h >= 0: + seed[h] = old + if old >= 0: + inverse[old] = h + seed[src], inverse[dst] = dst, src + best += gain if total - 2 * best == lower: return best - # Improve the feasible LAP seed by element-preserving swaps, including - # moving into a free target. Strict improvements guarantee termination. - for j in range(size): - inverse[j] = -1 - for i in range(len(a)): - if seed[i] >= 0: - inverse[seed[i]] = i - while True: - gain, src, dst = 0, 0, 0 - for i in range(len(a)): - old = seed[i] - for j in range(size): - h = inverse[j] - if a[i, 0] != b[j, 0] or (h >= 0 and h <= i and old >= 0): - continue - delta = move_gain(a[i], na, adj_b, size, seed, old, j, h) - if h >= 0: - delta += move_gain(a[h], na, adj_b, size, seed, j, old, i) - if delta > gain: - gain, src, dst = delta, i, j - if not gain: - break - old, h = seed[src], inverse[dst] - if h >= 0: - seed[h] = old - if old >= 0: - inverse[old] = h - seed[src], inverse[dst] = dst, src - best += gain - if total - 2 * best == lower: - return best - return best + return best - @compile_fn - def explore(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b, - w, best, first, stride, shared): - size = len(b) - total = wa + wb - mapping, used, cursor = w[0], w[1], w[2] - matched, free_a, free_b = w[3], w[4], w[5] - for j in range(size): - used[j] = 0 - dual = w[6] - dual[0] = 0 - for i in range(len(a)): - dual[0] += dual_a[i] - for j in range(size): - dual[0] += dual_b[j] - depth = frames = 0 - cursor[0], matched[0] = first, 0 - free_a[0], free_b[0] = wa, wb - while depth >= 0: - candidate = cursor[depth] - if candidate > size: - depth -= 1 - if depth >= 0 and mapping[depth] >= 0: - used[mapping[depth]] = 0 - continue - cursor[depth] += stride if depth == 0 else 1 - # Visit the assignment seed first, followed by all other targets and deletion. - preferred = seed[depth] - if preferred >= 0: - if candidate == 0: - candidate = preferred - elif candidate <= preferred: - candidate -= 1 - atom = a[depth] - if candidate == size: - # With nonnegative edge rewards a maximal same-element injection - # always attains the optimum. Only a surplus source may be deleted. - remaining = 0 - for i in range(depth, len(a)): - if a[i, 0] == atom[0]: - remaining += 1 - for j in range(size): - if b[j, 0] == atom[0] and not used[j]: - remaining -= 1 - if remaining <= 0: - continue - candidate = -1 - elif used[candidate] or atom[0] != b[candidate, 0]: - continue - frames += 1 - if gpu and stride > 1: - used_frames = cuda.atomic.add(shared, 0, 1) + 1 - best = cuda.atomic.max(shared, 1, best) - if total - 2 * best == lower: - return lower, frames - else: - used_frames = frames - if used_frames >= cap: - return -1, frames - mapping[depth] = candidate - common = matched[depth] - left_weight, right_weight = free_a[depth], free_b[depth] - for k in range(atom[3], atom[3] + atom[4]): - other, weight = na[k, 0], na[k, 2] - if other > depth: - left_weight -= weight - elif mapping[other] >= 0 and candidate >= 0: - common += min(weight, int(adj_b[candidate * size + mapping[other]])) - if candidate >= 0: - used[candidate] = 1 - for k in range(b[candidate, 3], b[candidate, 3] + b[candidate, 4]): - if not used[nb[k, 0]]: - right_weight -= nb[k, 2] - # Any completion has three disjoint edge sets: fixed prefix edges, - # edges crossing the cut, and edges wholly in the two unused suffixes. - # Relax each frontier vertex to an independent neighbor assignment. - remaining_dual = dual[depth] - dual_a[depth] - if candidate >= 0: - remaining_dual -= dual_b[candidate] - frontier = 0 - for i in range(depth + 1): - j = mapping[i] - if j >= 0: - frontier += incident(a[i], b[j], na, nb, depth, used) - # The LAP dual prices bound incident overlap for every unassigned - # vertex pair. Each preserved edge is counted at both endpoints. - upper = common + min(frontier + min(left_weight, right_weight), - (frontier + remaining_dual) // 2) - if common > best: - best = common - if gpu and stride > 1: - cuda.atomic.max(shared, 1, best) - if total - 2 * best == lower: - return lower, frames - if upper > best and total - 2 * upper <= limit and depth + 1 < len(a): - depth += 1 - matched[depth], free_a[depth], free_b[depth] = common, left_weight, right_weight - dual[depth] = remaining_dual - cursor[depth] = 0 - elif candidate >= 0: - used[candidate] = 0 - return total - 2 * best, frames - - @compile_fn - def search(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b, w): - best = feasible(a, b, na, adj_b, wa + wb, lower, seed, w[0]) - if wa + wb - 2 * best == lower: - return lower, 0 - return explore(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b, - w, best, 0, 1, w[0]) - - return bounds, search, feasible, explore - - -gpu_objective_bound = cuda.jit(device=True)(_objective_bound) -gpu_bounds, gpu_search, gpu_feasible, gpu_explore = _specialize(cuda.jit(device=True), gpu=True) +@njit(cache=True) +def lap(a, b, profits): + """Rectangular Hungarian per element. Return a feasible seed and dual reduced costs.""" + n, m = len(a.atoms), len(b.atoms) + mapping = np.full(n, -1, np.int32) + reduced = np.zeros((n, m), np.int64) + width = max(n, m) + cost = np.empty((min(n, m), width), np.int64) + u, v, slack = np.empty((3, width + 1), np.int64) + owner, parent = np.empty((2, width + 1), np.int32) + used = np.empty(width + 1, np.bool_) + p = q = overlap = 0 + while p < n and q < m: + element = a.atoms[a.atoms[p, 2], 0] + other = b.atoms[b.atoms[q, 2], 0] + if element < other: + p += 1 + continue + if other < element: + q += 1 + continue + end, stop = p + 1, q + 1 + while end < n and a.atoms[a.atoms[end, 2], 0] == element: + end += 1 + while stop < m and b.atoms[b.atoms[stop, 2], 0] == element: + stop += 1 + nr, nc = end - p, stop - q + transpose = nr > nc + if transpose: + nr, nc = nc, nr + for i in range(nr): + for j in range(nc): + x, y = (j, i) if transpose else (i, j) + cost[i, j] = -profits[a.atoms[p + x, 2], b.atoms[q + y, 2]] + owner[:nc + 1] = 0 + v[:nc + 1] = 0 + for i in range(1, nr + 1): + u[i] = cost[i - 1, 0] + for j in range(1, nc): + u[i] = min(u[i], cost[i - 1, j]) + # Subtract existing column prices before choosing an augmenting path. + owner[0] = i + slack[:nc + 1] = 1 << 60 + used[:nc + 1] = False + j = 0 + while True: + used[j] = True + row = owner[j] + delta, next_j = 1 << 60, 0 + for k in range(1, nc + 1): + if not used[k]: + r = cost[row - 1, k - 1] - u[row] - v[k] + if r < slack[k]: + slack[k], parent[k] = r, j + if slack[k] < delta or (slack[k] == delta and owner[k] == 0): + delta, next_j = slack[k], k + if delta == 0 and owner[k] == 0: + break + for k in range(nc + 1): + if used[k]: + u[owner[k]] += delta + v[k] -= delta + else: + slack[k] -= delta + j = next_j + if owner[j] == 0: + break + while j: + previous = parent[j] + owner[j] = owner[previous] + j = previous + for j in range(nc): + for i in range(nr): + x, y = (j, i) if transpose else (i, j) + src, dst = a.atoms[p + x, 2], b.atoms[q + y, 2] + reduced[src, dst] = cost[i, j] - u[i + 1] - v[j + 1] + if owner[j + 1] == i + 1: + mapping[src] = dst + overlap += profits[src, dst] + p, q = end, stop + return overlap, mapping, reduced -def pack(graphs): - """One ragged, contiguous library. Adjacency and neighbor indices are graph-local.""" - offsets = np.zeros((len(graphs) + 1, 5), np.int64) - for i, g in enumerate(graphs): - offsets[i + 1, :3] = offsets[i, :3] + (len(g.elements), g.adjacency.size, len(g.neighbors)) - offsets[i, 3:] = g.weight, g.weight_gcd - return (offsets, np.concatenate([g.vertices for g in graphs]), - np.concatenate([g.adjacency.ravel() for g in graphs]), - np.concatenate([g.neighbors for g in graphs])) +@njit(cache=True) +def improve(a, b, seed, lower): + inverse = np.empty(len(b.atoms), np.int32) + total = a.weight + b.weight + overlap = feasible(a.atoms, b.atoms, a.bonds, b.adjacent, total, lower, seed, inverse) + return total - 2 * overlap -@cuda.jit -def filter_kernel(meta, vertices, neighbors, pairs, limit, stronger, costs, work, seeds, lower): - k = cuda.grid(1) - if k < len(pairs): - i, j = pairs[k, 0], pairs[k, 1] - if i < 0 or j < 0 or i == j: - lower[k] = 0 - return - 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]] - lower[k] = gpu_bounds(a, b, na, nb, meta[i, 3] + meta[j, 3], limit, - stronger, costs[k], work[k], seeds[k, 0], seeds[k, 1], seeds[k, 2]) +@njit(cache=True) +def search(a, b, profits, relaxed, reduced, seed, best, lower, limit, cap): + """Bounded DFS. Each edge is fixed, crosses the frontier, or is wholly unassigned.""" + n, m = len(a.atoms), len(b.atoms) + total = a.weight + b.weight + mapping = np.full(n, -1, np.int32) + used = np.zeros(m, np.bool_) + cursor, matched, free_a, free_b, penalties, charged = np.zeros((6, n), np.int64) + free_a[0], free_b[0] = a.weight, b.weight + depth = frames = 0 + while depth >= 0: + col = cursor[depth] + cursor[depth] += 1 + if col > m: + depth -= 1 + if depth >= 0 and mapping[depth] >= 0: + used[mapping[depth]] = False + continue + preferred = seed[depth] + if preferred >= 0: + if col == 0: + col = preferred + elif col <= preferred: + col -= 1 + atom = a.atoms[depth] + if col == m: + surplus = 0 + for i in range(depth, n): + surplus += a.atoms[i, 0] == atom[0] + for j in range(m): + surplus -= b.atoms[j, 0] == atom[0] and not used[j] + if surplus <= 0: + continue + col = -1 + elif used[col] or atom[0] != b.atoms[col, 0]: + continue + frames += 1 + if frames > cap: + return -1, best + penalty, loss = penalties[depth], charged[depth] + if col >= 0: + penalty += reduced[depth, col] + loss += profits[depth, col] + if total - relaxed + penalty > min(limit, best - 1): + continue + mapping[depth] = col + common, left, right = matched[depth], free_a[depth], free_b[depth] + for e in range(atom[3], atom[3] + atom[4]): + i, weight = a.bonds[e, 0], a.bonds[e, 2] + if i > depth: + left -= weight + elif col >= 0 and mapping[i] >= 0: + common += min(weight, b.adjacent[col * m + mapping[i]]) + if col >= 0: + used[col] = True + for f in range(b.atoms[col, 3], b.atoms[col, 3] + b.atoms[col, 4]): + if not used[b.bonds[f, 0]]: + right -= b.bonds[f, 2] + best = min(best, total - 2 * common) + if best == lower: + return best, best + frontier = 0 + for h in range(depth + 1): + if mapping[h] >= 0: + frontier += _incident(a.atoms[h], b.atoms[mapping[h]], a.bonds, b.bonds, depth, used) + upper = min(common + frontier + min(left, right), + (relaxed - penalty - loss + 2 * common + frontier) // 2) + if depth + 1 < n and total - 2 * upper <= min(limit, best - 1): + depth += 1 + cursor[depth] = 0 + matched[depth], free_a[depth], free_b[depth] = common, left, right + penalties[depth], charged[depth] = penalty, loss + elif col >= 0: + used[col] = False + return best, best -@cuda.jit -def solve_kernel(meta, vertices, adjacency, neighbors, pairs, threshold, stronger, atom_cap, - frame_cap, lower, seeds, work, scores, exact, pending, count): - k = cuda.blockIdx.x - lane = cuda.threadIdx.x - stride = cuda.blockDim.x - i, j = pairs[k, 0], pairs[k, 1] - if i < 0 or j < 0 or i == j: - if lane == 0: - valid = i >= 0 and j >= 0 - scores[k] = 0.0 if valid else np.nan - exact[k] = valid - return - limit = threshold * 2 - lb = lower[k] - if lb > limit: - if lane == 0: - scores[k] = lb / 2 if stronger else threshold - exact[k] = False - return - a = vertices[meta[i, 0]:meta[i + 1, 0]] - b = vertices[meta[j, 0]:meta[j + 1, 0]] - distance = -1 - if max(len(a), len(b)) <= atom_cap: - lb = gpu_objective_bound(meta[i, 3] + meta[j, 3], lb, meta[i, 4], meta[j, 4]) - if lb > limit: - if lane == 0: - scores[k], exact[k] = threshold, False - return - na = neighbors[meta[i, 2]:meta[i + 1, 2]] - nb = neighbors[meta[j, 2]:meta[j + 1, 2]] - adj = adjacency[meta[j, 1]:meta[j + 1, 1]] - if max(len(a), len(b)) <= 64 and max(len(na), len(nb)) <= 256: - # Cache graph data once per pair for the cooperating search lanes. - vertex_cache = cuda.shared.array((2, 64, 5), np.int32) - neighbor_cache = cuda.shared.array((2, 256, 3), np.int32) - bond_cache = cuda.shared.array(4096, np.uint8) - prices = cuda.shared.array((3, 64), np.int32) - stack = cuda.shared.array((8, 7, 65), np.int32) - shared = cuda.shared.array(3, np.int32) - for v in range(lane, max(len(a), len(b)), stride): - for col in range(5): - if v < len(a): - vertex_cache[0, v, col] = a[v, col] - if v < len(b): - vertex_cache[1, v, col] = b[v, col] - if v < len(a): - prices[0, v] = seeds[k, 0, v] - prices[1, v] = seeds[k, 1, v] - if v < len(b): - prices[2, v] = seeds[k, 2, v] - for e in range(lane, max(len(na), len(nb)), stride): - for col in range(3): - if e < len(na): - neighbor_cache[0, e, col] = na[e, col] - if e < len(nb): - neighbor_cache[1, e, col] = nb[e, col] - for e in range(lane, len(adj), stride): - bond_cache[e] = adj[e] - cuda.syncthreads() - local_a, local_b = vertex_cache[0, :len(a)], vertex_cache[1, :len(b)] - wa, wb = meta[i, 3], meta[j, 3] - if lane == 0: - shared[0] = shared[2] = 0 - shared[1] = gpu_feasible(local_a, local_b, neighbor_cache[0], bond_cache, - wa + wb, lb, prices[0], stack[0, 0]) - cuda.syncthreads() - # Independent lanes enumerate disjoint root choices. All lanes - # share the incumbent and one frame budget for the entire pair. - lanes = min(stride, 8) - initial = cuda.atomic.add(shared, 1, 0) - if lane < lanes and wa + wb - 2 * initial > lb: - distance, _ = gpu_explore(local_a, local_b, neighbor_cache[0], neighbor_cache[1], - bond_cache, wa, wb, lb, limit, frame_cap, prices[0], - prices[1], prices[2], stack[lane], initial, lane, lanes, shared) - if distance < 0: - cuda.atomic.max(shared, 2, 1) - else: - cuda.atomic.max(shared, 1, (wa + wb - distance) // 2) - cuda.syncthreads() - distance = wa + wb - 2 * shared[1] - if shared[2] and distance > lb: - distance = -1 - elif lane == 0: - distance, _ = gpu_search(a, b, na, nb, adj, meta[i, 3], meta[j, 3], lb, - limit, frame_cap, seeds[k, 0], seeds[k, 1], seeds[k, 2], work[k]) - if lane == 0: - if distance < 0: - slot = cuda.atomic.add(count, 0, 1) - pending[slot] = k - else: - exact[k] = distance <= limit - scores[k] = distance / 2 if distance <= limit else threshold + +@njit(cache=True) +def front_one(lib, i, j, limit, frame_cap): + a, b = graph(lib, i), graph(lib, j) + n, m = len(a.atoms), len(b.atoms) + total = a.weight + b.weight + profits = np.empty((n, m), np.int32) + for h in range(n): + for k in range(m): + if len(lib.table): + profits[h, k] = lib.table[a.signatures[h], b.signatures[k]] + else: + profits[h, k] = _incident(a.atoms[h], b.atoms[k], a.bonds, b.bonds, -1, a.signatures) + overlap, seed, reduced = lap(a, b, profits) + bound = total - overlap + if bound > limit: + return bound, -2, total + step = max(1, 2 * np.gcd(a.step, b.step)) + lower = total - (overlap // step) * step + if lower > limit: + return lower, -1, total + best = improve(a, b, seed, lower) + if best == lower: + return lower, best, best + distance, best = search(a, b, profits, overlap, reduced, seed, best, lower, limit, frame_cap) + return lower, distance, best + + +@njit(parallel=True, nogil=True, cache=True) +def front(lib, left, right, limit, frame_cap): + result = np.empty((len(left), 3), np.int64) + for k in prange(len(left)): + result[k, 0], result[k, 1], result[k, 2] = front_one( + lib, left[k], right[k], limit, frame_cap) + return result diff --git a/simms/similarity/spectrum_similarity_functions.py b/simms/similarity/spectrum_similarity_functions.py index e77cb95..82e2cd6 100644 --- a/simms/similarity/spectrum_similarity_functions.py +++ b/simms/similarity/spectrum_similarity_functions.py @@ -93,7 +93,7 @@ def _collect( # Above this size local arrays can exhaust device memory at launch. Count # candidates first, then use bounded batches of global scratch for large heaps. -LOCAL_CANDIDATES = 2048 +LOCAL_CANDIDATES = 512 # The Wave 1 launch ABI passes False for fixed shift and True for modified cosine. NEUTRAL_LOSS_ONLY = 2 diff --git a/tests/similarity/test_myopic_mces.py b/tests/similarity/test_myopic_mces.py index 40c4b6a..0cc6e02 100644 --- a/tests/similarity/test_myopic_mces.py +++ b/tests/similarity/test_myopic_mces.py @@ -51,23 +51,25 @@ def test_threshold_contract(): @pytest.mark.github_ci @pytest.mark.parametrize("config", [{"max_frames": 1}, {"max_gpu_atoms": 4}]) def test_proven_fallback_before_filter(config, monkeypatch): - module = importlib.import_module("simms.similarity.CudaMyopicMCES") - original = module.solve_milp - calls = [] + # A tight DFS budget and a low CUDA atom limit can change the route, + # but every unique pair still needs a proof before expanding duplicates. + module = importlib.import_module("simms.similarity._mces_engine") + original = module.front + seen = [] - def observed(a, b, threshold): - calls.append((a.key, b.key)) - return original(a, b, threshold) + def observed(library, left, right, *args): + seen.extend(zip(left, right)) + return original(library, left, right, *args) - monkeypatch.setattr(module, "solve_milp", observed) + monkeypatch.setattr(module, "front", observed) s = CudaMyopicMCES(None, batch_size=1, **config) a, b = "C1CCCCC1", "C1CC1.C1CC1" result = s.sparse_matrix([a, b, a], idx_row=[0, 1], idx_col=[1, 2], max_distance=4, exact_only=True) assert sorted(result.to_coo("score").data) == [4.] * 4 - assert len(calls) == 1 + assert len(seen) == 1 s = CudaMyopicMCES(1, **config) assert s.pair(a, b).item() == (1, False) - assert len(calls) == 2 + assert len(seen) == 2 @pytest.mark.github_ci @@ -181,3 +183,144 @@ def test_above_default_atom_limit_and_torch_stream(): ["C1CCCCC1"], ["C1CC1.C1CC1"], array_type="torch", progress_bar=False ) np.testing.assert_equal(tensor.cpu().numpy().ravel(), [4, 1]) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("threshold", [0., 2., 5., 7.5, 10., 10.2, 15., 20., 50., None]) +@pytest.mark.parametrize("stronger", [True, False]) +def test_upstream_contract(threshold, stronger): + pytest.importorskip("myopic_mces") + from myopic_mces.myopic_mces import MCES + + pairs = [("CC", "NN"), ("C#N", "C=N"), ("c1ccoc1", "C1CCOC1"), + ("ClCCl", "BrCBr"), ("C1CCCCC1", "C1CC1.C1CC1"), + ("CC.CC", "CCC"), ("C#CC#C", "N#CC#N"), ("CO.CO", "CC.OO"), + ("C" * 12, "N")] + s = CudaMyopicMCES(threshold, stronger, backend="cpu") + left, right = zip(*pairs) + idx = np.arange(len(pairs)) + result = s.sparse_matrix(left, right, idx, idx, progress_bar=False) + for (a, b), score, exact in zip(pairs, result.to_coo("score").data, result.to_coo("exact").data): + _, expected, _, mode = MCES(a, b, threshold=-1 if threshold is None else threshold, + always_stronger_bound=stronger, solver="COIN_CMD", solver_options={"msg": False}) + if mode != 1 and not stronger: + expected = threshold + assert (score, exact) == pytest.approx((expected, mode == 1), abs=1e-7) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("backend", ["cpu", "cuda", "auto"]) +def test_sparse_contracts_and_backend(backend): + mols = ["CC", "NN", "CCC", None, "CC"] + scorer = CudaMyopicMCES(2., backend=backend) + scores = scorer.matrix(mols, array_type="numpy") + assert json.loads(json.dumps(scorer.to_dict()))["backend"] == backend + tensor = scorer.matrix(mols, score_fields=("exact", "score"), array_type="torch") + assert tensor.is_cuda == (backend != "cpu" and not cuda.config.ENABLE_CUDASIM) + np.testing.assert_equal(tensor.cpu().numpy()[1], scores["score"]) + for maximum, only_exact in [(None, False), (None, True), (1.5, False), (2., False), (3., True)]: + mask = np.ones(scores.shape, bool) + if only_exact: + mask &= scores["exact"] + if maximum is not None: + mask &= scores["score"] <= maximum + coo = scorer.sparse_matrix(mols, max_distance=maximum, exact_only=only_exact).to_coo("score") + assert sorted(zip(coo.row, coo.col)) == list(zip(*np.nonzero(mask))) + np.testing.assert_equal(coo.data, scores["score"][coo.row, coo.col]) + # An explicit pair of axes preserves coordinate direction, even if aliased. + assert scorer.sparse_matrix(mols, mols, [0], [2]).to_coo("score").nnz == 1 + assert scorer.sparse_matrix(mols, idx_row=[0], idx_col=[2]).to_coo("score").nnz == 2 + class Filtered(CudaMyopicMCES): + def keep_score(self, record): + return record["exact"] and record["score"] == 1 + projected = Filtered(backend=backend).sparse_matrix(mols, score_fields="score") + np.testing.assert_equal(projected.to_coo().data, np.ones(4)) + + +@pytest.mark.github_ci +def test_without_cuda(monkeypatch): + monkeypatch.setattr(cuda, "is_available", lambda: False) + for backend in ("cpu", "auto"): + scorer = CudaMyopicMCES(backend=backend) + assert scorer.device is None and scorer.pair("ClCl", "Cl").item() == (1., True) + with pytest.raises(RuntimeError): + CudaMyopicMCES(backend="cuda") + with pytest.raises(ValueError, match="backend"): + CudaMyopicMCES(backend="invalid") + + +@pytest.mark.github_ci +def test_dynamic_graph_size_and_histogram_counts(): + s = CudaMyopicMCES(backend="cpu") + chain = "C" * 200 # 398 directed edges + assert s.pair(chain, "CC").item() == (198., False) + assert CudaMyopicMCES(None, backend="cpu").pair(chain, "C=C").item() == (199., True) + # Repeated disjoint bonds produce histogram channel counts greater than 255. + disjoint = ".".join(["CC"] * 130) + close = disjoint + ".C" + assert s.sparse_matrix([disjoint], [close], exact_only=True).to_coo("score").data.tolist() == [0.] + assert s.pair(Chem.Mol(), "CC").item() == (1., True) + assert s.pair(Chem.Mol(), Chem.Mol()).item() == (0., True) + for bad in [-1., np.nan, np.inf]: + with pytest.raises(ValueError, match="threshold"): + CudaMyopicMCES(bad, backend="cpu") + + +# GNPS axes (805, 14) and (680, 389). The LP can fractionally preserve a +# cycle in a forest, although every integer injection must drop a ring edge. +@pytest.mark.parametrize("left,right,expected", [ + ("C=CCCCCCCCCCC(=O)NC(Cc1ccccc1)C(=O)O", "CCCCCCC=CCCCCCCCCC(=O)NCC(=O)O", (10., True)), + ("CCCCCCCCC=CCCCCCCCC(=O)NCc1ccccc1", "CCCCCCCCC=CCCCCCCCCCCCCCC(=O)O", (10., False)), +]) +def test_ring_integrality_gap(left, right, expected): + assert CudaMyopicMCES(backend="cpu").pair(left, right).item() == expected + + +@pytest.mark.github_ci +def test_explicit_symmetric_axes(): + scorer = CudaMyopicMCES(backend="cpu") + axes = ["CC", "CCO"] + result = scorer.sparse_matrix(axes, list(axes), idx_row=[0], idx_col=[1], is_symmetric=True) + assert sorted(zip(result.to_coo("score").row, result.to_coo("score").col)) == [(0, 1), (1, 0)] + with pytest.raises(ValueError, match="identical molecular axes"): + scorer.matrix(axes, ["N", "Cl"], is_symmetric=True) + + +@pytest.mark.github_ci +def test_oriented_milp_and_concurrent_calls(): + from concurrent.futures import ThreadPoolExecutor + from simms.similarity._mces_milp import solve_milp + + # Both sides contain cycles, so the forest disjunction cannot settle this. + a, b = MolecularGraphs.from_smiles(["C1CCCCC1", "C1CC1.C1CC1"]).graphs + assert solve_milp(a, b, None) == (4., True) + assert solve_milp(a, b, 3.5) == (3.5, False) + assert solve_milp(b, a, 4.) == (4., True) + scorer = CudaMyopicMCES(2.) + def run(pair): + return scorer.sparse_matrix([pair[0]], [pair[1]], exact_only=True, + progress_bar=False).to_coo("score").data.tolist() + with ThreadPoolExecutor(2) as pool: + actual = list(pool.map(run, [("CC", "NN"), ("CCCC", "N"), ("C", "C")])) + assert actual == [[2.], [], [0.]] + + +@pytest.mark.github_ci +def test_histogram_word_boundaries_and_wide_counts(): + from simms.similarity._mces_search import cpu_screen, device_features, screen_kernel + + for large_count, expect_packed in [(3, True), (1024, False)]: + hist = np.zeros((4, 64), np.uint16) + hist[0, :32] = 1 + hist[1, 31:33] = large_count + hist[2, 32:] = 1 + hist[3] = hist[0] + features, packed = device_features(hist) + assert packed == expect_packed + weights = hist.sum(axis=1, dtype=np.int64) // 2 + left, right = np.indices((4, 4), dtype=np.int32).reshape(2, -1) + device = [cuda.to_device(x) for x in (left, right, weights, features)] + keep = cuda.device_array(16, np.bool_) + for limit in (0., 2., 10.2, 32.): + screen_kernel[1, 16](*device, packed, limit, keep) + np.testing.assert_equal(keep.copy_to_host(), cpu_screen(left, right, weights, hist, limit))