Skill Tracer
Skills › Scientific Agent Skills › esm › workflows.md

workflows.md

141 lines · skills/esm/references/workflows.md at 5f2bc03

Open on GitHub

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

1# Worked ESM workflows
2
3These recipes target `esm==3.4.1.post1`. Pretrained generation and folding remain
4illustrative; tiny random-model embedding behavior and synthetic downstream
5analysis were executed. Scientific quality requires task-specific evaluation.
6

Worked ESM workflows

These recipes target esm==3.4.1.post1. Pretrained generation and folding remain illustrative; tiny random-model embedding behavior and synthetic downstream analysis were executed. Scientific quality requires task-specific evaluation.

Raw lines 1 to 6
7## Variant library with preserved constraints
8
9Start from an identified parent and an explicit set of mutable positions. This
10example takes a loaded ESM3 `model` and a real `parent_sequence`; positions are
11**0-based Python indices**. A sampled position need not change amino acid, so
12record realized changes as well as masks. The local seed below controls mask
13selection only; it does not seed the hosted model.
15```python
16import random
17from esm.sdk.api import ESMProtein, ESMProteinError, GenerationConfig
19rng = random.Random(17)
20mutable_positions = list(range(len(parent_sequence))) # Exclude fixed sites first.
21variants = {}
22for attempt in range(20):
23 positions = rng.sample(mutable_positions, k=min(3, len(mutable_positions)))
24 if not positions:
25 raise ValueError("No mutable positions")
26 prompt = list(parent_sequence)
27 for position in positions:
28 prompt[position] = "_"
29 prompt = "".join(prompt)
30 result = model.generate(ESMProtein(sequence=prompt), GenerationConfig(
31 track="sequence", num_steps=min(20, len(positions)), temperature=0.7,
32 ))
33 if isinstance(result, ESMProteinError):
34 raise result
35 sequence = result.sequence
36 if sequence is None or len(sequence) != len(parent_sequence) or "_" in sequence:
37 raise ValueError("Incomplete or wrong-length generation")
38 if any(a != "_" and a != b for a, b in zip(prompt, sequence)):
39 raise ValueError("Generation changed a fixed residue")
40 changes = [i for i, (a, b) in enumerate(zip(parent_sequence, sequence)) if a != b]
41 if changes and sequence not in variants:
42 variants[sequence] = {"attempt": attempt, "masks": positions, "changes": changes}
43```
45Deduplicate, retain candidate IDs and rejected attempts, and avoid claiming 20
46attempts yield 20 distinct variants. For a GFP project, use an experimentally
47annotated parent and mapped essential residues: a word such as
48`green_fluorescent_protein` or a chosen range does not enforce chromophore
49chemistry. Function prompts require the model's actual vocabulary.

Variant library with preserved constraints

Start from an identified parent and an explicit set of mutable positions. This example takes a loaded ESM3 model and a real parent_sequence; positions are 0-based Python indices. A sampled position need not change amino acid, so record realized changes as well as masks. The local seed below controls mask selection only; it does not seed the hosted model.

import random
from esm.sdk.api import ESMProtein, ESMProteinError, GenerationConfig

rng = random.Random(17)
mutable_positions = list(range(len(parent_sequence)))  # Exclude fixed sites first.
variants = {}
for attempt in range(20):
    positions = rng.sample(mutable_positions, k=min(3, len(mutable_positions)))
    if not positions:
        raise ValueError("No mutable positions")
    prompt = list(parent_sequence)
    for position in positions:
        prompt[position] = "_"
    prompt = "".join(prompt)
    result = model.generate(ESMProtein(sequence=prompt), GenerationConfig(
        track="sequence", num_steps=min(20, len(positions)), temperature=0.7,
    ))
    if isinstance(result, ESMProteinError):
        raise result
    sequence = result.sequence
    if sequence is None or len(sequence) != len(parent_sequence) or "_" in sequence:
        raise ValueError("Incomplete or wrong-length generation")
    if any(a != "_" and a != b for a, b in zip(prompt, sequence)):
        raise ValueError("Generation changed a fixed residue")
    changes = [i for i, (a, b) in enumerate(zip(parent_sequence, sequence)) if a != b]
    if changes and sequence not in variants:
        variants[sequence] = {"attempt": attempt, "masks": positions, "changes": changes}

