Skip to content

[FEATURE] Biosaur2Algorithm: up to 24x faster, OpenMP-parallel, identical output - #10793

Merged
timosachsenberg merged 7 commits into
OpenMS:developfrom
okohlbacher:feature/biosaur2-speed
Nov 3, 2026
Merged

timosachsenberg merged 7 commits into
OpenMS:developfrom
okohlbacher:feature/biosaur2-speed

Conversation

@okohlbacher

@okohlbacher okohlbacher commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes Biosaur2Algorithm 3–9x faster on one thread and 4–27x faster on 16 threads; on a diaPASEF run with per-peak ion mobility it takes 117 s, where develop did not finish in 3 h. The hills and peptide features are bit-identical to develop at every thread count, and peak memory is lower than or equal to develop's, except +3 % on the one-CV FAIMS run. One deliberate difference: with several FAIMS CVs, the FeatureMap's unique ids are now drawn in CV order (develop drew them in completion order, which varied with the thread count).

run() on public data, develop (cfc1a09) vs this PR. AMD EPYC 7543, threads pinned to cores, one run each. The hills and features (all fields) hash identically wherever develop finished:

input (MS1 scans) develop, 1 / 16 threads this PR, 1 / 16 threads peak RSS, develop / PR
PXD063917, Orbitrap DIA (736) 7.6 / 7.6 s 1.3 / 0.54 s 0.63 / 0.51 GB
PXD021394, Orbitrap DIA (1,821) 18.8 / 18.8 s 3.0 / 1.2 s 1.30 / 1.13 GB
PXD032263, Orbitrap DIA (2,592) 73.0 / 72.8 s 8.0 / 2.7 s 2.80 / 2.28 GB
PXD017703 run 19, diaPASEF with per-peak IM (4,028 frames, 19.8 M hills) > 3 h (16 threads, stopped) 501 / 117 s ≥ 53 GB when stopped / 72 GB
PXD016662, FAIMS DIA, one CV (556) 4.8 / 4.8 s 1.5 / 1.0 s 0.65 / 0.67 GB
PXD026448, FAIMS DDA, 4 CVs (19,668) 110 / 47 s 19.8 / 11.8 s 6.0 / 6.0 GB

Changes

Less work:

  • cosineCorrelation_: a merge walk over the two scan lists replaces the two std::maps built per candidate pair. Hill scan lists are strictly increasing (one peak per scan, in scan order; a debug precondition checks it), so the walk visits the same pairs in the same order and gives the same sums.
  • hill_idx lookups (the occupied set and the hill lookups in the final selection and in convertToFeatureMap_) use dense vectors instead of std::map/std::set.
  • Hills and pattern candidates are sorted through index permutations and moved, not copied. std::sort with a user comparator decides only on comparison results (libstdc++, libc++, MS STL), so sorting the indices gives the same permutation as sorting the objects, ties included; verified on GCC by the hashes below.
  • Hill detection looks up the ion-mobility array once per scan, not once per peak.
  • processHills_ and splitHills_ take the hills by value and move them.
  • performInitialIsotopeCalibration_ is removed. Its result was discarded, so it only produced log lines.

Parallel (OpenMP), with order-preserving concatenation (orderedParallel_):

  • Hill detection: the per-scan part (filter, intensity sort, m/z and IM bins) is prepared in parallel, 256 scans at a time. Scan-to-scan linking stays sequential and only records peak→hill references; the Hill objects are then built in parallel. The dense m/z-bin table that linking reads exists only for the scan being linked to (one reused buffer) and is capped at 1 M bins (or 16 per peak); a sub-ppm htol that would need more makes linking binary-search the scan's sorted bin list instead, with the same candidates.
  • processHills_ and splitHills_ run in parallel. New hill ids for split segments are still assigned serially, in the original order.
  • Isotope candidate generation, the RT-apex and calibration filters, and convertToFeatureMap_ run in parallel; unique ids are still drawn serially in feature order.
  • Exceptions raised inside parallel regions are caught there and rethrown after the region ends (parallelFor_), including the per-CV FAIMS loop, which develop left unguarded. The two consistency-warning log lines are in a critical section.
  • FAIMS: with several CVs the groups run in parallel (as on develop); with one CV there is no outer region, so the new inner loops get the threads. The feature maps are built after the CV loop, in CV order, so their unique ids are drawn in the same order at every thread count (develop drew them in completion order).
  • Per-peak IM bins are allocated only for scans with per-peak IM.

Header: new private types ScanPrep and PeakRef. The private methods linkScanToHills_, processHills_ and splitHills_ have new signatures, the private filter methods take a std::vector<Size> instead of a std::map<Size, Size>, and performInitialIsotopeCalibration_ is gone. The public API is unchanged.

Limits: scan-to-scan linking and the greedy final selection stay serial and dominate beyond about 16 threads. With several FAIMS CVs the parallelism is over the CVs (as on develop); the new inner loops then run serially inside each CV.

