Repository navigation
[3/4] Andes batch prediction bridge and student distillation #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+2,228
−143
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
3c3102d
Add versioned YAML batch prediction bridge for Andes
singjc 804a19e
Batch bridge: load original v0.52 + v0.35 research checkpoints
singjc 92585b4
v0.52 inference: constant weights, single trunk pass, dedup + paralle…
singjc b9ec823
v0.52 inference: dynamic padding to the batch's longest peptide
singjc a4028fa
Inference Linear without per-call weight repacking; length-sorted bat…
singjc 0c05450
Opt-in --fast-math: fused LayerNorm for inference weights
singjc 73c572d
Add foundation distillation: train a small fast student on teacher la…
singjc 0853c3e
Batch bridge: --rt-ms2-checkpoint alone loads one FoundationModel (e.…
singjc 2f170da
Distill: reuse cached teacher labels; cap training threads
singjc 347b443
foundation_distill: add --size medium
singjc b27446a
distill: opt-in task_weights [rt, ccs, ms2] in FoundationDistillConfig
singjc e68e124
feat(foundation): adapt Andes peptide forms
singjc 4a5fb52
feat(foundation): expose UINT32 tensor boundary
singjc 809370e
Wire Andes forms to Foundation tensors
singjc c2b003c
fix(foundation): adapt batch bridge and distillation to the stack 2 APIs
singjc ef29855
fix(foundation): treat instrument id 0 as unknown in the Andes tensor…
singjc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| //! YAML subprocess bridge. See foundation_batch_predict.md for the contract. | ||
| use anyhow::{bail, ensure, Context, Result}; | ||
| use candle_core::Device; | ||
| use redeem_properties::foundation::{ | ||
| batch_prediction::BatchPredictionRequest, FoundationModel, ResearchV0520Mobility, | ||
| }; | ||
| use redeem_properties::models::model_interface::PredictionModel; | ||
| use std::{ | ||
| collections::HashMap, | ||
| io::{Read, Write}, | ||
| path::PathBuf, | ||
| }; | ||
|
|
||
| fn main() { | ||
| if let Err(error) = run() { | ||
| eprintln!("{error:#}"); | ||
| std::process::exit(1); | ||
| } | ||
| } | ||
|
|
||
| fn run() -> Result<()> { | ||
| let mut args = std::env::args().skip(1); | ||
| let mut options = HashMap::new(); | ||
| while let Some(key) = args.next() { | ||
| if key == "--help" { | ||
| eprintln!("foundation_batch_predict [--rt-ms2-checkpoint DIR --ccs-checkpoint DIR] [--inverse-checkpoint DIR] [--request PATH|-] [--response PATH|-] [--batch-size 32] [--fast-math]\nSupply the property checkpoint pair, inverse checkpoint, or both.\n--fast-math: fused LayerNorm kernel, faster but float-reordered (~1e-6 relative) vs default."); | ||
| return Ok(()); | ||
| } | ||
| if key == "--fast-math" { | ||
| redeem_properties::foundation::layers::set_fused_layer_norm(true); | ||
| continue; | ||
| } | ||
| ensure!( | ||
| [ | ||
| "--request", | ||
| "--response", | ||
| "--rt-ms2-checkpoint", | ||
| "--ccs-checkpoint", | ||
| "--inverse-checkpoint", | ||
| "--batch-size" | ||
| ] | ||
| .contains(&key.as_str()), | ||
| "unknown option {key}" | ||
| ); | ||
| let value = args.next().context("option requires a value")?; | ||
| ensure!(options.insert(key, value).is_none(), "duplicate option"); | ||
| } | ||
| let request_path = options.get("--request").map_or("-", String::as_str); | ||
| let response_path = options.get("--response").map_or("-", String::as_str); | ||
| if request_path != "-" && response_path != "-" { | ||
| let request = std::fs::canonicalize(request_path)?; | ||
| let response = PathBuf::from(response_path); | ||
| let resolved = if response.exists() { | ||
| std::fs::canonicalize(&response)? | ||
| } else { | ||
| std::fs::canonicalize( | ||
| response | ||
| .parent() | ||
| .filter(|p| !p.as_os_str().is_empty()) | ||
| .unwrap_or(std::path::Path::new(".")), | ||
| )? | ||
| .join( | ||
| response | ||
| .file_name() | ||
| .context("response requires a filename")?, | ||
| ) | ||
| }; | ||
| ensure!(request != resolved, "request and response must differ"); | ||
| } | ||
| let mut text = String::new(); | ||
| if request_path == "-" { | ||
| std::io::stdin().read_to_string(&mut text)?; | ||
| } else { | ||
| text = std::fs::read_to_string(request_path)?; | ||
| } | ||
| let request: BatchPredictionRequest = | ||
| serde_yaml::from_str(&text).context("parse request YAML")?; | ||
| request.validate()?; | ||
| let batch_size: usize = options.get("--batch-size").map_or(Ok(32), |v| v.parse())?; | ||
| ensure!(batch_size > 0, "batch-size must be positive"); | ||
| let predictor = match ( | ||
| options.get("--rt-ms2-checkpoint"), | ||
| options.get("--ccs-checkpoint"), | ||
| ) { | ||
| // A checkpoint pair is the original v0.52 student + v0.35 teacher. | ||
| (Some(rt), Some(ccs)) => Some(Box::new( | ||
| ResearchV0520Mobility::load(rt.as_ref(), ccs.as_ref(), Device::Cpu) | ||
| .context("load v0.52 RT/MS2 + v0.35 CCS research checkpoint pair")?, | ||
| ) as Box<dyn PredictionModel + Sync>), | ||
| // A single FoundationModel checkpoint (e.g. a distilled student) predicts RT/CCS/MS2. | ||
| (Some(rt), None) => Some(Box::new(FoundationModel::load(rt, Device::Cpu).context( | ||
| "--rt-ms2-checkpoint without --ccs-checkpoint must be a FoundationModel checkpoint", | ||
| )?) as Box<dyn PredictionModel + Sync>), | ||
| (None, None) => None, | ||
| _ => bail!("--ccs-checkpoint requires --rt-ms2-checkpoint"), | ||
| }; | ||
| let inverse = options | ||
| .get("--inverse-checkpoint") | ||
| .map(|p| FoundationModel::load(p, Device::Cpu)) | ||
| .transpose()?; | ||
| let response = serde_yaml::to_string(&request.predict( | ||
| predictor.as_deref(), | ||
| inverse.as_ref(), | ||
| batch_size, | ||
| )?)?; | ||
| if response_path == "-" { | ||
| std::io::stdout().lock().write_all(response.as_bytes())?; | ||
| } else { | ||
| // Do not truncate an existing response or leave a stale partial success. | ||
| let mut file = match std::fs::OpenOptions::new() | ||
| .write(true) | ||
| .create_new(true) | ||
| .open(response_path) | ||
| { | ||
| Ok(file) => file, | ||
| Err(error) => bail!("create response {response_path}: {error}"), | ||
| }; | ||
| if let Err(error) = file | ||
| .write_all(response.as_bytes()) | ||
| .and_then(|_| file.sync_all()) | ||
| { | ||
| drop(file); | ||
| let _ = std::fs::remove_file(response_path); | ||
| return Err(error.into()); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| schema_version: 1 | ||
| rows: | ||
| - id: psm-1 | ||
| sequence: ACDMPEPTIDEK | ||
| modifications: | ||
| - {position: 2, mass_delta: 57.021464, unimod_id: 4} | ||
| - {position: 4, mass_delta: 15.994915, unimod_id: 35} | ||
| charge: 2 | ||
| precursor_mz: 660.3 | ||
| rt: 1234.5 | ||
| peaks: | ||
| - {mz: 147.1128, intensity: 100.0} | ||
| - {mz: 250.1254, intensity: 30.0} | ||
| nce: 30.0 | ||
| instrument: timsTOF |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| //! Distil a foundation teacher into a small fast student checkpoint. | ||
| //! | ||
| //! foundation_distill --peptides peptides.yaml --output STUDENT_DIR | ||
| //! (--rt-ms2-checkpoint V052 --ccs-checkpoint V035 | --labels teacher_response.yaml) | ||
| //! [--config distill.yaml] [--size tiny|small|medium] [--train-threads N] | ||
| //! | ||
| //! `peptides.yaml` uses the batch-prediction request schema (rows of sequence, | ||
| //! modifications, charge, precursor_mz, nce, instrument); peaks/rt are ignored. With | ||
| //! checkpoints the teacher (original v0.52 research stack) labels the peptides live. With | ||
| //! `--labels`, a cached `foundation_batch_predict` response for the same request is used | ||
| //! instead, so training can be re-run without the slow teacher. `--train-threads` caps | ||
| //! training parallelism: the student's small matrices do not scale past a few threads. | ||
| //! The student is a standard FoundationModel checkpoint for | ||
| //! `foundation_batch_predict --rt-ms2-checkpoint STUDENT_DIR`. | ||
| use anyhow::{bail, ensure, Context, Result}; | ||
| use candle_core::Device; | ||
| use redeem_properties::foundation::batch_prediction::{ | ||
| BatchPredictionRequest, BatchPredictionResponse, | ||
| }; | ||
| use redeem_properties::foundation::distill::{ | ||
| distill_from_records, labelled_record, small_student_config, teacher_labelled_records, | ||
| FoundationDistillConfig, | ||
| }; | ||
| use redeem_properties::foundation::ResearchV0520Mobility; | ||
| use redeem_properties::models::model_interface::PredictionOutput; | ||
| use std::{collections::HashMap, path::Path, time::Instant}; | ||
|
|
||
| fn main() -> Result<()> { | ||
| env_logger::init(); | ||
| let mut args = std::env::args().skip(1); | ||
| let mut options = HashMap::new(); | ||
| while let Some(key) = args.next() { | ||
| ensure!( | ||
| [ | ||
| "--rt-ms2-checkpoint", | ||
| "--ccs-checkpoint", | ||
| "--labels", | ||
| "--peptides", | ||
| "--output", | ||
| "--config", | ||
| "--size", | ||
| "--train-threads" | ||
| ] | ||
| .contains(&key.as_str()), | ||
| "unknown option {key}" | ||
| ); | ||
| options.insert(key, args.next().context("option requires a value")?); | ||
| } | ||
| let get = |k: &str| options.get(k).with_context(|| format!("missing {k}")); | ||
| let request: BatchPredictionRequest = | ||
| serde_yaml::from_str(&std::fs::read_to_string(get("--peptides")?)?)?; | ||
| let inputs = request.prediction_inputs()?; | ||
| let config: FoundationDistillConfig = match options.get("--config") { | ||
| Some(p) => serde_yaml::from_str(&std::fs::read_to_string(p)?)?, | ||
| None => FoundationDistillConfig::default(), | ||
| }; | ||
| let mut student = small_student_config(); | ||
| match options.get("--size").map(String::as_str).unwrap_or("small") { | ||
| "small" => {} | ||
| "tiny" => { | ||
| student.peptide.model_dim = 64; | ||
| student.peptide.transformer_ff_dim = 128; | ||
| student.peptide.transformer_layers = 2; | ||
| student.peptide.graph_hidden_dim = 32; | ||
| } | ||
| "medium" => { | ||
| student.peptide.model_dim = 256; | ||
| student.peptide.num_attention_heads = 8; | ||
| student.peptide.transformer_ff_dim = 512; | ||
| student.peptide.transformer_layers = 4; | ||
| student.peptide.graph_hidden_dim = 128; | ||
| } | ||
| other => bail!("unknown --size {other} (tiny|small|medium)"), | ||
| } | ||
| let t = Instant::now(); | ||
| let records = match options.get("--labels") { | ||
| Some(path) => { | ||
| let response: BatchPredictionResponse = | ||
| serde_yaml::from_str(&std::fs::read_to_string(path)?) | ||
| .with_context(|| format!("parse teacher labels {path}"))?; | ||
| let by_id: HashMap<_, _> = response | ||
| .rows | ||
| .into_iter() | ||
| .map(|r| (r.id.clone(), r)) | ||
| .collect(); | ||
| ensure!( | ||
| by_id.len() == request.rows.len(), | ||
| "labels must cover every peptide row" | ||
| ); | ||
| request | ||
| .rows | ||
| .iter() | ||
| .zip(&inputs) | ||
| .map(|(row, input)| { | ||
| let label = by_id | ||
| .get(&row.id) | ||
| .with_context(|| format!("no teacher label for row {}", row.id))?; | ||
| let output = PredictionOutput { | ||
| rt: label.predicted_rt, | ||
| ccs: label.predicted_ccs, | ||
| ms2: label.predicted_ms2.clone(), | ||
| }; | ||
| labelled_record(input, output) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()? | ||
| } | ||
| None => { | ||
| let teacher = ResearchV0520Mobility::load( | ||
| Path::new(get("--rt-ms2-checkpoint")?), | ||
| Path::new(get("--ccs-checkpoint")?), | ||
| Device::Cpu, | ||
| )?; | ||
| teacher_labelled_records(&teacher, &inputs, config.teacher_batch_size)? | ||
| } | ||
| }; | ||
| eprintln!( | ||
| "teacher labels for {} peptides ready in {:.0}s", | ||
| records.len(), | ||
| t.elapsed().as_secs_f64() | ||
| ); | ||
| let output = Path::new(get("--output")?); | ||
| let train = || distill_from_records(records, student, &config, output, Device::Cpu); | ||
| let summary = match options.get("--train-threads") { | ||
| Some(n) => rayon::ThreadPoolBuilder::new() | ||
| .num_threads(n.parse().context("--train-threads must be a number")?) | ||
| .build()? | ||
| .install(train)?, | ||
| None => train()?, | ||
| }; | ||
| std::fs::write( | ||
| output.join("distill_summary.yaml"), | ||
| serde_yaml::to_string(&summary)?, | ||
| )?; | ||
| eprintln!( | ||
| "distilled {} train / {} validation peptides in {:.0}s; validation: {:?}", | ||
| summary.train_records, | ||
| summary.validation_records, | ||
| t.elapsed().as_secs_f64(), | ||
| summary.validation | ||
| ); | ||
| Ok(()) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Publish the response only after the file is complete.
If the subprocess is terminated after
create_newbut beforewrite_allfinishes, the destination contains an empty or partial response. Termination bypasses the cleanup branch, and a retry fails because the destination already exists. Write and sync a temporary file in the destination directory, then publish it atomically without replacing an existing response. An interrupted write should leave the final path free for a retry.