Skip to content
2 changes: 1 addition & 1 deletion redeem-properties/docs/foundation_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The foundation model predicts three peptide properties:
- collision cross section (CCS)
- MS2 fragment intensities

The model trains from scratch. It does not use teacher distillation.
The full model trains from scratch. A compact student can optionally use the full model as a frozen teacher for RT, CCS, and MS2 distillation. The default training recipe keeps distillation disabled.

## Architecture

Expand Down
205 changes: 205 additions & 0 deletions redeem-properties/src/foundation/loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,156 @@ pub struct FoundationTargets {
pub chemistry_mask: Option<Tensor>,
}

/// Optional outputs from a frozen foundation-model teacher.
#[derive(Debug, Clone, Default)]
pub struct FoundationTeacherOutputs {
/// Teacher RT/iRT prediction `[batch, 1]`.
pub rt: Option<Tensor>,
/// Teacher CCS prediction `[batch, 1]`.
pub ccs: Option<Tensor>,
/// Teacher fragment intensities matching the native MS2 output.
pub ms2: Option<Tensor>,
/// Teacher-forced inverse decoder logits `[batch, tokens, vocabulary]`.
pub inverse_token_logits: Option<Tensor>,
}

/// Weights for combining frozen-teacher regression with native objectives.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct FoundationDistillationConfig {
pub rt_weight: f64,
pub ccs_weight: f64,
pub ms2_weight: f64,
pub inverse_token_weight: f64,
}

impl Default for FoundationDistillationConfig {
fn default() -> Self {
Self {
rt_weight: 0.0,
ccs_weight: 0.0,
ms2_weight: 0.0,
inverse_token_weight: 0.0,
}
}
}

impl FoundationDistillationConfig {
pub fn validate(self) -> Result<Self> {
for (name, value) in [
("RT", self.rt_weight),
("CCS", self.ccs_weight),
("MS2", self.ms2_weight),
("inverse token", self.inverse_token_weight),
] {
if !(value >= 0.0 && value.is_finite()) {
candle_core::bail!(
"foundation distillation {name} weight must be finite and non-negative"
);
}
}
Ok(self)
}
}

/// Native loss plus optional RT, CCS, and MS2 teacher matching terms.
#[derive(Debug, Clone)]
pub struct FoundationDistillationLosses {
pub total: Tensor,
pub native: FoundationLosses,
pub teacher_rt: Option<Tensor>,
pub teacher_ccs: Option<Tensor>,
pub teacher_ms2: Option<Tensor>,
pub teacher_inverse_tokens: Option<Tensor>,
}

/// Compose native supervised losses with available frozen-teacher predictions.
pub fn multi_task_loss_with_distillation(
output: &FoundationMultiTaskOutput,
targets: &FoundationTargets,
teacher: &FoundationTeacherOutputs,
weights: FoundationLossWeights,
ms2_config: FoundationMs2LossConfig,
distillation: FoundationDistillationConfig,
) -> Result<FoundationDistillationLosses> {
let distillation = distillation.validate()?;
let native = multi_task_loss_with_ms2_config(output, targets, weights, ms2_config)?;
// Only active terms reach the teacher shape check, so e.g. RT-only distillation works
// when student and teacher emit different MS2 channel counts.
let active_term = |weight: f64, prediction: &Tensor, teacher: Option<&Tensor>| {
if weight > 0.0 {
paired_teacher_mse(prediction, teacher)
} else {
Ok(None)
}
};
let teacher_rt = active_term(distillation.rt_weight, &output.rt, teacher.rt.as_ref())?;
let teacher_ccs = active_term(distillation.ccs_weight, &output.ccs, teacher.ccs.as_ref())?;
let teacher_ms2 = active_term(distillation.ms2_weight, &output.ms2, teacher.ms2.as_ref())?;
let teacher_inverse_tokens = None;
let mut total = native.total.clone();
for (term, weight) in [
(&teacher_rt, distillation.rt_weight),
(&teacher_ccs, distillation.ccs_weight),
(&teacher_ms2, distillation.ms2_weight),
] {
if let Some(term) = term {
total = (total + term.affine(weight, 0.0)?)?;
}
}
Ok(FoundationDistillationLosses {
total,
native,
teacher_rt,
teacher_ccs,
teacher_ms2,
teacher_inverse_tokens,
})
}

