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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion redeem-foundation-featurizer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ license = "BSD-3-Clause"
repository = "https://github.com/singjc/redeem"

[dependencies]
candle-core = { version = "0.8.4", default-features = false }
candle-core = { version = "0.8.4", default-features = false, optional = true }
serde = { version = "1.0", features = ["derive"] }

[features]
default = ["candle"]
# Candle tensor output (`PeptideGraphFeaturizer::featurize`). Disable for a dependency-light
# featurizer that only produces plain `Vec` payloads (`featurize_data`), e.g. for ONNX hosts.
candle = ["dep:candle-core"]

[lib]
path = "src/lib.rs"
161 changes: 141 additions & 20 deletions redeem-foundation-featurizer/src/featurize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,33 @@ use super::chemistry::{
ATOM_FEATURE_DIM,
};
use crate::FoundationFeaturizerConfig;
use candle_core::{DType, Device, Result, Tensor};
#[cfg(feature = "candle")]
use candle_core::{DType, Device, Tensor};

/// Error raised by the featurizer (invalid configuration or unencodable peptide).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeaturizerError(pub String);

impl std::fmt::Display for FeaturizerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}

impl std::error::Error for FeaturizerError {}

#[cfg(feature = "candle")]
impl From<FeaturizerError> for candle_core::Error {
fn from(e: FeaturizerError) -> Self {
candle_core::Error::Msg(e.0)
}
}

pub type Result<T> = std::result::Result<T, FeaturizerError>;

macro_rules! bail {
($($t:tt)*) => { return Err(FeaturizerError(format!($($t)*))) };
}
use serde::{Deserialize, Serialize};

/// Chemical scope of a peptide modification.
Expand Down Expand Up @@ -149,7 +175,45 @@ pub struct FoundationTensorBatch {
pub instrument_present: Vec<f32>,
}

/// Optional precursor/acquisition context for one peptide. `None` means unknown and is
/// encoded as value 0 with presence 0; nothing is inferred.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct PrecursorContext {
pub charge: Option<i32>,
pub precursor_mz: Option<f32>,
pub nce: Option<f32>,
/// Instrument vocabulary id. Id 0 is the learned unknown category, so `Some(0)`
/// is encoded exactly like `None` (presence 0), matching the training collator.
pub instrument_id: Option<u32>,
}