Deduplicate, retain candidate IDs and rejected attempts, and avoid claiming 20 attempts yield 20 distinct variants. For a GFP project, use an experimentally annotated parent and mapped essential residues: a word such as green_fluorescent_protein or a chosen range does not enforce chromophore chemistry. Function prompts require the model's actual vocabulary.

Raw lines 7 to 50
51## Structure-conditioned design and screening
53Use the inverse-folding recipe in `esm3-api.md` with an explicit PDB chain and
54cloned coordinates. For each candidate:
561. Confirm length, fixed residues, alphabet, chain mapping and absence of masks.
572. Predict again from a **sequence-only** input. Retaining target coordinates
58 conditions the result and prevents a meaningful round-trip check.
593. Compare matching finite atoms after superposition. Report residue coverage,
60 missing regions, structural deviations and model confidence together.
614. Prioritize designs using a specified, validated assay model or experimental
62 protocol. Increasing total hydrophobic fraction is not a valid generic
63 stability objective; it can promote aggregation or harm solubility.
645. Save candidate sequences as valid FASTA (headers and sequence lines only);
65 put properties, parent IDs, mutations, seeds and model settings in JSON/TSV.
67Coordinate existence is a software-success check, not biological validation.
68Neither confidence nor same-model structure agreement establishes improved
69stability, preserved catalytic function or experimental success. Keep candidate
70selection criteria explicit and plan the relevant wet-lab assay.

Structure-conditioned design and screening

Use the inverse-folding recipe in esm3-api.md with an explicit PDB chain and cloned coordinates. For each candidate:

  1. Confirm length, fixed residues, alphabet, chain mapping and absence of masks.
  2. Predict again from a sequence-only input. Retaining target coordinates conditions the result and prevents a meaningful round-trip check.
  3. Compare matching finite atoms after superposition. Report residue coverage, missing regions, structural deviations and model confidence together.
  4. Prioritize designs using a specified, validated assay model or experimental protocol. Increasing total hydrophobic fraction is not a valid generic stability objective; it can promote aggregation or harm solubility.
  5. Save candidate sequences as valid FASTA (headers and sequence lines only); put properties, parent IDs, mutations, seeds and model settings in JSON/TSV.

Coordinate existence is a software-success check, not biological validation. Neither confidence nor same-model structure agreement establishes improved stability, preserved catalytic function or experimental success. Keep candidate selection criteria explicit and plan the relevant wet-lab assay.

Raw lines 51 to 71
72## Embedding clustering and representative selection
74Compute residue-only features using `embed_sequences` from
75`scripts/esm_embeddings.py`, in memory-bounded batches. Keep a parallel list of
76unique input IDs; do not use an embedding-only cache across model revisions.
77The following consumes a real `(N,D)` finite feature matrix. Synthetic vectors
78were used to validate its small-dataset behavior, not biological clusters.
80```python
81import numpy as np
82from sklearn.cluster import KMeans
83from sklearn.decomposition import PCA
84from sklearn.preprocessing import normalize
86X = np.asarray(embeddings, dtype=float)
87if X.ndim != 2 or len(X) < 2 or X.shape[1] == 0 or not np.isfinite(X).all():
88 raise ValueError("Need at least two finite, nonempty embedding vectors")
89if np.any(np.linalg.norm(X, axis=1) == 0):
90 raise ValueError("Zero embeddings cannot be used for cosine-style comparison")
91X = normalize(X)
92unique_count = len(np.unique(X, axis=0))
93n_clusters = min(5, len(X), unique_count)
94clusterer = KMeans(n_clusters=n_clusters, n_init=10, random_state=42).fit(X)
95labels = clusterer.labels_
96representative_indices = []
97for label in np.unique(labels):
98 indices = np.flatnonzero(labels == label)
99 distances = np.linalg.norm(X[indices] - clusterer.cluster_centers_[label], axis=1)
100 representative_indices.append(int(indices[np.argmin(distances)]))
102# Exploratory coordinates; cluster in the defined feature space, not in t-SNE.
103components = min(2, len(X) - 1, X.shape[1])
104projection = PCA(n_components=components).fit_transform(X)
105```
107The representative indices refer to the original input order. Choose clustering
108settings using task-specific stability checks and biological controls; automatic
109`min(5,...)` is a runnable illustration, not a scientifically chosen cluster
110count. A one-component projection needs a one-dimensional plot. If using t-SNE,
111require `perplexity < N`, record settings and seed, and avoid interpreting visual
112separation as evidence of separate functions.

Embedding clustering and representative selection

