Repository navigation
feat(inference): implement native AASequence modification parsing and 109-element tensor mapping - #9765
Conversation
… 109-element tensor mapping
|
@satyam102006 The following names might be missing from the
Please consider applying the following patch: --- AUTHORS 2026-07-20 14:08:14.723024562 +0000
+++ AUTHORS.new 2026-07-20 14:08:20.267544936 +0000
@@ -114,6 +114,7 @@
- Samuel Wein
- Sandro Andreotti
- Santhil
+ - satyam yadav
- Simon Gene Gottlieb
- Steffen Sass
- Stephan Aiche |
timosachsenberg
left a comment
There was a problem hiding this comment.
Thanks for pushing this forward — modification support is the right next step. However, I don't think this can land as-is: the feature doesn't produce correct model input, and it introduces a heap-corruption path. Details below, roughly in severity order.
Blocking
1. Out-of-bounds write into mod_x (heap corruption)
The guard that rejected fixed_sequence_length < longest_encoded was removed, but the modification offset arithmetic still uses the unbounded written:
size_t tensor_offset = (batch_idx * sequence_length * PEPTDEEP_MOD_ELEMENTS) + (written * PEPTDEEP_MOD_ELEMENTS);
batch.mod_x[tensor_offset + elem] = mod_features[elem]; // nothing bounds `written`
mod_x is sized exactly batch_size * sequence_length * 109. This is reachable in production: RT/CCS/MS2 all set fixed_sequence_length from the ONNX static input shape (e.g. PeptDeepRTInference.cpp:38-40), and in that branch every peptide goes into a single group with no length filter (PeptDeepRTInference.cpp:45-53). A peptide longer than the model's static length writes past its row — into the next peptide's features, or past the end of the vector entirely on the final batch row.
The removed guard was the only thing preventing this. It needs to be restored (or replaced with an explicit clamp/skip policy).
Overlong unmodified peptides are also affected more subtly: aa_indices ends up larger than, and differently row-aligned from, the declared [batch, fixed_length] tensor.
2. The 109 channels are mapped in the wrong order — every modified prediction is silently wrong
createModVector maps by atomic-number-minus-one (H→0, C→5, N→6, O→7, P→14, S→15). AlphaPeptDeep does not use that ordering. From peptdeep/constants/model_const.yaml:
0=C 1=H 2=N 3=O 4=P 5=S 6=B 7=F ... (count: 109)
That file carries the comment "We MUST keep the order of these elements for models." And tools/scripts/export_peptdeep_models_to_onnx.py:21 already derives MOD_HIDDEN from exactly this list, so it is unambiguously the contract our exported ONNX models were built against.
Concretely: Oxidation should set channel 3 but sets channel 7 (fluorine). Phospho's H/O/P land on C/F/Y. The tensor is structurally valid, the model runs without error, and the outputs are meaningless — the worst failure mode, since nothing surfaces the problem.
The new tests pass because they assert the implementation's own assumption rather than the model's contract.
Serious
3. N- and C-terminal modifications are silently dropped
Only seq[i].isModified() is checked. AASequence stores terminal modifications separately, via getNTerminalModification() / getCTerminalModification(). So (UniMod:1)PEPTIDE (N-terminal Acetyl) yields an all-zero mod_x with no warning. AlphaPeptDeep places these at site 0 and site -1 respectively.
4. Two of the six "supported" modifications can never match
Residue::getModificationName() returns ResidueModification::getId(), which is the Unimod title. In share/OpenMS/CHEMISTRY/unimod.xml the titles are Amidated (line 230) and Deamidated (line 551) — Amidation / Deamidation are the full_name fields.
The dictionary keys use the latter, so N(Deamidated) throws IllegalArgument despite being on the whitelist. Only 4 of the 6 advertised modifications actually resolve.
5. MS2 fragment count uses raw string length
PeptDeepMS2Inference.cpp:158:
int64_t valid_fragments = current_peptide.size() - 1;
For PEPM(Oxidation)TIDE (8 residues) this yields 18 fragment rows instead of 7, and pulls padding rows into base-peak normalization. encodedLength_ was correctly updated to use AASequence::size(); this call site was not.
6. Caller length-grouping still uses raw string length
PeptDeepRTInference.cpp:57 (and the CCS/MS2 equivalents) group by peptides[i].size() + 2. M(Oxidation)PEPT (5 residues) and a plain 16-mer both have raw length 16, so they share a group and the 5-mer is padded to 18 — whereas predicted alone it gets length 7. The same peptide receives different model input depending on which peptides happen to share its chunk.
Design suggestion
Rather than a hardcoded 6-entry table, this can be derived. ResidueModification::getDiffFormula() gives exactly the composition AlphaPeptDeep parses out of MOD_DF. Walking that formula and indexing into the mod_elements order — accumulating unknown elements into the final "Other" channel, as upstream's _parse_mod_formula does — would support every modification generically and eliminate the whitelist, the naming mismatch in #4, and the hand-transcribed compositions in one move. It also matches the repo guideline of preferring existing OpenMS APIs over bespoke tables.
Note that upstream's fallback is to bucket unknown elements into the last channel, not to throw; worth considering whether the hard rejection in the current code is the behavior we want.
Test coverage
The new tests don't yet provide the coverage the description claims:
- The element assertions encode the incorrect channel mapping from #2, so they pass for the wrong reason.
- The "mixed-batch memory check" uses dynamic sequence length, so it never exercises the fixed-length path where the out-of-bounds in #1 actually lives.
- No terminal-modification tests (#3) and no parsed-length grouping tests (#6).
- The
Methyltest codifies an incompatibility with AlphaPeptDeep rather than validating parity with it.
Most importantly: the one ground-truth test we have — the ONNX parity test — contains no modified peptides. In proteomicsml_test_data_ms2_spectra.csv the mods and mod_sites columns are empty on every row, so mod_x is all zeros on both sides and the comparison holds regardless of the encoding. Extending that reference dataset with modified peptides is the highest-value test change here; with it in place, #2 could not have shipped.
Minor
- Public API documentation was deleted wholesale from
PeptDeepInput.hrather than updated to describe the new behavior. OpenMS expects documented public API. PeptDeepInput.cppandPeptDeepInference_test.cppboth lost their trailing newline;PeptDeepInput.cppalso lost its namespace-closing comments.- Several exception messages were reflowed onto single lines with no functional change, adding avoidable diff noise.
Happy to help with the getDiffFormula()-based rewrite or with regenerating the parity dataset with modified peptides if that's useful.
|
I will pivot to your design suggestion using ResidueModification::getDiffFormula() mapped exactly to the YAML element order. It’s definitely the cleanest approach and completely removes the need for a whitelist. I'm working on the revisions now, specifically: Implementing the getDiffFormula() logic. Restoring the fixed_sequence_length guard to fix the out-of-bounds memory issue. Using AASequence size instead of raw string length across all inference engines. Adding N/C-terminal modification support. Reverting the API doc deletions and formatting noise. I would absolutely love your help regenerating the ONNX parity dataset with modified peptides! Once you drop that in, I will update our ground-truth tests to use it. |
|
haha sorry that was my agent talking ;) regenerating needs to be probably done by @singjc - sorry :P |
…gth grouping, and restore sequence length guards
|
The pipeline is now using getDiffFormula() mapped exactly to the AlphaPeptDeep element indices. I've also restored the out-of-bounds memory guards, fixed the raw .size() bugs across the inference engines, and added the N/C-terminal modifications. The unit tests have been updated to reflect the new dynamic dictionary and all local tests are passing green. Whenever you have a chance to drop in the regenerated ONNX parity CSV with modified peptides, let me know and I will hook it right into the test suite |
|
Right, I will regenerate the test files with modified peptides and upload them to the PR when I get the chance |
… modified_sequence for ground truth tests
| /// @return A PeptDeepInputBatch with aa_indices, mod_x, and charges populated. | ||
| /// @throws Exception::IllegalArgument if charges.size() != peptides.size(), or via buildUnmodifiedPeptideBatch(). | ||
| static PeptDeepInputBatch buildUnmodifiedChargedBatch( | ||
| /// @brief Builds a tensor batch incorporating precursor charge states (primarily for CCS and RT). |
There was a problem hiding this comment.
This is only for CCS. The RT model doesn't take into account the charge of the peptide, since the retention time is information about the peptide prior to ionization.
| /// @param config Configuration dictating padding and terminal token policies. | ||
| /// @return A PeptDeepInputBatch populated with baseline features and scaled charges. | ||
| /// @throws Exception::IllegalArgument If the size of the peptides and charges vectors do not match. | ||
| static PeptDeepInputBatch buildChargedBatch( |
There was a problem hiding this comment.
Let's change this to buildPrecursorBatch. A precursor is the ionized peptide.
| /// @param config Configuration dictating padding and terminal token policies. | ||
| /// @return A fully populated PeptDeepInputBatch ready for MS2 ONNX inference. | ||
| /// @throws Exception::IllegalArgument If any of the input vectors differ in size. | ||
| static PeptDeepInputBatch buildInstrumentBatch( |
There was a problem hiding this comment.
Lets changes this to buildProductMetaBatch. A product ion is the fragmented precursor ion.
| /** | ||
| * @brief Predicts Retention Times for a list of peptide sequences | ||
| * @param peptides A vector of raw uppercase, unmodified peptide strings (e.g., "PEPTIDEK") | ||
| * @param peptides A vector of peptide strings (e.g., "PEPTIDEK") |
There was a problem hiding this comment.
Maybe add that these can be modified peptides using notation that OpenMS supports (i.e. UniMod annotation, mass shift annotation etc), and extend the example to include a modified peptide.
| @@ -186,7 +190,6 @@ std::vector<std::vector<float>> PeptDeepMS2Inference::predictMS2( | |||
| val /= apex; | |||
| if (val < 1e-4f) val = 0.0f; | |||
There was a problem hiding this comment.
Can you make the 10.0f and 1e-4f named constants with a short explanation? So that if someone looks at the code in a few years they won't have to guess why these values are used.
| // 1. Verify "PEP(Oxidation)TIDE" | ||
| size_t pep_mod_pos = 3; | ||
| size_t pep_oxygen_idx = (0 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (pep_mod_pos * ML::PEPTDEEP_MOD_ELEMENTS) + 3; | ||
| TEST_REAL_SIMILAR(mod_batch.mod_x[pep_oxygen_idx], 1.0f); | ||
| TEST_REAL_SIMILAR(mod_batch.mod_x[pep_oxygen_idx - 1], 0.0f); | ||
|
|
||
| // 2. Verify "M(Oxidation)Y(Phospho)PEP" | ||
| size_t phos_mod_pos = 2; | ||
| size_t phos_h_idx = (1 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (phos_mod_pos * ML::PEPTDEEP_MOD_ELEMENTS) + 1; | ||
| size_t phos_o_idx = (1 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (phos_mod_pos * ML::PEPTDEEP_MOD_ELEMENTS) + 3; | ||
| size_t phos_p_idx = (1 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (phos_mod_pos * ML::PEPTDEEP_MOD_ELEMENTS) + 4; | ||
|
|
||
| TEST_REAL_SIMILAR(mod_batch.mod_x[phos_h_idx], 1.0f); | ||
| TEST_REAL_SIMILAR(mod_batch.mod_x[phos_o_idx], 3.0f); | ||
| TEST_REAL_SIMILAR(mod_batch.mod_x[phos_p_idx], 1.0f); | ||
|
|
||
| STATUS("Testing terminal modifications..."); | ||
| std::vector<std::string> term_peptides = {"(Acetyl)PEPTIDE"}; | ||
| ML::PeptDeepInputBatch term_batch = ML::PeptDeepInputBuilder::buildPeptideBatch(term_peptides); | ||
|
|
||
| size_t acetyl_c_idx = (0 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (0 * ML::PEPTDEEP_MOD_ELEMENTS) + 0; | ||
| size_t acetyl_h_idx = (0 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (0 * ML::PEPTDEEP_MOD_ELEMENTS) + 1; | ||
| size_t acetyl_o_idx = (0 * 9 * ML::PEPTDEEP_MOD_ELEMENTS) + (0 * ML::PEPTDEEP_MOD_ELEMENTS) + 3; | ||
|
|
||
| TEST_REAL_SIMILAR(term_batch.mod_x[acetyl_c_idx], 2.0f); | ||
| TEST_REAL_SIMILAR(term_batch.mod_x[acetyl_h_idx], 2.0f); | ||
| TEST_REAL_SIMILAR(term_batch.mod_x[acetyl_o_idx], 1.0f); |
There was a problem hiding this comment.
The current tests cover Oxidation, Phospho, and Acetyl, which only exercise the first six CHNOPS channels. Could we add one modification containing an element or isotope after channel 5? That would directly verify the exact 109-channel ordering and would have caught the current element-table mismatch.
There was a problem hiding this comment.
Is generateUnmodifiedModXTensor() still used anywhere? PeptDeepInputBuilder::buildPeptideBatch() now initializes and populates mod_x for both modified and unmodified peptides, so this helper appears obsolete and could be removed?
| for (size_t i = 0; i < peptides.size(); ++i) | ||
| { | ||
| indices_by_encoded_length[peptides[i].size() + 2].push_back(i); | ||
| // FIX: Parse the sequence first so modification strings aren't counted as length |
There was a problem hiding this comment.
Could remove the FIX: in the comment? Or does it still need to be fixed? Same in other files
| @@ -33,7 +33,6 @@ namespace OpenMS | |||
| /// @param peptides A vector of raw uppercase peptide strings. | |||
There was a problem hiding this comment.
This API now supports modified OpenMS peptide strings, so “unmodified peptide sequences” and “raw uppercase peptide strings” are outdated. Could the documentation state that OpenMS AASequence modification notation is accepted?
There was a problem hiding this comment.
Check the other inference methods docs to see if they need to be updated accordingly as well.
…pes test, and safety guards
singjc
left a comment
There was a problem hiding this comment.
There still seems to be some mistmatch with the modification feature mapping still not being aligned with AlphaPeptDeep: the element table does not match the current 109-channel model order, and isotope symbols are still not normalized from OpenMS’s "(13)C"-style representation to AlphaPeptDeep’s 13C/15N/2H/18O channels. There is also still an unchecked batch_size == 0 path that can hang all three predictors.
| /// @brief AlphaPeptDeep's exact 109-element array for modification tensor mapping. | ||
| /// Elements missing from this list (e.g., isotopes like "13C") are gracefully binned into the final "Other" channel. | ||
| const std::vector<std::string> ALPHAPEPTDEEP_MOD_ELEMENTS = { | ||
| "C", "H", "N", "O", "P", "S", "Br", "Cl", "F", "Fe", "I", "K", "Na", "Zn", | ||
| "Se", "Mg", "Ca", "Cu", "Mn", "Ni", "Mo", "Ag", "Co", "Au", "V", "Pt", | ||
| "Ru", "Cd", "Cr", "W", "Pb", "Li", "Rb", "Cs", "Fr", "Be", "Sr", "Ba", | ||
| "Ra", "Sc", "Y", "Ti", "Zr", "Hf", "Rf", "Nb", "Ta", "Db", "Tc", "Re", | ||
| "Bh", "Os", "Hs", "Rh", "Ir", "Mt", "Pd", "Ds", "Rg", "Cn", "Nh", "Fl", | ||
| "Mc", "Lv", "Ts", "Og", "B", "Al", "Ga", "In", "Tl", "Si", "Ge", "Sn", | ||
| "Uut", "As", "Sb", "Bi", "Uup", "Te", "Po", "At", "Uus", "Rn", "Uuo", | ||
| "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", | ||
| "Yb", "Lu", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", | ||
| "Fm", "Md", "No", "Lr" | ||
| }; |
There was a problem hiding this comment.
Something still doesn't seem right? This still does not seem match AlphaPeptDeep’s current model_const.yaml. The model expects 109 channels ending in 2H, 13C, 15N, 18O, ?, but this branch defines a different 113-entry order, and downstream code clamps any matched index >= 109 back into Other. That means element features beyond CHNOPS will be written to the wrong channels. Is there a specific reason why you've defined it this way, not in the same order and list as APD?
AlphaPeptDeeps model_cosnt.yml
# We MUST keep the order of these elemments for models
mod_elements:
- C
- H
- N
- O
- P
- S
#first 6 are the basic elements, do not change them
- B
- F
- I
- K
- U
- V
- W
- X
- Y
- Ac
- Ag
- Al
- Am
- Ar
- As
- At
- Au
- Ba
- Be
- Bi
- Bk
- Br
- Ca
- Cd
- Ce
- Cf
- Cl
- Cm
- Co
- Cr
- Cs
- Cu
- Dy
- Er
- Es
- Eu
- Fe
- Fm
- Fr
- Ga
- Gd
- Ge
- He
- Hf
- Hg
- Ho
- In
- Ir
- Kr
- La
- Li
- Lr
- Lu
- Md
- Mg
- Mn
- Mo
- Na
- Nb
- Nd
- Ne
- Ni
- 'No'
- Np
- Os
- Pa
- Pb
- Pd
- Pm
- Po
- Pr
- Pt
- Pu
- Ra
- Rb
- Re
- Rh
- Rn
- Ru
- Sb
- Sc
- Se
- Si
- Sm
- Sn
- Sr
- Ta
- Tb
- Tc
- Te
- Th
- Ti
- Tl
- Tm
- Xe
- Yb
- Zn
- Zr
- 2H
- 13C
- 15N
- 18O
# ?=unknown
- '?'
# We MUST keep the order of these instruments for models
# We can add at most 3 instruments after SciexTOF
instruments:
- QE
- Lumos
- timsTOF
- SciexTOF
- ThermoTOF
# DO NOT change values below, unless you know how to deal with them
max_instrument_num: 8
aa_embedding_size: 27
|
|
||
| for (auto const& element_count : diff_formula) | ||
| { | ||
| std::string symbol = element_count.first->getSymbol(); |
There was a problem hiding this comment.
I believe this is still not addressed?
| TEST_REAL_SIMILAR(term_batch.mod_x[acetyl_h_idx], 2.0f); | ||
| TEST_REAL_SIMILAR(term_batch.mod_x[acetyl_o_idx], 1.0f); | ||
|
|
||
| STATUS("Testing element beyond CHNOPS and isotope fallback (Channel 108)..."); |
There was a problem hiding this comment.
This test is currently asserting the wrong behavior. AlphaPeptDeep has dedicated channels for heavy isotopes, so Label:13C(6)15N(2) should not be expected to accumulate in the final unknown channel. As written, the test would pass even if isotope handling is still broken.
|
|
||
| for (const std::vector<size_t>& group_indices : groups) | ||
| { | ||
| for (size_t chunk_start = 0; chunk_start < group_indices.size(); chunk_start += batch_size_) |
There was a problem hiding this comment.
batch_size_ == 0 is still not rejected. In that case this loop never advances because chunk_start += batch_size_ adds zero each iteration, so any non-empty request hangs. Please validate batch_size in the constructor or before the batching loop and add a regression test.
There was a problem hiding this comment.
Similar issue in the CCS and MS2 Inference predictors
There was a problem hiding this comment.
This output-shape handling is still pretty permissive. It would be safer to validate the expected MS2 output rank and dimensions explicitly before indexing into the buffer, instead of inferring actual_rows from multiple shape cases.
| PeptDeepMS2Inference ms2_engine(ms2_model); | ||
|
|
||
| float max_abs_error = 0.0f; | ||
| for (size_t i = 0; i < peptides.size(); ++i) |
There was a problem hiding this comment.
This parity test still calls predictMS2() one peptide at a time, so it never exercises the batched code path introduced above. It would be good to add at least one multi-peptide call with mixed sequence lengths and a batch size smaller than the input size.
|
@singjc Added string normalization so isotopes (e.g., (13)C -> 13C) correctly map to their dedicated channels. Added exceptions to reject batch_size == 0 across all predictors. Enforced strict 3D tensor rank validation for MS2 outputs. Updated unit tests (including a forced batching test on mixed lengths). |
singjc
left a comment
There was a problem hiding this comment.
@satyam102006 Thanks for addressing all the comments. I think the current state is pretty much good as-is.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughPeptDeep now accepts modified peptide notation through ChangesModified peptide inference
Sequence Diagram(s)sequenceDiagram
participant PeptDeepRTInference
participant AASequence
participant PeptDeepInputBuilder
participant ONNXModel
PeptDeepRTInference->>AASequence: Parse modified peptide
AASequence->>PeptDeepInputBuilder: Provide sequence and modifications
PeptDeepInputBuilder->>ONNXModel: Submit encoded batch
ONNXModel-->>PeptDeepRTInference: Return prediction tensor
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp (2)
24-29: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winRedundant
AASequence::fromStringparse withinbuildPeptideBatch.
encodedLength_(called at line 48) parses each peptide withAASequence::fromStringpurely to get a length. The same peptide is parsed again at line 67 to buildseqfor modification encoding. Each parse repeats chemical validation and modification-database lookups. Caching the parsedAASequenceobjects from the first loop and reusing them in the second loop avoids the duplicate parse.The same pattern of re-parsing peptide strings with
AASequence::fromStringrecurs in the calling inference files (see the grouping stage inPeptDeepRTInference.cpp,PeptDeepCCSInference.cpp, andPeptDeepMS2Inference.cpp, and again in the MS2 output loop). I list the cross-file instances in a consolidated comment.Also applies to: 44-49, 65-68
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp` around lines 24 - 29, Update buildPeptideBatch and its encodedLength_ flow to parse each peptide into an AASequence once, cache those parsed sequences during the first loop, and reuse them for length calculation and modification encoding instead of calling AASequence::fromString again. Apply the same reuse pattern to the identified grouping and MS2 output loops in the inference implementations, preserving existing token-length and encoding behavior.
1-1: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winRepeated
AASequence::fromStringparsing of the same peptide across grouping, batching, and output stages. Each site independently re-parses the same peptide string, repeating chemical validation and modification-database lookups; the shared root cause is that no parsedAASequenceis cached or passed between stages.
src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp#L44-49: cache theAASequenceparsed forencodedLength_in the validation loop and reuse it in the per-peptide encoding loop below instead of re-parsing at line 67.src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp#L65-68: reuse the cachedAASequencefrom the validation loop here instead of callingAASequence::fromStringagain.src/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cpp#L63-64: this length-only parse duplicates the parse performed inside the subsequentbuildPeptideBatchcall; consider a builder API that accepts pre-parsed sequences to avoid the double parse.src/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cpp#L68-68: same duplication feeding intobuildPrecursorBatch.src/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cpp#L67-67,173-173: the grouping-stage parse, the internalbuildProductMetaBatchparse, and the output-processing parse at line 173 mean this peptide is parsed three times per call.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp` at line 1, Repeated AASequence::fromString calls re-parse identical peptides across validation, batching, grouping, and output stages. Cache each parsed AASequence during validation and reuse it in the encoding loop in PeptDeepInput; update buildPeptideBatch, buildPrecursorBatch, and buildProductMetaBatch call paths to accept and reuse pre-parsed sequences. Ensure PeptDeepRTInference, PeptDeepCCSInference, and PeptDeepMS2Inference pass cached sequences through all stages, including output processing, without changing validation behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp`:
- Around line 142-145: Guard the C-terminal modification handling in the
hasCTerminalModification branch before calling apply_modification: only pass
written - 1 when the sequence is non-empty, and skip or explicitly handle the
empty modification-only case without writing a tensor offset.
In `@src/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cpp`:
- Around line 159-179: Validate the MS2 output tensor’s batch dimension in the
existing shape-check block before deriving indexing values: require out_shape[0]
to match the expected batch size for the chunk, such as
batch_size_cast/current_chunk_size. Reject mismatches with the established
OpenMS exception path, then retain the existing elements_per_batch and buffer
indexing logic for valid rank-3 outputs.
---
Nitpick comments:
In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp`:
- Around line 24-29: Update buildPeptideBatch and its encodedLength_ flow to
parse each peptide into an AASequence once, cache those parsed sequences during
the first loop, and reuse them for length calculation and modification encoding
instead of calling AASequence::fromString again. Apply the same reuse pattern to
the identified grouping and MS2 output loops in the inference implementations,
preserving existing token-length and encoding behavior.
- Line 1: Repeated AASequence::fromString calls re-parse identical peptides
across validation, batching, grouping, and output stages. Cache each parsed
AASequence during validation and reuse it in the encoding loop in PeptDeepInput;
update buildPeptideBatch, buildPrecursorBatch, and buildProductMetaBatch call
paths to accept and reuse pre-parsed sequences. Ensure PeptDeepRTInference,
PeptDeepCCSInference, and PeptDeepMS2Inference pass cached sequences through all
stages, including output processing, without changing validation behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 34c3e719-875b-46c3-9cbe-bb9ba7a4d71f
⛔ Files ignored due to path filters (5)
src/tests/class_tests/openms/data/peptdeep_irt_peptides_predicted.csvis excluded by!**/*.csvsrc/tests/class_tests/openms/data/proteomicsml_test_data_ccs_predicted.csvis excluded by!**/*.csvsrc/tests/class_tests/openms/data/proteomicsml_test_data_ms2_predicted_intensities.csvis excluded by!**/*.csvsrc/tests/class_tests/openms/data/proteomicsml_test_data_ms2_spectra.csvis excluded by!**/*.csvsrc/tests/class_tests/openms/data/proteomicsml_test_data_retention_time_predicted.csvis excluded by!**/*.csv
📒 Files selected for processing (10)
src/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepCCSInference.hsrc/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepInput.hsrc/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepMS2Inference.hsrc/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepRTInference.hsrc/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepUtils.hsrc/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepInput.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cppsrc/tests/class_tests/openms/source/PeptDeepInference_test.cpp
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp (1)
81-86: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winApply the required C++ formatting to modified blocks.
src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp#L81-L86: Put theifbraces on separate aligned lines.src/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cpp#L26-L28: Use 2-space indentation and put theifbraces on separate aligned lines.As per coding guidelines, C++ uses 2-space indentation and braces on their own aligned lines.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp` around lines 81 - 86, Reformat the modified if blocks in src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp lines 81-86 and src/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cpp lines 26-28 to use 2-space indentation with opening and closing braces on separate, aligned lines; preserve all logic unchanged.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepInput.h`:
- Around line 55-81: Complete the public API documentation for the visible
batch-building methods, including the remaining method declaration such as
buildProductMetaBatch: mark every input parameter with `@param`[in], and document
that buildPrecursorBatch and buildProductMetaBatch may throw
Exception::IllegalArgument when the peptide batch is empty or an encoded peptide
exceeds config.fixed_sequence_length. Ensure all documented exceptions and
parameter directions follow the project’s tagging conventions.
In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp`:
- Around line 142-146: In the sequence-encoding flow around the
terminal-modification handling, reject or skip zero-residue AASequence inputs
before either N-terminal or C-terminal modification is applied. Ensure the check
occurs before the branch that can write batch.mod_x[0], while preserving
existing encoding behavior for sequences with at least one residue.
---
Outside diff comments:
In `@src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp`:
- Around line 81-86: Reformat the modified if blocks in
src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp lines 81-86 and
src/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cpp lines 26-28 to use
2-space indentation with opening and closing braces on separate, aligned lines;
preserve all logic unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 253c80cd-f8ed-48a0-8974-2c3f972b66d3
📒 Files selected for processing (6)
src/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepInput.hsrc/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepInput.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cppsrc/tests/class_tests/openms/source/PeptDeepInference_test.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
- src/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cpp
- src/tests/class_tests/openms/source/PeptDeepInference_test.cpp
- src/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cpp
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepInput.h`:
- Line 58: Update the `@throws` documentation for the three builder methods around
buildPrecursorBatch, buildProductMetaBatch, and buildPeptideBatch to explicitly
state that Exception::IllegalArgument is thrown when any AASequence is empty, in
addition to the existing conditions. Ensure all three clauses consistently
document this validation behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ca31b024-4d47-4bc6-bf04-3044b05be3d5
📒 Files selected for processing (5)
src/openms/include/OpenMS/ML/PEPTDEEP/PeptDeepInput.hsrc/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepInput.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cppsrc/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cpp
🚧 Files skipped from review as they are similar to previous changes (4)
- src/openms/source/ML/PEPTDEEP/PeptDeepMS2Inference.cpp
- src/openms/source/ML/PEPTDEEP/PeptDeepRTInference.cpp
- src/openms/source/ML/PEPTDEEP/PeptDeepCCSInference.cpp
- src/openms/source/ML/PEPTDEEP/PeptDeepInput.cpp
| } | ||
| } | ||
|
|
||
| auto it = std::find(ALPHAPEPTDEEP_MOD_ELEMENTS.begin(), ALPHAPEPTDEEP_MOD_ELEMENTS.end(), symbol); |
There was a problem hiding this comment.
Right now every modification's element symbols are resolved via std::find over a 109-entry std::vectorstd::string — a linear string-comparison scan done at runtime for every element of every modification, for every peptide, in every batch. Since ALPHAPEPTDEEP_MOD_ELEMENTS is fixed and known at compile time, this is a good candidate for a compile-time/static lookup instead — e.g. a static std::unordered_map<std::string, int> built once at static-init, or a constexpr perfect-hash mapping. That turns an O(109) string comparison per element into an O(1) lookup and removes real overhead from what's effectively the innermost loop of the tensor-building code. Example: build a static unordered_map from ALPHAPEPTDEEP_MOD_ELEMENTS once, then just call .find(symbol) per lookup instead of std::find over the vector.
Why this matters: this code runs in the hottest part of the inference pipeline — once per element of a modification's diff formula, for every modified residue, every peptide, every batch, potentially across large-scale proteomics datasets. Replacing the linear scan with a hash map (or a compile-time perfect hash) gives O(1) average lookup instead of O(109), which matters as peptide/modification counts scale — especially since this PR is specifically about performance-sensitive tensor construction for ML inference.
jpfeuffer
left a comment
There was a problem hiding this comment.
The modification path looks very inefficient. Was this benchmarked?
|
@jpfeuffer I hadn't run formal benchmarks on it yet, but you are completely right about the bottleneck. I just pushed a commit that replaces the linear string scan with a static O(1) unordered_map lookup to resolve it. |
|
Hi @singjc and @jpfeuffer,Following up on the optimization, I ran a benchmark on the PeptDeepInputBuilder to compare the Original (std::find linear scan): 139 ms Updated (unordered_map O(1) lookup): 147 ms
Interestingly, the performance is practically identical. While the hash map is theoretically |
The current PeptDeep models implemented are fixed with the modifications vocab size, so it's unlikely this would change/grow. If it does, it would likely be a new arch/model, which would need it's own impl. The linear search probably works well here because the first 5 initial elements are the most common elements, so typical modifications only a need a few comparisons and likely terminate earlier than searching all 109 elements. So I'm wondering if it makes sense to keep the unordered map or the similar linear search? |
| /// @brief AlphaPeptDeep's exact 109-element array for modification tensor mapping. | ||
| /// Elements missing from this list are binned into the final "Other" channel ("?"). | ||
| /// Heavy isotopes (2H, 13C, 15N, 18O) map strictly to their dedicated channels. | ||
| const std::vector<std::string> ALPHAPEPTDEEP_MOD_ELEMENTS = { |
There was a problem hiding this comment.
I'm wondering if we should make this something like inline constexpr std::array<std::string_view, 109>?
| if (tensor_elem_index >= static_cast<int>(PEPTDEEP_MOD_ELEMENTS)) | ||
| { | ||
| tensor_elem_index = static_cast<int>(PEPTDEEP_MOD_ELEMENTS) - 1; | ||
| } |
There was a problem hiding this comment.
This could probably be removed if the element table is compile-time-sized
|
Good job benchmarking, thanks. Sorry for the noise. But worth a try in this very central loop. |
|
@singjc |
|
HI @satyam102006, perfect, thanks! Were there any changes with the benchmark times, or still about the same (it's okay if it is, but just for verification). I think we can merge once all the builds and test are green. |
|
@singjc Basically identical! The new string_view version clocked in at 186 ms for 100,000 peptides (compared to 139 ms on the old vector). The early termination keeps the speed exactly where we want it. |





Summary
This PR finalizes the PeptDeep Phase 2 modification featurization. To avoid the overhead of shipping and parsing an external ReDeeM TSV file at runtime, this implementation uses a highly optimized native in-memory dictionary.
Changes
PeptDeepInput.cpp.AASequenceto extract modifications and map them directly to the correct tensor indices.PeptDeepUtils.hto fully process modified strings.CCS,MS2,RT) to interface seamlessly with the new modified peptide builder logic.PeptDeepInference_test.cpp, including:FakeMod), while the custom dictionary cleanly traps chemically valid but currently unsupported mods (e.g.,Methyl).All tests are passing locally.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation