Developer docs / AI Fabric tutorials

Protein folding with ESMFold

  • GPU
  • Volume
  • Image DSL

Predicting a protein's 3D shape from its amino-acid sequence used to mean hours of CPU compute or a wet lab. ESMFold does it with a single forward pass through a neural network, but that network is large, and on a CPU it crawls. On a GPU the same prediction finishes in seconds, which is the kind of work AI Fabric is built for.

In this tutorial you'll fold a protein sequence with ESMFold and write the result as a PDB file you can open in any molecular viewer. The model's weights are a few gigabytes, so you'll cache them on a Volume: downloaded once, reused on every later run.

Before you start

Install and authenticate the AI Fabric CLI with blade setup. The function runs on a single RTX A4500 and builds on fabric/torch, the catalog image with CUDA and PyTorch already installed, so there's no image to build by hand.

Create the app and a weights Volume

Create esmfold.py. Declare the app and a Volume to hold the model weights. create_if_missing=True makes the first run provision it. A Volume persists across runs, so the multi-gigabyte ESMFold download happens only once.

esmfold.py
import bladekit

app = bladekit.app("esmfold")

weights_vol = bladekit.Volume.from_name("esm-weights", create_if_missing=True)

Build the image on fabric/torch, add transformers and biotite, and point TRANSFORMERS_CACHE at the mounted Volume so downloaded weights land in durable storage instead of the ephemeral container filesystem:

Python
image = (
    bladekit.Image.from_catalog("fabric/torch")
    .pip_install("torch", "transformers", "biotite")
    .env({"TRANSFORMERS_CACHE": "/weights"})
)

Define the GPU folding function

Request the GPU, the image, and mount the Volume at /weights. The _model and _tokenizer globals are loaded lazily on the first call and then reused while the container stays warm. It's the same load-once pattern that keeps repeated folds fast:

Python
_model = None
_tokenizer = None

@app.function(
    gpu="RTX-A4500",
    image=image,
    timeout=600,
    volumes={"/weights": weights_vol},
)
def fold(sequence: str) -> str:
    """Return a PDB-format string for the predicted structure."""
    global _model, _tokenizer
    import torch
    from transformers import AutoTokenizer, EsmForProteinFolding

    if _model is None:
        _tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
        _model = EsmForProteinFolding.from_pretrained(
            "facebook/esmfold_v1", low_cpu_mem_usage=True
        ).to("cuda")

Run inference and emit PDB

Tokenize the sequence onto the GPU and run a no-grad forward pass. There's no training here, so gradients are pure overhead. ESMFold knows how to convert its own outputs into PDB text, so you get a ready-to-save structure string back:

Python
    inputs = _tokenizer([sequence], return_tensors="pt", add_special_tokens=False).to("cuda")
    with torch.no_grad():
        outputs = _model(**inputs)
    # EsmForProteinFolding converts its own outputs to PDB (one string per input).
    return _model.output_to_pdb(outputs)[0]

Fold a sequence from your machine

The local_entrypoint runs on your laptop. It sends a hemoglobin alpha-chain excerpt to the GPU with .remote(), then writes the returned PDB string to a local file:

Python
@app.local_entrypoint()
def main():
    # Hemoglobin alpha chain (short excerpt)
    seq = "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR"
    pdb = fold.remote(seq)
    with open("structure.pdb", "w") as f:
        f.write(pdb)
    print("Saved structure.pdb")

Run it

Launch the run with the AI Fabric CLI:

Terminal
blade run esmfold.py

On the first run, ESMFold's weights (~2.7 GB) download to the Volume; that's the cold start. Every later run loads them straight from the Volume, so it's much faster. When it finishes you'll have a local structure.pdb you can open in PyMOL, ChimeraX, or Mol* to inspect the predicted fold. To fold many sequences at once, hand a list to .map() and AI Fabric runs them in parallel.

Take it for a spin

Everything above in one file, ready to run.

esmfold.py
import bladekit

app = bladekit.app("esmfold")

weights_vol = bladekit.Volume.from_name("esm-weights", create_if_missing=True)

image = (
    bladekit.Image.from_catalog("fabric/torch")
    .pip_install("torch", "transformers", "biotite")
    .env({"TRANSFORMERS_CACHE": "/weights"})
)

_model = None
_tokenizer = None

@app.function(
    gpu="RTX-A4500",
    image=image,
    timeout=600,
    volumes={"/weights": weights_vol},
)
def fold(sequence: str) -> str:
    """Return a PDB-format string for the predicted structure."""
    global _model, _tokenizer
    import torch
    from transformers import AutoTokenizer, EsmForProteinFolding

    if _model is None:
        _tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
        _model = EsmForProteinFolding.from_pretrained(
            "facebook/esmfold_v1", low_cpu_mem_usage=True
        ).to("cuda")

    inputs = _tokenizer([sequence], return_tensors="pt", add_special_tokens=False).to("cuda")
    with torch.no_grad():
        outputs = _model(**inputs)
    # EsmForProteinFolding converts its own outputs to PDB (one string per input).
    return _model.output_to_pdb(outputs)[0]

@app.local_entrypoint()
def main():
    # Hemoglobin alpha chain (short excerpt)
    seq = "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR"
    pdb = fold.remote(seq)
    with open("structure.pdb", "w") as f:
        f.write(pdb)
    print("Saved structure.pdb")

Concepts used: GPU, Cold start

Contact the team

Loading the form…