Testing

  • Biosaur2Algorithm_test has a new [EXTRA] section: a synthetic 600-scan run (crosses the 256-scan block and several parallel chunks; charges 1–10 with cmax 10; gaps, empty scans, equal-intensity twins within htol, noise), plain, with per-peak ion mobility, and with two FAIMS CVs. Hills and features must be identical at 1 and 4 threads (with OpenMP), and features of charge ≥ 9 must be found.
  • Biosaur2Algorithm_test, TOPP_FeatureFinderLFQ_1 (+ _out1) and the FeatureFinderLFQ INI/CTD tests pass at OMP_NUM_THREADS 1 and 4 (Linux, GCC 13.3, -DWITH_THERMO_RAW=OFF).
  • Equivalence on the six public runs above: a standalone driver ran run() with develop and with this PR, hashing every hill (id, scan/peak indices, m/z, intensities, RT, IM and apex fields) and every feature (all fields, isotopes included). Identical at 1 and 16 threads.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance
    • Improved the processing of mass spectrometry data, including runs with multiple FAIMS compensation voltages.
  • Reliability
    • Results remain consistent across different thread counts and when processing data with ion mobility or FAIMS settings.

…output

Removes work and parallelises the independent parts of Biosaur2, keeping the
hills and features bit-identical to the sequential implementation at any
thread count:

- cosineCorrelation_: merge walk over the (strictly increasing) scan lists
  instead of building two std::maps per candidate pair; same sums, same order
- hill_idx lookups as dense vectors instead of std::map/std::set
- hills and pattern candidates sorted through index permutations and moved,
  not copied (std::sort takes the same decisions, so ties keep their order)
- hill detection: the per-scan part (filter, intensity sort, m/z and IM bins,
  dense bin offsets) is prepared in parallel; scan-to-scan linking stays
  sequential and records peak->hill references; the Hill objects are then
  built in parallel
- processHills_, splitHills_ (fresh hill ids handed out in the original order),
  the RT and calibration filters and convertToFeatureMap_ (unique ids drawn
  serially in feature order) run in parallel with ordered concatenation;
  isotope candidate generation in parallel over chunks of mono hills
- the per-peak ion-mobility format lookup is done once per scan
- the initial isotope calibration, whose result was discarded (log only), is
  no longer run
- exceptions inside parallel regions are rethrown after the region

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Walkthrough

Biosaur2Algorithm now prepares scans and links peaks through references, then assembles hills and processes isotope candidates in parallel. Dense hill-ID lookups support candidate selection and feature construction. Tests compare results across thread counts and run modes.

Changes: Biosaur2 processing

Layer / File(s) Summary
Scan preparation and hill linking
src/openms/include/OpenMS/FEATUREFINDER/Biosaur2Algorithm.h, src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
ScanPrep stores filtered peak and bin data, and PeakRef records peak-to-hill assignments. Scan preparation and hill assembly run in parallel; linking between adjacent scans remains sequential.
Hill processing and splitting
src/openms/include/OpenMS/FEATUREFINDER/Biosaur2Algorithm.h, src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
Hill processing and splitting take hill vectors by value and process hills in parallel. Split-segment IDs are assigned in output order.
Isotope candidates and pattern selection
src/openms/include/OpenMS/FEATUREFINDER/Biosaur2Algorithm.h, src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
Candidate generation and filtering use ordered parallel work and dense hill-ID lookups. Pattern selection uses dense occupancy tables. cosineCorrelation_ uses a merge walk when scan lists are strictly increasing. The initial isotope calibration method was removed.
Feature-map construction and validation
src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp, src/tests/class_tests/openms/source/Biosaur2Algorithm_test.cpp
Feature construction runs in parallel while preserving result order. Multiple FAIMS groups run in parallel, with feature-map conversion in CV order. Tests compare one-thread and four-thread results across plain, ion-mobility, and two-FAIMS-CV runs.

Sequence Diagram(s)

sequenceDiagram
  participant Spectra
  participant Biosaur2Algorithm
  participant HillProcessing
  participant IsotopeCandidateProcessing
  participant FeatureMapConversion
  Spectra->>Biosaur2Algorithm: prepare scans and link peaks
  Biosaur2Algorithm->>HillProcessing: assemble and process hills
  HillProcessing->>IsotopeCandidateProcessing: provide processed hills
  IsotopeCandidateProcessing->>FeatureMapConversion: provide selected candidates
  FeatureMapConversion-->>Biosaur2Algorithm: return ordered feature map
Loading

Possibly related issues

  • OpenMS/OpenMS#10744: The PR adds parallel stages and exception handling in Biosaur2Algorithm, but does not implement the proposed pipeline API.

Suggested reviewers: timosachsenberg

Change: Refactor

Merge Risk: Minimal · up to 8b863

No identified issue remains that should block merging after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: a performance upgrade to Biosaur2Algorithm (up to 24x faster) through OpenMP parallelism, with the stated constraint that output is identical. The raw summary and obje…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: a performance upgrade to Biosaur2Algorithm (up to 24x faster) through OpenMP parallelism, with the stated constraint that output is identical. The raw summary and objectives both center on this speedup and parallelization work, including the hill/feature restructuring, the FAIMS group parallelism, and the new synthetic test. The title is specific and matches the changeset. The objectives report a 3-9x speedup on one thread and 4-27x on 16 threads, so the 'up to 24x' figure is within the reported range, although it is not an exact match to any single run. The title also omits the FAIMS CV ordering change, which the author describes as a deliberate output difference. That makes the 'identical output' claim slightly overstated, but the title is still a fair description of the primary change.

Full details: Docstring Coverage

Explanation

Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 19 functions across 3 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