/// Match teacher-forced inverse decoder logits `[batch, max_tokens, vocabulary]`.
///
/// The squared error is averaged only over the active prediction positions
/// (`active_indices` into the flattened `batch * max_tokens` axis, as produced by the
/// causal collator) and the vocabulary axis, so padding never contributes.
pub fn inverse_token_distillation_loss(
prediction: &Tensor,
teacher: Option<&Tensor>,
active_indices: &Tensor,
) -> Result<Option<Tensor>> {
let Some(teacher) = teacher else {
return Ok(None);
};
if prediction.dims() != teacher.dims() {
candle_core::bail!(
"inverse distillation requires matching teacher/student logits (same inverse.max_tokens and vocabulary): prediction {:?}, teacher {:?}",
prediction.dims(),
teacher.dims()
);
}
let (batch, tokens, classes) = prediction.dims3()?;
let active = |logits: &Tensor| -> Result<Tensor> {
logits
.reshape((batch * tokens, classes))?
.index_select(active_indices, 0)
};
paired_teacher_mse(&active(prediction)?, Some(&active(teacher)?))
}

fn paired_teacher_mse(prediction: &Tensor, teacher: Option<&Tensor>) -> Result<Option<Tensor>> {
let Some(teacher) = teacher else {
return Ok(None);
};
if prediction.dims() != teacher.dims() {
candle_core::bail!(
"teacher loss shape mismatch: prediction {:?}, teacher {:?}",
prediction.dims(),
teacher.dims()
);
}
Ok(Some((prediction - teacher)?.sqr()?.mean_all()?))
}

fn legacy_ms2_pearson_weight() -> f64 {
0.0
}
Expand Down Expand Up @@ -511,4 +661,59 @@ mod tests {
assert_eq!(config.cosine_weight, 0.25);
assert_eq!(config.pearson_weight, 0.25);
}

#[test]
fn distillation_config_round_trips_and_defaults_to_disabled() {
let config = FoundationDistillationConfig::default();
assert_eq!(config, serde_yaml::from_str("{}").unwrap());
let restored: FoundationDistillationConfig =
serde_yaml::from_str("rt_weight: 0.5\nccs_weight: 0.25\nms2_weight: 0.75\n").unwrap();
assert_eq!(restored.rt_weight, 0.5);
assert_eq!(restored.ccs_weight, 0.25);
assert_eq!(restored.ms2_weight, 0.75);
}

#[test]
fn inverse_distillation_averages_only_active_positions() {
let device = Device::Cpu;
// [batch=1, tokens=3, vocabulary=2]; position 2 is padding.
let prediction =
Tensor::new(&[[[1.0f32, 2.0], [3.0, 4.0], [100.0, -100.0]]], &device).unwrap();
let teacher = Tensor::new(&[[[1.0f32, 2.0], [3.0, 6.0], [0.0, 0.0]]], &device).unwrap();
let loss = |indices: &[u32]| {
let active = Tensor::new(indices, &device).unwrap();
inverse_token_distillation_loss(&prediction, Some(&teacher), &active)
.unwrap()
.unwrap()
.to_scalar::<f32>()
.unwrap()
};
// Only position 1 differs among active positions: (4-6)^2 / (2 positions * 2 classes).
assert!((loss(&[0, 1]) - 1.0).abs() < 1e-6);
assert!(
loss(&[0, 1, 2]) > 1000.0,
"padding would dominate if included"
);
let wider = Tensor::zeros((1, 4, 2), DType::F32, &device).unwrap();
let active = Tensor::new(&[0u32], &device).unwrap();
assert!(inverse_token_distillation_loss(&prediction, Some(&wider), &active).is_err());
}

#[test]
fn teacher_mse_is_optional_and_shape_checked() {
let device = Device::Cpu;
let prediction = Tensor::new(&[[1.0f32], [3.0]], &device).unwrap();
let teacher = Tensor::new(&[[0.0f32], [1.0]], &device).unwrap();
let loss = paired_teacher_mse(&prediction, Some(&teacher))
.unwrap()
.unwrap()
.to_scalar::<f32>()
.unwrap();
assert!((loss - 2.5).abs() < 1e-6);
assert!(paired_teacher_mse(&prediction, None).unwrap().is_none());
assert!(
paired_teacher_mse(&prediction, Some(&Tensor::new(&[1.0f32], &device).unwrap()))
.is_err()
);
}
}
7 changes: 4 additions & 3 deletions redeem-properties/src/foundation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,10 @@ pub use identifier_core::{
};

pub use loss::{
FoundationLossWeights, FoundationLosses, FoundationMs2LossConfig, FoundationMs2Losses,
FoundationTargets, contrastive_info_nce_loss, foundation_ms2_loss, multi_task_loss,
multi_task_loss_with_ms2_config,
FoundationDistillationConfig, FoundationDistillationLosses, FoundationLossWeights,
FoundationLosses, FoundationMs2LossConfig, FoundationMs2Losses, FoundationTargets,
FoundationTeacherOutputs, contrastive_info_nce_loss, foundation_ms2_loss, multi_task_loss,
multi_task_loss_with_distillation, multi_task_loss_with_ms2_config,
};

pub use metadata::{
Expand Down
Loading
Loading