impl FoundationTensorBatch {
/// Fill the context tensors from one [`PrecursorContext`] per peptide, using the
/// same encoding as the Redeem training collator.
pub fn set_context(&mut self, contexts: &[PrecursorContext]) -> Result<()> {
if contexts.len() != self.batch_size {
bail!(
"expected {} precursor contexts, got {}",
self.batch_size,
contexts.len()
);
}
let flag = |present: bool| f32::from(u8::from(present));
let c = contexts;
self.charge = c.iter().map(|x| x.charge.unwrap_or(0) as f32).collect();
self.charge_present = c.iter().map(|x| flag(x.charge.is_some())).collect();
self.precursor_mz = c.iter().map(|x| x.precursor_mz.unwrap_or(0.0)).collect();
self.precursor_mz_present = c.iter().map(|x| flag(x.precursor_mz.is_some())).collect();
self.nce = c.iter().map(|x| x.nce.unwrap_or(0.0)).collect();
self.nce_present = c.iter().map(|x| flag(x.nce.is_some())).collect();
self.instrument_ids = c.iter().map(|x| x.instrument_id.unwrap_or(0)).collect();
self.instrument_present = c
.iter()
.map(|x| flag(x.instrument_id.is_some_and(|id| id > 0)))
.collect();
Ok(())
}

pub fn validate(&self) -> Result<()> {
let expected = [
self.batch_size
Expand Down Expand Up @@ -188,7 +252,7 @@ impl FoundationTensorBatch {
self.instrument_present.len(),
];
if expected != actual {
candle_core::bail!(
bail!(
"Foundation tensor payload lengths do not match declared shapes: expected {:?}, got {:?}",
expected,
actual
Expand All @@ -199,6 +263,7 @@ impl FoundationTensorBatch {
}

/// Tensorized peptide batch used by [`crate::foundation::PeptideFoundationEncoder`].
#[cfg(feature = "candle")]
#[derive(Debug, Clone)]
pub struct FoundationBatch {
/// Atom descriptors with shape `[batch, residues, atoms, atom_features]`.
Expand All @@ -213,6 +278,14 @@ pub struct FoundationBatch {
pub residue_mask: Tensor,
}

struct Dense {
atom_features: Vec<f32>,
adjacency: Vec<f32>,
atom_mask: Vec<f32>,
residue_ids: Vec<u32>,
residue_mask: Vec<f32>,
}

/// CPU-side featurizer for canonical residue chemistry.
#[derive(Debug, Clone)]
pub struct PeptideGraphFeaturizer {
Expand All @@ -222,16 +295,35 @@ pub struct PeptideGraphFeaturizer {
impl PeptideGraphFeaturizer {
/// Create a featurizer and validate the model configuration.
pub fn new(config: FoundationFeaturizerConfig) -> Result<Self> {
config.validate().map_err(candle_core::Error::Msg)?;
config.validate().map_err(FeaturizerError)?;
Ok(Self { config })
}

/// Convert a peptide batch into dense graph tensors on `device`.
#[cfg(feature = "candle")]
pub fn featurize(
&self,
peptides: &[PeptidoformInput],
device: &Device,
) -> Result<FoundationBatch> {
) -> candle_core::Result<FoundationBatch> {
let (b, l, a, f) = (
peptides.len(),
self.config.max_sequence_len,
self.config.max_atoms_per_residue,
self.config.atom_feature_dim,
);
let d = self.dense(peptides)?;
Ok(FoundationBatch {
atom_features: Tensor::from_vec(d.atom_features, (b, l, a, f), device)?,
adjacency: Tensor::from_vec(d.adjacency, (b, l, a, a), device)?,
atom_mask: Tensor::from_vec(d.atom_mask, (b, l, a), device)?,
residue_ids: Tensor::from_vec(d.residue_ids, (b, l), device)?.to_dtype(DType::U32)?,
residue_mask: Tensor::from_vec(d.residue_mask, (b, l), device)?,
})
}

/// Dense row-major graph arrays of a peptide batch.
fn dense(&self, peptides: &[PeptidoformInput]) -> Result<Dense> {
let b = peptides.len();
let l = self.config.max_sequence_len;
let a = self.config.max_atoms_per_residue;
Expand All @@ -246,7 +338,7 @@ impl PeptideGraphFeaturizer {
for (batch_idx, peptide) in peptides.iter().enumerate() {
let residues: Vec<char> = peptide.sequence.chars().collect();
if residues.len() > l {
candle_core::bail!(
bail!(
"peptide length {} exceeds configured maximum {} for {}",
residues.len(),
l,
Expand All @@ -259,7 +351,7 @@ impl PeptideGraphFeaturizer {
.iter()
.find(|m| m.residue_index >= residues.len())
{
candle_core::bail!(
bail!(
"modification residue index {} is outside peptide {} (length {})",
m.residue_index,
peptide.sequence,
Expand All @@ -269,7 +361,7 @@ impl PeptideGraphFeaturizer {

for (residue_idx, residue) in residues.iter().copied().enumerate() {
let mut graph = residue_graph(residue).ok_or_else(|| {
candle_core::Error::Msg(format!("unsupported amino acid '{residue}'"))
FeaturizerError(format!("unsupported amino acid '{residue}'"))
})?;
for modification in peptide
.modifications
Expand All @@ -283,7 +375,7 @@ impl PeptideGraphFeaturizer {
}
}
if graph.atoms.len() > a {
candle_core::bail!(
bail!(
"residue {} at index {} needs {} atom slots, configured maximum is {}",
residue,
residue_idx,
Expand Down Expand Up @@ -318,27 +410,27 @@ impl PeptideGraphFeaturizer {
}
}

Ok(FoundationBatch {
atom_features: Tensor::from_vec(atom_features, (b, l, a, f), device)?,
adjacency: Tensor::from_vec(adjacency, (b, l, a, a), device)?,
atom_mask: Tensor::from_vec(atom_mask, (b, l, a), device)?,
residue_ids: Tensor::from_vec(residue_ids, (b, l), device)?.to_dtype(DType::U32)?,
residue_mask: Tensor::from_vec(residue_mask, (b, l), device)?,
Ok(Dense {
atom_features,
adjacency,
atom_mask,
residue_ids,
residue_mask,
})
}

pub fn featurize_data(&self, peptides: &[PeptidoformInput]) -> Result<FoundationTensorBatch> {
let batch = self.featurize(peptides, &Device::Cpu)?;
let batch = self.dense(peptides)?;
let data = FoundationTensorBatch {
batch_size: peptides.len(),
max_sequence_len: self.config.max_sequence_len,
max_atoms_per_residue: self.config.max_atoms_per_residue,
atom_feature_dim: self.config.atom_feature_dim,
atom_features: batch.atom_features.flatten_all()?.to_vec1()?,
adjacency: batch.adjacency.flatten_all()?.to_vec1()?,
atom_mask: batch.atom_mask.flatten_all()?.to_vec1()?,
residue_ids: batch.residue_ids.flatten_all()?.to_vec1()?,
residue_mask: batch.residue_mask.flatten_all()?.to_vec1()?,
atom_features: batch.atom_features,
adjacency: batch.adjacency,
atom_mask: batch.atom_mask,
residue_ids: batch.residue_ids,
residue_mask: batch.residue_mask,
instrument_ids: vec![0; peptides.len()],
charge: vec![0.0; peptides.len()],
charge_present: vec![0.0; peptides.len()],
Expand Down Expand Up @@ -398,6 +490,35 @@ mod tests {
assert!(error.to_string().contains("outside peptide"));
}

#[test]
fn set_context_matches_training_collator_encoding() {
let featurizer =
PeptideGraphFeaturizer::new(FoundationFeaturizerConfig::default()).unwrap();
let peptides = ["PEPTIDE", "PEPTIDE", "PEPTIDE"].map(PeptidoformInput::unmodified);
let mut batch = featurizer.featurize_data(&peptides).unwrap();
let known = PrecursorContext {
charge: Some(2),
precursor_mz: Some(500.0),
nce: Some(30.0),
instrument_id: Some(3),
};
let zero_instrument = PrecursorContext {
instrument_id: Some(0),
..Default::default()
};
batch
.set_context(&[known, zero_instrument, PrecursorContext::default()])
.unwrap();
batch.validate().unwrap();
assert_eq!(batch.charge, vec![2.0, 0.0, 0.0]);
assert_eq!(batch.charge_present, vec![1.0, 0.0, 0.0]);
assert_eq!(batch.precursor_mz, vec![500.0, 0.0, 0.0]);
assert_eq!(batch.nce_present, vec![1.0, 0.0, 0.0]);
assert_eq!(batch.instrument_ids, vec![3, 0, 0]);
assert_eq!(batch.instrument_present, vec![1.0, 0.0, 0.0]);
assert!(batch.set_context(&[known]).is_err());
}

#[test]
fn unmodified_peptide_preserves_explicit_context_fields() {
let featurizer =
Expand Down
5 changes: 4 additions & 1 deletion redeem-foundation-featurizer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ pub use chemistry::{
common_unimod_definition, exact_graph_modification, ElementalComposition,
ExactGraphModification, FoundationModificationDefinition, ModificationAttachmentSite,
};
#[cfg(feature = "candle")]
pub use featurize::FoundationBatch;
pub use featurize::{
exact_graph_modification_for, residue_token_id, FoundationBatch, FoundationModification,
exact_graph_modification_for, residue_token_id, FeaturizerError, FoundationModification,
FoundationModificationSite, FoundationTensorBatch, PeptideGraphFeaturizer, PeptidoformInput,
PrecursorContext,
};

/// Shape-only configuration required by the graph featurizer.
Expand Down