ast-grep (0.51.1)

ast-grep could not parse rule config: /ast-grep-rules/ast-grep-essentials/rules/java/security/weak-ssl-context-java.yml

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the scans at dawn
Peak references hop along
Hills assemble, ordered and bright
Isotope candidates take flight
Four threads race; results align
The rabbit nibbles, pleased with the design

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b188e373-7afa-4860-b113-729279aa05db
Commits

Reviewing files that changed from the base of the PR and between 5d814db and 8b863bd.

Files selected for processing: 3
  • src/openms/include/OpenMS/FEATUREFINDER/Biosaur2Algorithm.h
  • src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
  • src/tests/class_tests/openms/source/Biosaur2Algorithm_test.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Fix comments: Fix CodeRabbit comments on this PR

…the candidate loop

charge_ban_map has keys 1-8; look the charge up with find() so higher charges ban nothing,
as before. Exceptions in the parallel candidate generation are caught inside the OpenMP
region and rethrown after it. Removes an unused variable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI-generated initial review

This is an automated, AI-generated first review. It looks for high- and medium-priority issues only (no nits) and checks whether the PR has tests and measurements. I read the code at 5d814db against develop (cfc1a09). Please double-check anything before acting on it. A maintainer will follow up.

I could not build OpenMS here: the vcpkg submodule is not initialized and none of the dependencies are installed. Instead, I compiled the hill detection of both versions verbatim against a small mock of the OpenMS types and compared them on synthetic data. That covers linkScanToHills_ and detectHills_ from develop, and prepareScan_, linkScanToHills_ and detectHills_ from this PR. The only change to these functions since c9f22b0 removes an unused variable, so the results below hold for 5d814db.

Verdict: no high-priority issue. The abort with cmax >= 9 that CodeRabbit found is fixed correctly in 5d814db:

  • the ban lookup uses find(), so charges above 8 again ban nothing;
  • the candidate loop now catches exceptions inside the OpenMP region and rethrows them after it.

One medium issue: the memory held by the 256-scan look-ahead window in detectHills_.

Checked and found sound

  • Hill detection, old vs new (harness):
    • Result: 96 comparisons (24 synthetic runs × 1/2/4/8 threads), 0 mismatches. Every Hill field was compared, plus the hill_mass_diffs sequence. In total, 7.3 M hills from 11.2 M linked peaks.
    • What the runs contain:
      • 300–1,000 scans each;
      • empty or all-filtered scans on either side of the 256-scan block boundaries;
      • equal-intensity neighbours within htol, in the same m/z bin and in adjacent bins;
      • out-of-range and below-threshold peaks;
      • per-peak IM with paseftol 0.05 and 0;
      • htol 3, 8 and 20.
    • The harness catches real differences:
      • checking bin fm - 1 before fm: 48/48 runs differ;
      • dropping the block carry: 16/48;
      • disabling the IM gating: 12/48.
    • Why this adds something: it covers the ion-mobility linking and the block edges. The three Orbitrap DIA runs in the description test neither.
  • cosineCorrelation_ merge walk.
    • It adds the dot product and n1 in ascending scan order, as the map1 loop did, and n2 over scans2 in ascending order, as the map2 loop did. So the sums are bit-identical.
    • Scan lists that are not strictly increasing still take the old map path.
  • orderedParallel_.
    • Each index writes only into its own chunk, and the chunks are concatenated in order.
    • The first exception is rethrown after the region.
  • processHills_. Making hill an alias of processed_hill is safe: the function writes only scalar fields and reads only the vectors.
  • splitHills_.
    • The FRESH ids are numbered serially in output order. That is the sequential numbering.
    • This also holds when segment 0 is dropped as too short.
  • Sorting index permutations. std::sort takes the same path on the indices as on the elements, because its control flow depends only on comparison results. So the order is the same, ties included.
  • Dense lookup tables.
    • The dense hill_idx tables reproduce the maps' last-assignment-wins behaviour.
    • The isotope ids are bounds-checked in occupied, and mono ids are always below its size.
  • Thread safety.
    • computeAveragine_ uses a function-local static, which is initialized thread-safely.
    • MetaInfoRegistry is guarded by a mutex, so setMetaValue in the parallel feature build is safe.
    • The two warning log lines in parallel code are inside critical sections.
  • performInitialIsotopeCalibration_. It is const and its result was already discarded on develop, so dropping the call changes only the log output.

Medium: the look-ahead window keeps a dense m/z-bin table for 257 scans

What happens:

  • detectHills_ prepares block = 256 scans at a time (Biosaur2Algorithm.cpp:1701) and keeps them alive, plus carry.
  • Each ScanPrep::bin_start (:1522) is dense over the scan's m/z-bin range: (max − min m/z) / mz_step + 1 ints, with mz_step = htol · 1e-6 · max m/z.
  • So its size depends on htol and the m/z window, not on how many peaks the scan has.
  • On IM data, im_bin_per_peak (:1458) is sized by all peaks of the frame, not only the valid ones, and is also held 257 times.
  • develop kept only two scans' std::map lookups alive.

Measured with prepareScan_ verbatim (minmz 350, maxmz 1500):

