Overview
You finish with a local marimo app that embeds a pasted sequence with ESMC-300M, names its likely Pfam families from the nearest labelled neighbours and predicts a three-state secondary structure track. Accession queries add proteome annotations and a cached AlphaFold Database record. Each family call carries its neighbour distance and a calibrated confidence label, and both models report a measured margin over a k-mer baseline.
- Cleaned Parquet files for the Pfam seed split, a PISCES secondary structure file and the human proteome, with a printed report of their counts and lengths.
- A resumable ESMC embedding cache, and MLflow runs that record the model, the package version, the batch size and the run time.
- Registered Pfam and secondary structure models with k-mer baseline runs, a metrics table with margins and a distance calibration table.
- A marimo app that answers a pasted sequence with five family calls and a structure track, and an accession with annotations and a cached pLDDT summary.
- A pytest suite that passes on a fresh clone in seconds, plus a README crediting every data source and stating the limits of each prediction.
Tools
- ESM
The current README places its released models under MIT and documents local use. Biohub's hosted platform manages API credits and rate limits separately; no exact hosted price is asserted.
- Hugging Face Datasets
The library is free Apache 2.0 software. Dataset licenses, gated access and any remote storage charges are separate.
- MLflow
The MLflow project is free Apache 2.0 software and can run on a local server. Managed hosting, storage and external model calls have separate charges.
- marimo
The local marimo notebook is free Apache 2.0 software. Hosted products, optional assistants and remote data services have separate terms; their paid entitlements are not established here.
- AlphaFold Protein Structure Database
Database structure data are freely available for academic and commercial reuse under CC-BY-4.0. The open-data tag describes those records, without asserting a license for website software; attribution and EMBL-EBI service terms apply.
Datasets
- Pfam seed random split Kaggle
Labeled protein domain sequences for training and testing the nearest-neighbour family classifier on its provided split.
- Protein Secondary Structure - 2022 Kaggle
Sequences with assigned secondary structures for training and scoring the per-residue predictor.
- Human Proteome Kaggle
Lookup table of human UniProt proteins whose function text and GO terms appear beside an accession query.
Before you begin
Python 3.12 or newer
The esm package requires it, and Python itself is free. Check with python --version, or with py -3.12 --version on Windows.
16 GB of RAM and about 25 GB of free disk
The install, the 1.3 GB ESMC weights, the raw downloads, the embedding cache and the MLflow artifacts share that disk.
An NVIDIA GPU, optional
Every stage runs on a CPU. A GPU turns the overnight embedding jobs into a few hours and keeps the app response short.
A Kaggle account and API token
The account is free. Your token comes from the account settings page and is used only by the kaggle command line tool.
Git and a terminal
Use Bash or zsh on macOS and Linux and PowerShell on Windows. All of these are free.
Working Python and some biology
You should read pandas and NumPy code with ease and know the meaning of a Pfam domain and a UniProt accession.
Stage 01 · setup2.5 hours
Set up the project, Python and the tools
Create an isolated Python 3.12 environment with ESM, Hugging Face Datasets, MLflow, marimo and scikit-learn, and start a local MLflow server.
The esm package on PyPI requires Python 3.12 or newer and PyTorch 2.11 or newer, so check your interpreter before anything else. Create one folder for the whole build and keep every command running from its root.
protein-triage/
app.py # the marimo app
pyproject.toml
requirements.txt
triage/
__init__.py
config.py
tests/
fixtures/
data/
raw/ # Kaggle downloads, never committed
clean/ # Parquet written by the ingest script
cache/ # embeddings and AlphaFold Database responses
reports/ # metrics, predictions, calibrationmkdir -p protein-triage/triage protein-triage/tests/fixtures
cd protein-triage
touch triage/__init__.py
python3.12 -m venv .venv
source .venv/bin/activate
python --versionNew-Item -ItemType Directory -Force protein-triage\triage, protein-triage\tests\fixtures
Set-Location protein-triage
New-Item -ItemType File triage\__init__.py
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1
python --versionThe ESM README puts the default pip install esm at about 5.6 GB, and 4.6 GB of that is the CUDA build of PyTorch. Without an NVIDIA GPU, install PyTorch from its CPU index first, which the README gives as a 0.8 GB build.
| Machine | First command |
|---|---|
| No NVIDIA GPU (any OS, Apple Silicon included) | pip install esm --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple |
| Linux with an NVIDIA GPU | pip install esm |
| Windows with an NVIDIA GPU | pip install torch --index-url https://download.pytorch.org/whl/cu132 and then pip install esm |
esm>=3.5.0
datasets>=5.2.0
mlflow>=3.18.0
marimo>=0.26.0
scikit-learn>=1.9.0
pandas>=2.2
pyarrow>=15
requests>=2.32
pytest>=8
kaggle>=2.2
pip install -r requirements.txt
python -c "import torch, esm, datasets, mlflow, marimo, sklearn; print(torch.__version__, torch.cuda.is_available(), mlflow.__version__, marimo.__version__)"<torch version> <True or False> <mlflow version, 3.18.0 or newer> <marimo version, 0.26.0 or newer>
[project]
name = "protein-triage"
version = "0.1.0"
requires-python = ">=3.12"
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
.venv/
data/
cache/
reports/*.parquet
mlflow.db
mlartifacts/
__pycache__/
.pytest_cache/
Kaggle downloads need an API token from your Kaggle account settings page. Run kaggle auth login for the browser flow, or paste the token into an environment variable for the current shell only.
export KAGGLE_API_TOKEN=paste-your-token-here
kaggle datasets list -s pfam$env:KAGGLE_API_TOKEN = "paste-your-token-here"
kaggle datasets list -s pfamMLflow 3 starts a local tracking server with a SQLite store when you give it no backend. Open a second terminal in the project root and activate the same environment there. Leave this server running for the rest of the build.
mlflow server --host 127.0.0.1 --port 5000Backend store URI not provided. Using sqlite:///mlflow.db Registry store URI not provided. Using backend store URI. ... INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)
"""Paths and settings shared by every script."""
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RAW = ROOT / "data" / "raw"
CLEAN = ROOT / "data" / "clean"
CACHE = ROOT / "cache"
REPORTS = ROOT / "reports"
ESM_MODEL = os.environ.get("TRIAGE_ESM_MODEL", "biohub/ESMC-300M")
MAX_LEN = 1000 # ESMC takes up to 2,046 residues; 1,000 keeps batches in memory
STANDARD = frozenset("ACDEFGHIKLMNPQRSTVWY")
TOP_FAMILIES = 1000
PER_FAMILY = 200
SS_FILE = "2022-12-17-pdb-intersect-pisces_pc25_r2.5.csv"
SS_PROTEINS = 5000
SS_TEST_FRACTION = 0.2
SEED = 7
TRACKING_URI = os.environ.get("MLFLOW_TRACKING_URI", "http://127.0.0.1:5000")
EXPERIMENT = "protein-triage"
PFAM_MODEL = "pfam-family"
SS_MODEL = "ss-three-state"
python --version reports 3.12 or newer, the import line prints versions, kaggle datasets list -s pfam returns a table, and http://127.0.0.1:5000 opens the MLflow UI in a browser.
Stage 02 · data2 hours
Download and inspect the three Kaggle sources
Put the Pfam seed split, the 2022 secondary structure set and the human proteome table under data/raw and read their real columns before writing a loader.
| Dataset | Download | License | Used for |
|---|---|---|---|
googleai/pfam-seed-random-split | 651 MB zip | CC0: Public Domain | Family labels with train, dev and test folders |
kirkdco/protein-secondary-structure-2022 | 446 MB zip | Open Database License (contents: Database Contents License) | Per-residue DSSP states for PISCES-culled chains |
samyakrajbayar/human-proteome | 50 MB zip | CC BY 4.0 | Function text and GO term IDs per UniProt accession |
kaggle datasets download googleai/pfam-seed-random-split -p data/raw/pfam --unzip
kaggle datasets download kirkdco/protein-secondary-structure-2022 -p data/raw/ss --unzip
kaggle datasets download samyakrajbayar/human-proteome -p data/raw/proteome --unzipThe Pfam download holds 200 shard files with no extension, one copy under random_split/ and a second copy of the same shards under random_split/random_split/. Point every loader at one copy only, or each family is counted twice.
data/
raw/
pfam/
random_split/
train/ # data-00000-of-00080 to data-00079-of-00080
dev/ # 10 shards
test/ # 10 shards, the held-out split
random_split/ # duplicate copy, ignored
ss/
2022-12-17-pdb-intersect-pisces_pc25_r2.5.csv
2022-08-03-ss.cleaned.csv # plus five more culled files
proteome/
human_proteins.csv
data_dictionary.csvRead the headers yourself before trusting any column name, including the ones used later. The script prints each header and checks two things in the secondary structure file that change how the loader works.
"""Look at the raw Kaggle files before trusting any column name."""
from collections import Counter
import pandas as pd
from triage import config
SOURCES = {
"pfam": config.RAW / "pfam" / "random_split" / "train" / "data-00000-of-00080",
"ss": config.RAW / "ss" / config.SS_FILE,
"proteome": config.RAW / "proteome" / "human_proteins.csv",
}
def main():
for name, path in SOURCES.items():
head = pd.read_csv(path, nrows=3)
print(f"== {name}: {path.name}, {len(head.columns)} columns")
print(", ".join(head.columns[:12]), "..." if len(head.columns) > 12 else "")
ss = pd.read_csv(SOURCES["ss"], usecols=["seq", "sst8", "sst3", "has_nonstd_aa"])
pairs = Counter(p for a, b in zip(ss["sst8"], ss["sst3"]) for p in zip(a, b))
mapping = {}
for eight, three in pairs:
mapping.setdefault(eight, set()).add(three)
print("sst8 to sst3:", {k: "".join(sorted(v)) for k, v in sorted(mapping.items())})
odd = ss["seq"].str.contains(r"[^ACDEFGHIKLMNPQRSTVWY]")
print(f"rows with letters outside the 20: {int(odd.sum())}; "
f"of those flagged has_nonstd_aa: {int(ss.loc[odd, 'has_nonstd_aa'].sum())}")
if __name__ == "__main__":
main()
python -m triage.inspect_raw== pfam: data-00000-of-00080, 5 columns
family_id, sequence_name, family_accession, aligned_sequence, sequence
== ss: 2022-12-17-pdb-intersect-pisces_pc25_r2.5.csv, 12 columns
pdb_id, chain_code, seq, sst8, sst3, len_x, has_nonstd_aa, len_y, method, resol, rfac, freerfac
== proteome: human_proteins.csv, 60 columns
accession, entry_name, protein_name, gene_names, organism, length, ... go_ids ...
sst8 to sst3: {'B': 'E', 'C': 'C', 'E': 'E', 'G': 'H', 'H': 'H', 'I': 'H', 'S': 'C', 'T': 'C'}
rows with letters outside the 20: <count>; of those flagged has_nonstd_aa: <count>The sst3 column already folds the eight DSSP states into three. Helix takes H, G and I; strand takes E and B; coil takes C, S and T. The loader uses sst3 directly, and the mapping line is your evidence that no state was dropped.
The three folders exist under data/raw/, and python -m triage.inspect_raw prints three headers with 5, 12 and 60 columns. The sst8 to sst3 line maps each of the eight states to one of H, E or C.
Stage 03 · data3 hours
Clean each source and write Parquet
Load every source with Hugging Face Datasets, drop rows ESMC cannot take, cap Pfam at 1,000 families of up to 200 training sequences, split the structures by PDB entry and write Parquet.
ESMC-300M has 2,048 positions, and the tokenizer adds a cls token and an eos token, so 2,046 residues is the hard ceiling. MAX_LEN in config.py is 1,000 because a padded batch of long chains is what runs out of memory first; raise it if your GPU allows.
The loader keeps only the 20 standard residues. ESMC's tokenizer does accept X, B, U, Z and O, yet the three-state labels and the k-mer baseline both assume the standard alphabet, so mixed rows would make the comparison unfair.
"""Read the three Kaggle sources, clean them and write Parquet."""
import re
import numpy as np
import pandas as pd
from datasets import load_dataset
from triage import config
def is_clean(seq: str | None, max_len: int = config.MAX_LEN) -> bool:
return bool(seq) and len(seq) <= max_len and set(seq) <= config.STANDARD
def clean_query(text: str) -> str:
"""Turn pasted text (FASTA or bare letters) into one uppercase sequence."""
lines = [l for l in text.strip().splitlines() if not l.startswith(">")]
seq = re.sub(r"\s+", "", "".join(lines)).upper()
if seq and not is_clean(seq):
bad = sorted(set(seq) - config.STANDARD)
raise ValueError(f"use 20 standard residues, up to {config.MAX_LEN}; found {bad or len(seq)}")
return seq
def _keep(batch, column):
return [is_clean(s) for s in batch[column]]
def load_pfam(raw=config.RAW / "pfam"):
split_dir = raw / "random_split"
files = {s: (split_dir / s / "data-*").as_posix() for s in ("train", "dev", "test")}
ds = load_dataset("csv", data_files=files)
ds = ds.select_columns(["sequence_name", "family_accession", "sequence"])
return ds.filter(_keep, batched=True, fn_kwargs={"column": "sequence"})
def restrict_pfam(train: pd.DataFrame, test: pd.DataFrame, top=config.TOP_FAMILIES,
per=config.PER_FAMILY, seed=config.SEED):
counts = train["family_accession"].value_counts().sort_index()
counts = counts.sort_values(ascending=False, kind="stable")
keep = set(counts.index[:top])
train = train[train["family_accession"].isin(keep)]
train = train.sample(frac=1.0, random_state=seed).groupby("family_accession").head(per)
test = test[test["family_accession"].isin(keep)]
return train.sort_index().reset_index(drop=True), test.reset_index(drop=True)
restrict_pfam ranks families by their training count, keeps the top 1,000, shuffles with a fixed seed and takes up to 200 rows per family. Test rows stay in the dataset's own test split and are kept only for families that survived the cut.
def load_ss(path=config.RAW / "ss" / config.SS_FILE):
ds = load_dataset("csv", data_files=path.as_posix(), split="train")
ds = ds.select_columns(["pdb_id", "chain_code", "seq", "sst3"])
ds = ds.filter(lambda b: [is_clean(s) and len(s) == len(t) for s, t in zip(b["seq"], b["sst3"])],
batched=True)
return ds.rename_columns({"seq": "sequence"})
def split_ss(df: pd.DataFrame, n=config.SS_PROTEINS, test_fraction=config.SS_TEST_FRACTION,
seed=config.SEED) -> pd.DataFrame:
df = df.sample(n=min(n, len(df)), random_state=seed).reset_index(drop=True)
entries = np.array(sorted(df["pdb_id"].unique()))
rng = np.random.default_rng(seed)
test_ids = set(rng.choice(entries, size=int(len(entries) * test_fraction), replace=False))
df["split"] = np.where(df["pdb_id"].isin(test_ids), "test", "train")
return df
PROTEOME_COLUMNS = ["accession", "entry_name", "protein_name", "gene_names", "function",
"go_ids", "sequence_similarity", "sequence", "length"]
def load_proteome(path=config.RAW / "proteome" / "human_proteins.csv"):
ds = load_dataset("csv", data_files=path.as_posix(), split="train", usecols=PROTEOME_COLUMNS)
return ds.map(lambda b: {"embeddable": [is_clean(s) for s in b["sequence"]]}, batched=True)
def main():
config.CLEAN.mkdir(parents=True, exist_ok=True)
pfam = load_pfam()
train, test = restrict_pfam(pfam["train"].to_pandas(), pfam["test"].to_pandas())
for name, df in (("pfam_train", train), ("pfam_test", test)):
df.insert(0, "row_id", range(len(df)))
df.to_parquet(config.CLEAN / f"{name}.parquet", index=False)
ss = split_ss(load_ss().to_pandas())
ss.insert(0, "row_id", range(len(ss)))
ss.to_parquet(config.CLEAN / "ss.parquet", index=False)
load_proteome().to_parquet((config.CLEAN / "proteome.parquet").as_posix())
print("wrote", sorted(p.name for p in config.CLEAN.glob("*.parquet")))
if __name__ == "__main__":
main()
Chains from one PDB entry land on the same side of the split, because two chains of one entry can be near copies. PISCES culling at 25 percent identity already keeps different entries far apart, which makes the held-out proteins a fair test.
Each cleaned file needs its counts printed before any model touches it. The report shows row and label counts with length percentiles for every source, plus the split sizes for the structure set.
"""Print row counts, label counts and length percentiles for every cleaned source."""
import numpy as np
import pandas as pd
from triage import config
LABELS = {
"pfam_train": ("families", lambda df: df["family_accession"].nunique()),
"pfam_test": ("families", lambda df: df["family_accession"].nunique()),
"ss": ("states", lambda df: {k: int(v) for k, v in pd.Series(list("".join(df["sst3"]))).value_counts().items()}),
"proteome": ("similarity families", lambda df: df["sequence_similarity"].dropna().nunique()),
}
def describe(name: str, df: pd.DataFrame) -> str:
label, count = LABELS[name]
p5, p50, p95 = np.percentile(df["sequence"].str.len(), [5, 50, 95]).round().astype(int)
extra = ""
if "split" in df:
extra = " | " + ", ".join(f"{k} {v}" for k, v in df["split"].value_counts().items())
if "embeddable" in df:
extra = f" | embeddable {int(df['embeddable'].sum())}"
return f"{name:<11} rows {len(df):>7} | {label} {count(df)} | length p5/p50/p95 {p5}/{p50}/{p95}{extra}"
def main():
for name in LABELS:
print(describe(name, pd.read_parquet(config.CLEAN / f"{name}.parquet")))
if __name__ == "__main__":
main()
python -m triage.ingest
python -m triage.reportwrote ['pfam_test.parquet', 'pfam_train.parquet', 'proteome.parquet', 'ss.parquet']
pfam_train rows <rows> | families 1000 | length p5/p50/p95 <p5>/<p50>/<p95>
pfam_test rows <rows> | families <up to 1000> | length p5/p50/p95 <p5>/<p50>/<p95>
ss rows 5000 | states {'C': <n>, 'H': <n>, 'E': <n>} | length p5/p50/p95 <p5>/<p50>/<p95> | train <n>, test <n>
proteome rows 20429 | similarity families <n> | length p5/p50/p95 <p5>/<p50>/<p95> | embeddable <n>data/clean/ holds four Parquet files, python -m triage.report prints one line per source, and the pfam_train line reports 1,000 families.
Stage 04 · build2 hours
Load ESMC locally and time it on your hardware
Wrap the smallest ESMC model from the Hugging Face collection in an Embedder class and measure 100 sequences before committing to the full embedding job.
The ESM README links an ESMC collection on Hugging Face with three models: biohub/ESMC-300M, biohub/ESMC-600M and biohub/ESMC-6B. The 300M model has 30 layers and a hidden size of 960, and its weights file is about 1.3 GB.
Load it with EsmcForMaskedLM.from_pretrained and the EsmcTokenizer, the classes the README uses. The hidden states live in last_hidden_state. Position 0 holds the cls token, so residue i sits at position i + 1.
"""Embed sequences with a local ESMC model, one resumable batch file at a time."""
import argparse
import os
import time
from importlib.metadata import version
from pathlib import Path
import numpy as np
import pandas as pd
from triage import config
class Embedder:
def __init__(self, model_name: str = config.ESM_MODEL, device: str | None = None):
import torch
from esm.models.esmc import EsmcForMaskedLM, EsmcTokenizer
self.torch = torch
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
self.model = EsmcForMaskedLM.from_pretrained(model_name, device=self.device).eval()
self.tokenizer = EsmcTokenizer()
self.model_name = model_name
def residues(self, seqs: list[str]) -> list[np.ndarray]:
"""One (length, hidden) array per sequence, without the cls and eos tokens."""
inputs = self.tokenizer(seqs, return_tensors="pt", padding=True)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
with self.torch.inference_mode():
hidden = self.model(**inputs).last_hidden_state.float().cpu().numpy()
return [hidden[i, 1 : len(s) + 1] for i, s in enumerate(seqs)]
def mean(self, seqs: list[str]) -> np.ndarray:
return np.stack([r.mean(axis=0) for r in self.residues(seqs)])
Time a sample before starting a job that may run overnight. The script loads the model and times 100 random training sequences in batches of 16. It then scales that rate by the residue count of each job.
"""Time 100 Pfam sequences and estimate how long each embedding job will take."""
import sys
import time
import pandas as pd
from triage import config
from triage.embed import JOBS, Embedder, batches
def main(batch_size: int = 16):
df = pd.read_parquet(config.CLEAN / "pfam_train.parquet", columns=["row_id", "sequence"])
sample = df.sample(n=100, random_state=config.SEED)
t0 = time.perf_counter()
embedder = Embedder()
load_s = time.perf_counter() - t0
embedder.mean(sample["sequence"].head(2).tolist()) # warm-up call
t0 = time.perf_counter()
for _, chunk in batches(sample, batch_size):
embedder.mean(chunk["sequence"].tolist())
secs = time.perf_counter() - t0
residues = sample["sequence"].str.len().sum()
print(f"model {embedder.model_name} on {embedder.device}, loaded in {load_s:.1f} s")
print(f"100 sequences ({residues} residues) in {secs:.1f} s")
for job, (file, _) in JOBS.items():
total = pd.read_parquet(config.CLEAN / file, columns=["sequence"])["sequence"].str.len().sum()
print(f"estimate for {job}: {total / residues * secs / 3600:.1f} h")
if __name__ == "__main__":
main(int(sys.argv[1]) if len(sys.argv) > 1 else 16)
python -m triage.timingmodel biohub/ESMC-300M on <cpu or cuda>, loaded in <seconds> s 100 sequences (<residues> residues) in <seconds> s estimate for pfam-train: <hours> h estimate for pfam-test: <hours> h estimate for ss: <hours> h
The timing script prints the model name and device followed by three job estimates, and the Hugging Face cache now holds models--biohub--ESMC-300M.
Stage 05 · build4 hours
Run the resumable embedding job
Write mean-pooled vectors for Pfam rows and per-residue vectors for structure rows in numbered batch files that survive a stop, and record each run in MLflow.
Each batch gets a fixed number, and a finished batch is a file on disk. Batches are ordered by sequence length with row_id as the tie-breaker, so a rerun builds the same batches and can skip every file that already exists.
def batches(df: pd.DataFrame, size: int):
"""Fixed batch order: shortest sequences first, ties broken by row_id."""
order = df.assign(n=df["sequence"].str.len()).sort_values(["n", "row_id"], kind="stable")
for start in range(0, len(order), size):
yield start // size, order.iloc[start : start + size]
def write_atomic(path: Path, **arrays):
tmp = path.with_name(path.name + ".tmp")
with open(tmp, "wb") as fh:
np.savez(fh, **arrays)
os.replace(tmp, path) # a stop mid-write leaves only the .tmp file
def run(df: pd.DataFrame, out: Path, embedder, mode: str, size: int) -> dict:
out.mkdir(parents=True, exist_ok=True)
done = skipped = 0
for number, chunk in batches(df, size):
path = out / f"batch_{number:05d}.npz"
if path.exists():
skipped += 1
continue
seqs = chunk["sequence"].tolist()
ids = chunk["row_id"].to_numpy()
if mode == "mean":
write_atomic(path, ids=ids, vectors=embedder.mean(seqs).astype(np.float32))
else:
per = embedder.residues(seqs)
write_atomic(path, ids=ids, lengths=np.array([len(r) for r in per]),
vectors=np.concatenate(per).astype(np.float16))
done += 1
print(f"batch {number:05d} written ({len(seqs)} sequences)", flush=True)
return {"batches_computed": done, "batches_skipped": skipped}
os.replace swaps the finished temporary file into place in one step. A stop in the middle of np.savez leaves only a .tmp file for the next run to overwrite, so a half-written batch never counts as finished.
def load_mean(out: Path, n_rows: int) -> np.ndarray:
"""Stack cached mean vectors so that row i belongs to row_id i."""
X = None
seen = 0
for path in sorted(out.glob("batch_*.npz")):
with np.load(path) as f:
ids, vec = f["ids"], f["vectors"]
if X is None:
X = np.zeros((n_rows, vec.shape[1]), dtype=np.float32)
X[ids] = vec
seen += len(ids)
if seen != n_rows:
raise RuntimeError(f"{out} holds {seen} of {n_rows} rows; finish the embedding job first")
return X
def load_residues(out: Path) -> dict[int, np.ndarray]:
per = {}
for path in sorted(out.glob("batch_*.npz")):
with np.load(path) as f:
parts = np.split(f["vectors"], np.cumsum(f["lengths"])[:-1])
per.update(zip(f["ids"].tolist(), parts))
return per
JOBS = {
"pfam-train": ("pfam_train.parquet", "mean"),
"pfam-test": ("pfam_test.parquet", "mean"),
"ss": ("ss.parquet", "residues"),
}
def main():
import mlflow
parser = argparse.ArgumentParser()
parser.add_argument("job", choices=JOBS)
parser.add_argument("--batch-size", type=int, default=16)
args = parser.parse_args()
file, mode = JOBS[args.job]
df = pd.read_parquet(config.CLEAN / file, columns=["row_id", "sequence"])
mlflow.set_tracking_uri(config.TRACKING_URI)
mlflow.set_experiment(config.EXPERIMENT)
embedder = Embedder()
with mlflow.start_run(run_name=f"embed-{args.job}"):
mlflow.set_tags({"task": "embed", "job": args.job})
mlflow.log_params({"model": embedder.model_name, "esm_version": version("esm"),
"batch_size": args.batch_size, "device": embedder.device,
"rows": len(df), "mode": mode})
start = time.perf_counter()
counts = run(df, config.CACHE / "emb" / args.job, embedder, mode, args.batch_size)
mlflow.log_metrics(counts | {"run_seconds": time.perf_counter() - start})
print(counts)
if __name__ == "__main__":
main()
Structure vectors are stored as float16 to halve their size, since 5,000 chains of per-residue vectors at 960 values each run to a few gigabytes. Pfam vectors stay float32 because each row is one pooled vector.
python -m triage.embed pfam-train --batch-size 16batch 00000 written (16 sequences)
batch 00001 written (16 sequences)
...
{'batches_computed': <n>, 'batches_skipped': 0}Test the resume on purpose with the test split. Start its job, press Ctrl+C after a few batches print, then run the same command again and let it finish.
python -m triage.embed pfam-test --batch-size 16
# press Ctrl+C after a few batches, then run it again:
python -m triage.embed pfam-test --batch-size 16
python -m triage.embed ss --batch-size 8batch 00004 written (16 sequences)
KeyboardInterrupt
...
batch 00005 written (16 sequences)
...
{'batches_computed': <remaining>, 'batches_skipped': <finished before the stop>}cache/emb/pfam-train, cache/emb/pfam-test and cache/emb/ss hold numbered .npz files, a rerun prints batches_computed of 0 with every batch skipped, and the MLflow UI shows embed-* runs with the ESM version as a parameter.
Stage 06 · build2 hours
Build the k-mer baselines for both tasks
Write hashed k-mer count features for whole sequences and for residue windows, so every ESM number has a baseline beside it.
A baseline only counts if it sees the same rows and the same classifier as the ESM run. For Pfam the baseline swaps the 960-value ESM vector for 3-mer counts, and for secondary structure it swaps each residue vector for 1-mer and 2-mer counts in a 15-residue window.
"""k-mer count features: the baseline both ESM models have to beat."""
from sklearn.feature_extraction.text import HashingVectorizer
SEQ_KMERS = HashingVectorizer(analyzer="char", ngram_range=(3, 3), n_features=2**14,
alternate_sign=False, norm="l2", lowercase=False)
WINDOW_KMERS = HashingVectorizer(analyzer="char", ngram_range=(1, 2), n_features=2**12,
alternate_sign=False, norm=None, lowercase=False)
HALF_WINDOW = 7
def sequence_kmers(seqs):
"""3-mer counts per sequence, as a sparse matrix with unit-length rows."""
return SEQ_KMERS.transform(seqs)
def windows(seq: str, half: int = HALF_WINDOW) -> list[str]:
padded = "-" * half + seq + "-" * half
return [padded[i : i + 2 * half + 1] for i in range(len(seq))]
def residue_kmers(seq: str):
"""1-mer and 2-mer counts in a 15-residue window around every residue."""
return WINDOW_KMERS.transform(windows(seq))
HashingVectorizer keeps no vocabulary, so the same function turns training and test rows into features without a fit step. With alternate_sign=False the hashed values stay non-negative counts, and norm="l2" lets the cosine search treat k-mer rows like ESM rows.
python -c "from triage.kmer import sequence_kmers, residue_kmers; print(sequence_kmers(['MKTAYIAKQR']).shape, residue_kmers('MKTAYIAKQR').shape)"(1, 16384) (10, 4096)
The one-line check prints (1, 16384) (10, 4096): one row per sequence for Pfam and one row per residue for the structure task.
Stage 07 · build3.5 hours
Fit the Pfam family index and log both runs
Call each family from its closest training vectors, report top-1, top-5 and macro F1 on the held-out split, and log ESM and k-mer runs to MLflow with their model files.
The family index stores unit-length training vectors and ranks them by cosine distance to a query. Top-1 is the family of the nearest neighbour, and top-5 is the first five distinct families met while walking outward through the 50 nearest neighbours.
"""Nearest-neighbour Pfam family calls with the distance behind each call."""
import numpy as np
from scipy import sparse
from sklearn.base import BaseEstimator
from sklearn.preprocessing import normalize
class FamilyIndex(BaseEstimator):
def __init__(self, k: int = 50, chunk: int = 128):
self.k = k
self.chunk = chunk
def fit(self, X, y, names=None):
self.X_ = normalize(X)
self.y_ = np.asarray(y)
self.names_ = np.asarray(names) if names is not None else self.y_
return self
def kneighbors(self, Q):
"""Cosine distances and indices of the k nearest training rows, nearest first."""
k = min(self.k, self.X_.shape[0])
Q = normalize(Q)
dists, idxs = [], []
for start in range(0, Q.shape[0], self.chunk):
sims = Q[start : start + self.chunk] @ self.X_.T
sims = sims.toarray() if sparse.issparse(sims) else np.asarray(sims)
idx = np.argpartition(-sims, k - 1, axis=1)[:, :k]
part = np.take_along_axis(sims, idx, axis=1)
order = np.argsort(-part, axis=1)
idxs.append(np.take_along_axis(idx, order, axis=1))
dists.append(1.0 - np.take_along_axis(part, order, axis=1))
return np.vstack(dists), np.vstack(idxs)
def rank(self, Q, top: int = 5):
"""For each query, up to `top` distinct families with their nearest neighbour."""
dist, idx = self.kneighbors(Q)
ranked = []
for d_row, i_row in zip(dist, idx):
seen = {}
for d, i in zip(d_row, i_row):
family = self.y_[i]
if family not in seen:
seen[family] = {"family": str(family), "distance": float(d),
"neighbour": str(self.names_[i])}
if len(seen) == top:
break
ranked.append(list(seen.values()))
return ranked
def predict(self, Q):
return np.array([r[0]["family"] for r in self.rank(Q, top=1)])
Every call keeps the distance and the name of the neighbour behind it. The app shows both, and calibration bins turn the distance into a confidence label.
"""Small MLflow helpers shared by the training scripts."""
import mlflow
from triage import config
def start(run_name: str, task: str, features: str):
mlflow.set_tracking_uri(config.TRACKING_URI)
mlflow.set_experiment(config.EXPERIMENT)
run = mlflow.start_run(run_name=run_name)
mlflow.set_tags({"task": task, "features": features})
return run
def log_model(model):
info = mlflow.sklearn.log_model(model, name="model", serialization_format="cloudpickle")
mlflow.set_tag("model_uri", info.model_uri)
return info
"""Fit the Pfam family index on ESM or k-mer vectors and score the held-out split."""
import argparse
import mlflow
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score
from triage import config, tracking
from triage.embed import load_mean
from triage.kmer import sequence_kmers
from triage.pfam_model import FamilyIndex
def features(name: str, split: str, df: pd.DataFrame):
if name == "esm":
return load_mean(config.CACHE / "emb" / f"pfam-{split}", len(df))
return sequence_kmers(df["sequence"])
def evaluate(index: FamilyIndex, Q, truth: np.ndarray):
ranked = index.rank(Q, top=5)
top1 = np.array([r[0]["family"] for r in ranked])
top5 = np.array([t in {c["family"] for c in r} for r, t in zip(ranked, truth)])
metrics = {"top1": float((top1 == truth).mean()), "top5": float(top5.mean()),
"macro_f1": float(f1_score(truth, top1, average="macro"))}
nearest = np.array([r[0]["distance"] for r in ranked])
return metrics, top1, nearest
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--features", choices=["esm", "kmer"], default="esm")
parser.add_argument("--k", type=int, default=50)
args = parser.parse_args()
train = pd.read_parquet(config.CLEAN / "pfam_train.parquet")
test = pd.read_parquet(config.CLEAN / "pfam_test.parquet")
with tracking.start(f"pfam-{args.features}", "pfam", args.features):
mlflow.log_params({"k": args.k, "train_rows": len(train), "test_rows": len(test),
"families": train["family_accession"].nunique(), "model": config.ESM_MODEL})
index = FamilyIndex(k=args.k).fit(features(args.features, "train", train),
train["family_accession"], train["sequence_name"])
metrics, top1, nearest = evaluate(index, features(args.features, "test", test),
test["family_accession"].to_numpy())
mlflow.log_metrics(metrics)
config.REPORTS.mkdir(exist_ok=True)
out = config.REPORTS / f"pfam-{args.features}-test.parquet"
test.assign(predicted=top1, nearest_distance=nearest,
correct=top1 == test["family_accession"]).drop(columns="sequence").to_parquet(out)
mlflow.log_artifact(str(out))
tracking.log_model(index)
print(args.features, metrics)
if __name__ == "__main__":
main()
python -m triage.train_pfam --features esm
python -m triage.train_pfam --features kmeresm {'top1': <top-1>, 'top5': <top-5>, 'macro_f1': <macro F1>}
kmer {'top1': <top-1>, 'top5': <top-5>, 'macro_f1': <macro F1>}The bounty targets 0.85 top-1 and 0.95 top-5 for the ESM run. If top-1 falls short, inspect reports/pfam-esm-test.parquet for families that swap with each other before changing k, because a near-tie between two families shows up as many errors at small distances.
Both commands print three metrics, the MLflow UI lists pfam-esm and pfam-kmer runs under protein-triage with a model artifact each, and reports/ holds one prediction file per run.
Stage 08 · build3.5 hours
Train the per-residue secondary structure classifier
Train a one-hidden-layer classifier on residue vectors from training chains and score its three-state accuracy on held-out chains. Then run the same classifier on k-mer windows.
gather samples up to 300,000 training residues across all training chains with a fixed seed, then stacks their features and labels. Test chains are scored on every residue, so Q3 is the fraction of held-out residues whose state matches sst3.
"""Train the per-residue three-state classifier on ESM or k-mer features."""
import argparse
import mlflow
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn.metrics import accuracy_score, classification_report, f1_score
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from triage import config, tracking
from triage.embed import load_residues
from triage.kmer import residue_kmers
def gather(df: pd.DataFrame, feats, max_residues: int | None = None, seed: int = config.SEED):
"""Stack per-residue features and labels, sampling residues across proteins."""
lengths = df["sequence"].str.len().to_numpy()
total, ends = lengths.sum(), np.cumsum(lengths)
keep = None
if max_residues and total > max_residues:
rng = np.random.default_rng(seed)
keep = np.sort(rng.choice(total, size=max_residues, replace=False))
blocks, labels = [], []
for row, end, n in zip(df.itertuples(), ends, lengths):
if keep is None:
pos = np.arange(n)
else:
pos = keep[np.searchsorted(keep, end - n) : np.searchsorted(keep, end)] - (end - n)
if len(pos):
blocks.append(feats(row)[pos])
labels.append(np.array(list(row.sst3))[pos])
X = sparse.vstack(blocks).tocsr() if sparse.issparse(blocks[0]) else np.vstack(blocks).astype(np.float32)
return X, np.concatenate(labels)
def make_model(is_sparse: bool, seed: int = config.SEED):
return make_pipeline(StandardScaler(with_mean=not is_sparse),
MLPClassifier(hidden_layer_sizes=(256,), early_stopping=True,
max_iter=40, random_state=seed))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--features", choices=["esm", "kmer"], default="esm")
parser.add_argument("--max-residues", type=int, default=300_000)
args = parser.parse_args()
df = pd.read_parquet(config.CLEAN / "ss.parquet")
if args.features == "esm":
per = load_residues(config.CACHE / "emb" / "ss")
feats = lambda row: per[row.row_id].astype(np.float32)
else:
feats = lambda row: residue_kmers(row.sequence)
train, test = df[df["split"] == "train"], df[df["split"] == "test"]
with tracking.start(f"ss-{args.features}", "ss", args.features):
X, y = gather(train, feats, args.max_residues)
Xt, yt = gather(test, feats)
mlflow.log_params({"train_proteins": len(train), "test_proteins": len(test),
"train_residues": len(y), "test_residues": len(yt),
"hidden": 256, "model": config.ESM_MODEL})
model = make_model(sparse.issparse(X)).fit(X, y)
pred = model.predict(Xt)
metrics = {"q3": float(accuracy_score(yt, pred)), "macro_f1": float(f1_score(yt, pred, average="macro"))}
mlflow.log_metrics(metrics)
mlflow.log_text(classification_report(yt, pred, digits=3), "classification_report.txt")
tracking.log_model(model)
print(args.features, metrics)
if __name__ == "__main__":
main()
python -m triage.train_ss --features esm
python -m triage.train_ss --features kmeresm {'q3': <Q3>, 'macro_f1': <macro F1>}
kmer {'q3': <Q3>, 'macro_f1': <macro F1>}The target is 0.72 Q3 on held-out chains. The classification_report.txt artifact in each run shows per-state precision and recall. Strand is often the hardest state, so look there first when Q3 is short.
Both runs print q3 and macro_f1. In the MLflow UI, ss-esm and ss-kmer each carry a model artifact and a classification report.
Stage 09 · test1.5 hours
Register the best runs and compare against the baseline
Register the best run of each task under a champion alias and write the ESM versus k-mer metrics table with run ids and margins.
register.py picks the run with the highest headline metric in each task and registers its model. It then points the champion alias at that version. The app loads models:/pfam-family@champion and models:/ss-three-state@champion, so a better run later needs only a rerun of this script.
"""Register the best run for each task and point the `champion` alias at it."""
import mlflow
from mlflow import MlflowClient
from triage import config
TASKS = {"pfam": ("top1", config.PFAM_MODEL), "ss": ("q3", config.SS_MODEL)}
def main():
mlflow.set_tracking_uri(config.TRACKING_URI)
client = MlflowClient()
for task, (metric, name) in TASKS.items():
best = mlflow.search_runs(experiment_names=[config.EXPERIMENT],
filter_string=f"tags.task = '{task}'",
order_by=[f"metrics.{metric} DESC"], max_results=1).iloc[0]
version = mlflow.register_model(best["tags.model_uri"], name)
client.set_registered_model_alias(name, "champion", version.version)
print(f"{name} v{version.version} <- run {best['run_id']} "
f"({best['tags.features']}, {metric} {best[f'metrics.{metric}']:.3f})")
if __name__ == "__main__":
main()
"""Write the ESM versus k-mer comparison, with MLflow run ids, to reports/metrics.md."""
import mlflow
from triage import config
COLUMNS = {"pfam": ["top1", "top5", "macro_f1"], "ss": ["q3", "macro_f1"]}
HEADLINE = {"pfam": "top1", "ss": "q3"}
def main():
mlflow.set_tracking_uri(config.TRACKING_URI)
margins = []
lines = ["| task | features | metrics | run id |", "| --- | --- | --- | --- |"]
for task, metrics in COLUMNS.items():
runs = mlflow.search_runs(experiment_names=[config.EXPERIMENT],
filter_string=f"tags.task = '{task}'", order_by=["start_time DESC"])
latest = {f: runs[runs["tags.features"] == f].iloc[0] for f in ("esm", "kmer")}
for features, run in latest.items():
values = ", ".join(f"{m} {run[f'metrics.{m}']:.3f}" for m in metrics)
lines.append(f"| {task} | {features} | {values} | `{run['run_id']}` |")
key = f"metrics.{HEADLINE[task]}"
margins.append(f"{task} {HEADLINE[task]} margin, ESM minus k-mer: "
f"{latest['esm'][key] - latest['kmer'][key]:+.3f}")
lines += [""] + margins
config.REPORTS.mkdir(exist_ok=True)
(config.REPORTS / "metrics.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines))
if __name__ == "__main__":
main()
python -m triage.register
python -m triage.metrics_tablepfam-family v1 <- run <run id> (esm, top1 <top-1>) ss-three-state v1 <- run <run id> (esm, q3 <Q3>) | task | features | metrics | run id | | --- | --- | --- | --- | | pfam | esm | top1 <top-1>, top5 <top-5>, macro_f1 <F1> | `<run id>` | | pfam | kmer | top1 <top-1>, top5 <top-5>, macro_f1 <F1> | `<run id>` | | ss | esm | q3 <Q3>, macro_f1 <F1> | `<run id>` | | ss | kmer | q3 <Q3>, macro_f1 <F1> | `<run id>` | pfam top1 margin, ESM minus k-mer: <margin> ss q3 margin, ESM minus k-mer: <margin>
The MLflow Models page lists pfam-family and ss-three-state, each with a champion alias, and reports/metrics.md holds four rows plus two margin lines.
Stage 10 · test2 hours
Calibrate family calls by neighbour distance
Bin held-out Pfam calls into ten distance bins with an accuracy for each. The weakest bins become the app's low-confidence label.
A close neighbour and a distant one both produce a top-1 call, and the calibration table shows how often each kind is right. Bin edges come from distance quantiles, so every bin holds about a tenth of the held-out rows.
"""Accuracy of held-out Pfam calls by neighbour distance, and the low-confidence bins."""
import json
import mlflow
import numpy as np
import pandas as pd
from triage import config, tracking
N_BINS = 10
LOW_ACCURACY = 0.80
def calibration_table(distance: np.ndarray, correct: np.ndarray, n_bins: int = N_BINS) -> pd.DataFrame:
edges = np.unique(np.quantile(distance, np.linspace(0, 1, n_bins + 1)))
bins = np.clip(np.searchsorted(edges, distance, side="right") - 1, 0, len(edges) - 2)
rows = []
for b in range(len(edges) - 1):
hit = correct[bins == b]
rows.append({"bin": b, "low": float(edges[b]), "high": float(edges[b + 1]),
"count": int(hit.size), "accuracy": float(hit.mean()) if hit.size else float("nan")})
table = pd.DataFrame(rows)
weakest = table["accuracy"].idxmin()
table["low_confidence"] = (table["accuracy"] < LOW_ACCURACY) | (table.index == weakest)
return table
def confidence(distance: float, table: list[dict]) -> str:
"""Label one call with the confidence of the bin its distance falls in."""
if distance > table[-1]["high"]:
return "low (farther than any held-out call)"
for row in table:
if distance <= row["high"]:
return "low" if row["low_confidence"] else "normal"
return "low"
def main():
preds = pd.read_parquet(config.REPORTS / "pfam-esm-test.parquet")
table = calibration_table(preds["nearest_distance"].to_numpy(), preds["correct"].to_numpy())
table.to_csv(config.REPORTS / "calibration.csv", index=False)
(config.REPORTS / "calibration.json").write_text(json.dumps(table.to_dict("records"), indent=2))
with tracking.start("pfam-calibration", "calibration", "esm"):
mlflow.log_artifact(str(config.REPORTS / "calibration.csv"))
print(table.to_string(index=False, float_format=lambda v: f"{v:.3f}"))
if __name__ == "__main__":
main()
python -m triage.calibratebin low high count accuracy low_confidence 0 <low> <high> <count> <acc> False ... 9 <low> <high> <count> <acc> True
A query farther from every training vector than any held-out call gets its own low label, because the table holds no evidence about that distance. Change LOW_ACCURACY if your own triage needs a stricter line, and record the value you chose in the README.
reports/calibration.csv and reports/calibration.json exist, the printed table has ten rows with at least one marked True, and accuracy falls as distance grows across most of the bins.
Stage 11 · build2.5 hours
Add proteome and AlphaFold Database lookups
Return the proteome annotations and GO IDs for any UniProt accession, plus a disk-cached summary of its AlphaFold Database record, with clear results for missing and malformed input.
The AlphaFold Database API answers GET /api/prediction/{qualifier} with a JSON list of model records keyed on UniProt accession. globalMetricValue is the mean pLDDT, and the four fractionPlddt fields give the share of residues above 90, from 70 to 90, from 50 to 70 and below 50.
curl -s https://alphafold.ebi.ac.uk/api/prediction/P69905[{"toolUsed":"AlphaFold Monomer v2.0 pipeline", ... "entryId":"AF-P69905-F1", ... "globalMetricValue":<mean pLDDT>, ... "latestVersion":<version>, ... "cifUrl":"https://alphafold.ebi.ac.uk/files/AF-P69905-F1-model_v<version>.cif", ...}]An accession with no prediction returns HTTP 404 with an empty object, and a string that is no accession at all returns HTTP 400. The client checks the UniProt accession pattern first, so malformed input never reaches the network.
"""AlphaFold Database lookups, cached on disk so a repeat query stays local."""
import json
import re
import requests
from triage import config
API = "https://alphafold.ebi.ac.uk/api/prediction/{}"
ACCESSION = re.compile(r"[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}")
FIELDS = ["entryId", "uniprotDescription", "globalMetricValue", "fractionPlddtVeryHigh",
"fractionPlddtConfident", "fractionPlddtLow", "fractionPlddtVeryLow",
"latestVersion", "modelCreatedDate", "cifUrl", "paeImageUrl"]
def fetch(accession: str, cache_dir=config.CACHE / "afdb", session=requests) -> dict:
accession = accession.strip().upper()
if not ACCESSION.fullmatch(accession):
return {"status": "invalid", "accession": accession, "from_cache": False}
path = cache_dir / f"{accession}.json"
if path.exists():
return json.loads(path.read_text()) | {"from_cache": True}
response = session.get(API.format(accession), timeout=30)
if response.status_code == 404:
record = {"status": "missing", "accession": accession}
else:
response.raise_for_status()
first = response.json()[0]
record = {"status": "ok", "accession": accession} | {k: first.get(k) for k in FIELDS}
cache_dir.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(record, indent=2))
return record | {"from_cache": False}
Missing records are cached too, so a repeat query for an accession without a prediction stays local. Delete cache/afdb/ to refresh everything after a database release.
"""Function text and GO terms from the cleaned proteome table."""
import pandas as pd
from triage import config
class Proteome:
def __init__(self, df: pd.DataFrame):
self.df = df.set_index("accession")
@classmethod
def load(cls, path=config.CLEAN / "proteome.parquet"):
return cls(pd.read_parquet(path))
def get(self, accession: str) -> dict | None:
accession = accession.strip().upper()
if accession not in self.df.index:
return None
row = self.df.loc[accession]
go = [g.strip() for g in str(row["go_ids"] or "").split(";") if g.strip()]
return {"accession": accession, "name": row["protein_name"], "genes": row["gene_names"],
"function": row["function"], "go_ids": go, "family": row["sequence_similarity"],
"length": int(row["length"]), "embeddable": bool(row["embeddable"])}
python -c "from triage import afdb; print([afdb.fetch('P69905')['from_cache'] for _ in range(2)], afdb.fetch('P0DPR3')['status'])"[False, True] missing
The first fetch of P69905 reports False and the second True, cache/afdb/P69905.json exists, and P0DPR3 returns missing without raising.
Stage 12 · build4.5 hours
Build the marimo app
Wrap the champion models in one predict call, then serve a marimo app with a sequence box, an accession field, a family table with confidence, a secondary structure track and the attribution footer.
The app and the benchmark call the same Triage.predict, so the time the app shows is the time the benchmark measures. One ESMC pass gives the residue vectors. Their mean feeds the family index, and the vectors themselves feed the structure classifier.
"""One call from a pasted sequence to family calls and a secondary structure track."""
import json
import time
import numpy as np
from triage import config
from triage.calibrate import confidence
class Triage:
def __init__(self, embedder, family_index, ss_model, calibration: list[dict]):
self.embedder = embedder
self.family_index = family_index
self.ss_model = ss_model
self.calibration = calibration
@classmethod
def from_registry(cls):
import mlflow
from triage.embed import Embedder
mlflow.set_tracking_uri(config.TRACKING_URI)
load = lambda name: mlflow.sklearn.load_model(f"models:/{name}@champion")
calibration = json.loads((config.REPORTS / "calibration.json").read_text())
return cls(Embedder(), load(config.PFAM_MODEL), load(config.SS_MODEL), calibration)
def families(self, residues: np.ndarray, top: int = 5) -> list[dict]:
calls = self.family_index.rank(residues.mean(axis=0, keepdims=True), top=top)[0]
return [c | {"confidence": confidence(c["distance"], self.calibration)} for c in calls]
def secondary_structure(self, residues: np.ndarray) -> str:
return "".join(self.ss_model.predict(residues.astype(np.float32)))
def predict(self, seq: str) -> dict:
start = time.perf_counter()
residues = self.embedder.residues([seq])[0]
result = {"families": self.families(residues), "ss": self.secondary_structure(residues)}
return result | {"seconds": time.perf_counter() - start}
"""Median response time of the app's predict call for a 300-residue human protein."""
import statistics
import pandas as pd
from triage import config
from triage.predict import Triage
def main(runs: int = 11):
proteome = pd.read_parquet(config.CLEAN / "proteome.parquet")
row = proteome[(proteome["length"] == 300) & proteome["embeddable"]].iloc[0]
triage = Triage.from_registry()
triage.predict(row["sequence"]) # warm-up
times = [triage.predict(row["sequence"])["seconds"] for _ in range(runs)]
print(f"{row['accession']} (300 residues): median {statistics.median(times):.2f} s over {runs} runs")
if __name__ == "__main__":
main()
python -m triage.bench<accession> (300 residues): median <seconds> s over 11 runs
A marimo notebook is a Python file of cells that rerun when the values they read change. UI elements must be assigned to global variables so other cells can read their .value, which is why seq_box and acc_box are returned from their cell.
import marimo
__generated_with = "0.26.0"
app = marimo.App(width="medium", app_title="Protein triage")
@app.cell
def _():
import marimo as mo
from triage import afdb
from triage.ingest import clean_query
from triage.lookup import Proteome
from triage.predict import Triage
return Proteome, Triage, afdb, clean_query, mo
@app.cell
def _(Proteome, Triage, mo):
with mo.status.spinner(title="Loading ESMC and the registered models"):
triage = Triage.from_registry()
proteome = Proteome.load()
return proteome, triage
@app.cell
def _(mo):
seq_box = mo.ui.text_area(placeholder="Paste a protein sequence or a FASTA record",
label="Sequence", rows=6, full_width=True)
acc_box = mo.ui.text(placeholder="P69905", label="UniProt accession")
mo.vstack([mo.md("# Protein triage"), seq_box, acc_box])
return acc_box, seq_box
mo.stop halts a cell and shows its second argument, so an empty box shows nothing and a bad sequence shows the parser's message. The track prints 60 residues per line with the predicted states under them.
@app.cell
def _(clean_query, mo, seq_box, triage):
try:
seq, problem = clean_query(seq_box.value), None
except ValueError as err:
seq, problem = "", mo.md(f"**Cannot read that sequence:** {err}").callout(kind="danger")
mo.stop(not seq, problem)
result = triage.predict(seq)
rows = [{"rank": i + 1, "family": c["family"], "distance": round(c["distance"], 4),
"nearest neighbour": c["neighbour"], "confidence": c["confidence"]}
for i, c in enumerate(result["families"])]
track = "\n\n".join(f"{n + 1:>5} {seq[n:n + 60]}\n {result['ss'][n:n + 60]}"
for n in range(0, len(seq), 60))
mo.vstack([
mo.md(f"## Family calls ({len(seq)} residues, {result['seconds']:.2f} s)"),
mo.ui.table(rows, selection=None, pagination=False),
mo.md("## Secondary structure (H helix, E strand, C coil)"),
mo.md(f"```text\n{track}\n```"),
])
return
@app.cell
def _(acc_box, afdb, mo, proteome):
accession = acc_box.value.strip().upper()
mo.stop(not accession)
entry = proteome.get(accession)
record = afdb.fetch(accession)
parts = [mo.md(f"## {accession}")]
if entry:
parts.append(mo.md(f"**{entry['name']}** ({entry['genes']})\n\n{entry['function']}\n\n"
f"GO terms: {', '.join(entry['go_ids']) or 'none listed'}"))
else:
parts.append(mo.md("This accession is not in the human proteome table.").callout(kind="warn"))
if record["status"] == "ok":
source = "disk cache" if record["from_cache"] else "AlphaFold Database API"
parts.append(mo.md(
f"AlphaFold Database entry `{record['entryId']}` (model v{record['latestVersion']}): "
f"mean pLDDT **{record['globalMetricValue']:.1f}**, "
f"{record['fractionPlddtVeryHigh']:.0%} of residues above 90. Served from the {source}."))
elif record["status"] == "missing":
parts.append(mo.md("The AlphaFold Database has no prediction for this accession.").callout(kind="warn"))
else:
parts.append(mo.md("That is not a valid UniProt accession.").callout(kind="danger"))
mo.vstack(parts)
return
@app.cell
def _(mo):
mo.md("""
---
Structure confidence comes from the AlphaFold Protein Structure Database (EMBL-EBI and
Google DeepMind), used under CC BY 4.0. Cite Jumper et al., Nature 2021, and Varadi et al.,
Nucleic Acids Research 2021. Embeddings come from ESMC (Biohub, MIT licence). Every output
here is a computational prediction and does not replace a laboratory measurement.
""")
return
if __name__ == "__main__":
app.run()
marimo edit app.py
marimo run app.pyRunning app.py URL: http://localhost:2718
python -c "import pandas as pd; print(pd.read_parquet('data/clean/proteome.parquet').set_index('accession').loc['P69905', 'sequence'])"- Open the URL that
marimo runprints and wait for the loading spinner to clear. - Paste the sequence of
P69905fromdata/clean/proteome.parquetinto the sequence box and read the family table and the structure track. - Type
P69905into the accession field and check the function text and GO IDs above the mean pLDDT line. - Type
P69905again in a new browser tab and check that the pLDDT line now says it came from the disk cache. - Type
P0DPR3and check for the warning that the AlphaFold Database has no prediction.
A pasted 300-residue sequence returns five family rows with distances and confidence labels, plus an H, E, C track, in under ten seconds. A repeat accession query reports the disk cache as its source.
Stage 13 · test2.5 hours
Test on a clean checkout with a ten-sequence fixture
Cover the loaders, the embedding cache, both prediction functions, the calibration labels and the AlphaFold client with pytest tests that run offline, without model weights or an MLflow server.
The fixture holds ten real Pfam seed domains, two from each of five families, taken from one test shard of the CC0 Pfam split. A fake embedder one-hot encodes residues, so the cache and prediction code run end to end in seconds.
sequence_name,family_accession,sequence
C1N8T9_MICPC/93-154,PF00013.29,QQIVECPKDMVGRVIGRGGETIKGLQSQTGARIQIDQSVSPCLITITGNPYCVDAASRAVVD
RNY_TREPA/195-256,PF00013.29,VSTVNLPSEEMKGRIIGREGRNIRALETLTGADVVVDDTPEAVVISCFDPVRKEIARISLER
M3XKL0_LATCH/67-107,PF00020.18,CPADHYTQVWNYIEKCQYCNNFCKRDQYVKHECNATHNRVC
F7G4F9_MONDO/39-74,PF00020.18,CADQQYYEPRHEVCCSRCPPGMHVLEFCNRHRNTTC
O16004_LYTVA/1849-1892,PF00023.30,DGLTPLMLAVMRSKASITDQEEETHAHFIEDLITRGGDINHRTE
ANR24_HUMAN/213-245,PF00023.30,QGRTALMLACEGASPETVEVLLQGGAQPGITDA
MMP1_HUMAN/426-466,PF00045.19,VDAVFMKDGFFYFFHGTRQYKFDPKTKRILTLQKANSWFNC
HE_PARLI/521-565,PF00045.19,VEAVVRADRNYIHFYRDGRYYRMTDYGRQFVNFPNGLPYSDVIES
LAMB1_DROME/418-475,PF00053.24,CDCDPQGSSDDGICDSLNELEEGAVAGACHCKAFVTGRRCNQCKDGYWNLQSDNPEGC
LAMC1_MOUSE/933-978,PF00053.24,CDCHALGSTNGQCDIRTGQCECQPGITGQHCERCETNHFGFGPEGC
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
ALPHABET = "ACDEFGHIKLMNPQRSTVWY"
class FakeEmbedder:
"""Stands in for ESMC: one-hot residues, so tests run in seconds without weights."""
def __init__(self, fail_after: int | None = None):
self.calls = 0
self.fail_after = fail_after
def residues(self, seqs):
if self.fail_after is not None and self.calls >= self.fail_after:
raise KeyboardInterrupt("simulated stop")
self.calls += 1
eye = np.eye(len(ALPHABET), dtype=np.float32)
return [eye[[ALPHABET.index(c) for c in s]] for s in seqs]
def mean(self, seqs):
return np.stack([r.mean(axis=0) for r in self.residues(seqs)])
@pytest.fixture
def ten() -> pd.DataFrame:
df = pd.read_csv(Path(__file__).parent / "fixtures" / "ten.csv")
return df.assign(row_id=range(len(df)))
@pytest.fixture
def fake():
return FakeEmbedder()
@pytest.fixture
def make_fake():
return FakeEmbedder
import pytest
from triage.ingest import clean_query, is_clean, restrict_pfam
def test_is_clean_rejects_nonstandard_and_long():
assert is_clean("ACDEFGHIK")
assert not is_clean("ACDXK")
assert not is_clean("A" * 1001)
assert not is_clean("")
def test_clean_query_reads_fasta():
assert clean_query(">sp|P1|demo\nacde\nfghik\n") == "ACDEFGHIK"
with pytest.raises(ValueError):
clean_query("ACDJ")
def test_restrict_pfam_caps_families_and_rows(ten):
train, test = restrict_pfam(ten, ten, top=3, per=1)
assert train["family_accession"].nunique() == 3
assert train.groupby("family_accession").size().max() == 1
assert set(test["family_accession"]) <= set(train["family_accession"])
The resume test stops the job after two of four batches, then checks that a second run computes only the two missing batches. Run the suite after every change to embed.py, since this test is the only automatic check on the resume.
import pytest
from triage.embed import load_mean, load_residues, run
def test_resume_skips_finished_batches(ten, tmp_path, make_fake):
with pytest.raises(KeyboardInterrupt):
run(ten, tmp_path, make_fake(fail_after=2), "mean", size=3)
assert len(list(tmp_path.glob("batch_*.npz"))) == 2
second = make_fake()
counts = run(ten, tmp_path, second, "mean", size=3)
assert counts == {"batches_computed": 2, "batches_skipped": 2}
assert second.calls == 2
X = load_mean(tmp_path, len(ten))
assert X.shape == (10, 20)
def test_residue_cache_keeps_lengths(ten, tmp_path, fake):
run(ten, tmp_path, fake, "residues", size=4)
per = load_residues(tmp_path)
assert {i: len(v) for i, v in per.items()} == dict(zip(ten["row_id"], ten["sequence"].str.len()))
import numpy as np
from triage.calibrate import calibration_table, confidence
from triage.pfam_model import FamilyIndex
from triage.predict import Triage
from triage.train_ss import make_model
HELIX, STRAND = set("AELMQKR"), set("VIYFWT")
def toy_labels(seq):
return "".join("H" if c in HELIX else "E" if c in STRAND else "C" for c in seq)
def build(ten, fake):
index = FamilyIndex(k=5).fit(fake.mean(ten["sequence"].tolist()),
ten["family_accession"], ten["sequence_name"])
X = np.vstack(fake.residues(ten["sequence"].tolist()))
y = np.array(list("".join(toy_labels(s) for s in ten["sequence"])))
ss = make_model(False).fit(X, y)
table = calibration_table(np.linspace(0, 0.5, 20), np.arange(20) < 15).to_dict("records")
return Triage(fake, index, ss, table)
def test_training_sequence_finds_its_own_family(ten, fake):
triage = build(ten, fake)
first = ten.iloc[0]
result = triage.predict(first["sequence"])
calls = result["families"]
assert calls[0]["family"] == first["family_accession"]
assert calls[0]["distance"] < 1e-6
assert len({c["family"] for c in calls}) == len(calls) <= 5
assert {c["confidence"] for c in calls} <= {"normal", "low", "low (farther than any held-out call)"}
def test_secondary_structure_track_matches_length(ten, fake):
triage = build(ten, fake)
seq = ten.iloc[3]["sequence"]
track = triage.predict(seq)["ss"]
assert len(track) == len(seq) and set(track) <= set("HEC")
def test_weakest_bins_are_low_confidence():
table = calibration_table(np.linspace(0, 1, 100), np.arange(100) < 70)
assert table["low_confidence"].iloc[-1] and not table["low_confidence"].iloc[0]
rows = table.to_dict("records")
assert confidence(0.0, rows) == "normal"
assert confidence(0.99, rows) == "low"
assert confidence(5.0, rows).startswith("low")
from triage import afdb
class FakeResponse:
def __init__(self, status, payload):
self.status_code, self.payload = status, payload
def json(self):
return self.payload
def raise_for_status(self):
assert self.status_code < 400
class FakeSession:
def __init__(self, status, payload):
self.calls = 0
self.response = FakeResponse(status, payload)
def get(self, url, timeout):
self.calls += 1
return self.response
def test_repeat_query_comes_from_cache(tmp_path):
session = FakeSession(200, [{"entryId": "AF-P69905-F1", "globalMetricValue": 98.0}])
first = afdb.fetch("p69905", tmp_path, session)
second = afdb.fetch("P69905", tmp_path, session)
assert first["status"] == "ok" and not first["from_cache"]
assert second["from_cache"] and second["globalMetricValue"] == 98.0
assert session.calls == 1
def test_missing_and_invalid_accessions(tmp_path):
assert afdb.fetch("P0DPR3", tmp_path, FakeSession(404, {}))["status"] == "missing"
assert afdb.fetch("not-an-id", tmp_path, FakeSession(200, []))["status"] == "invalid"
git clone <your repository> /tmp/triage-check
cd /tmp/triage-check
python -m venv .venv
source .venv/bin/activate
pip install esm --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple
pip install -r requirements.txt
pytest -q.......... [100%] 10 passed in <seconds>s
pytest -q reports 10 passed in well under a minute on the fresh clone, with no MLflow server running and the network switched off.
Stage 14 · ship1.5 hours
Write the README and ship the repository
Commit the code with a README that explains each prediction, lists MLflow run ids and licenses, credits the AlphaFold Database and states the limits.
The README is where a reader learns what each number means and where it stops meaning anything. Paste reports/metrics.md and the calibration table into it, and keep the MLflow run ids so anyone with your store can open the exact runs.
# Protein triage
A local marimo app that embeds a pasted protein sequence with ESMC-300M, calls its Pfam family
from the nearest labelled training domains, predicts a three-state secondary structure track,
and, for a UniProt accession, shows proteome annotations and the AlphaFold Database record.
## How each prediction is made
- **Pfam family.** Mean-pooled ESMC vector, cosine distance to 200 or fewer training domains in
each of the 1,000 most frequent families. Top-1 is the nearest neighbour's family.
- **Confidence.** The nearest distance is looked up in `reports/calibration.csv`. Bins under
0.80 held-out accuracy, and the worst bin, are labelled low.
- **Secondary structure.** A 256-unit MLP on each residue's ESMC vector, trained on PISCES chains
(25% identity, 2.5 A) and scored on chains from other PDB entries.
## Results
<paste reports/metrics.md here>
Registered models: `pfam-family@champion`, `ss-three-state@champion`.
Median response time for a 300-residue sequence: <your median> s on <your hardware>.
## Data and licenses
- Pfam seed random split (Google, Kaggle `googleai/pfam-seed-random-split`): CC0.
- Protein Secondary Structure 2022 (Kaggle `kirkdco/protein-secondary-structure-2022`): ODbL,
contents under the Database Contents License.
- Human Proteome (Kaggle `samyakrajbayar/human-proteome`, from UniProtKB/Swiss-Prot): CC BY 4.0.
- ESMC weights (Biohub): MIT, with the third-party notice linked from the model card.
- AlphaFold Protein Structure Database (EMBL-EBI, Google DeepMind): CC BY 4.0. Cite Jumper et al.,
Nature (2021) and Varadi et al., Nucleic Acids Research (2021).
## Limits
Every output is a computational prediction. A family call says which labelled domains a sequence
resembles, a structure track is a per-residue guess, and a pLDDT value is AlphaFold's own
confidence in a predicted model. None of them replaces a laboratory measurement.
git init
git status --short
git add app.py pyproject.toml requirements.txt .gitignore README.md triage tests reports/metrics.md reports/calibration.csv
git commit -m "Protein triage app with ESMC, Pfam calls and AlphaFold Database records"git log shows one commit, git status --short lists nothing large, and the README names both registered models, all four run ids, the three dataset licenses, the AlphaFold Database citation and the laboratory disclaimer.
Troubleshooting
Loading biohub/ESMC-300M fails with 401 Client Error and Repository Not Found, often with a line saying a user access token is expired.
The model is public, so an old Hugging Face token in your environment or credential store is the problem. Remove it from HF_TOKEN, or set HF_HUB_DISABLE_IMPLICIT_TOKEN=1 for the shell, and run the command again.
A script finishes its work and then crashes with UnicodeEncodeError: 'charmap' codec can't encode character on Windows.
MLflow prints run links with emoji when a run ends, and a redirected Windows console cannot encode them. Set PYTHONUTF8=1 (in PowerShell, $env:PYTHONUTF8 = "1") before running the scripts.
Training or the app fails with a connection error to 127.0.0.1:5000, or with a registered model that cannot be found.
Start mlflow server --host 127.0.0.1 --port 5000 from the project root in a second terminal. If the server runs, rerun python -m triage.register so both champion aliases exist.
The embedding job stops with CUDA out of memory, or the machine starts swapping near the end of a job.
Batches are sorted by length, so the last ones are the longest. Rerun the same job with a smaller --batch-size; finished batches are skipped, and only the remaining ones use the new size.
RuntimeError: cache/emb/pfam-test holds N of M rows; finish the embedding job first.
A job stopped before its last batch. Rerun python -m triage.embed with the same job name, and delete any leftover .npz.tmp file only while no job is running.
torch.cuda.is_available() prints False on a Windows machine with an NVIDIA GPU.
PyPI's Windows wheel of PyTorch is CPU-only. Run pip uninstall torch, install it from the CUDA index (for example https://download.pytorch.org/whl/cu132), and check the version line again.
kaggle datasets download fails with 401 or 403.
The CLI found no valid token. Run kaggle auth login, or set KAGGLE_API_TOKEN in the same shell, then retry the download.
marimo run app.py reports that the port is already in use.
Another marimo session holds port 2718. Stop it, or start this one with marimo run app.py --port 2719.
Done when
- The ingest script prints row counts and family counts for every cleaned source.
- The embedding job resumes after a mid-run stop without recomputing finished batches.
- Top-1 Pfam family accuracy on the held-out split is at least 0.85, and the ESM model beats the k-mer baseline by a reported margin.
- Three-state secondary structure accuracy on held-out proteins is at least 0.72 and sits in MLflow beside the baseline run.
- The marimo app returns families, neighbours and a secondary structure track for a pasted sequence.
- An accession query shows proteome function text and the AlphaFold Database confidence, and a repeat query is served from the cache.
- The pytest suite passes on a clean checkout using the ten-sequence fixture.
- The calibration table reports accuracy for each distance bin, and the app marks matches in the weakest bins as low confidence.
Deliverables
- A Git repository with loaders, the embedding job, training scripts, the marimo app and tests.
- An MLflow store holding registered models for both tasks and their baseline runs.
- A metrics table comparing ESM vectors with the k-mer baseline on both tasks.
- A README write-up covering data licenses, AlphaFold Database attribution and the limits of each prediction.
How to measure it
Report top-1 and top-5 Pfam family accuracy and macro F1 on the held-out split, with targets of 0.85 top-1 and 0.95 top-5. Report three-state per-residue accuracy on proteins absent from training, with a 0.72 target. Measure median app response time for a 300-residue sequence and keep it under ten seconds on the reader's machine.
Going further
- Fit the calibration bins on the Pfam dev split and report the low-confidence rate on the test split, so the labels are checked on rows they never saw.
- Add a FASTA upload that triages many sequences in one batch and exports the family calls and confidence labels as a CSV.
- Show the per-residue pLDDT from the AlphaFold confidence file as a second track under the predicted secondary structure.
- Compare ESMC-300M with ESMC-600M by rerunning the embedding and training stages into a new cache folder and adding both to the metrics table.
Bounty stretch goals
- Use ESM's folding mode on sequences without an AlphaFold Database record, and compare its confidence with database records for 50 shared proteins.
- Extend the Pfam index to every family in the training data and measure how query time and top-1 accuracy change.
- Wrap the pipeline in DVC stages so a new ESM release reruns ingest, embedding and training with one command.
- Train a GO term predictor on the proteome table if its columns include sequences, and report precision at five.
References
- ESM README (Biohub/esm)
- ESM v3.5.0 release notes
- esm on PyPI
- ESMC-300M model card
- PyTorch wheel index
- Hugging Face Datasets: Load
- MLflow tracking server
- mlflow.sklearn API reference
- MLflow Model Registry workflow
- marimo key concepts
- marimo text area reference
- AlphaFold Database API (OpenAPI)
- AlphaFold Database data README: licence and citation
- UniProt accession numbers
- Kaggle CLI authentication
- Kaggle CLI datasets commands
- Pfam seed random split on Kaggle
- Protein Secondary Structure 2022 on Kaggle
- Human Proteome on Kaggle
Reporting behind this quest
- ESM speeds up protein folding, with settings worth keeping 2026-11-25 · source
- ESM's current package connects protein representations with structure prediction 2026-11-25 · source
- AlphaFold Database makes a predicted structure a traceable research record 2026-11-25 · source
- AI protein tools still have to earn their lab coats 2026-11-24 · source
- marimo keeps notebook outputs connected to their inputs 2026-11-25 · source
- MLflow keeps experiment records beside application traces 2026-11-25 · source
An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.