Compute residue-only features using embed_sequences from scripts/esm_embeddings.py, in memory-bounded batches. Keep a parallel list of unique input IDs; do not use an embedding-only cache across model revisions. The following consumes a real (N,D) finite feature matrix. Synthetic vectors were used to validate its small-dataset behavior, not biological clusters.

import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import normalize

X = np.asarray(embeddings, dtype=float)
if X.ndim != 2 or len(X) < 2 or X.shape[1] == 0 or not np.isfinite(X).all():
    raise ValueError("Need at least two finite, nonempty embedding vectors")
if np.any(np.linalg.norm(X, axis=1) == 0):
    raise ValueError("Zero embeddings cannot be used for cosine-style comparison")
X = normalize(X)
unique_count = len(np.unique(X, axis=0))
n_clusters = min(5, len(X), unique_count)
clusterer = KMeans(n_clusters=n_clusters, n_init=10, random_state=42).fit(X)
labels = clusterer.labels_
representative_indices = []
for label in np.unique(labels):
    indices = np.flatnonzero(labels == label)
    distances = np.linalg.norm(X[indices] - clusterer.cluster_centers_[label], axis=1)
    representative_indices.append(int(indices[np.argmin(distances)]))

# Exploratory coordinates; cluster in the defined feature space, not in t-SNE.
components = min(2, len(X) - 1, X.shape[1])
projection = PCA(n_components=components).fit_transform(X)

The representative indices refer to the original input order. Choose clustering settings using task-specific stability checks and biological controls; automatic min(5,...) is a runnable illustration, not a scientifically chosen cluster count. A one-component projection needs a one-dimensional plot. If using t-SNE, require perplexity < N, record settings and seed, and avoid interpreting visual separation as evidence of separate functions.

Raw lines 72 to 113
Runs code scripts/esm_embeddings.py :75
114## Function prediction with embeddings
116For a supervised task, curate labels and split homologous sequence groups into
117train/validation/test before fitting a classifier. Fit scalers, PCA, feature
118selection and hyperparameters on training/validation data only; retain an
119independent test set. Report class balance and suitable metrics/calibration,
120not accuracy alone on an arbitrary random split. A pretrained-model benchmark
121also needs an explicit policy for training-set homology and historical leakage.
123ESM3 function annotations are model hypotheses; compare them with experimentally
124supported annotations and assess false positives. Low sampling temperature does
125not turn them into calibrated probabilities. Do not assign names such as
126"kinase" to arbitrary toy sequences and use those as evaluation truth.

Function prediction with embeddings

For a supervised task, curate labels and split homologous sequence groups into train/validation/test before fitting a classifier. Fit scalers, PCA, feature selection and hyperparameters on training/validation data only; retain an independent test set. Report class balance and suitable metrics/calibration, not accuracy alone on an arbitrary random split. A pretrained-model benchmark also needs an explicit policy for training-set homology and historical leakage.

ESM3 function annotations are model hypotheses; compare them with experimentally supported annotations and assess false positives. Low sampling temperature does not turn them into calibrated probabilities. Do not assign names such as "kinase" to arbitrary toy sequences and use those as evaluation truth.

Raw lines 114 to 127
128## Reproducibility record
130Save input identifiers, exact sequences and hashes, selected chain/residue maps,
131model/checkpoint revision or hosted ID, SDK version, mask positions, generated
132candidates, confidence outputs, settings and all applicable seeds. Define whether
133a reported result is synthetic code verification, pretrained inference, or
134experimental validation. Retain errors without presenting failed records as
135completed predictions.
137Sources: [ESM3 generation example](https://github.com/Biohub/esm/blob/main/_assets/ESM3_README.md),
138[ESMC interface](https://github.com/Biohub/esm/blob/main/esm/models/esmc/model.py),
139[scikit-learn leakage guidance](https://scikit-learn.org/stable/common_pitfalls.html),
140[PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html),
141[KMeans](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html).

Reproducibility record

Save input identifiers, exact sequences and hashes, selected chain/residue maps, model/checkpoint revision or hosted ID, SDK version, mask positions, generated candidates, confidence outputs, settings and all applicable seeds. Define whether a reported result is synthetic code verification, pretrained inference, or experimental validation. Retain errors without presenting failed records as completed predictions.

Sources: ESM3 generation example, ESMC interface, scikit-learn leakage guidance, PCA, KMeans.

Raw lines 128 to 141