peaks/scan htol bin_start per scan whole ScanPrep per scan 257-scan window
5,000 8 374 KB 472 KB 118 MB
5,000 3 997 KB 1.1 MB 275 MB
5,000 1 3.0 MB 3.1 MB 776 MB
20,000 8 374 KB 765 KB 192 MB
20,000 1 3.0 MB 3.4 MB 850 MB

Peak RSS of hill detection alone, on a synthetic run (1,500 scans, about 7k peaks per scan, htol 8, 4 threads): develop 3,191 MB, this PR 3,372 MB.

Suggested mitigation: size the window by the thread count. The blocks only exist to feed the parallel prepareScan_ step.

#include <OpenMS/SYSTEM/BuildInfo.h>
// detectHills_: enough prepared scans to keep every thread busy; each one holds a dense m/z-bin table
const SignedSize block = static_cast<SignedSize>(std::max<Size>(8, 4 * Internal::OpenMSBuildInfo::getOpenMPMaxNumThreads()));

Verified in the harness with a window of 4 × threads:

  • identical hills at 1/2/4/8 threads;
  • the same speed: 7.3 s / 4.2 s at 1 / 4 threads, vs 7.6 s / 4.0 s with 256 scans;
  • peak RSS 3,257 MB.

I also tried replacing bin_start by a binary search over by_bin. The output was identical and the memory scaled with the peaks. But the serial linking became about 40% slower (7.6 s → 10.7 s on 1 thread), so the window size is the better place to fix it.

Tests

  • Good:
    • Biosaur2Algorithm_test and the FeatureFinderLFQ TOPP and INI/CTD tests were run at OMP_NUM_THREADS 1 and 4.
    • The out-of-tree equivalence check hashed all hills and features on three real runs at 1, 16 and 32 threads. That is strong evidence for the non-IM, non-FAIMS path.
  • Gap: the in-tree tests do not reach the new parallel structure.
    • Biosaur2Algorithm_test uses at most 20 scans (10 per FAIMS CV).
    • TOPP_FeatureFinderLFQ_1 has 112 MS1 scans and 20 features (-htol 100, -cmin 2 -cmax 2).
    • So no test crosses a 256-scan block or a 1,024 / 2,048 / 4,096 chunk, and none compares thread counts. The equivalence driver is not committed.
  • Gap: there is no regression test for cmax >= 9, the bug fixed in 5d814db.
  • Suggestion: one [EXTRA] section in Biosaur2Algorithm_test.
    • Data: a synthetic run of about 600 scans with a few thousand persistent traces (with isotopes) plus noise.
    • Thread counts: run it with omp_set_num_threads(1) and (4), guarded by _OPENMP. Compare hills and peptide_features field by field.
    • High charge: run it once more with cmax 10, which must not throw.
    • Benefit: this pins down the "identical at every thread count" claim for later changes.
    • Generator: a generator like the one in my harness would do. It has persistent analytes with gaps, equal-intensity twins within htol, empty scans around the block edges, and optional per-peak IM.

Measurements

Yes, on real data: three public Orbitrap DIA runs (PXD032263, PXD021394, PXD063917), at 1 and 16 threads, median of 2 runs. The speedups are 5.5–9x on 1 thread and 12–24x on 16 threads. That fits the harness: on synthetic data, hill detection alone went from 26.7 s to 7.6 s (1 thread) and 4.0 s (4 threads).

Missing:

  • Peak memory, develop vs PR (/usr/bin/time -v, max RSS) on one of the three runs. Besides the window above, the refs and order arrays add 32 B per linked peak while the hills are built (:1688, :1740).
  • Ion-mobility (timsTOF) input. The IM gating and the per-scan IM lookup are rewritten, and none of the timed runs has IM. My harness covers the equivalence of the IM linking, but not the rest of the pipeline or the runtime. The data of TOPP_ProteomicsLFQ_DDA_PASEF_biosaur2 or any PASEF run would do.
  • FAIMS input.
    • On FAIMS data, processFAIMSGroup_ already runs inside the parallel loop over CVs in run().
    • OpenMS does not enable nested OpenMP there, so the new inner loops run on one thread per CV.
    • This is not a bug. But the speedups in the table should not be read as applying to FAIMS data; one FAIMS timing would show what the PR gains there.

CI: all build-and-test jobs on 5d814db were still queued when I looked. The runs on c9f22b0 were cancelled.


Generated by Claude Code

@timosachsenberg

Copy link
Copy Markdown
Contributor

looks good

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI-generated initial review

This is an automated, AI-generated first review. It looks for high- and medium-priority issues only (no nits) and checks whether the PR has tests and measurements. I read the code at 5d814db against its merge base cfc1a09 on develop; develop has not touched Biosaur2 since then, and the PR merges cleanly. Please double-check anything before acting on it. A maintainer will follow up.

I could not build OpenMS here (no vcpkg sources or system dependencies). Instead, I compiled the develop and PR versions of the changed code side by side in a standalone harness, with small stand-ins for MSSpectrum and friends. The harness covers detectHills_ → processHills_ → splitHills_ → detectIsotopePatterns_, i.e. all of run() except the preprocessing and convertToFeatureMap_. I used it to check equivalence on the paths the description does not cover, and to measure memory.

Verdict: no high-priority issue. The output is bit-identical in every configuration I tried, including ion mobility data. I found one medium-priority problem: the per-scan dense bin table raises peak memory, by an amount that grows as 1/htol. There is also a test gap: none of the committed tests reach the new parallel or block paths.

