multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
9f6462d verified
Raw History Blame Contribute Delete
15.6 kB
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import argparse # noqa: E402
import html # noqa: E402
import json # noqa: E402
import re # noqa: E402
import tempfile # noqa: E402
import time # noqa: E402
import urllib.request # noqa: E402
from pathlib import Path # noqa: E402
import gradio as gr # noqa: E402
import torch # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
from calpha.constants import ( # noqa: E402
AMINO, CANONICAL_TEMPLATE, COND_LAYERS, STRUCT_TOKEN, seq_tokens, user_turn,
)
from calpha.esm_adapter import Adapter, EsmEncoder # noqa: E402
from calpha.language_model import CalphaLM # noqa: E402
from calpha.structure_head import ( # noqa: E402
StructureHead, _add_simplefold_to_path, _use_fair_esm_registry, retarget_condition,
)
REPO = "liuyong9975/Calpha"
MAX_LEN = 512
SF_DIR = Path(os.path.expanduser("~/.cache/calpha/simplefold"))
SF_URL = "https://ml-site.cdn-apple.com/models/simplefold/simplefold_3B.ckpt"
# --------------------------------------------------------------------------- weights
weights = Path(snapshot_download(
REPO, allow_patterns=["calpha_config.json", "esm_adapter.safetensors",
"frontend.safetensors", "llm/*"]))
cfg = json.loads((weights / "calpha_config.json").read_text())
LAYERS = tuple(cfg.get("cond_layers", COND_LAYERS))
import lightning.pytorch as pl # noqa: E402
from safetensors.torch import load_file # noqa: E402
from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402
pl.seed_everything(42, workers=True)
# ---- language model (Qwen3.5-9B fine-tuned) + ESM2 adapter + ESM2-3B
# Mirrors calpha.language_model.CalphaLM.__init__, with dtype casts done on CPU before the
# single .to("cuda") (identical numerics: rotary buffers end up in bf16 as in the reference).
lm = CalphaLM.__new__(CalphaLM)
lm.device, lm.layers = "cuda", LAYERS
lm.tok = AutoTokenizer.from_pretrained(str(weights / "llm"))
_llm = AutoModelForCausalLM.from_pretrained(str(weights / "llm"), dtype=torch.bfloat16)
lm.lm = _llm.to(torch.bfloat16).eval().requires_grad_(False).to("cuda")
lm.im_end = lm.tok.convert_tokens_to_ids("<|im_end|>")
lm.hidden = lm.lm.get_input_embeddings().weight.shape[1]
_adapter = Adapter(lm.hidden)
_adapter.load_state_dict(load_file(str(weights / "esm_adapter.safetensors")), strict=True)
lm.adapter = _adapter.to(torch.bfloat16).eval().requires_grad_(False).to("cuda")
import esm # noqa: E402 (fair-esm)
_esm_model, _alphabet = esm.pretrained.esm2_t36_3B_UR50D()
lm.esm = EsmEncoder.__new__(EsmEncoder)
lm.esm.model = _esm_model.eval().to(torch.bfloat16).requires_grad_(False).to("cuda")
lm.esm.conv = _alphabet.get_batch_converter()
lm.esm.device = "cuda"
_ids = lm.tok.convert_tokens_to_ids
lm.seq_open, lm.seq_close = _ids("<seq>"), _ids("</seq>")
lm.aa = {_ids(f"<aa{a}>"): a for a in AMINO}
lm.aa[_ids("<aaX>")] = "X"
print("Language model + ESM2-3B loaded", flush=True)
# ---- structure head: public SimpleFold-3B with Calpha's conditioning front-end
_add_simplefold_to_path()
_use_fair_esm_registry()
import hydra # noqa: E402
import omegaconf # noqa: E402
import inference as sf_inference # noqa: E402 (SimpleFold)
from utils import fasta_utils # noqa: E402
SF_DIR.mkdir(parents=True, exist_ok=True)
_ckpt = SF_DIR / "simplefold_3B.ckpt"
if not _ckpt.exists():
print("Downloading SimpleFold-3B from Apple's CDN ...", flush=True)
urllib.request.urlretrieve(SF_URL, str(_ckpt) + ".part")
os.replace(str(_ckpt) + ".part", _ckpt)
_ccd = SF_DIR / "cache" / "ccd.pkl"
if not _ccd.exists():
_ccd.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(fasta_utils.CCD_URL, str(_ccd))
_sf_cfg = sf_inference.get_config_path("configs/model/architecture/foldingdit_3B.yaml")
_sf = hydra.utils.instantiate(omegaconf.OmegaConf.load(_sf_cfg))
try:
_sd = torch.load(_ckpt, map_location="cpu", weights_only=False, mmap=True)
except Exception:
_sd = torch.load(_ckpt, map_location="cpu", weights_only=False)
_sf.load_state_dict(_sd, strict=True)
del _sd
retarget_condition(_sf, len(LAYERS), lm.hidden)
_res = _sf.load_state_dict(load_file(str(weights / "frontend.safetensors")), strict=False)
assert not _res.unexpected_keys and not any(k.startswith("esm_s_") for k in _res.missing_keys), _res
_sf = _sf.eval().requires_grad_(False).to("cuda")
head = StructureHead.__new__(StructureHead)
head.dir = SF_DIR
head.args = argparse.Namespace(
simplefold_model="simplefold_3B", ckpt_dir=str(SF_DIR), backend="torch",
num_steps=cfg["sampling"]["num_steps"], tau=cfg["sampling"]["tau"],
nsample_per_protein=1, plddt=False, output_format="mmcif", seed=42)
head.model = _sf
head.device = torch.device("cuda")
head.tokenizer, head.featurizer, head.processor, head.flow, head.sampler = \
sf_inference.initialize_others(head.args, head.device)
pl.seed_everything(42, workers=True)
print("SimpleFold-3B head loaded", flush=True)
OUT_ROOT = Path(tempfile.gettempdir()) / "calpha_out"
OUT_ROOT.mkdir(exist_ok=True)
# --------------------------------------------------------------------------- helpers
def clean_sequence(text: str) -> str:
"""Accept a raw sequence or FASTA; return an upper-case one-letter sequence."""
if not text or not text.strip():
raise gr.Error("Please enter a protein sequence.")
lines = [ln for ln in text.strip().splitlines() if not ln.startswith(">")]
seq = re.sub(r"[\s\d*]", "", "".join(lines)).upper()
bad = sorted(set(seq) - set(AMINO + "X"))
if bad:
raise gr.Error(f"Unsupported residue letters: {''.join(bad)} (use the 20 standard amino acids or X).")
if len(seq) < 10:
raise gr.Error("Sequence is too short (minimum 10 residues).")
if len(seq) > MAX_LEN:
raise gr.Error(f"Sequence has {len(seq)} residues; this demo is limited to {MAX_LEN}.")
return seq
def viewer_html(cif: str | None, message: str = "") -> str:
if cif is None:
return (f"<div style='height:480px;display:flex;align-items:center;justify-content:center;"
f"border:1px dashed #999;border-radius:8px;opacity:.7'>{html.escape(message or 'The structure will appear here.')}</div>")
doc = f"""<!DOCTYPE html><html><head>
<script src="https://cdn.jsdelivr.net/npm/3dmol@2.5.2/build/3Dmol-min.js"></script>
<style>html,body{{margin:0;height:100%;background:#fff}}#v{{width:100%;height:100%;position:relative}}</style>
</head><body><div id="v"></div><script>
const data = {json.dumps(cif)};
const viewer = $3Dmol.createViewer(document.getElementById('v'), {{backgroundColor:'white'}});
viewer.addModel(data, 'cif');
viewer.setStyle({{}}, {{cartoon: {{color: 'spectrum'}}}});
viewer.zoomTo(); viewer.render();
</script></body></html>"""
return (f'<iframe style="width:100%;height:480px;border:none;border-radius:8px" '
f'srcdoc="{html.escape(doc, quote=True)}"></iframe>')
def _fold(seq: str, prompt: str, seed: int, num_steps: int) -> Path:
"""Run the SimpleFold-3B head conditioned on the LM hidden states of `prompt`."""
pl.seed_everything(int(seed), workers=True)
head.args.num_steps = int(num_steps)
_, _, _, _, head.sampler = sf_inference.initialize_others(head.args, head.device)
out_dir = Path(tempfile.mkdtemp(dir=OUT_ROOT))
with tempfile.TemporaryDirectory() as tmp:
files = head.prepare({"calpha": seq}, Path(tmp))
paths = head.sample(files[0], Path(tmp), lambda s: lm.residue_states(prompt), out_dir)
return paths[0]
def _fold_duration(sequence, seed=42, num_steps=200, *args, **kwargs):
# Measured on ZeroGPU (200 steps): warm 28 s @129 aa, 38 s @356 aa, 45 s @507 aa;
# cold first call 58 s @70 aa. Sized to the cold-start case + ~15%.
n = len(sequence or "")
return int(40 + (max(int(num_steps), 20) / 200) * (25 + 0.05 * n))
def _chat_duration(request, sequence, seed=42, num_steps=200, *args, **kwargs):
return _fold_duration(sequence, seed, num_steps) + 10
# --------------------------------------------------------------------------- endpoints
@spaces.GPU(duration=_fold_duration)
def fold(sequence: str, seed: int = 42, num_steps: int = 200,
progress=gr.Progress(track_tqdm=True)):
"""Fold a protein sequence with Calpha (benchmark path: canonical request, answer `<structure>`).
Args:
sequence: protein sequence (one-letter codes) or FASTA text, up to 512 residues.
seed: random seed of the flow-matching sampler.
num_steps: number of sampling steps of the SimpleFold-3B head (200 in the report).
Returns:
3D viewer HTML, path of the predicted mmCIF file, and a short summary.
"""
seq = clean_sequence(sequence)
t0 = time.perf_counter()
prompt = user_turn(CANONICAL_TEMPLATE[0].format(seq=seq_tokens(seq)))
prompt += CANONICAL_TEMPLATE[1].format(tag=STRUCT_TOKEN) + "<|im_end|>"
path = _fold(seq, prompt, seed, num_steps)
dt = time.perf_counter() - t0
info = f"**{len(seq)} residues** folded in {dt:.1f} s (seed {int(seed)}, {int(num_steps)} steps)."
print(f"[fold] L={len(seq)} steps={num_steps} time={dt:.1f}s", flush=True)
return viewer_html(path.read_text()), str(path), info
@spaces.GPU(duration=_chat_duration)
def chat(request: str, sequence: str, seed: int = 42, num_steps: int = 200,
progress=gr.Progress(track_tqdm=True)):
"""Ask Calpha anything about a protein in plain language. If the model answers with
`<structure>`, a 3D structure is generated from the hidden states of this very turn.
Args:
request: question in natural language; write `{seq}` where the protein goes
(appended at the end if missing).
sequence: protein sequence (one-letter codes) or FASTA text, up to 512 residues.
seed: random seed of the flow-matching sampler.
num_steps: number of sampling steps of the SimpleFold-3B head.
Returns:
The model's text answer, 3D viewer HTML, and the mmCIF path (None if no structure).
"""
seq = clean_sequence(sequence)
request = (request or "").strip() or "What does this protein look like in 3D? Please show the structure.\n{seq}"
if "{seq}" not in request:
request = request + "\n{seq}"
text = request.replace("{seq}", seq_tokens(seq))
prompt = user_turn(text)
t0 = time.perf_counter()
reply = lm.generate(prompt, max_new_tokens=128)
shown = reply.replace(STRUCT_TOKEN, "`<structure>`")
if STRUCT_TOKEN not in reply:
return shown, viewer_html(None, "The model answered in text only (no <structure> token)."), None
turn = prompt + reply + "<|im_end|>"
path = _fold(seq, turn, seed, num_steps)
print(f"[chat] L={len(seq)} time={time.perf_counter() - t0:.1f}s", flush=True)
return shown, viewer_html(path.read_text()), str(path)
# --------------------------------------------------------------------------- UI
EXAMPLES = [
# sequence from the Calpha README quick start
"MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQAPILSRVGDGTQDNLSGAEKAVQVKVKALPDAQFEVV",
# PDB 8REH chain A (CAMEO-2025 test set of the report)
"KVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL",
# PDB 8RI4 chain A (CAMEO-2025 test set)
"SGFRKMAFPSGKVEGCMVQVTCGTTTLNGLWLDDVVYCPRHVICTSEDMLNPNYEDLLIRKSNHNFLVQAGNVQLRVIGHSMQNCVLK",
# Ubiquitin
"MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG",
]
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks() as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# Calpha: a chat model that folds proteins\n"
"Qwen3.5-9B reads the sequence (with frozen ESM2-3B features) and answers with a "
"`<structure>` token; its hidden states drive the frozen SimpleFold-3B flow-matching head "
"to produce an all-atom structure. \n"
"[Model](https://huggingface.co/liuyong9975/Calpha) · [Code](https://github.com/yliust/Calpha) · "
"[Homepage](https://calpha-ai.com) · Research use only (SimpleFold-3B is under Apple's ML Research Model License)."
)
with gr.Tabs():
with gr.Tab("Fold"):
with gr.Row():
with gr.Column(scale=2):
seq_in = gr.Textbox(label="Protein sequence or FASTA", lines=6,
placeholder="MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQ...")
fold_btn = gr.Button("Fold", variant="primary")
info_out = gr.Markdown()
cif_out = gr.File(label="Predicted structure (mmCIF)")
with gr.Column(scale=3):
view_out = gr.HTML(viewer_html(None))
with gr.Accordion("Advanced settings", open=False):
seed_in = gr.Number(label="Seed", value=42, precision=0)
steps_in = gr.Slider(label="Sampling steps", minimum=20, maximum=200, step=10, value=200)
gr.Markdown("Best accuracy for chains of 100–300 residues; single chains only.")
gr.Examples(examples=[[s] for s in EXAMPLES], inputs=[seq_in],
outputs=[view_out, cif_out, info_out], fn=fold,
cache_examples=True, cache_mode="lazy")
with gr.Tab("Ask Calpha"):
with gr.Row():
with gr.Column(scale=2):
req_in = gr.Textbox(label="Your request ({seq} marks where the protein goes)", lines=2,
value="Can you show me what this protein looks like in 3D? {seq}")
cseq_in = gr.Textbox(label="Protein sequence or FASTA", lines=4)
chat_btn = gr.Button("Ask", variant="primary")
answer_out = gr.Textbox(label="Calpha's answer", lines=3)
ccif_out = gr.File(label="Predicted structure (mmCIF)")
with gr.Column(scale=3):
cview_out = gr.HTML(viewer_html(None))
with gr.Accordion("Advanced settings", open=False):
cseed_in = gr.Number(label="Seed", value=42, precision=0)
csteps_in = gr.Slider(label="Sampling steps", minimum=20, maximum=200, step=10, value=200)
gr.Markdown("The model decides whether to fold. Accuracy was only measured for the canonical request used in the Fold tab.")
gr.Examples(
examples=[
["Can you show me what this protein looks like in 3D? {seq}", EXAMPLES[0]],
["How many residues does this protein have? {seq}", EXAMPLES[0]],
["What is the 3D structure of this protein?\n{seq}", EXAMPLES[3]],
],
inputs=[req_in, cseq_in], outputs=[answer_out, cview_out, ccif_out], fn=chat,
cache_examples=False, run_on_click=True)
fold_btn.click(fold, inputs=[seq_in, seed_in, steps_in], outputs=[view_out, cif_out, info_out],
api_name="fold")
chat_btn.click(chat, inputs=[req_in, cseq_in, cseed_in, csteps_in],
outputs=[answer_out, cview_out, ccif_out], api_name="chat")
demo.queue().launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)