esmfold2
Browse files- README.md +52 -77
- app.py +121 -94
- requirements.txt +1 -20
README.md
CHANGED
|
@@ -8,7 +8,7 @@ python_version: "3.12"
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
-
short_description: Protein structure prediction with ESMFold2
|
| 12 |
tags:
|
| 13 |
- biology
|
| 14 |
- protein
|
|
@@ -20,92 +20,67 @@ tags:
|
|
| 20 |
# Foldy
|
| 21 |
|
| 22 |
Predicts 3D protein structure from amino acid sequences using
|
| 23 |
-
[
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
##
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
-
##
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
history — no evidence-based cap has been set yet).
|
| 50 |
|
| 51 |
-
##
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
## Notes
|
| 58 |
|
| 59 |
-
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
linear projection (`proj_bundle`, 4× the pair width) is computed over the full, unchunked
|
| 65 |
-
`(L, L, ...)` grid *before* chunking is applied to the later einsum step. At L=1888 this one
|
| 66 |
-
tensor needs ~7.3GB, and it OOM'd even on ZeroGPU's `large` (48GB) tier. We now also call
|
| 67 |
-
`model.set_kernel_backend("cuequivariance")` at load time, which routes triangle updates
|
| 68 |
-
through a fused kernel that avoids materializing that tensor at all — but this requires the
|
| 69 |
-
`cuequivariance-torch`/`cuequivariance-ops-torch-cu13` packages (added to requirements.txt)
|
| 70 |
-
*and* a CUDA 13 runtime, which we could not confirm ZeroGPU's RTX Pro 6000 Blackwell nodes
|
| 71 |
-
actually have without testing live. It's wrapped in a try/except that falls back to the
|
| 72 |
-
chunked (OOM-prone-on-large-inputs) path if unavailable — check the Space logs at startup
|
| 73 |
-
for "Enabled cuequivariance..." vs "cuequivariance backend unavailable..." to see which path
|
| 74 |
-
is actually active.
|
| 75 |
-
- **The cuequivariance fix worked, but moved the OOM further down the pipeline, not away.**
|
| 76 |
-
A second 1888-residue test (after adding cuequivariance) crashed later, in
|
| 77 |
-
`pair_loop_proj` (a `LayerNorm -> Linear` run once per recycling loop over the full
|
| 78 |
-
`(L, L, d_pair)` pair tensor) — this op has *no* chunking in the checkpoint's own code at
|
| 79 |
-
all, unlike `pair_transition`, which we confirmed chunks correctly (the whole computation
|
| 80 |
-
happens inside the chunk loop, not just part of it — this checkpoint's memory engineering is
|
| 81 |
-
genuinely inconsistent across ops, not fundamentally incapable of scale; see conversation
|
| 82 |
-
history for why we now believe production AlphaFold/OpenFold can do 3k+ residues on 48GB but
|
| 83 |
-
this experimental checkpoint currently can't). We patch `model.pair_loop_proj.forward` at
|
| 84 |
-
load time with our own chunked version — verified mathematically exact (bitwise-identical
|
| 85 |
-
output) against the unchunked version in isolation, since LayerNorm-over-last-dim and Linear
|
| 86 |
-
are both purely position-wise with no cross-`(i,j)` interaction.
|
| 87 |
-
- **Open question, not yet resolved:** at the point `pair_loop_proj` failed, only ~0.4GB was
|
| 88 |
-
free out of 48GB — meaning cumulative memory from everything *before* it (ESMC backbone,
|
| 89 |
-
weights, prior recycling iterations) was already near the ceiling. The `pair_loop_proj` fix
|
| 90 |
-
reduces its own transient peak but may not be enough on its own if upstream accumulation is
|
| 91 |
-
the real driver. Only a live test will tell; if it still OOMs, the next places to look are
|
| 92 |
-
whether intermediate tensors from earlier recycling loop iterations are being retained
|
| 93 |
-
longer than necessary, and whether `num_loops`/`chunk_size` need to go lower for very large
|
| 94 |
-
inputs.
|
| 95 |
-
- Folding goes through `model.input_types.StructurePredictionInput` /
|
| 96 |
-
`.ProteinInput` and `model.fold(...)` / `model.result_to_cif(...)` — all native to this
|
| 97 |
-
checkpoint's bundle, not the hand-rolled multi-chain featurization used in earlier
|
| 98 |
-
iterations of this app.
|
| 99 |
-
- GPU size is the ZeroGPU default (`large`, 48GB) — the 300M model's weights are ~685MB, so
|
| 100 |
-
this should have real headroom versus the old 7B setup. Bump `@spaces.GPU(size="xlarge")`
|
| 101 |
-
if you still hit OOM on large complexes.
|
| 102 |
- "Recycling loops" and "diffusion sampling steps" trade accuracy for speed — raise them for
|
| 103 |
-
harder targets, lower them for a faster demo.
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
|
| 110 |
## Local development
|
| 111 |
|
|
@@ -115,5 +90,5 @@ python app.py
|
|
| 115 |
```
|
| 116 |
|
| 117 |
Folding requires a CUDA GPU; on Spaces, ZeroGPU provides this on demand via the `spaces`
|
| 118 |
-
package. Locally, you need your own GPU — `
|
| 119 |
present at import time.
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
+
short_description: Protein structure prediction with ESMFold2 (ZeroGPU)
|
| 12 |
tags:
|
| 13 |
- biology
|
| 14 |
- protein
|
|
|
|
| 20 |
# Foldy
|
| 21 |
|
| 22 |
Predicts 3D protein structure from amino acid sequences using
|
| 23 |
+
[biohub/ESMFold2-Fast](https://huggingface.co/biohub/ESMFold2-Fast) — the official,
|
| 24 |
+
7B-parameter checkpoint from Biohub, loaded via `transformers`' own native ESMFold2 support
|
| 25 |
+
(`transformers.models.esmfold2`, no `trust_remote_code`, no third-party wrapper). Runs on
|
| 26 |
+
Hugging Face's ZeroGPU.
|
| 27 |
|
| 28 |
+
## Input
|
| 29 |
|
| 30 |
+
Up to 6 protein chains (fixed rows in the UI), each with a copies slider (1–16) — set
|
| 31 |
+
copies > 1 for a homooligomer. Chains are combined into one complex via a hand-rolled
|
| 32 |
+
multi-chain featurizer (`prepare_multi_chain_protein_features` in [app.py](app.py)), since the
|
| 33 |
+
native `transformers` path only ships a single-chain helper
|
| 34 |
+
(`prepare_protein_features`) — ours reassigns `asym_id`/`entity_id`/`sym_id` per the
|
| 35 |
+
convention `EsmFold2Model.forward` documents, verified against the model's own
|
| 36 |
+
multi-chain grouping logic (`_compute_lm_hidden_states`). No cap on total residues; oversized
|
| 37 |
+
inputs just hit the `@spaces.GPU(duration=300, size="xlarge")` timeout/OOM instead of a
|
| 38 |
+
friendly error.
|
| 39 |
|
| 40 |
+
DNA/RNA/ligands aren't supported: that needs the `esm` PyPI package's
|
| 41 |
+
`StructurePredictionInput` builder, which pulls in a dependency tree (a hard `torch<2.12` pin,
|
| 42 |
+
`cuequivariance-torch`, ...) that conflicts with the versions this Space's ZeroGPU/Gradio build
|
| 43 |
+
forces (`gradio` needs `huggingface-hub>=1.16`, `esm`'s own `transformers<5.0` pin needs
|
| 44 |
+
`huggingface-hub<1.0` — genuinely unsatisfiable together). Protein-only, via the version of
|
| 45 |
+
ESMFold2 natively vendored inside `transformers`, is the tradeoff that keeps this Space's
|
| 46 |
+
dependencies conflict-free.
|
| 47 |
|
| 48 |
+
## Output
|
| 49 |
|
| 50 |
+
- An interactive 3D viewer (py3Dmol), colored by predicted confidence (pLDDT)
|
| 51 |
+
- Mean pLDDT, pTM, and (for multi-chain folds) ipTM
|
| 52 |
+
- A downloadable PDB file
|
|
|
|
| 53 |
|
| 54 |
+
## Known limitation: large inputs OOM
|
| 55 |
|
| 56 |
+
This checkpoint has a dense O(L²) pairwise representation (like AlphaFold/Evoformer-style
|
| 57 |
+
architectures) — memory scales quadratically with total residue count. In practice:
|
| 58 |
+
- Small-to-moderate proteins/complexes (up to several hundred residues) fold reliably.
|
| 59 |
+
- Multi-thousand-residue complexes have reliably OOM'd in testing, even on ZeroGPU's `xlarge`
|
| 60 |
+
(96GB) tier — this is a known, currently-unaddressed limitation, not a bug to casually "fix."
|
| 61 |
+
A real fix would mean auditing every large tensor operation in `transformers`' ESMFold2
|
| 62 |
+
implementation for complete chunking coverage (see the `sfold`/Synthyra-checkpoint chapter of
|
| 63 |
+
this project's history for how deep that rabbit hole goes on a *different*, less mature
|
| 64 |
+
checkpoint) — genuinely out of scope for casual iteration.
|
| 65 |
+
- For context: even production AlphaFold3 needs 80GB+ VRAM for large multimers and is
|
| 66 |
+
described as needing H100/H200-class hardware above ~1500 residues. 10,000-residue multimer
|
| 67 |
+
folding on a single GPU is not something published tooling demonstrates without novel,
|
| 68 |
+
paper-worthy techniques (e.g. activation quantization) — not a realistic goal for this app.
|
| 69 |
|
| 70 |
## Notes
|
| 71 |
|
| 72 |
+
- Model weights load once at startup in **float32** (not bfloat16) and move to `cuda` at
|
| 73 |
+
**module load time** (not inside the `@spaces.GPU` function) — both per HF's current ZeroGPU
|
| 74 |
+
guidance and hard-won lessons: blanket bf16 casting crashes (`expected Float but found
|
| 75 |
+
BFloat16`) because the diffusion sampling loop hardcodes fp32 tensors internally regardless
|
| 76 |
+
of the model's overall dtype.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
- "Recycling loops" and "diffusion sampling steps" trade accuracy for speed — raise them for
|
| 78 |
+
harder targets, lower them for a faster demo.
|
| 79 |
+
- GPU size is `xlarge` (96GB, 2× ZeroGPU quota cost) — bumped up from the `large` default after
|
| 80 |
+
the 7B model's fp32 weights (~28GB) left too little headroom for anything but small folds.
|
| 81 |
+
- Do **not** add `esm`, `torch`, `spaces`, or `gradio` to `requirements.txt`: the platform
|
| 82 |
+
force-pins `torch`/`spaces`/`gradio` during the ZeroGPU build, and `esm`'s own pins
|
| 83 |
+
(`torch<2.12`, `transformers<5.0`) directly conflict with them.
|
| 84 |
|
| 85 |
## Local development
|
| 86 |
|
|
|
|
| 90 |
```
|
| 91 |
|
| 92 |
Folding requires a CUDA GPU; on Spaces, ZeroGPU provides this on demand via the `spaces`
|
| 93 |
+
package. Locally, you need your own GPU — `model.to("cuda")` at module scope assumes one is
|
| 94 |
present at import time.
|
app.py
CHANGED
|
@@ -1,9 +1,4 @@
|
|
| 1 |
-
"""Foldy — protein structure prediction with ESMFold2
|
| 2 |
-
|
| 3 |
-
Uses the Synthyra/ESMFold2-300 FastPLMs bundle (trust_remote_code=True), which wraps
|
| 4 |
-
Biohub's experimental 300M-backbone ESMFold2 checkpoint. This is third-party remote code —
|
| 5 |
-
see the README for what that means before touching MODEL_NAME.
|
| 6 |
-
"""
|
| 7 |
|
| 8 |
import os
|
| 9 |
import re
|
|
@@ -14,9 +9,13 @@ import gradio as gr
|
|
| 14 |
import py3Dmol
|
| 15 |
import spaces
|
| 16 |
import torch
|
| 17 |
-
from transformers import
|
|
|
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
NUM_ROWS = 6
|
| 21 |
VALID_AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWYXBZUO")
|
| 22 |
|
|
@@ -24,48 +23,11 @@ EXAMPLE_UBIQUITIN = "MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDY
|
|
| 24 |
EXAMPLE_CAP = "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"
|
| 25 |
|
| 26 |
print(f"Loading {MODEL_NAME} (this happens once at startup)...")
|
| 27 |
-
model =
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
esmc_precision="bf16",
|
| 33 |
-
attn_implementation="sdpa",
|
| 34 |
-
).eval()
|
| 35 |
-
model.set_chunk_size(32)
|
| 36 |
-
try:
|
| 37 |
-
# set_chunk_size only chunks the triangle-update einsum step — the linear projection
|
| 38 |
-
# feeding it (proj_bundle, 4x the pair width) is materialized in full over (L, L, ...)
|
| 39 |
-
# regardless, which is what actually OOMs on large complexes. The fused cuequivariance
|
| 40 |
-
# kernel avoids materializing that intermediate at all; requires a CUDA 13 runtime,
|
| 41 |
-
# which we can't confirm ZeroGPU has without testing live, hence the fallback.
|
| 42 |
-
model.set_kernel_backend("cuequivariance")
|
| 43 |
-
print("Enabled cuequivariance fused kernels for triangle multiplication.")
|
| 44 |
-
except Exception as exc:
|
| 45 |
-
print(f"cuequivariance backend unavailable ({exc}); falling back to the chunked path.")
|
| 46 |
-
|
| 47 |
-
# `pair_loop_proj` (LayerNorm -> Linear, run once per recycling loop on the full (L, L, d_pair)
|
| 48 |
-
# pair tensor) has no chunking in the checkpoint's own code, unlike pair_transition, which chunks
|
| 49 |
-
# correctly. Both LayerNorm-over-last-dim and Linear are purely position-wise (no mixing across
|
| 50 |
-
# different (i, j) pairs), so chunking along the sequence axis here is mathematically exact, not
|
| 51 |
-
# an approximation.
|
| 52 |
-
_PAIR_LOOP_PROJ_CHUNK_SIZE = 32
|
| 53 |
-
_original_pair_loop_proj_forward = model.pair_loop_proj.forward
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def _chunked_pair_loop_proj_forward(x: torch.Tensor) -> torch.Tensor:
|
| 57 |
-
if x.shape[1] <= _PAIR_LOOP_PROJ_CHUNK_SIZE:
|
| 58 |
-
return _original_pair_loop_proj_forward(x)
|
| 59 |
-
out = torch.empty_like(x)
|
| 60 |
-
for start in range(0, x.shape[1], _PAIR_LOOP_PROJ_CHUNK_SIZE):
|
| 61 |
-
end = min(start + _PAIR_LOOP_PROJ_CHUNK_SIZE, x.shape[1])
|
| 62 |
-
out[:, start:end] = _original_pair_loop_proj_forward(x[:, start:end])
|
| 63 |
-
return out
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
model.pair_loop_proj.forward = _chunked_pair_loop_proj_forward
|
| 67 |
-
|
| 68 |
-
input_types = model.input_types
|
| 69 |
print("Model loaded.")
|
| 70 |
|
| 71 |
|
|
@@ -76,83 +38,148 @@ def clean_sequence(raw_sequence: str) -> str:
|
|
| 76 |
return re.sub(r"[^A-Z]", "", sequence)
|
| 77 |
|
| 78 |
|
| 79 |
-
def render_structure(
|
| 80 |
view = py3Dmol.view(width=600, height=500)
|
| 81 |
-
view.addModel(
|
| 82 |
-
|
| 83 |
-
# chain instead of pLDDT.
|
| 84 |
-
view.setStyle({"cartoon": {"colorscheme": "chain"}})
|
| 85 |
view.zoomTo()
|
| 86 |
raw_html = view._make_html()
|
| 87 |
escaped = raw_html.replace('"', """)
|
| 88 |
return f'<iframe style="width: 100%; height: 500px; border: none;" srcdoc="{escaped}"></iframe>'
|
| 89 |
|
| 90 |
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def fold_rows(*args, progress=gr.Progress()):
|
| 93 |
*seqs, num_loops, num_sampling_steps = args
|
| 94 |
|
| 95 |
-
|
| 96 |
-
for
|
| 97 |
sequence = clean_sequence(raw_seq or "")
|
| 98 |
if not sequence:
|
| 99 |
continue
|
| 100 |
invalid_chars = set(sequence) - VALID_AMINO_ACIDS
|
| 101 |
if invalid_chars:
|
| 102 |
raise gr.Error(f"Invalid characters in sequence: {', '.join(sorted(invalid_chars))}")
|
| 103 |
-
|
| 104 |
|
| 105 |
-
if not
|
| 106 |
raise gr.Error("Please enter at least one protein sequence.")
|
| 107 |
|
| 108 |
-
total_residues = sum(len(s) for s in
|
| 109 |
|
| 110 |
-
progress(0.2, desc=f"Folding {len(
|
| 111 |
-
|
| 112 |
-
complex_input = input_types.StructurePredictionInput(
|
| 113 |
-
sequences=[
|
| 114 |
-
input_types.ProteinInput(id=chain_id, sequence=seq) for chain_id, seq in zip(chain_ids, chains)
|
| 115 |
-
]
|
| 116 |
-
)
|
| 117 |
|
| 118 |
start = time.time()
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
seed=0,
|
| 126 |
-
verbose=False,
|
| 127 |
-
)
|
| 128 |
elapsed = time.time() - start
|
| 129 |
|
| 130 |
progress(0.9, desc="Building structure file...")
|
| 131 |
-
|
| 132 |
|
| 133 |
-
|
| 134 |
-
with open(
|
| 135 |
-
f.write(
|
| 136 |
|
| 137 |
-
viewer_html = render_structure(
|
|
|
|
|
|
|
| 138 |
summary_lines = [
|
| 139 |
-
f"**Chains:** {len(
|
| 140 |
f"**Total length:** {total_residues} residues",
|
| 141 |
-
"**
|
| 142 |
-
f"**
|
| 143 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
return viewer_html, " \n".join(summary_lines),
|
| 146 |
|
| 147 |
|
| 148 |
with gr.Blocks(title="Foldy — ESMFold2 Protein Structure Prediction") as demo:
|
| 149 |
gr.Markdown(
|
| 150 |
"""
|
| 151 |
# 🧬 Foldy
|
| 152 |
-
Predict 3D protein structure using [ESMFold2
|
| 153 |
-
(
|
| 154 |
-
Fill in one row per chain, and set copies > 1 for a homooligomer. This checkpoint has no
|
| 155 |
-
confidence head, so pLDDT/pTM aren't available.
|
| 156 |
"""
|
| 157 |
)
|
| 158 |
|
|
@@ -179,13 +206,13 @@ with gr.Blocks(title="Foldy — ESMFold2 Protein Structure Prediction") as demo:
|
|
| 179 |
copies_boxes.append(copies)
|
| 180 |
|
| 181 |
with gr.Accordion("Advanced settings", open=False):
|
| 182 |
-
num_loops = gr.Slider(1, 3, value=
|
| 183 |
-
num_sampling_steps = gr.Slider(10, 50, value=
|
| 184 |
gr.Markdown("Higher values improve accuracy but increase inference time.")
|
| 185 |
|
| 186 |
fold_btn = gr.Button("Fold", variant="primary")
|
| 187 |
summary_output = gr.Markdown()
|
| 188 |
-
|
| 189 |
|
| 190 |
with gr.Column(scale=2):
|
| 191 |
structure_output = gr.HTML(label="Predicted structure")
|
|
@@ -196,7 +223,7 @@ with gr.Blocks(title="Foldy — ESMFold2 Protein Structure Prediction") as demo:
|
|
| 196 |
fold_btn.click(
|
| 197 |
fn=fold_rows,
|
| 198 |
inputs=[*seq_boxes, *copies_boxes, num_loops, num_sampling_steps],
|
| 199 |
-
outputs=[structure_output, summary_output,
|
| 200 |
)
|
| 201 |
|
| 202 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
"""Foldy — protein structure prediction with ESMFold2, on HF ZeroGPU."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import re
|
|
|
|
| 9 |
import py3Dmol
|
| 10 |
import spaces
|
| 11 |
import torch
|
| 12 |
+
from transformers.models.esmfold2.modeling_esmfold2 import EsmFold2Model
|
| 13 |
+
from transformers.models.esmfold2.protein_utils import output_to_pdb, prepare_protein_features
|
| 14 |
|
| 15 |
+
# The -Fast checkpoint is single-sequence (no MSA), which keeps inference time
|
| 16 |
+
# reasonable on a shared ZeroGPU slot. Swap for "biohub/ESMFold2" for MSA-conditioned
|
| 17 |
+
# accuracy on hard targets (slower, and needs an MSA pipeline this app doesn't provide).
|
| 18 |
+
MODEL_NAME = "biohub/ESMFold2-Fast"
|
| 19 |
NUM_ROWS = 6
|
| 20 |
VALID_AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWYXBZUO")
|
| 21 |
|
|
|
|
| 23 |
EXAMPLE_CAP = "MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLAGG"
|
| 24 |
|
| 25 |
print(f"Loading {MODEL_NAME} (this happens once at startup)...")
|
| 26 |
+
model = EsmFold2Model.from_pretrained(MODEL_NAME).eval()
|
| 27 |
+
# Per HF's ZeroGPU docs, models must move to "cuda" at module load time (not inside an
|
| 28 |
+
# @spaces.GPU function) — a CUDA emulation mode makes this safe even without a real GPU
|
| 29 |
+
# attached yet, and it's more efficient than a per-call transfer.
|
| 30 |
+
model.to("cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
print("Model loaded.")
|
| 32 |
|
| 33 |
|
|
|
|
| 38 |
return re.sub(r"[^A-Z]", "", sequence)
|
| 39 |
|
| 40 |
|
| 41 |
+
def render_structure(pdb_str: str) -> str:
|
| 42 |
view = py3Dmol.view(width=600, height=500)
|
| 43 |
+
view.addModel(pdb_str, "pdb")
|
| 44 |
+
view.setStyle({"cartoon": {"colorscheme": {"prop": "b", "gradient": "roygb", "min": 50, "max": 90}}})
|
|
|
|
|
|
|
| 45 |
view.zoomTo()
|
| 46 |
raw_html = view._make_html()
|
| 47 |
escaped = raw_html.replace('"', """)
|
| 48 |
return f'<iframe style="width: 100%; height: 500px; border: none;" srcdoc="{escaped}"></iframe>'
|
| 49 |
|
| 50 |
|
| 51 |
+
def prepare_multi_chain_protein_features(sequences: list[str], device) -> dict[str, torch.Tensor]:
|
| 52 |
+
"""Combine several single-chain protein featurizations into one complex.
|
| 53 |
+
|
| 54 |
+
Reuses ``prepare_protein_features`` per chain (already correct for one chain), then
|
| 55 |
+
reassigns the complex-level bookkeeping fields per the convention ``EsmFold2Model.forward``
|
| 56 |
+
documents: ``token_index``/``atom_to_token``/``ref_space_uid`` become complex-global,
|
| 57 |
+
``residue_index`` stays chain-local, ``asym_id`` is unique per chain instance, ``entity_id``
|
| 58 |
+
is shared by chains with an identical sequence, and ``sym_id`` numbers the copies within an
|
| 59 |
+
entity (so copies of one sequence fold as a homooligomer, not independent monomers).
|
| 60 |
+
"""
|
| 61 |
+
per_chain = [prepare_protein_features(seq, device="cpu") for seq in sequences]
|
| 62 |
+
|
| 63 |
+
entity_id_by_sequence: dict[str, int] = {}
|
| 64 |
+
next_entity_id = 1
|
| 65 |
+
copies_seen: dict[int, int] = {}
|
| 66 |
+
token_offset = 0
|
| 67 |
+
atom_offset = 0
|
| 68 |
+
|
| 69 |
+
for asym_idx, (seq, feats) in enumerate(zip(sequences, per_chain)):
|
| 70 |
+
entity_id = entity_id_by_sequence.setdefault(seq, next_entity_id)
|
| 71 |
+
if entity_id == next_entity_id:
|
| 72 |
+
next_entity_id += 1
|
| 73 |
+
sym_id = copies_seen.get(entity_id, 0)
|
| 74 |
+
copies_seen[entity_id] = sym_id + 1
|
| 75 |
+
|
| 76 |
+
num_tokens = feats["token_index"].shape[1]
|
| 77 |
+
|
| 78 |
+
feats["token_index"] = feats["token_index"] + token_offset
|
| 79 |
+
feats["asym_id"] = torch.full_like(feats["asym_id"], asym_idx)
|
| 80 |
+
feats["sym_id"] = torch.full_like(feats["sym_id"], sym_id)
|
| 81 |
+
feats["entity_id"] = torch.full_like(feats["entity_id"], entity_id)
|
| 82 |
+
feats["atom_to_token"] = feats["atom_to_token"] + token_offset
|
| 83 |
+
feats["ref_space_uid"] = feats["ref_space_uid"] + token_offset
|
| 84 |
+
feats["distogram_atom_idx"] = feats["distogram_atom_idx"] + atom_offset
|
| 85 |
+
|
| 86 |
+
token_offset += num_tokens
|
| 87 |
+
atom_offset += feats["ref_pos"].shape[1]
|
| 88 |
+
|
| 89 |
+
total_tokens = token_offset
|
| 90 |
+
|
| 91 |
+
def cat(key: str, dim: int = 1) -> torch.Tensor:
|
| 92 |
+
return torch.cat([f[key] for f in per_chain], dim=dim)
|
| 93 |
+
|
| 94 |
+
combined = {
|
| 95 |
+
"token_index": cat("token_index"),
|
| 96 |
+
"residue_index": cat("residue_index"),
|
| 97 |
+
"asym_id": cat("asym_id"),
|
| 98 |
+
"sym_id": cat("sym_id"),
|
| 99 |
+
"entity_id": cat("entity_id"),
|
| 100 |
+
"mol_type": cat("mol_type"),
|
| 101 |
+
"res_type": cat("res_type"),
|
| 102 |
+
"input_ids": cat("input_ids"),
|
| 103 |
+
"attention_mask": cat("attention_mask"),
|
| 104 |
+
"distogram_atom_idx": cat("distogram_atom_idx"),
|
| 105 |
+
"ref_pos": cat("ref_pos"),
|
| 106 |
+
"ref_element": cat("ref_element"),
|
| 107 |
+
"ref_charge": cat("ref_charge"),
|
| 108 |
+
"ref_atom_name_chars": cat("ref_atom_name_chars"),
|
| 109 |
+
"ref_space_uid": cat("ref_space_uid"),
|
| 110 |
+
"atom_attention_mask": cat("atom_attention_mask"),
|
| 111 |
+
"atom_to_token": cat("atom_to_token"),
|
| 112 |
+
"msa": cat("msa", dim=2),
|
| 113 |
+
"msa_attention_mask": cat("msa_attention_mask", dim=2),
|
| 114 |
+
"has_deletion": cat("has_deletion", dim=2),
|
| 115 |
+
"deletion_value": cat("deletion_value", dim=2),
|
| 116 |
+
"deletion_mean": cat("deletion_mean"),
|
| 117 |
+
"token_bonds": torch.zeros(1, total_tokens, total_tokens, 1, dtype=torch.float32),
|
| 118 |
+
}
|
| 119 |
+
return {k: v.to(device) for k, v in combined.items()}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@spaces.GPU(duration=300, size="xlarge")
|
| 123 |
def fold_rows(*args, progress=gr.Progress()):
|
| 124 |
*seqs, num_loops, num_sampling_steps = args
|
| 125 |
|
| 126 |
+
chain_sequences: list[str] = []
|
| 127 |
+
for raw_seq, copies in zip(seqs[:NUM_ROWS], seqs[NUM_ROWS:]):
|
| 128 |
sequence = clean_sequence(raw_seq or "")
|
| 129 |
if not sequence:
|
| 130 |
continue
|
| 131 |
invalid_chars = set(sequence) - VALID_AMINO_ACIDS
|
| 132 |
if invalid_chars:
|
| 133 |
raise gr.Error(f"Invalid characters in sequence: {', '.join(sorted(invalid_chars))}")
|
| 134 |
+
chain_sequences.extend([sequence] * max(1, int(copies or 1)))
|
| 135 |
|
| 136 |
+
if not chain_sequences:
|
| 137 |
raise gr.Error("Please enter at least one protein sequence.")
|
| 138 |
|
| 139 |
+
total_residues = sum(len(s) for s in chain_sequences)
|
| 140 |
|
| 141 |
+
progress(0.2, desc=f"Folding {len(chain_sequences)} chain(s), {total_residues} residues total...")
|
| 142 |
+
features = prepare_multi_chain_protein_features(chain_sequences, device="cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
start = time.time()
|
| 145 |
+
output = model.fold(
|
| 146 |
+
**features,
|
| 147 |
+
num_loops=num_loops,
|
| 148 |
+
num_sampling_steps=num_sampling_steps,
|
| 149 |
+
num_diffusion_samples=1,
|
| 150 |
+
)
|
|
|
|
|
|
|
|
|
|
| 151 |
elapsed = time.time() - start
|
| 152 |
|
| 153 |
progress(0.9, desc="Building structure file...")
|
| 154 |
+
pdb_str = output_to_pdb(output, features)
|
| 155 |
|
| 156 |
+
pdb_path = os.path.join(tempfile.gettempdir(), f"foldy_{int(time.time())}.pdb")
|
| 157 |
+
with open(pdb_path, "w") as f:
|
| 158 |
+
f.write(pdb_str)
|
| 159 |
|
| 160 |
+
viewer_html = render_structure(pdb_str)
|
| 161 |
+
mean_plddt = float(output["plddt"].mean())
|
| 162 |
+
ptm = float(output["ptm"].mean())
|
| 163 |
summary_lines = [
|
| 164 |
+
f"**Chains:** {len(chain_sequences)}",
|
| 165 |
f"**Total length:** {total_residues} residues",
|
| 166 |
+
f"**Mean pLDDT:** {mean_plddt:.1f} / 100",
|
| 167 |
+
f"**pTM:** {ptm:.3f}",
|
| 168 |
]
|
| 169 |
+
iptm_tensor = output.get("iptm") if hasattr(output, "get") else None
|
| 170 |
+
if len(chain_sequences) > 1 and iptm_tensor is not None:
|
| 171 |
+
summary_lines.append(f"**ipTM:** {float(iptm_tensor.mean()):.3f}")
|
| 172 |
+
summary_lines.append(f"**Inference time:** {elapsed:.1f}s")
|
| 173 |
|
| 174 |
+
return viewer_html, " \n".join(summary_lines), pdb_path
|
| 175 |
|
| 176 |
|
| 177 |
with gr.Blocks(title="Foldy — ESMFold2 Protein Structure Prediction") as demo:
|
| 178 |
gr.Markdown(
|
| 179 |
"""
|
| 180 |
# 🧬 Foldy
|
| 181 |
+
Predict 3D protein structure using [ESMFold2](https://huggingface.co/biohub/ESMFold2-Fast)
|
| 182 |
+
(Biohub). Fill in one row per chain, and set copies > 1 for a homooligomer.
|
|
|
|
|
|
|
| 183 |
"""
|
| 184 |
)
|
| 185 |
|
|
|
|
| 206 |
copies_boxes.append(copies)
|
| 207 |
|
| 208 |
with gr.Accordion("Advanced settings", open=False):
|
| 209 |
+
num_loops = gr.Slider(1, 3, value=1, step=1, label="Recycling loops")
|
| 210 |
+
num_sampling_steps = gr.Slider(10, 50, value=20, step=5, label="Diffusion sampling steps")
|
| 211 |
gr.Markdown("Higher values improve accuracy but increase inference time.")
|
| 212 |
|
| 213 |
fold_btn = gr.Button("Fold", variant="primary")
|
| 214 |
summary_output = gr.Markdown()
|
| 215 |
+
pdb_output = gr.File(label="Download PDB", interactive=False)
|
| 216 |
|
| 217 |
with gr.Column(scale=2):
|
| 218 |
structure_output = gr.HTML(label="Predicted structure")
|
|
|
|
| 223 |
fold_btn.click(
|
| 224 |
fn=fold_rows,
|
| 225 |
inputs=[*seq_boxes, *copies_boxes, num_loops, num_sampling_steps],
|
| 226 |
+
outputs=[structure_output, summary_output, pdb_output],
|
| 227 |
)
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
|
@@ -1,21 +1,2 @@
|
|
| 1 |
-
|
| 2 |
-
transformers>=5.13,<5.14
|
| 3 |
-
huggingface-hub>=0.34,<2
|
| 4 |
-
tokenizers>=0.22,<0.23
|
| 5 |
-
safetensors>=0.5,<1
|
| 6 |
-
numpy>=1.26,<3
|
| 7 |
-
einops>=0.8,<1
|
| 8 |
-
tqdm>=4.67,<5
|
| 9 |
-
accelerate>=1.10,<2
|
| 10 |
-
biopython>=1.85,<2
|
| 11 |
-
biotite>=1.4,<2
|
| 12 |
-
brotli>=1.1,<2
|
| 13 |
-
msgpack>=1.1,<2
|
| 14 |
-
msgpack-numpy>=0.4.8,<1
|
| 15 |
-
omegaconf>=2.3,<3
|
| 16 |
-
rdkit>=2025.9,<2027
|
| 17 |
-
scipy>=1.15,<2
|
| 18 |
-
zstandard>=0.23,<1
|
| 19 |
py3Dmol
|
| 20 |
-
cuequivariance-torch
|
| 21 |
-
cuequivariance-ops-torch-cu13
|
|
|
|
| 1 |
+
transformers>=5.16
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
py3Dmol
|
|
|
|
|
|