Harness results (develop vs. this PR, g++ 13, -O2 -fopenmp):

  • Synthetic LC-MS data:
    • 300–1,030 MS1 scans, so the run crosses the 256-scan block boundary up to 4 times;
    • 180k–342k peaks and 67k–210k raw hills, so every parallel stage runs several chunks;
    • isotope envelopes of charge 1–10;
    • with and without per-peak IM and IM gating, with empty scans and with tied intensities.
  • Hills (all fields), hill_mass_diffs and peptide features (all fields, isotopes included) are bit-identical in all 42 combinations of configuration and thread count (1, 4, 16 threads), with cmax 6 and 10 and iuse −1, 0 and 1.
  • The harness is sensitive to tie order: swapping the candidate bin order to fm - 1, fm, fm + 1 makes it report differences.
  • An IM array shorter than the peak list raises the same InvalidValue in both versions, with and without IM gating.
  • cosineCorrelation_: the merge walk and the map path agree bitwise on 200,000 random pairs of strictly increasing scan lists.
  • detectHills_ alone, 800 scans × 8,000 peaks: develop 21.3 s; this PR 8.8–9.0 s on 1 thread and 2.7–3.0 s on 4 threads. This is in line with the description.

Checked and found sound:

  • Linking.
    • Candidates are visited in the same order: bins fm, fm − 1, fm + 1, and within a bin by descending intensity, via the (bin, pos) sort.
    • The banned set becomes vector<char>.
    • An empty scan still resets linking.
    • assigned_hill < hill_idx_counter equals the old < hills.size().
  • Hill build from PeakRefs. Same peak order (scan order), first-maximum apex, sums in scan order. IM errors are deferred but still raised for the same scans.
  • processHills_ / splitHills_.
    • Only scalar fields change after the move.
    • Fresh ids are handed out serially in the old order.
  • Index-permutation sorts and dense lookups.
    • The sorts keep the same comparator.
    • All hill ids are ≤ max.
    • The iso.hill_idx < occupied.size() guard drops nothing, because isotope ids come from the hill list.
  • Thread safety of the parallel bodies.
    • They read only shared data.
    • The averagine table is a thread-safe function-local static.
    • setMetaValue goes through the lock-protected MetaInfoRegistry.
    • Unique ids are drawn serially, the debug warnings are in a critical section, and charge_ban_map is no longer written (find).
  • The removed performInitialIsotopeCalibration_ call was const and its result unused.
  • CI. Linux g++/clang++ and ARM are green. Windows (cl.exe) and macOS were still running when I looked.

Medium: the per-scan dense bin table raises peak memory, scaling as 1/htol

Where: prepareScan_ builds bin_start over the scan's whole m/z-bin range (Biosaur2Algorithm.cpp:1519-1525). detectHills_ keeps 256 prepared scans plus carry alive at once (:1701).

The bin width is htol · 1e-6 · max m/z. So each table has about (scan m/z span / max m/z) · 1e6 / htol ints, however many peaks the scan has. For MS1 at 350–1,650 m/z, that is about 0.8 GB / htol[ppm] for the window, e.g. ~100 MB at the default of 8 ppm. Linking only ever reads the previous scan's table.

Measured peak RSS (synthetic, 1,000 scans × 3,000 peaks, 4 threads, detect + process + split):

htol develop this PR lazy variant (below)
8 ppm 944 MB 1,023 MB (+79) 927 MB
3 ppm 999 MB 1,222 MB (+223) 966 MB
1 ppm 1,516 MB 2,011 MB (+495) 1,313 MB
  • Large inputs are not affected. On 2,600 scans × 8,000 peaks, the hills dominate and the PR is below develop (6.30 vs 6.70 GB). So the cost shows on small and medium runs and at low htol. This matters when several files run per node.
  • A tiny htol has no limit. htol only has a lower bound of 0. At 0.1 ppm the window would need ~8 GB, where develop needs nothing extra.

Suggested mitigation (tested in the harness):

  • Build the dense table in the sequential loop, only for the scan that is about to be prev, and free it after linking.
  • This keeps the O(1) lookup. Output stays bit-identical (all 42 combinations), and peak memory is at or below develop (last column).
  • detectHills_ time was within run-to-run noise of the PR on this shared VM.
  • A binary search on by_bin instead of the table also restores memory, but it cost ~30 % of detectHills_ time.
// prepareScan_: keep by_bin sorted, drop the dense-offset block. New helper:
void buildBinOffsets_(ScanPrep& sp) const   // no-op if built or empty
{
  if (sp.by_bin.empty() || !sp.bin_start.empty()) return;
  sp.bin_lo = sp.by_bin.front().first;
  const Size range = static_cast<Size>(sp.by_bin.back().first - sp.bin_lo) + 1;
  sp.bin_start.assign(range + 1, 0);
  for (const auto& e : sp.by_bin) ++sp.bin_start[static_cast<Size>(e.first - sp.bin_lo) + 1];
  for (Size k = 0; k < range; ++k) sp.bin_start[k + 1] += sp.bin_start[k];
}

