examples.impress_r.mpnn¶
ProteinMPNN trainer task — the IMPRESS-R half of ROME's trainers.
IMPRESS runs backbone -> ProteinMPNN -> structure prediction -> pLDDT/pTM/pAE -> keep/fallback/migrate/drop, and it is open loop: every campaign improves the designs, never the model. IMPRESS-R closes that loop by fine-tuning ProteinMPNN on the campaign's own high-confidence designs.
Which ProteinMPNN. IMPRESS runs the original dauparas/ProteinMPNN: its
mpnn_wrapper.py shells out to protein_mpnn_run.py with the original CLI
and helper scripts, and its setup clones that repo directly. So this trainer
targets the same implementation — it fine-tunes the original model and writes
a checkpoint in the original {"model_state_dict": ...} format that
protein_mpnn_run.py loads. A foundry / re-implementation checkpoint would
not load into what IMPRESS runs; that was the previous version's mistake.
(PyRosetta is in the IMPRESS stack too, but for FastRelax and pLDDT extraction, not for sequence design — the design model is vanilla ProteinMPNN.)
Dimers, not monomers. An IMPRESS protein-binding design is a complex: a
designed chain (A) plus a fixed target peptide (B). Fine-tuning has to
respect that — the model should learn to design chain A in the context of the
peptide, scoring sequence recovery on the designed chain only. That is exactly
what ProteinMPNN's chain mask expresses, and build_chain_designation
sets it up: designed chains are predicted, context chains are visible but not
scored.
This trainer is an IMPRESS-R integration, not framework core — ROME is
workflow-agnostic — so it lives with the example, beside the inference wrapper
(mpnn_wrapper.py) it complements. Import it from here::
from examples.impress_r.mpnn import ProteinMPNNTrainer, ProteinMPNNConfig
Runs as a command, not a function. Like IMPRESS — which submits
mpnn_wrapper.py as a shell command rather than calling ProteinMPNN in the
campaign process — the training manager submits this round as an executable
task: ProteinMPNNTrainer.as_command stages the structures, writes a
self-contained job spec, and returns python mpnn_train_wrapper.py --job
<job.json>. The fine-tune therefore runs in its own process on its own GPU,
and that process exits when the round finishes, so its VRAM is released with it.
The training loop itself lives in mpnn_train_wrapper.run_round (the sibling
script) — one dragon-free copy, so the standalone script and the in-process path
(a direct train call, used by the tests) share it. It mirrors
training/training.py's inner loop using the repo's own featurize,
loss_smoothed, NoamOpt and training ProteinMPNN, verified end to end
against a real checkout and the public v_48_020 weights — the loss runs on
the designed chain only and the checkpoint reloads into protein_mpnn_run.py.
config.train_func substitutes your own loop (and keeps it in-process). See
docs/proteinmpnn_training.md.
MPNN_ALPHABET
module-attribute
¶
ProteinMPNN's amino-acid alphabet (index -> letter). Position 20 is X.
REQUIRED_FIELDS
module-attribute
¶
Fields a corpus record must carry.
path is the structure file whose designed chain IS the training label.
sequence is optional (ProteinMPNN reads the label out of the structure); it
is kept for the manifest and for sizing.
DEFAULT_DESIGN_CHAINS
module-attribute
¶
Chains scored by the loss. In the IMPRESS layout, chain A is the designed binder.
DEFAULT_CONTEXT_CHAINS
module-attribute
¶
Chains visible to the model but not scored — the fixed target peptide.
DEFAULT_NUM_NEIGHBORS
module-attribute
¶
k_neighbors of the public v_48_020 weights. Read back from the checkpoint.
DEFAULT_HIDDEN_DIM
module-attribute
¶
Hidden dimension protein_mpnn_run.py hardcodes.
DEFAULT_NUM_LAYERS
module-attribute
¶
Encoder and decoder layers protein_mpnn_run.py hardcodes.
DEFAULT_BACKBONE_NOISE
module-attribute
¶
Backbone noise the original training loop uses.
DEFAULT_RANK_BY
module-attribute
¶
Default ranking for the PDZ binder case: interface pAE down, pTM up.
pLDDT is deliberately absent — in a measured campaign it never fell below 88, so it separates almost nothing.
ProteinMPNNConfig
dataclass
¶
ProteinMPNNConfig(mpnn_repo: Optional[str] = None, initial_weights: Optional[str] = None, model_name: str = 'v_48_020', dataset_name: str = 'impress_r', design_chains: Sequence[str] = DEFAULT_DESIGN_CHAINS, context_chains: Sequence[str] = DEFAULT_CONTEXT_CHAINS, chains_func: Optional[Callable[..., Tuple[List[str], List[str]]]] = None, num_neighbors: int = DEFAULT_NUM_NEIGHBORS, hidden_dim: int = DEFAULT_HIDDEN_DIM, num_layers: int = DEFAULT_NUM_LAYERS, backbone_noise: float = DEFAULT_BACKBONE_NOISE, dropout: float = 0.1, max_epochs: int = 3, batch_tokens: int = 10000, max_protein_length: int = 2000, learning_rate_factor: float = 2.0, warmup_steps: int = 4000, label_smoothing: float = 0.1, gradient_norm: Optional[float] = 1.0, publish_into_repo: bool = False, seed: int = 0, num_workers: int = 4, device: str = 'cuda', manifest_dir: Optional[str] = None, train_func: Optional[Callable[..., str]] = None, train_script: Optional[str] = None)
Configuration for fine-tuning the original ProteinMPNN on campaign designs.
Defaults describe a short mid-campaign round that starts from the public weights and nudges them, not a from-scratch training run.
Parameters:
-
mpnn_repo(Optional[str], default:None) –Path to the
dauparas/ProteinMPNNcheckout — the same directory IMPRESS passes as-mpnn. The trainer importsprotein_mpnn_utilsfrom here, and (withpublish_into_repo) writes the new weights back into itsvanilla_model_weights/. -
initial_weights(Optional[str], default:None) –Checkpoint the first round starts from, in original format — normally
{mpnn_repo}/vanilla_model_weights/v_48_020.pt. Later rounds resume from whatever the previous round published (passed asmodel_path). -
model_name(str, default:'v_48_020') –Basename of the published weights (no extension). Must match the
--model_nameIMPRESS runs with; the defaultv_48_020isprotein_mpnn_run.py's default. -
design_chains(sequence of str, default:DEFAULT_DESIGN_CHAINS) –Default chain designation. For IMPRESS binders,
("A",)designed and("B",)context. Overridable per record or viachains_func. -
context_chains(sequence of str, default:DEFAULT_DESIGN_CHAINS) –Default chain designation. For IMPRESS binders,
("A",)designed and("B",)context. Overridable per record or viachains_func. -
chains_func(optional callable, default:None) –(record, present_chains) -> (designed, context)to decide chains per structure. Overrides the defaults when set. -
num_neighbors(..., default:DEFAULT_NUM_NEIGHBORS) –Architecture. Must match the weights being fine-tuned — the public
v_48_*weights arenum_neighborsin {48}, hidden_dim 128, 3+3 layers.protein_mpnn_run.pyreadsnum_neighborsback from the checkpoint, so a mismatch will not load. -
hidden_dim(..., default:DEFAULT_NUM_NEIGHBORS) –Architecture. Must match the weights being fine-tuned — the public
v_48_*weights arenum_neighborsin {48}, hidden_dim 128, 3+3 layers.protein_mpnn_run.pyreadsnum_neighborsback from the checkpoint, so a mismatch will not load. -
num_layers(..., default:DEFAULT_NUM_NEIGHBORS) –Architecture. Must match the weights being fine-tuned — the public
v_48_*weights arenum_neighborsin {48}, hidden_dim 128, 3+3 layers.protein_mpnn_run.pyreadsnum_neighborsback from the checkpoint, so a mismatch will not load. -
backbone_noise(..., default:DEFAULT_NUM_NEIGHBORS) –Architecture. Must match the weights being fine-tuned — the public
v_48_*weights arenum_neighborsin {48}, hidden_dim 128, 3+3 layers.protein_mpnn_run.pyreadsnum_neighborsback from the checkpoint, so a mismatch will not load. -
dropout(..., default:DEFAULT_NUM_NEIGHBORS) –Architecture. Must match the weights being fine-tuned — the public
v_48_*weights arenum_neighborsin {48}, hidden_dim 128, 3+3 layers.protein_mpnn_run.pyreadsnum_neighborsback from the checkpoint, so a mismatch will not load. -
max_epochs(int, default:3) –Round length and batching.
batch_tokenscaps residues per batch (ProteinMPNN uses ~10000). A short round is a few epochs. -
batch_tokens(int, default:3) –Round length and batching.
batch_tokenscaps residues per batch (ProteinMPNN uses ~10000). A short round is a few epochs. -
max_protein_length(int, default:3) –Round length and batching.
batch_tokenscaps residues per batch (ProteinMPNN uses ~10000). A short round is a few epochs. -
learning_rate_factor(..., default:2.0) –Noam schedule + label-smoothed NLL, as the original trainer uses.
-
warmup_steps(..., default:2.0) –Noam schedule + label-smoothed NLL, as the original trainer uses.
-
label_smoothing(..., default:2.0) –Noam schedule + label-smoothed NLL, as the original trainer uses.
-
gradient_norm(..., default:2.0) –Noam schedule + label-smoothed NLL, as the original trainer uses.
-
publish_into_repo(bool, default:False) –Also copy each round's versioned checkpoint onto the repo's fixed
{mpnn_repo}/vanilla_model_weights/{model_name}.ptpointer, so the campaign's next pass runs the new weights with no wrapper change. The versioned checkpoints in the round's own directory are the kept history; this only refreshes the "current" pointer. Off by default: it mutates the shared repo, which a workflow should opt into knowingly. -
seed(..., default:0) –Reproducibility / loader / placement.
-
num_workers(..., default:0) –Reproducibility / loader / placement.
-
device(..., default:0) –Reproducibility / loader / placement.
-
train_func(optional callable, default:None) –(manifest_path, output_dir, config) -> checkpoint_pathescape hatch, bypassing the built-in loop. The recommended path until the loop is validated on your checkout, and the way the examples stay runnable.
train_script
class-attribute
instance-attribute
¶
The wrapper script the round is submitted as a command to run.
Defaults to the sibling examples/impress_r/mpnn_train_wrapper.py;
override to point at a copy staged elsewhere on the cluster (as IMPRESS
points -mpnn at its own checkout).
ProteinMPNNTrainer
¶
ProteinMPNNTrainer(config: Optional[ProteinMPNNConfig] = None, *, gpus: Optional[int] = None, nodes: Optional[int] = None, name: Optional[str] = None)
Bases: TrainTask
Fine-tunes the original ProteinMPNN on the campaign's confident designs.
Returns the checkpoint file (original format), which the training manager
publishes and — with publish_into_repo — drops straight into the repo's
weights directory so IMPRESS's next pass runs it.
Set config.train_func to bypass the built-in loop with your own
(manifest_path, output_dir, config) -> checkpoint_path. Recommended
until the built-in loop is validated on your ProteinMPNN checkout.
Source code in examples/impress_r/mpnn.py
wants_hf_dataset
class-attribute
instance-attribute
¶
Records are plain dicts of paths and scores, not a HuggingFace dataset.
write_manifest
¶
Write the round's training manifest (parquet); returns its path.
The audit trail for "what did this round train on": one row per design with its staged structure, chain designation, and scores. Public and side-effect-light so a workflow can inspect a round before trusting it.
Source code in examples/impress_r/mpnn.py
as_command
¶
Submit this round as a shell command, IMPRESS-style.
Stages the round's structures, writes a self-contained job spec, and
returns (command, checkpoint_path) where command runs
mpnn_train_wrapper.py on that spec. The training manager runs it as an
executable task, so the fine-tune is a separate process on its own GPU
rather than a function in the manager's address space.
Returns None when config.train_func is set — a custom loop is
Python, not a command, so it runs in-process through train.
Source code in examples/impress_r/mpnn.py
train
¶
Fine-tune ProteinMPNN in-process; return the checkpoint.
This is the direct/in-process path — the training manager normally goes
through as_command instead. Kept because a workflow (or a test)
may want to run a round synchronously, and because config.train_func
plugs in here. It shares the exact loop the command runs, via
mpnn_train_wrapper.run_round.
kwargs carries model_version from the training manager and
model_path when a previous round published one.
Source code in examples/impress_r/mpnn.py
pdb_chain_ids
¶
Chain IDs present in a PDB, in first-seen order — column 22 of ATOM/HETATM.
Plain text parsing so a campaign's monomer-vs-complex shape can be checked (and a bad chain designation caught) without importing a structure library.
Source code in examples/impress_r/mpnn.py
build_chain_designation
¶
build_chain_designation(records: List[Dict[str, Any]], *, design_chains: Sequence[str] = DEFAULT_DESIGN_CHAINS, context_chains: Sequence[str] = DEFAULT_CONTEXT_CHAINS, chains_func: Optional[Callable[[Dict[str, Any], List[str]], Tuple[List[str], List[str]]]] = None) -> Dict[str, Tuple[List[str], List[str]]]
Map each design to (designed_chains, context_chains).
This is the dimer fix. ProteinMPNN's tied_featurize takes exactly this
mapping and builds the chain mask from it: designed chains are predicted and
scored, context chains are visible to the model but excluded from the loss.
For an IMPRESS binder that means "learn chain A given chain B", which is the
thing the campaign is actually optimising.
A record may override the defaults per structure with a design_chains /
context_chains field, or a chains_func(record, present_chains) may
decide from the structure itself. Chains named but absent from the file are
dropped with the designation still valid for whatever remains; a design with
no designable chain present is an error, caught in
ProteinMPNNTrainer.validate.
Returns {design_name: (designed, context)} keyed by the staged structure
name (see stage_structures), which is what tied_featurize keys on.
Source code in examples/impress_r/mpnn.py
stage_structures
¶
Copy each design's structure into one directory under a unique name.
ProteinMPNN parses a folder of PDBs, and a campaign's paths collide on
basename (every pipeline writes {target}.pdb) and get overwritten pass to
pass. Staging copies each file under its unique design name, so the training
set is a stable snapshot rather than a set of paths whose contents move.
Returns {design_name: staged_path}.
Source code in examples/impress_r/mpnn.py
original_checkpoint
¶
original_checkpoint(model_state_dict: Any, *, num_edges: int = DEFAULT_NUM_NEIGHBORS, noise_level: float = DEFAULT_BACKBONE_NOISE, **extra: Any) -> Dict[str, Any]
The checkpoint dict protein_mpnn_run.py loads.
It reads checkpoint['model_state_dict'] and checkpoint['num_edges']
(used as k_neighbors when constructing the model), so both are required
for the published weights to load at all. noise_level is carried for
parity with the original trainer's saves.
Source code in examples/impress_r/mpnn.py
versioned_checkpoint_path
¶
The round's durable checkpoint — versioned, in its own directory.
Every round writes {model_name}_v{version}.pt into its own output_dir
(the training manager lays these out per version, …/v<version>/), so no
round ever overwrites another's weights and the whole history is kept, with
the version right in the filename. This is the path ROME publishes as the
current model, so rome.Manager.get_current_model (and any reload off
it) points at the exact versioned file.
Source code in examples/impress_r/mpnn.py
repo_pointer_path
¶
The fixed weights path IMPRESS's next pass loads, or None.
mpnn_wrapper.py never passes --path_to_model_weights, so
protein_mpnn_run.py loads {mpnn_repo}/vanilla_model_weights/{model_name}.pt
by default. With publish_into_repo set (and mpnn_repo known) the round
copies its versioned checkpoint onto this fixed path so the next pass runs
the new weights with no wrapper change — a pointer to the latest version, not
the archive: the versioned files in output_dir remain the kept history.
Returns None when the round should not touch the repo.
Source code in examples/impress_r/mpnn.py
impress_corpus_filter
¶
impress_corpus_filter(min_pLDDT: float = 80.0, min_pTM: float = 0.8, max_pAE: float = 5.0) -> Callable[[Dict[str, Any]], bool]
Build the IMPRESS admission predicate for DataConfig.
IMPRESS-R only trains on designs the campaign is confident in, and these are the thresholds IMPRESS already uses to decide a design is worth keeping::
DataConfig(min_samples=24, filter_func=impress_corpus_filter())
Warning
These defaults are known to be too permissive, and are kept only because
a correct replacement cannot be derived yet. Measured against a real
PDZ campaign they admit 83% of records: pLDDT >= 80 alone admits 100%,
because everything reaching the score CSVs has already cleared IMPRESS's
own keep/drop rule — the filter is being applied downstream of itself.
That campaign was run with Boltz, while the branch ROME targets
(archive/ipdps_pdz_usecase) runs AlphaFold2-multimer, and the two
predictors do not share a confidence scale. Prefer percentile_sampler,
which needs no scale; see docs/impress.md.
Source code in examples/impress_r/mpnn.py
score_percentiles
¶
score_percentiles(records: Sequence[Dict[str, Any]], keys: Sequence[str] = ('pLDDT', 'pTM', 'pAE')) -> Dict[str, Dict[str, float]]
Summarise the score distribution a campaign has produced so far.
Calibration data, gathered from the run itself. Every confidence threshold in IMPRESS-R is predictor-specific — AlphaFold2-multimer and Boltz do not share a scale — so the only safe way to set one is to look at what this campaign is producing::
from examples.impress_r.mpnn import score_percentiles
print(score_percentiles(manager.data.get_records()))
Returns {key: {"n", "min", "p10", "p25", "median", "p75", "p90", "max"}},
skipping keys no record carries.
Source code in examples/impress_r/mpnn.py
percentile_sampler
¶
percentile_sampler(fraction: float = 0.33, *, rank_by: Optional[Dict[str, str]] = None, min_shard: int = 8, on_summary: Optional[Callable[[Dict[str, Any]], None]] = None) -> Callable[[List[Dict[str, Any]]], List[Dict[str, Any]]]
Select the best fraction of the corpus, calibrating as it goes.
Use this instead of tuning impress_corpus_filter's thresholds::
DataConfig(min_samples=24, sample_func=percentile_sampler(0.33))
Why a fraction rather than a cutoff. A threshold like pTM >= 0.90
is a claim about a specific predictor's confidence scale, and IMPRESS
campaigns have been run on both AlphaFold2-multimer and Boltz, which do not
share one. A fraction says "the best third of what this campaign has
produced", which needs no scale and calibrates itself on the fly — including
on the first round, before anyone has seen the distribution.
It also sidesteps the trap that makes IMPRESS's own keep/drop thresholds useless here: everything in the corpus already cleared them, so reusing them as an admission filter selects nothing.
Ranking is by average rank across rank_by, not by a weighted sum of
raw values. Rank-averaging is non-parametric, so pTM (0–1) and pAE (Å, open
ended) contribute equally without needing to be normalised, and it is
unaffected by either metric's outliers.
Parameters:
-
fraction(float, default:0.33) –Portion of the corpus to keep, in (0, 1].
-
rank_by(Optional[Dict[str, str]], default:None) –Record field ->
'high'(higher is better) or'low'. Defaults toDEFAULT_RANK_BY. Fields absent from every record are ignored, so a corpus carrying only some of them still ranks. -
min_shard(int, default:8) –Never return fewer than this many records — a strict fraction of a small early corpus can otherwise produce a shard too small to train on. Capped at the corpus size.
-
on_summary(Optional[Callable[[dict], None]], default:None) –Called with
{"corpus", "selected", "ranked_by", "percentiles", "cutoffs"}each time a shard is built. Passprintor a logger to watch the campaign's distribution move, and to read off the thresholds an equivalent fixed filter would have used.
Source code in examples/impress_r/mpnn.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 | |