Skill Tracer
Skills › Scientific Agent Skills › torchdrug › protein_modeling.md

protein_modeling.md

252 lines · skills/torchdrug/references/protein_modeling.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Protein Modeling
2
3TorchDrug 0.2.1 documents protein data structures, datasets, sequence encoders,
4and geometry-aware graph models in its
5[data](https://torchdrug.ai/docs/api/data.html),
6[dataset](https://torchdrug.ai/docs/api/datasets.html), and
7[model](https://torchdrug.ai/docs/api/models.html) APIs. The primary tutorial
8index focuses on molecular and knowledge-graph workflows, so avoid inventing a
9protein tutorial API that upstream does not provide.
11Large dataset and pretrained-weight examples are source-verified illustrations;
12this review does not download protein archives or pretrained ESM weights.

Protein Modeling

TorchDrug 0.2.1 documents protein data structures, datasets, sequence encoders, and geometry-aware graph models in its data, dataset, and model APIs. The primary tutorial index focuses on molecular and knowledge-graph workflows, so avoid inventing a protein tutorial API that upstream does not provide.

Large dataset and pretrained-weight examples are source-verified illustrations; this review does not download protein archives or pretrained ESM weights.

Raw lines 1 to 13
14## Build protein objects

Build protein objects

Raw lines 14 to 15
16### From sequence
18```python
19from torchdrug import data
21protein = data.Protein.from_sequence(
22 "MKTAYIAKQRQISFVKSHFSRQ",
23 atom_feature=None,
24 bond_feature=None,
25 residue_feature="default",
27print(protein.to_sequence())
28```
30For sequence-only work, setting atom and bond features to `None` avoids the cost
31of constructing a full atom-level representation.
32In that fast path, 0.2.1 converts unknown residue symbols to glycine with a
33warning. Validate sequences against the supported 20-residue alphabet first;
34do not allow `X`, gaps, or chain separators to become silently altered biology.
35Also preserve the original sequence separately: the fast path creates no bonds,
36so `to_sequence()` inserts component separators between residues (for example,
37`"M.K.T.A.Y"`). It is not a faithful chain-annotated round trip of this input.

From sequence

from torchdrug import data

protein = data.Protein.from_sequence(
    "MKTAYIAKQRQISFVKSHFSRQ",
    atom_feature=None,
    bond_feature=None,
    residue_feature="default",
)
print(protein.to_sequence())

For sequence-only work, setting atom and bond features to None avoids the cost of constructing a full atom-level representation. In that fast path, 0.2.1 converts unknown residue symbols to glycine with a warning. Validate sequences against the supported 20-residue alphabet first; do not allow X, gaps, or chain separators to become silently altered biology. Also preserve the original sequence separately: the fast path creates no bonds, so to_sequence() inserts component separators between residues (for example, "M.K.T.A.Y"). It is not a faithful chain-annotated round trip of this input.

Raw lines 16 to 38
39### From PDB
41```python
42protein = data.Protein.from_pdb(
43 "protein.pdb",
44 atom_feature="default",
45 bond_feature="default",
46 residue_feature="default",
48```
50Use trusted local PDB files and validate chain selection, missing residues,
51alternate locations, and nonstandard residues before training.
53Documented conversion methods include:
55- `Protein.from_sequence`
56- `Protein.from_pdb`
57- `Protein.from_molecule`
58- `Protein.to_sequence`
59- `Protein.to_pdb`
60- `Protein.to_molecule`
62Packed equivalents operate on lists:
64- `PackedProtein.from_sequence(sequences)`
65- `PackedProtein.from_pdb(pdb_files)`
66- `PackedProtein.from_molecule(mols)`

From PDB

protein = data.Protein.from_pdb(
    "protein.pdb",
    atom_feature="default",
    bond_feature="default",
    residue_feature="default",
)

Use trusted local PDB files and validate chain selection, missing residues, alternate locations, and nonstandard residues before training.

Documented conversion methods include:

  • Protein.from_sequence
  • Protein.from_pdb
  • Protein.from_molecule
  • Protein.to_sequence
  • Protein.to_pdb
  • Protein.to_molecule

Packed equivalents operate on lists:

  • PackedProtein.from_sequence(sequences)
  • PackedProtein.from_pdb(pdb_files)
  • PackedProtein.from_molecule(mols)
Raw lines 39 to 67
68## Protein datasets
70Documented dataset families include:
72- Property / sequence: `BetaLactamase`, `BinaryLocalization`,
73 `SubcellularLocalization`
74- Function / structure: `EnzymeCommission`, `GeneOntology`, `AlphaFoldDB`
75- Structure labels: `Fold`, `SecondaryStructure`
76- Protein-protein: `HumanPPI`, `YeastPPI`, `PPIAffinity`
77- Protein-ligand: `BindingDB`, `PDBBind`
79Example:
81```python
82from torchdrug import datasets, transforms
84dataset = datasets.EnzymeCommission(
85 "~/protein-datasets/",
86 atom_feature=None,
87 bond_feature=None,
88 residue_feature="default",
89 transform=transforms.ProteinView(view="residue"),
91train_set, valid_set, test_set = dataset.split()
92```
94Unlike sequence-only construction, loading a PDB with `atom_feature=None` still
95creates atoms and an atom view. `ProteinView` exposes residue features as
96`graph.node_feature` to sequence models. EC and GO samples contain a single
97multi-hot `"targets"` tensor; see the matching task below. Keep `lazy=False`
98(the default) for EnzymeCommission: its released lazy `get_item` passes the
99options dictionary positionally to `Protein.from_pdb`, an upstream defect.
101Class signatures differ. Options such as `branch`, `test_cutoff`, `lazy`, or
102species/split IDs are dataset-specific; check the API before using them.

Protein datasets

Documented dataset families include:

  • Property / sequence: BetaLactamase, BinaryLocalization, SubcellularLocalization
  • Function / structure: EnzymeCommission, GeneOntology, AlphaFoldDB
  • Structure labels: Fold, SecondaryStructure
  • Protein-protein: HumanPPI, YeastPPI, PPIAffinity
  • Protein-ligand: BindingDB, PDBBind

Example:

from torchdrug import datasets, transforms

dataset = datasets.EnzymeCommission(
    "~/protein-datasets/",
    atom_feature=None,
    bond_feature=None,
    residue_feature="default",
    transform=transforms.ProteinView(view="residue"),
)
train_set, valid_set, test_set = dataset.split()

Unlike sequence-only construction, loading a PDB with atom_feature=None still creates atoms and an atom view. ProteinView exposes residue features as graph.node_feature to sequence models. EC and GO samples contain a single multi-hot "targets" tensor; see the matching task below. Keep lazy=False (the default) for EnzymeCommission: its released lazy get_item passes the options dictionary positionally to Protein.from_pdb, an upstream defect.

Class signatures differ. Options such as branch, test_cutoff, lazy, or species/split IDs are dataset-specific; check the API before using them.

Raw lines 68 to 103
104## Sequence encoders

Sequence encoders

Raw lines 104 to 105
106### ESM
108`models.ESM` is the alias for `EvolutionaryScaleModeling`. The constructor takes
109a directory for downloaded weights, not a checkpoint filename:
111```python
112from torchdrug import models
114model = models.ESM(
115 path="~/model-weights/esm/",
116 model="ESM-2-150M",
117 readout="mean",
119```
121TorchDrug 0.2.1 supports these ESM-2 names:
123- `ESM-2-8M`
124- `ESM-2-35M`
125- `ESM-2-150M`
126- `ESM-2-650M`
127- `ESM-2-3B`
128- `ESM-2-15B`
130It also supports `ESM-1b` and `ESM-1v`. Maximum sequence input is 1022 residues
131before special tokens. Large checkpoints require substantial memory; start with
132`ESM-2-8M` or `ESM-2-35M` for pipeline validation.
133The wrapper warns and truncates each longer sequence to its **first** 1022
134residues; the returned residue features no longer cover the original full chain.
135Use an explicit cropping/chunking policy and retain residue offsets. Its `esm`
136import comes from `fair-esm==2.0.0`, not the modern `esm` SDK. Checkpoint URLs are
137public static files on `dl.fbaipublicfiles.com`; successful HEAD requests do not
138verify their checksums or model inference.

ESM

models.ESM is the alias for EvolutionaryScaleModeling. The constructor takes a directory for downloaded weights, not a checkpoint filename:

from torchdrug import models

model = models.ESM(
    path="~/model-weights/esm/",
    model="ESM-2-150M",
    readout="mean",
)

TorchDrug 0.2.1 supports these ESM-2 names:

  • ESM-2-8M
  • ESM-2-35M
  • ESM-2-150M
  • ESM-2-650M
  • ESM-2-3B
  • ESM-2-15B

It also supports ESM-1b and ESM-1v. Maximum sequence input is 1022 residues before special tokens. Large checkpoints require substantial memory; start with ESM-2-8M or ESM-2-35M for pipeline validation. The wrapper warns and truncates each longer sequence to its first 1022 residues; the returned residue features no longer cover the original full chain. Use an explicit cropping/chunking policy and retain residue offsets. Its esm import comes from fair-esm==2.0.0, not the modern esm SDK. Checkpoint URLs are public static files on dl.fbaipublicfiles.com; successful HEAD requests do not verify their checksums or model inference.

Raw lines 106 to 139
Names a skill esm :135
140### Other sequence models
142Documented classes include:
144- `models.ProteinCNN`
145- `models.ProteinResNet`
146- `models.ProteinLSTM`
147- `models.ProteinBERT`
149These models require explicit input/hidden dimensions. Derive input dimensions
150from the dataset's residue feature configuration.

Other sequence models

Documented classes include:

  • models.ProteinCNN
  • models.ProteinResNet
  • models.ProteinLSTM
  • models.ProteinBERT

These models require explicit input/hidden dimensions. Derive input dimensions from the dataset's residue feature configuration.

Raw lines 140 to 151
152## Structure encoders
154Documented structure-aware models include:
156- `models.GearNet`
157- `models.SchNet`
158- general graph models such as `GCN`, `GAT`, `GIN`, and `RGCN`
160`SchNet` requires `node_position`. `GearNet` requires a graph whose relation and
161geometric feature configuration matches its constructor.
163Use TorchDrug graph-construction and geometry layers to create sequential,
164radius, and nearest-neighbor relations. Do not use a nonexistent
165`protein.residue_graph(...)` method.
167Before training a structure model, inspect:
169```python
170print(protein.num_node)
171print(protein.num_residue)
172print(protein.node_position.shape)
173print(protein.residue_feature.shape)
174```
176Confirm whether nodes represent atoms or residues and ensure the model input
177matches that choice.

Structure encoders

Documented structure-aware models include:

  • models.GearNet
  • models.SchNet
  • general graph models such as GCN, GAT, GIN, and RGCN

SchNet requires node_position. GearNet requires a graph whose relation and geometric feature configuration matches its constructor.

Use TorchDrug graph-construction and geometry layers to create sequential, radius, and nearest-neighbor relations. Do not use a nonexistent protein.residue_graph(...) method.

Before training a structure model, inspect:

print(protein.num_node)
print(protein.num_residue)
print(protein.node_position.shape)
print(protein.residue_feature.shape)

Confirm whether nodes represent atoms or residues and ensure the model input matches that choice.

Raw lines 152 to 178
179## Property-prediction task
181For the EnzymeCommission dataset above, use integer indices into its target
182vector and a sequence encoder. This is an illustrative training setup:
184```python
185from torchdrug import models, tasks
187model = models.ProteinCNN(
188 input_dim=dataset[0]["graph"].residue_feature.shape[-1],
189 hidden_dims=[64, 64],
190 readout="mean",
192task = tasks.MultipleBinaryClassification(
193 model,
194 task=list(range(len(dataset.tasks))),
195 criterion="bce",
196 metric=("auprc@micro", "f1_max"),
198```
200Construct an optimizer and `Engine` to preprocess/train this task. For datasets
201that instead return separately named scalar targets, `PropertyPrediction` with
202`task=dataset.tasks` is appropriate. Choose criteria from the actual target:
204- binary or multi-label classification: BCE, AUPRC/AUROC
205- multiclass classification: CE with `"acc"` or `"mcc"`
206- regression: MSE, MAE/RMSE
208Vector labels require the matching task even for a small dataset; target schema,
209not dataset size, determines the choice. `MultipleBinaryClassification` does
210not implement `PropertyPrediction`'s NaN label mask. Do not feed missing labels
211as NaN or silently replace unknown annotation status with negative labels.

Property-prediction task

For the EnzymeCommission dataset above, use integer indices into its target vector and a sequence encoder. This is an illustrative training setup:

from torchdrug import models, tasks

model = models.ProteinCNN(
    input_dim=dataset[0]["graph"].residue_feature.shape[-1],
    hidden_dims=[64, 64],
    readout="mean",
)
task = tasks.MultipleBinaryClassification(
    model,
    task=list(range(len(dataset.tasks))),
    criterion="bce",
    metric=("auprc@micro", "f1_max"),
)

Construct an optimizer and Engine to preprocess/train this task. For datasets that instead return separately named scalar targets, PropertyPrediction with task=dataset.tasks is appropriate. Choose criteria from the actual target:

  • binary or multi-label classification: BCE, AUPRC/AUROC
  • multiclass classification: CE with "acc" or "mcc"
  • regression: MSE, MAE/RMSE

Vector labels require the matching task even for a small dataset; target schema, not dataset size, determines the choice. MultipleBinaryClassification does not implement PropertyPrediction's NaN label mask. Do not feed missing labels as NaN or silently replace unknown annotation status with negative labels.

Raw lines 179 to 212
213## Workflow checks
2151. Decide sequence-only versus structure-aware modeling.
2162. Configure protein features to match that representation.
2173. Verify dataset splits and sequence identity cutoffs.
2184. Check maximum sequence length before selecting ESM.
2195. Build graph relations explicitly for structure models.
2206. Derive dimensions from the loaded dataset.
2217. Smoke-test one batch before long training.
2228. Record checkpoint name, feature settings, split, and TorchDrug version.

Workflow checks

  1. Decide sequence-only versus structure-aware modeling.
  2. Configure protein features to match that representation.
  3. Verify dataset splits and sequence identity cutoffs.
  4. Check maximum sequence length before selecting ESM.
  5. Build graph relations explicitly for structure models.
  6. Derive dimensions from the loaded dataset.
  7. Smoke-test one batch before long training.
  8. Record checkpoint name, feature settings, split, and TorchDrug version.
Raw lines 213 to 223
224## Common failures

Common failures

Raw lines 224 to 225
226### ESM constructor error
228Use `models.ESM(path=<directory>, model=<supported-name>)`. Do not pass a
229downloaded `.pt` filename as `path`.

ESM constructor error

Use models.ESM(path=<directory>, model=<supported-name>). Do not pass a downloaded .pt filename as path.

Raw lines 226 to 230
231### Out-of-memory error
233Choose a smaller ESM model, reduce batch size, crop or filter long sequences, or
234freeze the encoder and precompute embeddings.

Out-of-memory error

Choose a smaller ESM model, reduce batch size, crop or filter long sequences, or freeze the encoder and precompute embeddings.

Raw lines 231 to 235
236### Missing coordinates
238Sequence-created proteins do not acquire experimental 3D coordinates. Load a PDB
239or another validated structure source before using coordinate-dependent models.

Missing coordinates

Sequence-created proteins do not acquire experimental 3D coordinates. Load a PDB or another validated structure source before using coordinate-dependent models.

Raw lines 236 to 240
241### Relation mismatch
243Build the same relation types expected by the structure model and set
244`num_relation` accordingly.

Relation mismatch

Build the same relation types expected by the structure model and set num_relation accordingly.

Raw lines 241 to 245
246## Source links
248- [Protein data API](https://torchdrug.ai/docs/api/data.html#protein)
249- [Protein datasets](https://torchdrug.ai/docs/api/datasets.html#protein-property-prediction-datasets)
250- [Protein sequence encoders](https://torchdrug.ai/docs/api/models.html#protein-sequence-encoders)
251- [Graph neural networks](https://torchdrug.ai/docs/api/models.html#graph-neural-networks)
252- [TorchDrug 0.2.1 release notes](https://github.com/DeepGraphLearning/torchdrug/releases/tag/v0.2.1)