// detectHills_, sequential loop:
ScanPrep* prev = s == b0 ? (have_carry ? &carry : nullptr) : &preps[static_cast<Size>(s - b0 - 1)];
if (prev != nullptr) buildBinOffsets_(*prev);   // only the scan being linked to needs its table
linkScanToHills_(..., prev, ...);
if (prev != nullptr) vector<int>().swap(prev->bin_start);

Reusing one buffer across scans would also avoid the per-scan allocation.

Tests

  • Good: the existing class tests and TOPP_FeatureFinderLFQ_1 (+ _out1) pass in CI. The description also reports an equivalence check on three real runs at 1, 16 and 32 threads.

  • Gap: no committed test reaches the new code paths.

    • TOPP_FeatureFinderLFQ_1 has 112 spectra and 3,084 peaks. It never crosses the 256-scan block (carry) and never produces more than one chunk in orderedParallel_ or the candidate loop (1,024–4,096 items per chunk).
    • No class test uses per-peak IM.
    • TOPP_ProteomicsLFQ_DDA_PASEF_biosaur2 only runs when Sage is found, and it checks no output.
    • Nothing runs cmax ≥ 9, so the fix in 5d814db is not covered.
    • The equivalence driver is not committed, so a later change that breaks ordering would go unnoticed.
  • Suggested test: an [EXTRA] section in Biosaur2Algorithm_test.cpp with a synthetic MSExperiment:

    • about 600 MS1 scans, ~1,500 envelopes with charges 1–10, plus noise peaks;
    • one variant with an ION_MOBILITY float array and setIMFormat(IMFormat::IM_PEAK);
    • cmax = 10.

    Run run(fm, hills, features) with omp_set_num_threads(1) and (4) (inside #ifdef _OPENMP). Require identical hills (scan and peak indices, hill_idx, mz_weighted_mean) and identical features. To also pin today's behaviour, add the feature count, or a reference featureXML generated on develop.

Measurements

Yes, on real data:

  • three public Orbitrap DIA runs at 1 and 16 threads, with the develop baseline;
  • equivalence hashes at 1, 16 and 32 threads.

Missing:

  • Peak memory. The description reports runtime only; see the finding above. Please add max RSS for develop vs. this PR on one of the three runs. /usr/bin/time -v around FeatureFinderLFQ is enough.
  • timsTOF (IM_PEAK) and FAIMS data. Both code paths changed, but neither was timed or hash-checked on real data. My harness covers IM equivalence only synthetically.
    • On FAIMS input, processFAIMSGroup_ already runs inside the per-CV omp parallel for in run(). With default OpenMP settings, the new inner regions are nested and run single-threaded. So FAIMS runs get the serial gains, but no extra parallelism beyond the number of CVs.
    • One timsTOF run and one FAIMS run, before and after, would confirm both the identity and the expected speedup.

Generated by Claude Code

// dense offsets: bin b's entries are by_bin[bin_start[b - bin_lo] .. bin_start[b - bin_lo + 1])
sp.bin_lo = sp.by_bin.front().first;
const Size range = static_cast<Size>(sp.by_bin.back().first - sp.bin_lo) + 1;
sp.bin_start.assign(range + 1, 0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: this dense offset table spans the scan's whole m/z-bin range. That is about (scan m/z span / max m/z) · 1e6 / htol ints per scan, however many peaks the scan has. detectHills_ keeps 256 + 1 prepared scans alive (:1701), so for MS1 at 350–1,650 m/z the window costs about 0.8 GB / htol[ppm].

In my harness (1,000 scans × 3,000 peaks), peak RSS over develop was:

  • +79 MB at 8 ppm;
  • +223 MB at 3 ppm;
  • +495 MB at 1 ppm.

For a tiny htol, the cost is unbounded: htol only has a lower bound of 0.

Linking only ever reads the previous scan's table. Building the table in the sequential loop just before its scan becomes prev, and freeing it after linking:

  • keeps the O(1) lookup;
  • gives bit-identical output;
  • brings memory back to develop's level.

The review body has the numbers and a sketch.


Generated by Claude Code

okohlbacher and others added 5 commits November 2, 2026 17:48
…for single-CV FAIMS, thread-equivalence test

- The dense m/z-bin table (~1e6 / htol entries per scan) was kept for all 257 prepared scans. It is now built in
  one reused buffer for the scan being linked to; peak memory is below develop's.
- FAIMS input with one CV ran the per-CV loop as a parallel region with one iteration, so the new inner parallel
  loops ran nested, i.e. serially. The CV loop is parallel only with more than one CV.
- Biosaur2Algorithm_test: a synthetic 600-scan run (charges 1-10, gaps, empty scans, equal-intensity twins, noise),
  with and without per-peak ion mobility, cmax 10; hills and features must be identical at 1 and 4 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ation and the unreachable map path of cosineCorrelation_; one helper each for the OpenMP exception capture and the hill-id table

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s stay inside), feature maps built after the CV loop in CV order, IM bins only with per-peak IM; test: a two-CV FAIMS variant

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…per peak); a sub-ppm htol binary-searches the scan's sorted bins instead

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… parallel conversion (registry order independent of threads); header documents the sparse-bin fallback; test draws its noise peaks in a fixed order

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@okohlbacher

Copy link
Copy Markdown
Contributor Author

Thanks for both reviews. Both findings and the test and measurement gaps are addressed in 07c9706..8b863bd; the description is updated.

