Repository navigation
feat: Native PeptDeep RT and MS2 ONNX Inference Bindings - #9453
timosachsenberg merged 42 commits into
Conversation
|
@satyam102006 The following names might be missing from the
Please consider applying the following patch: --- AUTHORS 2026-06-06 15:08:23.769423559 +0000
+++ AUTHORS.new 2026-06-06 15:08:29.078669973 +0000
@@ -22,8 +22,8 @@
- Chirag Dave
- Chris Bauer
- Chris Bielow
- - Christie Mathews
- Christian Ehrlich
+ - Christie Mathews
- Clemens Groepl
- Cornelia Friedle
- Daniel Jameson
@@ -109,6 +109,7 @@
- Samuel Wein
- Sandro Andreotti
- Santhil
+ - satyam yadav
- Simon Gene Gottlieb
- Steffen Sass
- Stephan Aiche |
|
@timosachsenberg can you resolve conflicts of this branch |
|
@copilot resolve the merge conflicts in this pull request |
|
Hi @timosachsenberg , the C++ code is pushed, but CI is failing because the runners lack the ONNX Runtime binaries. Before touching build files, how should we handle this dependency? Should I add a custom FindONNXRuntime.cmake with a CI fetch step, or integrate it into the OpenMS contrib system like Percolator? |
|
You could gate it behind a cmake variable and add it to the CI scripts similar to the thermo raw file bridge or the bruker d file bridge |
|
The CI pipeline is finally green on the C++ compilation and 99% of the test suite (2604/2605 tests passed)! The ONNX CMake isolation and the OpenMS_Percolator linking fixes worked perfectly across the runners. The only failing check right now is Doxygen_Warning_test, which is throwing 105 warnings about unresolved references in unrelated TOPP tools and .doxygen files ( PeakPickerIterative, MRMFeatureQC). Since my PR doesn't touch any of those files, I assume this is a known documentation parsing issue currently on the develop branch? Let me know if you need anything else from my end to finalize the ML bindings |
|
currently a lot of onnx symbols / header files are leaked into the OpenMS library. Can you get rid of them in the public interface? e.g. pimpl might be a way to achieve this. |
|
Hi @timosachsenberg, Thanks for the feedback! I completely agree. I have refactored the inference engines using the Pimpl idiom to isolate the public API. Public Headers (PeptDeepRTInference.h / PeptDeepMS2Inference.h): Completely stripped of all ONNX includes and Ort:: namespaces, relying strictly on a forward-declared struct Impl and a std::unique_ptr. Source Files (PeptDeepRTInference.cpp / PeptDeepMS2Inference.cpp): All ONNX sessions, tokenization, tensors, and memory management are now fully sandboxed inside the private implementations. Let me know if this looks good to you! |
timosachsenberg
left a comment
There was a problem hiding this comment.
Verdict
The feature's correctness is unverified, and an unrelated regression is mixed in. The two big problems are (1) the amino-acid tokenization is almost certainly wrong — and is provably inconsistent between the two files — so predictions will be silently incorrect, and (2) the only test cannot execute under ctest, despite the PR description claiming "confirmed regression outputs … via a full forward pass." Separately, the CMake change accidentally deletes the Doxygen registration for the entire OpenMS core API, which hits every build regardless of the WITH_ONNX flag.
The feature is opt-in (WITH_ONNX=OFF by default), so the new .cpp files aren't compiled in normal CI — except the doc-path deletion, which is unconditional. Net: not mergeable as-is, but the fixes are well-contained.
Tier 1 — Must fix (all provable from the diff)
1. Amino-acid vocab is inconsistent between the two files → silently wrong predictions
src/openms/source/ML/PeptDeepMS2Inference.cpp:10 vs src/openms/source/ML/PeptDeepRTInference.cpp:29
The two hand-rolled vocabularies disagree on E and Q:
- MS2:
{'Q', 6}, {'E', 7}→ Q=6, E=7 - RT:
{'E', 6}, {'Q', 7}→ E=6, Q=7
Both classes consume models from the same AlphaPeptDeep framework, which has one canonical residue encoding. They cannot both be right, so at least one mistokenizes every peptide containing E or Q → wrong RT/MS2 output with no error. The PR description confirms the root cause: tokenization uses "a 1-based aa_vocab dictionary" — a custom packed 1–20 table — rather than reusing the model's own encoding.
How to settle which is correct (the discriminator): open either .onnx (netron, or onnx.load) and read the row count of the AA embedding weight:
- ~27 rows (room for A–Z + padding) ⇒ the model uses ord-offset encoding (
ord(c) - 'A' + 1, so C=3, E=5, Q=17 …) and both packed 1–20 tables are wrong; - ~21 rows ⇒ a packed scheme, and you still must pick the one ordering the model was exported with.
Either way: derive one shared table from the model's documented encoding (alphabase's get_batch_aa_indices uses the ord-offset scheme) and use it in both files. This is the headline correctness bug.
2. openms_doc_path(...) deleted — unconditional regression unrelated to this feature
src/openms/CMakeLists.txt (the target_sources block replaced it)
On develop, src/openms/CMakeLists.txt had:
openms_doc_path("${PROJECT_SOURCE_DIR}/include")The PR's if(WITH_ONNX) target_sources(...) block was pasted over it, deleting the only registration of src/openms/include into OPENMS_DOCUMENTATION_DIRECTORIES. That variable feeds Doxygen's INPUT (via doc/CMakeLists.txt → Doxyfile.in), so the entire OpenMS core C++ API drops out of the generated docs — for all builds, ONNX or not. Restore the call; add the target_sources block alongside it, not in place of it.
3. The test cannot run → zero coverage, contradicting the PR's validation claim
src/tests/class_tests/openms/source/PeptDeepInference_test.cpp:14, src/tests/class_tests/openms/executables.cmake:80
The test reads two .onnx paths from argv[1]/argv[2] and return 1s if argc < 3. But:
- The class-test runner registers tests via
add_test(<name> <exe>)with no arguments (src/tests/class_tests/openms/CMakeLists.txt:44) →argc == 1→ theargc < 3guard fires →return 1→ always FAILS. - Even if args were passed,
TEST::mainInitdoesexit(1)whenargc > 1(ClassTest.cpp:79-88) — the framework forbids extra args by design. - No
.onnxmodel files exist in the repo, so there's nothing to point it at anyway.
So none of the tokenization/shape logic is ever exercised. The PR text says "Confirmed regression outputs … via a full forward pass on valid .onnx models" — that was a manual/local run; nothing is captured in CI. Provide a small fixture model (or a generated dummy ONNX graph) committed as test data, locate it via the test-data dir mechanism other tests use (not argv), and add at least one numeric regression assertion (current asserts are only size()==1 / size()>0).
Sub-note (latent, currently unreachable):
TEST_EXCEPTION(std::runtime_error, PeptDeepRTInference("non_existent_path.onnx"))at line 30 would fail even if reached —Ort::SessionthrowsOrt::Exception, which derives fromstd::exception, notstd::runtime_error, soTEST_EXCEPTIONlands in itscase 3(exception != 1⇒ fail). Fix the expected type when you fix the harness.
4. find_package(ONNXRuntime REQUIRED) with no Find module / config shim
CMakeLists.txt:524
There is no FindONNXRuntime.cmake in the repo and no integration in cmake/cmake_findExternalLibs.cmake. This works only if the user has an ONNX Runtime install that exports a CMake config package named exactly ONNXRuntime with the imported target ONNXRuntime::ONNXRuntime — many distributions don't (the official prebuilt zips ship no CMake config; vcpkg's target casing differs). With WITH_ONNX=ON and a typical install, configuration hard-aborts. Ship a FindONNXRuntime.cmake (or document the exact package/target requirement and how to point CMake at it). The option is also entirely undocumented in doc/.
5. __attribute__((visibility("default"))) instead of OPENMS_DLLAPI → MSVC break + missing export
src/openms/include/OpenMS/ML/PeptDeepRTInference.h:10
class __attribute__((visibility("default"))) PeptDeepRTInferenceThis is GCC/Clang-only syntax — a hard compile error on MSVC — and the header doesn't include <OpenMS/config.h>. On Windows the class would also lack __declspec(dllexport), so its symbols wouldn't be exported. The sibling PeptDeepMS2Inference.h does it correctly (#include <OpenMS/config.h> + OPENMS_DLLAPI). Match it.
Tier 2 — Correctness to verify against a reference forward pass
Run PEPTIDEK through the real PeptDeep Python pipeline once and compare the input tensors your code builds against what the model is fed. The discriminators:
- N-/C-terminal padding frame. AlphaPeptDeep featurization frames each sequence with leading/trailing padding (aa length =
nAA + 2, mod_x shaped to match) and the MS2 net strips leading positions before emittingnAA-1fragment rows. This code builds tensors from the raw sequence length (MS2:42) / fixed 132 (RT) with no terminal frame → every position is shifted by one. Discriminator: the input AA-tensor length the reference passes for an 8-mer (10 vs 8) and the output fragment row count. - NCE scaling. The test passes
nce = 0.25f(PeptDeepInference_test.cpp:38) and the header calls it "normalized," but PeptDeep scales NCE internally and expects the raw collision energy (~20-40, default ~30). Discriminator: the literal NCE value the reference puts in the tensor. If it's ~30,0.25is off by ~100× and all intensity ratios are wrong. mod_dim = 109(MS2:57, hardcoded). Discriminator: the model's mod-feature input dim. Low priority — self-correcting: if wrong, ONNX raises a loud shape error atRun(), not silent corruption. (RT already reads this dynamically viaGetInputTypeInfo(1)— MS2 should too.)
Also genuinely-divergent, provable from the diff:
- RT doesn't uppercase; MS2 does. RT's
tokenizePeptides(PeptDeepRTInference.cpp:41) looks up the raw char and silently emits padding token0for anything not found — so a lowercase peptide becomes all-padding and returns a meaningless RT, whereas MS2 (:46) upper-cases and throws on unknown residues. Pick one policy for both. - RT silently truncates > 132 residues (
PeptDeepRTInference.cpp:40, loopi < 132). Long peptides lose their tail with no warning. At minimum log/throw; ideally size to the batch's longest sequence like the variable-length convention the model expects. - RT mod-shape has no rank/dynamic guard (
PeptDeepRTInference.cpp:62-72). It writesmod_shape[0]/mod_shape[1]and multiplies dims with no check: a rank-<2 input → out-of-bounds vector write; a surviving dynamic-1dim → negativetotal_mod_elements→ hugestd::vectoralloc (length_error/bad_alloc). - RT reads exactly
peptides.size()floats from the output (PeptDeepRTInference.cpp:97) without querying the element count (MS2 usesGetElementCount()). If the output isn't shaped[N], this reads past the buffer.
Tier 3 — Cleanup / minor
- Dead CMake append. Top-level
CMakeLists.txt:531list(APPEND OPENMS_DEP_PRIVATE_LIBRARIES ONNXRuntime::ONNXRuntime)is discarded by the freshset(...)atsrc/openms/CMakeLists.txt:77(subdirectory scope) — only the child append at:102actually links. Remove the top-level append (keep the top-levelfind_package, which is what creates the imported target). Same for the duplicatedoption(WITH_ONNX …)in both files — declare once. std::toupper(aa)on a plainchar(PeptDeepMS2Inference.cpp:46): negative values are UB; cast tounsigned char. Also<cctype>isn't included (only<map>/<stdexcept>).- RT
Ort::AllocatorWithDefaultOptions allocator_;member is unused (PeptDeepRTInference.cpp:14) — a localort_allocis created instead. Drop one. RT also rebuilds its vocabstd::unordered_mapon every call (insidetokenizePeptides); MS2's file-scopestatic constis the better pattern. ONNXEnvironment.h:3includes<onnxruntime_cxx_api.h>unconditionally in a public, installed header with no guard — fine within this gated PR, but any downstream including it needs the ONNX include path. (Note there's nocmakedefine WITH_ONNXinconfig.h, so you can't actually#if-guard it today.)- Doc comment mismatch:
PeptDeepMS2Inference.h:19promises@throws Exception::BaseException, but the ctor throwsOrt::Exception. - Unrelated drive-by includes:
<new>inGlobalExceptionHandler.cppand<thread>inExternalProcess.cppare unrelated to this feature. Harmless, but they don't belong in this PR — or call them out if they're fixing a real build breakage. - Missing trailing newline on all five new files; test sets
TOLERANCE_ABSOLUTE(1e-4)but never does a float comparison.
What's done well
The pimpl idiom cleanly hides ONNX types from the headers; the shared Ort::Env via a C++17 inline function-local static is the right pattern for one process-wide environment; tensor backing buffers are correctly kept alive until Run() returns; and RT's dynamic query of input names/shapes is the right instinct (MS2 should adopt it).
Bottom line: worth pursuing, but before merge it needs a single correct shared vocab verified against the model, a test that actually runs in CI, the openms_doc_path line restored, and the ONNX find_package/export-macro issues resolved.
🤖 Review assisted by Claude Code.
|
please address my comments before tagging me again |
|
please undo your last commits... they reintroduce the old String class |
d81203c to
4adaec3
Compare
Hi @timosachsenberg, Thank you for the rigorous review;. I have refactored the PR to resolve all identified issues Correctness & Build: Unified the AA vocabulary (canonical ord-offset), restored openms_doc_path in CMakeLists.txt, and fixed the CTest harness to execute correctly with validated numeric regression assertions. ONNX/MSVC: Resolved the ONNXRuntime CMake configuration and updated headers to use OPENMS_DLLAPI for MSVC compatibility. Neural Network Logic: Implemented terminal padding (nAA + 2) for MS2, enabled dynamic mod_dim querying, enforced strict sequence length limits (throwing invalid_argument), and added safe output buffer sizing guards. Cleanup: Sealed the header leak by moving ONNXEnvironment.h to the private source/ML/ directory and reverted unrelated drive-by changes to core files. The local test suite (ctest) is now passing 100% with the verified regression outputs. Please let me know if you spot anything else on the next pass |
…prove input processing
… time and fragmentation predictions
…tions and improved error handling
…eference data paths
| namespace ML { | ||
|
|
||
| // --- Shared PeptDeep Architecture Constants --- | ||
| constexpr size_t PEPTDEEP_MAX_SEQUENCE_LENGTH = 132; |
There was a problem hiding this comment.
@satyam102006 I'm wondering if we should still limit / set this limit now that all the models use a dynamic length?
There was a problem hiding this comment.
Great catch! Since we successfully migrated RT, MS2, and CCS over to the dynamic length grouping, this static limit is completely obsolete and just wasting memory. I'll delete it right now to keep the architecture clean
…piricalFormula::addChargeAdduct (#9719) - The CHANGELOG entry for #9453 described non-existent "ONNXRuntime"/"PeptDeep" classes and claimed a vendored ONNX Runtime + bundled model files; the actual classes are ONNXPredictorBase/PeptDeepRTInference/PeptDeepMS2Inference/ PeptDeepCCSInference, ONNX Runtime is an external dependency found via CMake, and PeptDeep models are downloaded (with checksum validation) during configuration, not bundled. Rewrote the entry to match the code. - Documented the previously undocumented PeptDeepInputBuilder static methods and added missing @throws to PeptDeepRTInference::predictRT and PeptDeepCCSInference::predictCCS, matching the sibling predictMS2() docs. - EmpiricalFormula::addChargeAdduct() (added in #9714) had no pyOpenMS binding; added it following the existing setCharge/__iadd__ pattern in bind_chemistry.cpp, plus a unit test. Claude-Session: https://claude.ai/code/session_011WvU2MJPuL6jLSCK9yPVDH Co-authored-by: Claude <[email protected]>
This PR introduces native C++ inference bindings for the PeptDeep deep learning models (PeptDeepRTInference and PeptDeepMS2Inference) using the ONNX Runtime backend framework. This provides a self-contained feature for fragment intensity and retention time prediction directly within OpenMS, eliminating external Python dependencies and setting up future integration with OpenMS_Percolator for PSM rescoring.
Implementation Details:
Thread-Safe Architecture (ONNXEnvironment.h): Implemented an inline singleton wrapper to centralize the Ort::Env lifecycle, preventing multi-threaded teardown crashes or double-free errors.
PeptDeepMS2Inference: Added character tokenization using a 1-based aa_vocab dictionary and synthesized required multi-dimensional input tensors (sequence, modifications, charge, NCE, instrument index) within contiguous memory blocks.
PeptDeepRTInference: Added native inference and batch-processing wrappers for retention time prediction.
Clean Build System (CMakeLists.txt): Leveraged the ONNXRuntime::ONNXRuntime transitive target in OPENMS_DEP_PRIVATE_LIBRARIES. Removed all hardcoded local paths to guarantee seamless upstream CI/CD and multi-platform compilation.
Testing & Validation:
Added automated unit tests in src/tests/class_tests/openms/source/PeptDeepInference_test.cpp.
Verified that sequential engine initialization executes without memory or environment faults.
Added strict exception boundaries for empty strings and unmapped amino acid characters.
Confirmed regression outputs and slice shapes via a full forward pass on valid .onnx models.
Summary by CodeRabbit