Memory of the dense m/z-bin table (both reviews, medium). Fixed along the lines of the second review's lazy variant: the dense table now exists only for the scan being linked to, in one reused buffer, and is freed after linking. It is also capped at 1 M bins (or 16 per peak); a sub-ppm htol that would need more falls back to a binary search over the scan's sorted bins, which gives the same candidates. So a tiny htol no longer has an unbounded cost. Per-peak IM bins are allocated only for scans that have per-peak IM.

Peak memory, develop vs PR. Measured on all six public runs (table in the description). The PR is at or below develop everywhere except +3 % on the one-CV FAIMS run (0.65 vs 0.67 GB).

timsTOF and FAIMS.

  • diaPASEF with per-peak IM (PXD017703): develop did not finish in 3 h at 16 threads; the PR takes 501 s / 117 s at 1 / 16 threads.
  • FAIMS, one CV (PXD016662) and four CVs (PXD026448): hashes identical to develop at 1 and 16 threads; timings in the description.
  • FAIMS groups now go through parallelFor_, so an exception inside the per-CV loop is caught and rethrown (develop left it unguarded). With one CV there is no outer region, so the inner loops get the threads. Feature maps are built after the CV loop in CV order, so unique ids no longer depend on the thread count; this is the one deliberate output difference, noted in the description.

Tests. Biosaur2Algorithm_test has a new [EXTRA] section with a synthetic 600-scan run (crosses the 256-scan block and several parallel chunks; charges 1–10 at cmax 10; gaps, empty scans, equal-intensity twins within htol, noise), plain, with per-peak IM, and with two FAIMS CVs. Hills and features must be identical at 1 and 4 threads, and features of charge ≥ 9 must be found, which covers the cmax >= 9 fix. All Biosaur2 and FeatureFinderLFQ tests pass at OMP_NUM_THREADS 1 and 4.

Also in these commits: the unused initial isotope calibration and the unreachable map path of cosineCorrelation_ are removed, and meta value names are registered before the parallel feature conversion, so the registry order does not depend on the thread count.

@timosachsenberg

Copy link
Copy Markdown
Contributor

No correctness bugs found. The "identical output" argument holds everywhere I could check, and the rewrite handles the places where this kind of change usually goes wrong. The suggestions below are about speed and memory still left on the table, and about tests that cover less than the description says.

What I verified

  • Linking: candidates are gathered in the same order as develop (bin fm, fm−1, fm+1; descending intensity within a bin, since by_bin is sorted by (bin, pos)), with the same >= tie rule, so the same previous peak wins. A previous scan without per-peak IM gates as bin 0, like develop's zero-filled prev_im_bins. An empty scan still breaks linking through prev_spectrum_ptr.
  • Sparse fallback: I copied by_bin / build_bin_offsets / bin_range into a standalone program and compared dense and forced-sparse lookups against develop's map<int, vector<int>>: 1.8 M lookups, including very sparse bin spans, zero mismatches.
  • Index sorts: sorting indices vs. objects gave the same order, ties included, in 2,000 trials with heavy ties (libstdc++).
  • cosineCorrelation_: the merge walk is valid because banned_prev lets each previous peak be claimed once (at most one peak per scan per hill), and split segments are contiguous slices.
  • Split ids: the NO_POS_ placeholder in splitHills_ hands out new ids in the sequential order.
  • Thread safety: no shared mutable state in the parallel lambdas (computeAveragine_ uses a thread-safe function-local static, charge_ban_map is only read via find(), MetaInfoRegistry is behind a shared_mutex).

1. Don't build the hills that processHills_ throws away (biggest opportunity)

detectHills_ now knows each hill's peak count from start before allocating anything, and processFAIMSGroup_ drops every hill shorter than minlh right afterwards (L1398). Every noise singleton still costs a 248-byte Hill plus seven one-element heap blocks (~470 B total), versus 32 B for its ref and order entries. On the diaPASEF run (72 GB peak) these throwaway hills are probably a large share.

Building only hills with at least min_length peaks, keeping hill_idx = h, gives the same output after processHills_ (same ids, same order). The calibration call only uses hill_mass_diffs, so it could skip building hills entirely. One catch: develop raised malformed-IM errors for any valid peak, so check those first, in scan order:

for (Size sc = 0; sc < exp.size(); ++sc)   // scan_has_peaks recorded during linking
  if (scan_err[sc] && scan_has_peaks[sc]) std::rethrow_exception(scan_err[sc]);
vector<Size> keep;
for (Size h = 0; h < hill_idx_counter; ++h)
  if (start[h + 1] - start[h] >= min_length) keep.push_back(h);
hills.resize(keep.size());
parallelFor_(0, static_cast<SignedSize>(keep.size()), 4096, [&](SignedSize k)
{
  const Size hs = keep[static_cast<Size>(k)];
  Hill& hill = hills[static_cast<Size>(k)];
  hill.hill_idx = hs;
  // ... fill from refs[order[start[hs] .. start[hs + 1])] as now
});

2. FAIMS runs with several CVs leave most cores idle

The 4-CV run goes from 19.8 s to only 11.8 s at 16 threads, which suggests one CV group dominates and runs on a single thread. The larger runs gain 3–4.3× from the inner loops, so processing the CVs one after another with full inner parallelism could plausibly reach ~5–7 s. Worth benchmarking, e.g. going sequential when there are few groups relative to the thread count. Separately, with nested parallelism enabled (OMP_MAX_ACTIVE_LEVELS > 1) the current code runs n_groups × threads threads; output is unaffected, speed is not.

3. Two cheap memory fixes in touched code

  • splitHills_ (L2078): Hill new_hill = hill; then clear() keeps the parent's full capacity in all seven arrays of every segment, so a hill split three ways holds three times the parent's storage. Assign each array from the segment's iterator range instead.
  • run() (L371): the FAIMS merge copies every hill and feature out of the per-group vectors; make_move_iterator avoids that (they aren't used afterwards). The 4-CV run's unchanged 6.0 GB peak may come from this copy.

Tests

  • The sparse-bin fallback has no in-tree coverage: it only triggers below ~0.8 ppm htol for m/z 350–1500, and the synthetic run uses the 8 ppm default. An htol 0.5 variant of the synthetic run would lock it in.
  • The 1-vs-4-thread comparison can't catch a change that is the same at every thread count, and the six-run hash comparison lives outside CI. A stored fingerprint of develop's output on the synthetic run (counts plus rounded sums, since std::exp and FMA contraction vary across compilers) would make "identical to develop" a regression test.
  • The FeatureMap itself isn't compared, so the deliberate unique-id ordering change in b4c38e4 is untested. Fixing the UniqueIdGenerator seed in runAt and comparing the FAIMS-mode feature maps at 1 and 4 threads would cover it.

Nits

  • The orderedParallel_ lambdas name their per-chunk output after the outer result (ready, processed, split_hills, ...), so a future ready.size() inside one would silently mean the chunk size. part would be safer.
  • Making charge_ban_map static const (L2276) turns the operator[] bug fixed in 5d814db into a compile error.
  • parallelFor_ rethrows the first exception caught rather than the lowest-index one, so on malformed input the reported error can vary between runs.
  • The reserve(candidates.size()) calls at L2526 and L2634 are now redundant, since orderedParallel_ reserves the exact total.

@timosachsenberg
timosachsenberg merged commit 36d6d89 into OpenMS:develop Nov 3, 2026
31 checks passed
@okohlbacher

Copy link
Copy Markdown
Contributor Author

Thanks for the post-merge review and the independent checks. I'll take all of it up in one follow-up PR:

  1. Skip the throwaway hills: build only hills with at least min_length peaks, keeping hill_idx. The malformed-IM errors are checked first, in scan order, as in your sketch. The calibration call skips hill building entirely. I'll report peak RSS on the diaPASEF run before and after.
  2. FAIMS with several CVs: I'll benchmark processing the CVs one after another with full inner parallelism against the current outer loop, on the 4-CV run (PXD026448). I'll switch whichever way is faster, depending on the number of groups relative to the thread count. I'll also make the nested case (OMP_MAX_ACTIVE_LEVELS > 1) use a total of threads, not n_groups × threads.
  3. Memory: in splitHills_, assign each segment's arrays from its iterator range. In the FAIMS merge in run(), use make_move_iterator. Peak RSS on the 4-CV run will show whether the merge copy explains its 6.0 GB.
  4. Tests:
    • an htol 0.5 variant of the synthetic run, for the sparse-bin fallback;
    • a stored fingerprint of develop's output on the synthetic run (counts plus rounded sums), so that "identical to develop" becomes a regression test;
    • FAIMS-mode feature maps compared at 1 and 4 threads, with a fixed UniqueIdGenerator seed.
  5. Nits:
    • part for the per-chunk outputs;
    • static const for charge_ban_map;
    • rethrow the lowest-index exception in parallelFor_;
    • drop the redundant reserve calls.

timosachsenberg added a commit that referenced this pull request Nov 6, 2026
…ding, tests) (#10835)

* Biosaur2Algorithm: follow-up to #10793 (memory, FAIMS threading, tests)

- detectHills_ builds only hills with at least min_length peaks; IM errors
  are checked first in scan order; calibration builds no hills
- FAIMS: nested per-CV regions share the thread budget
- splitHills_ and the FAIMS merge move instead of copying arrays
- tests: htol 0.5 case, fingerprint of develop output, FAIMS feature maps
  at 1/2/4 threads with a fixed UniqueIdGenerator seed
- nits: lowest-index rethrow in parallelFor_, static charge_ban_map,
  'part' naming, redundant reserve calls removed

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Biosaur2Algorithm: no process-wide thread count in the FAIMS loop; fingerprint test within 0.5 %

- The FAIMS CV loop no longer calls omp_set_num_threads() on its workers: on
  MSVC's vcomp the call sets the number for the whole process and nothing set
  it back, so the rest of the process ran on threads / n_CVs. The inner loops
  run serially as nested regions by default, so the sizing gained nothing.
- The test checks that run() leaves the caller's omp_get_max_threads() as it
  was (4 threads; 2 threads with the FAIMS CVs in parallel).
- develop's fingerprint is compared within 0.5 % instead of exactly: clang/
  libomp, macOS and MSVC differ from Linux g++ by a hill or a feature and up
  to 0.05 % in the sums (last-bit differences of std::exp/FMA flip threshold
  decisions on the synthetic data). The thread-count equality stays exact.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0149aXmY7heshmULGihPVydG

---------

Co-authored-by: Oliver <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants