# An Explorable Guide to Protein Language Models
Date: 2026-08-27

Proteins fold, function, and evolve according to rules written into their amino acid sequence — and it turns out transformers are shockingly good at learning those rules. This post walks through how models like ESM, AlphaFold, and RFdiffusion actually work, from first principles up to the real architectures.

This isn't just a wall of text — nearly every section below has something you can click, drag, or step through yourself. Here's a taste, playing on its own:

[Interactive: Preview](https://karthikvedula.com/assets/files/protein/intro_showcase.html) — A preview of the kind of interactive widgets used throughout this post, playing on its own.

> **Not trying to read all 60 minutes of this in order?** Jump to whatever you're actually here for:
> - New to proteins? Start with the [crash course](#crash-course) on amino acids and structure.
> - Just want the models themselves? Skip to [the model landscape](#the-model-landscape).
> - Here for AlphaFold specifically? Go straight to [AlphaFold 2](#alphafold-2-bake-priors-through-architecture) or [AlphaFold 3](#alphafold-3-same-reasoning-different-bets).
> - Want to know how folds get *scored*? See [metrics for protein folding](#metrics-for-protein-folding).
> - More interested in designing proteins than predicting them? Jump to [RFdiffusion + ProteinMPNN](#rfdiffusion--proteinmpnn-solving-inverse-folding).
> - Want the one model that does everything at once? Go to [ESM3](#esm3-one-model-three-modalities).
{: .prompt-tip}

> **Best viewed on a computer.** The interactive widgets throughout this post are click-and-drag heavy and assume a real cursor and a wide screen — they'll be cramped or hard to use on a phone.
{: .prompt-warning}

### Proteins are just like sentences

Proteins are sequences of amino acids, and every protein in living things is simply a unique sequence of these amino acids.  The ordering alone determines the shape and functionality of these proteins.  Now when ML researchers came across this domain, they figured, if we have transformers that create sentences--i.e. sequences of words--why can't we have transformers create proteins, which are sequences of amino acids.

Essentially, we could just swap **words → amino acids**!

Below are two sequences: an English sentence and the first 15 residues of ubiquitin, one of the most studied proteins in biology. Click any token to see what a language model (BERT) and a protein language model (ESM C 300M) think about swapping it out.

[Interactive: Mutation Explorer](https://karthikvedula.com/assets/files/protein/mutation_explorer.html) — Click any token in an English sentence or the first 15 residues of ubiquitin to see what BERT and ESM C 300M predict as substitutes.

Both models actually show a similar pattern here. Some positions are flexible, some substitutions make the sentence (or amino acid sequence) still work. Some are locked — replacing the word destroys the grammar of the sentence (analogously, the structure of the protein).

Notice how this illustrates the core problem.  To make a sentence, you must choose and order words in the right way for a target meaning.  To make a protein, you must choose and order amino acids the right way for a target functionality.  The entire problem is to make a model be able to do this effectively!

### Crash course!

Before we dive deep, let's do a crash course on amino acids and proteins!

#### Amino acids

```
        R group
         │
Amino ── Cα ── Carboxyl
         │
         H
```

An amino acid is made of multiple parts.  The **amino group** and **carboxyl group** are the two ends that connect amino acids together into a long chain which is a protein. Every amino acid has the same amino and carboxyl groups, meaning the protein backbone is nearly identical regardless of the sequence.

The **R group** (or side chain) is the only part that differs between amino acids. There are 20 standard amino acids, each with a different R group. These side chains determine each amino acid's chemical properties and interact with one another, ultimately causing the protein to fold into its three-dimensional structure. 

When these amino acids link up to make a protein, each amino acid is called a **residue**.

Finally, the **Cα (alpha carbon)** is the central carbon atom that connects all four components. Since every amino acid contains exactly one Cα atom, structural biology uses its 3D coordinates as a representative ***location for the entire residue***. 

Here's what that skeleton actually looks like in 3D. Drag to rotate the molecule below, and notice how the amino group, α-carbon, and carboxyl group form a fixed, shared backbone — the R group is the only piece hanging off to the side, waiting to be swapped out for one of the 20 options.

[Interactive: Anatomy of an amino acid](https://karthikvedula.com/assets/files/protein/amino_acid_anatomy.html) — Drag to rotate the amino acid skeleton and see how the amino group, alpha-carbon, and carboxyl group form a fixed backbone, with only the R group free to change.

> These protein models are rendered via [3Dmol.js](https://academic.oup.com/bioinformatics/article/31/8/1322/213186?login=false) -- super cool library!  Drag around with your mouse to rotate, right click and drag to pan.
{: .prompt-tip}

For example, some R groups are hydrophobic ("water-fearing") and prefer to be buried inside the protein away from water, while others are hydrophilic ("water-loving") and tend to remain exposed on the protein's surface. Some side chains carry positive or negative charges, attracting or repelling one another like magnets, while others can form hydrogen bonds that stabilize specific parts of the structure. The final folded protein is the **result of balancing thousands of these local interactions**, finding a stable three-dimensional arrangement that minimizes the protein's free energy.

[Interactive: What's a side chain?](https://karthikvedula.com/assets/files/protein/side_chain_gallery.html) — Explore how different R groups vary in hydrophobicity, charge, and hydrogen-bonding ability -- the local interactions that together determine how a protein folds.

Put together, a protein looks like this:

```
      R1          R2          R3
       │           │           │
H2N ─ Cα ─ C ─ N ─ Cα ─ C ─ N ─ Cα ─ C ─ OH
       │           │           │
       H           H           H
```


#### Four levels of structure

Proteins have four levels of structure, each emerging from the one below.

**Primary structure** is just the sequence. A string of amino acids, one after another. MQIFVKTLTG... This is what ESM trains on. This is the "text."

**Secondary structure** is what happens locally when the chain starts to fold. Certain stretches coil into helices, others flatten into sheets. These patterns are driven by hydrogen bonding between nearby residues and are relatively predictable from local sequence chemistry.

**Tertiary structure** is the full 3D shape of a single protein chain — how those helices and sheets pack together in space. This is what AlphaFold predicts. It's determined by long-range interactions between residues that may be hundreds of positions apart in the sequence. This is where it gets hard.

**Quaternary structure** is multiple chains coming together into a complex. Hemoglobin is four chains. AlphaFold 3 extended structure prediction to this level.

![Protein structure levels](https://upload.wikimedia.org/wikipedia/commons/a/a6/Protein-structure.png)
*The four levels of protein structure. (Source: [wikimedia](https://upload.wikimedia.org/wikipedia/commons/a/a6/Protein-structure.png))*

Below is an interactive showing the different levels.  Click the top buttons to view the different structures.

[Interactive: Four Levels of Protein Structure — Hemoglobin](https://karthikvedula.com/assets/files/protein/four_levels_of_structure.html) — Click the top buttons to view hemoglobin's primary, secondary, tertiary, and quaternary structure.

Each level comes from the one below it, but you can't predict it locally.  The sequence determines the 3D shape, yet no short stretch of the sequence tells you what that shape is.  You have to consider the whole sequence at once, which is why this problem is hard.  So it's surprising that protein language models, which only ever see sequences, learn anything about tertiary structure at all.  We'll see how they do it in the [ESM-1b section](#esm-1b-what-does-masked-language-modeling-learn-from-protein-sequences).

### The different protein modeling problems

Now protein models actually come in many types, each solving a different problem in the space.  We first want to be able to take a sequence and then be able to figure out how the protein will fold in 3D space.  This is the problem the famous AlphaFold models actually solve.  However, just knowing how a protein will fold isn't that useful.  We also need to know how its structure will affect its function—i.e. its behavior.  Finally, there's also an entire space of inverse-folding, where we want to start with what we want the protein to do (and hence what it should look like) and then come up with the sequence of amino acids that can produce this.  You can think of this inverse-folding problem as the thing that will enable us to make synthetic proteins for different applications.

```mermaid
flowchart LR
  SEQ["**Sequence**
  amino acid string"]
  STR["**Structure**
  3D coordinates"]
  FUN["**Function**
  what it does"]

  SEQ -->|folding| STR
  STR -.->|inverse folding| SEQ
  STR -->|structure → function| FUN
  SEQ -->|function prediction| FUN
```

Now a much simpler problem is the **representation problem**.  Before we even try to predict structure, we want to be able to represent amino acid sequences in a rich manner (embeddings).  Just like we have models like BERT for natural language, the protein domain has the same basic requirement: representing these amino acid sequences in a meaningful way that encodes important information about them.  Then we can use this model for downstream tasks, such as folding or function prediction, so they don't have to deal with understanding *what a sequence here means* and instead focus on *what to do with it*.

See below for an illustration of how ESM-2 turns a sequence into embeddings — the vectors shown are illustrative, not real ESM-2 activations.

[Interactive: PLM Embedding Explorer](https://karthikvedula.com/assets/files/protein/embedding.html) — An illustration of how ESM-2 turns a sequence into embeddings for a sequence, using illustrative (not real) vector values.

Just like BERT, each vector depends on the residue's context as well as its amino acid.  The three T residues at positions 7, 9, and 12 all get different vectors, even though they're the same letter, because their neighbors are different.

All these models are called **Protein Language Models (PLMs)** — transformers trained on protein sequences the same way BERT and GPT are trained on text. Some models combine multiple problems: ESMFold uses PLM embeddings to predict structure directly, skipping the need for a separate folding model. ESM3 goes furthest — it jointly reasons over sequence, structure, and function in a single model, so any modality can prompt any other.

See the table below for an overview—but don't feel nervous if it looks daunting, we'll break it down in this blog post!

| Problem | Models | Input → Output |
|---|---|---|
| Representation | [ESM-1b](https://www.pnas.org/doi/10.1073/pnas.2016239118), [ESM-2](https://www.science.org/doi/10.1126/science.ade2574), [ProtBERT](https://arxiv.org/abs/2007.06225), [ESM C](https://evolutionaryscale.ai/blog/esm-cambrian) | Sequence → Embeddings |
| Folding | [AlphaFold 2](https://www.nature.com/articles/s41586-021-03819-2), [RoseTTAFold](https://www.science.org/doi/10.1126/science.abj8754), [AF3](https://www.nature.com/articles/s41586-024-07487-w) | Sequence → 3D coordinates |
| Folding (from embeddings) | [ESMFold](https://www.science.org/doi/10.1126/science.ade2574) | PLM embeddings → 3D coordinates |
| Function prediction | [ESM-2 + head](https://www.science.org/doi/10.1126/science.ade2574), [SaProt](https://openreview.net/forum?id=6MRm3G4NiU) | Sequence → Function |
| Inverse folding | [ProteinMPNN](https://www.science.org/doi/10.1126/science.add2187), [RFdiffusion](https://www.nature.com/articles/s41586-023-06415-8) | Structure → Sequence |
| Multimodal | [ESM3](https://www.science.org/doi/10.1126/science.ads0018) | Any → Any |

### Hold up, proteins are NOT like sentences

So far, I've projected this protein modeling problem as being just like NLP.  I'm sorry to say that I may have actually severely overstated that :P.  **Turns out, there are a lot of difficult challenges in this domain.**

#### 1. The protein language only has 20 words

There are only 20 amino acids in nature.  So every single protein is a sequence of these 20 amino acids.  This means our protein models only have a vocabulary size of **20** tokens, compared to hundreds of thousands of tokens in GPT-4!

[Interactive: Vocabulary Comparison](https://karthikvedula.com/assets/files/protein/vocab_compare.html) — Comparing the 20-token amino acid vocabulary against GPT-4's vocabulary of hundreds of thousands of tokens.

> Technically 22 amino acids occur naturally — selenocysteine and pyrrolysine are rare, genetically-encoded exceptions found in a handful of organisms — and most models also reserve a token for unknown/non-standard residues (often X). The "20" convention holds for the vast majority of sequence data and is what virtually all PLMs are trained on.
{: .prompt-warning}

#### 2. Small errors yield catastrophic results

A single swap of an amino acid from Glutamate to Valine causes the hemoglobin protein (which is used to carry oxygen by red blood cells) to become unable to carry oxygen.

[Interactive: One Mutation, Different World](https://karthikvedula.com/assets/files/protein/sickle_cell.html) — A single Glutamate-to-Valine substitution causes hemoglobin to lose its ability to carry oxygen, as seen in sickle cell disease.

#### 3. No ground truth at scale

There are three main datasets in this space: [UniProt](https://www.uniprot.org/), [Protein Data Bank (PDB)](https://www.rcsb.org/), and [AlphaFold Database](https://alphafold.ebi.ac.uk/).  Let's go over what each of those contributes.

##### UniProt: tons of amino acid sequences

UniProt contains a bunch of amino acid sequences of different proteins—about ~250 million sequences in fact!  This is awesome—you can train models to predict the next amino acid (self-supervised learning) really easily at scale.  The problem is that not all of these sequences have *labels*—what each sequence actually corresponds to in terms of the protein's function.  This means it is really difficult to train models to predict downstream tasks, such as whether a mutation will cause a disease, or a protein's enzyme activity (i.e. how well it accelerates a reaction).  Of all the sequences only around 570,000 sequences have been manually curated by expert biologists — the rest are automatically annotated by rule systems.

{% capture uniprot_flow_content %}

Protein sequences are collected from genome sequencing labs worldwide and flow into TrEMBL, a massive database of ~246 million sequences that are automatically annotated by rule-based systems and ML models. A tiny fraction — around 570,000 — gets promoted to Swiss-Prot through expert human curation, where annotations are verified against published experimental evidence. Both feed into UniRef, a deduplicated version of the database that protein language models actually train on.

```mermaid
flowchart TD
  INSDC["Genome sequencing labs<br/>worldwide submit raw DNA sequences"]
  ENS["Genome annotation tools<br/>translate DNA into protein sequences"]
  UNIPARC["Complete archive<br/>of all known unique protein sequences"]
  FILTER["Quality checks<br/>remove duplicates and low-quality sequences"]
  TREMBL["TrEMBL<br/>~246M sequences<br/>not human-verified"]
  AUTO["Automatic annotation<br/>rule-based systems + ML models<br/>guess what each protein does"]
  LIT["Published research papers<br/>curators extract experimental findings"]
  COMM["Researcher submissions<br/>scientists contribute annotations"]
  CURATE(["expert curation"])
  SWISSPROT["Swiss-Prot<br/>~570K sequences<br/>human-verified, high confidence"]
  UNIREF["UniRef<br/>further deduplicated clusters<br/>what PLMs actually train on"]

  INSDC --> UNIPARC
  ENS --> UNIPARC
  UNIPARC --> FILTER
  FILTER --> TREMBL
  TREMBL --> AUTO
  AUTO --> TREMBL
  LIT --> SWISSPROT
  COMM --> SWISSPROT
  TREMBL --> CURATE --> SWISSPROT
  TREMBL --> UNIREF
  SWISSPROT --> UNIREF

  style CURATE fill:none,stroke:#888,stroke-dasharray: 3 3,color:#888
```
{% endcapture %}

{% include collapsible.html summary="Click here to see how UniProt's data flows from raw DNA to Swiss-Prot/UniRef" content=uniprot_flow_content mermaid=true %}


##### Protein Data Bank: dataset of experimentally verified structures

The PDB has around 200,000 experimentally verified examples of protein structures.  This is great—you really can't get a more accurate dataset than this.  The problem, though, is that 200,000 pales in comparison to the millions of amino acid sequences out there.  We really can't train a large model on just this 200,000 datapoints.  There is a whole lot more amino acid sequences out there that we don't know the shape for.

##### AlphaFold Database

The AlphaFold DB now contains more than 241 million predicted structures, essentially covering all of UniProt. This sounds like it closes the gap completely—and in some ways it does.  But the caveat is that these are *predicted* structures from their AlphaFold model.  These predictions could be wrong, making this not a gold-standard dataset.

As you can see, there is a major data shortage in this domain—despite being able to sequence the genome, which leads us to be able to store millions of amino acid sequences, the data of how these sequences behave as proteins simply isn't there at scale.

##### CASP: a competition, not a dataset

So how do we know whether any of these predicted structures, from AlphaFold or anyone else, can be trusted?  That's what **CASP (Critical Assessment of protein Structure Prediction)** is for.

CASP is a competition held every two years, where organizers work with biology labs around the world to identify target proteins that are being actively solved experimentally but haven't been published yet (i.e., no one publicly knows how it folds).  Organizers compile a set of proteins to test the ML models on.  At submission time these answers aren't known by the model-makers so this serves as an unbiased way of measuring model performance, where the test examples aren't leaked into the training data for these models.

> **Extra info on CASP:** It's run by an independent, worldwide research community and has taken place every two years since 1994.  Targets range from easy ones with close relatives in the PDB to new folds with no close relatives at all, so models get scored on both.  CASP ranks submissions with structure-comparison scores like GDT-TS and TM-score (covered below).  Recent rounds also have categories for protein complexes, RNA, protein–ligand complexes, and proteins with multiple shapes.  CASP14 (2020) is the round where AlphaFold 2 crossed a score threshold widely regarded as "solving" single-chain structure prediction.
{: .prompt-info}

#### 4. Verifying is difficult

Building off from the AlphaFold database discussion, even if you train a model to predict how a protein folds/behaves (or inversely find a predicted sequence given a target behavior), you need to then synthesize it in the lab in order to verify it actually works.  Contrast this with just having a human read a sentence from GPT to verify it makes sense.  Verifying PLM outputs is a physical, expensive task.  We've seen how much effort goes into CASP, and that serves as a testament for how hard verification is.

### Metrics for protein folding

So far we've discussed generally how proteins fold, challenges in the protein modeling space, and datasets within the field.  Before we dive into the models, we need to talk about one more thing: scoring model predictions.  There's quite a lot of science that goes into it.

#### Template modeling (TM) score

The TM score is, essentially, 

> Rotate the predicted protein until it lines up as well as possible. For every residue, give almost full credit if it's close, partial credit if it's somewhat off, and almost no credit if it's far away. Average those credits over the whole protein.

How is this expressed mathematically?  Like this:

$$
\mathrm{TM\text{-}score}
=
\max\left[
\frac{1}{L_{\mathrm{target}}}
\sum_{i=1}^{L_{\mathrm{common}}}
\frac{1}{1+\left(\frac{d_i}{d_0(L_{\mathrm{target}})}\right)^2}
\right],
$$

where,

$$
d_0(L_{\mathrm{target}}) = 1.24\sqrt[3]{L_{\mathrm{target}} - 15} - 1.8.
$$

Let's break down what all this means.

Fundamentally we want to compare pairs of residues in predicted and actual structures and aggregate the errors in a score.  $d_i$ is the distance between two corresponding residues.  We want to normalize this distance, so we divide this by $d_0(L_{target})$, which is a function of how long our target protein is ([empirically derived](https://pubmed.ncbi.nlm.nih.gov/15476259/)).  Why do we do this?  This is because if not, longer proteins will almost always look worse: more residues with small errors will add up over longer proteins.  A way to reason about this is to imagine two sticks, each bent by the same small angle.  The longer the sticks are, the further apart their ends end up, even though the bend itself is just as slight.  

![Two sticks with the same small bend, showing why distance error must be normalized by length](/assets/files/protein/two_sticks_length_normalization.png){:.light}
![Two sticks with the same small bend, showing why distance error must be normalized by length](/assets/files/protein/two_sticks_length_normalization_dark.png){:.dark}
*A short stick and a long stick bend by the same small angle. The short stick's endpoints end up close together, but the long stick's endpoints end up far apart — same bend, very different raw distance error.*

To smoothen this out, this $d_i / d_0(L_{target})$ is put as input in the $y = 1/(1+ x^2)$ graph.

[Interactive: TM-score Per-Residue Weighting Curve](https://karthikvedula.com/assets/files/protein/tm_score_curve.html) — The per-residue weighting curve y = 1/(1+x^2) used in TM-score: it approaches 1 as distance error goes to 0, and approaches 0 as the error grows large.

Notice how this curve reaches 1 when the distance (error) approaches 0, and approaches 0 when the distance gets large.  The curve also doesn't blow up with large inputs.  Together,

$$\frac{1}{1+\left(\frac{d_i}{d_0(L_{\mathrm{target}})}\right)^2}$$

is a way of taking each error distance and weighting the scores in a normalized manner.  Close residues are given score of near 1, and the rest are zeroed out, all while keeping in mind that we need to de-bias against long proteins.

We compute the average of the scores by adding them up and then dividing by $L_{target}$, the length of the actual protein.  We use $L_{target}$ and not $L_{common}$ because if the predicted protein has different amino acids, we don't even want to allow that to contribute to the score.

Finally, $\max$ here ensures the expression is evaluated when the two structures (predicted and actual) are most aligned with each other (think of how we align two sticks to be parallel to see which is longer), since any misalignment only lowers the score.

#### Long-range contact precision

Contact precision is defined as follows: for a protein of length $L$, take the top $L$ predicted contacts — pairs of amino acids indexed $i, j$ that the model is most confident are within 8Å.  The fraction of such pairs that are actually contacts is precision.  "Long-range" qualifies this metric as only picking pairs that are far apart (i.e. $\|i - j\| \geq 24$).  Why do they measure only long range pairs?  Because short-range contacts (like adjacent amino acids) are trivially connected since the backbone (i.e. the sequence ordering) connects them.  Even close amino acid contacts only contribute to secondary structure, meaning if we want to actually measure the difficult tertiary and quaternary structure prediction, we need to sample longer range pairs to get those examples.

This answers:

> "When the model is most confident, how often is it right?"

> Why 24 as the magic number?  This was also [empirically found](https://pmc.ncbi.nlm.nih.gov/articles/PMC3823628/) and now everyone agrees as this as the standard.
{: .prompt-tip}


#### Model confidence: pLDDT and PAE

Now these metrics go over how we can get model confidence when model folds.

##### pLDDT: Local Distance Difference Test

The naive approach would be to treat some internal network activation as a confidence score. But there is no reason a raw activation should correspond to anything meaningful. Instead, AlphaFold is trained to predict a well-defined quantity: **lDDT** (Local Distance Difference Test).

lDDT measures **local** structural accuracy. For each residue, it compares the predicted structure with the true structure by checking whether the distances to nearby atoms (within roughly 15 Å) are preserved. Because it only looks at a residue's local neighborhood, a residue can have a high lDDT score even if another part of the protein is positioned incorrectly.  Essentially, lDDT asks,

> For each residue, look at the other residues sitting close to it. In the model's predicted structure, do those neighbors sit the same distance away as they do in the real, experimentally-determined structure?

During training, the true structure is available, so the correct lDDT score can be computed for every residue. The model learns to predict these scores from many examples. At inference time, the true structure is unknown, so instead of computing lDDT, the model estimates what the lDDT score would be if the true structure were available. This predicted score is called **pLDDT**, and it ranges from 0 to 100 for each residue.

Here's a real AlphaFold 2 prediction — human lysozyme C — with its pLDDT scores baked directly into the structure (AlphaFold stores per-residue pLDDT in the B-factor column, which is exactly what's driving the coloring below). Toggle between AlphaFold DB's four discrete confidence bins and a continuous gradient over the same underlying values, and notice which parts of the structure the model is least sure about.

[Interactive: AlphaFold pLDDT Confidence Viewer — Lysozyme C](https://karthikvedula.com/assets/files/protein/plddt_confidence_viewer.html) — A real AlphaFold 2 prediction of human lysozyme C colored by pLDDT. Toggle between AlphaFold DB's four confidence bins and a continuous gradient to see which parts of the structure the model is least sure about.

##### PAE: Predicted Aligned Error

While pLDDT tells you how each residue is positioned within its locality, it cannot tell you, for example, whether a pair of residues on opposite sides of the protein are positioned correctly.  Predicted Aligned Error measures, for each residue pair $i, j$ in the protein, 

> If residue $j$ is fixed in place, how accurately do I know where residue $i$ should be?

This too, is learned by the model as part of its output.  It is important to use both pLDDT and PAE since a protein can have high pLDDT everywhere — i.e. individual residue neighbors are positioned correctly with each other, but one section of the protein as a whole is wrongly positioned with respect to another.

The best way to visualize / interpret PAE is through a grid, like what's below:

Take a toy 6-residue protein made of two contiguous domains: residues 1–3 form domain A, residues 4–6 form domain B. Since each domain folds rigidly on its own, any pair of residues *within* the same domain gets a confident, low PAE score.  This includes residues 4 and 6 (outlined in the grid below), which aren't next to each other in the sequence but sit in the same rigid block. Pairs that straddle the two domains get a high, uncertain PAE score, because how the two domains are oriented relative to each other is hard to pin down.  This includes residues 3 and 4, which are right next to each other in the sequence.  So being close in sequence doesn't make a pair low-PAE.

![A PAE grid for a toy 6-residue protein with two contiguous domains, showing confident diagonal blocks and uncertain off-diagonal blocks](/assets/files/protein/pae_grid_contiguous_blocks.png){:.light}
![A PAE grid for a toy 6-residue protein with two contiguous domains, showing confident diagonal blocks and uncertain off-diagonal blocks](/assets/files/protein/pae_grid_contiguous_blocks_dark.png){:.dark}
*Diagonal blocks (same domain) are dark blue: low PAE, confident. Off-diagonal blocks (different domains) are amber: high PAE, uncertain. The color depends on which domain each residue is in.*

> Take a look at [this resource](https://pae-viewer.uni-goettingen.de/) from University of Göttingen to see an interactive view of PAE.  **It has a visual for PAE in a similar style to the other ones in this blog**
{: .prompt-tip}


### Metrics for physical/energetic plausibility

So far, we've gone through metrics that are based on knowing the correct answer -- i.e. the way the protein truly folds.  However, there are other ways to get an idea if a predicted protein fold is valid or not.  This is all based on heuristics derived from science, such as:

* Proteins should fold in a way where they are at a low energy state (as that's stable)
* Atoms should not collide with each other, as that's impossible

#### DOPE (Discrete Optimized Protein Energy)

[DOPE](https://onlinelibrary.wiley.com/doi/10.1110/ps.062416606) is a statistical potential — meaning it's not derived from physics, but instead learned from patterns observed across thousands of known, experimentally solved protein structures in the PDB.  DOPE operates by looking at a pair of atoms, and asking "How often in nature do these two atoms sit at this distance."  Now, since this is $O(N^2)$ for all atom pairs, DOPE is really just calculated for atom pairs less than 15Å apart.

$$
\mathrm{DOPE} = -k_B T \sum_{i<j} \ln\left[\frac{p(r_{ij})}{p^{rs}(r_{ij})}\right]
$$

where:

- $r_{ij}$: the distance between two atoms in our model. This is the raw error signal — just how far apart these two atoms actually ended up.
- $p(r_{ij})$: how often this pair of atom types shows up at this distance, counted across thousands of real, experimentally solved protein structures.
- $p^{rs}(r_{ij})$: the reference state.  Even with no chemistry involved, some distances are more likely than others.  If you scatter two random points inside a ball the size of a folded protein, very short and very long distances are rare and medium distances are common.  Dividing by this geometric baseline leaves only the chemical preference.
- $k_B$: Boltzmann's constant.  It keeps the formula in the same form as the Boltzmann relation $p \propto e^{-E/k_BT}$, which lets us turn a probability ratio into something **that behaves like an energy.**
- $T$: a fixed reference temperature.  Nothing is actually being simulated at this temperature.  It's only there to complete the conversion from probability to a pseudo-energy.

[Interactive: DOPE Distance Scoring Curve](https://karthikvedula.com/assets/files/protein/dope_curve.html) — The DOPE statistical potential curve, built from how often pairs of atom types are observed at each distance across thousands of solved protein structures.

> Remember: proteins want to be at the most stable state, meaning at the lowest energy level.  Predicted configurations with high energies are likely not possible in nature.
{: .prompt-tip}

#### MolProbity Score

MolProbity combines several independent geometric sanity checks into a single composite score.

##### Clash score
Every atom has a physical size (its van der Waals radius — basically "how much space it takes up before it starts repelling neighboring atoms"). A clash happens when two atoms that aren't bonded to each other get placed closer together than physics allows — their electron clouds would be overlapping, which is energetically catastrophic and never happens in a real, stable protein.

Clash score is simply: the number of serious atomic clashes per 1,000 atoms in the structure. Lower is better — a good experimental structure typically has a clash score in the single digits; a bad or unrefined model can have scores in the dozens.

The reason it's normalized "per 1,000 atoms" rather than as a raw count is the same reason TM-score divides by protein length: bigger proteins have more atoms and more opportunities for clashes, so you need to normalize to compare a 100-residue protein fairly against a 500-residue one.

##### Ramachandran outliers

Remember from the crash course: every amino acid shares the same backbone — amino group, Cα, carboxyl group — strung together into a chain. That backbone isn't rigid. Two of its bonds can rotate freely: the N–Cα bond and the Cα–C bond, called φ (phi) and ψ (psi) respectively. Everything else in the backbone (the peptide bond linking one residue to the next) is locked flat by resonance, so phi and psi are really the only two knobs each residue has to turn. Get enough residues turning their knobs in a coordinated way and you get a helix; turn them a different coordinated way and you get a sheet.

You'd think two continuous angles, each free to spin 360°, would give you a huge space of possible shapes per residue.  However, most (φ, ψ) combinations jam backbone atoms into each other, the same steric-clash problem from the clash-score section, just visualized locally instead of aggregated over a whole structure. **G.N. Ramachandran** [worked this out in 1963](https://pubmed.ncbi.nlm.nih.gov/13990617/), before anyone had a computer that could fold a protein: plot every residue's φ against its ψ, and the allowed conformations cluster into a handful of tight islands, surrounded by a sea of geometrically impossible space. That plot is now the standard first-pass sanity check for any modeled or solved structure — it's literally one of the three ingredients baked into the MolProbity score you already met. Below, you can drag a point around that space yourself and watch a real backbone fragment twist to match, including the two outliers — glycine and proline — that live by different rules.

[Interactive: Ramachandran Plot — φ/ψ Explorer](https://karthikvedula.com/assets/files/protein/ramachandran.html) — Drag a point around phi/psi space and watch a real backbone fragment twist to match -- most combinations are geometrically impossible, and allowed conformations cluster into a few tight islands, with glycine and proline as outliers.

##### Sidechain rotamer outliers

Side chains (i.e. R groups) rotate too.  Lysine, for example, has a whole tail of rotatable bonds flapping around, each one called a chi angle (χ1, χ2, and so on, counting outward from Cα).

[Interactive: Lysine side chain — χ1–χ4](https://karthikvedula.com/assets/files/protein/lysine_chi_angles.html) — Lysine's side chain has a tail of rotatable chi angles (χ1, χ2, ...), counting outward from the Cα.

Those bonds don't spin freely either.  Like φ/ψ, they cluster into a few preferred positions, roughly three per bond and about 120° apart.  A side chain in one of those preferred positions is called a **rotamer**.  Like the Ramachandran regions, the list of preferred positions comes from what shows up over and over in real, solved structures.

A **rotamer outlier** is a side chain that isn't in any of those positions.  It might not clash with anything, but it's a shape real proteins almost never use.  This is the third thing MolProbity checks, after clashes and backbone angles.


### The model landscape

[Interactive: PLM Model Landscape](https://karthikvedula.com/assets/files/protein/model_landscape.html) — An overview of protein language models and how they relate to each other.

#### ESM-1b: what does masked language modeling learn from protein sequences?

ESM-1b takes the standard BERT objective of masked language modeling (based on RoBERTa architecture) used in NLP and applies it to proteins.  The idea is to have 15% of the residues (amino acids) masked at random, and have the model learn to fill in the blanks.  This is an attempt to solve the *representation problem*: if a model can fill in the missing amino acids, it probably means that it has a good idea of how proteins work.

However, like BERT, this is an *embedding model*—it can't predict specifically protein structure or anything useful on its own.  Instead, researchers attached probes (i.e. extra additions to the network) and fine-tuned ESM-1b for specific tasks.  One task is *unsupervised contact prediction*.  This is where a logistic regression probe (with the rest of the weights frozen) is attached to the ESM model and trained on 20 protein structures.  For a given pair of residues (i, j), it finds the probability that they are in physical contact in 3D space.  Concretely,

```
input:  attention[head_1][i][j], attention[head_2][i][j], ... attention[head_600][i][j]
output: P(distance(i,j) < 8Å)
```

Note that Å is an Angstrom, or $10^{-10}$ meters, where 8Å is a close enough distance to assume the two residues contact each other.


Remember the question from the [four levels of structure](#four-levels-of-structure) section: how can a model that only sees sequences learn anything about how a protein folds?  The answer is **coevolution**.  To fill in a masked residue, the model has to predict it from the rest of the sequence.  A good way to do that is to notice pairs of positions that mutate together across evolution.  Those pairs usually mutate together because they're in physical contact, so a change at one needs a matching change at the other.  Self-attention can learn these pairings, and they show up in the attention maps.  That's what the contact-prediction probe above reads out.

Below is a real ESM-1b forward pass over ubiquitin, no fine-tuning, with attention heads ranked by how well they predict real contacts. Some heads are near-random; others land startlingly close to the true contact map, just from being trained to fill in the blanks.

What matters is whether a head's attention shows up **off the diagonal**. On-diagonal attention is trivial — adjacent residues are chemically bonded, so of course they're relevant to each other. Off-diagonal attention connects residues far apart in sequence, and the only reason that would matter is if the chain folded back and put them physically close in 3D.  This means the model has internally learned, to some extent, how a protein folds just by looking at the amino acid sequence.

[Interactive: ESM-1b Attention vs. Real Contacts — Ubiquitin](https://karthikvedula.com/assets/files/protein/esm1b_attention_explorer.html) — A real ESM-1b forward pass over ubiquitin, no fine-tuning, with attention heads ranked by how well they predict real physical contacts -- some heads land startlingly close to the true contact map.

Now it might be a bit confusing visualizing what the contact map on the left actually means.  See below for how to interpret the graph.

Look at the real contact map on the left of that widget.  Cell $i,j$ is filled in if residue $i$ is in contact with residue $j$.  Right next to the main diagonal, there's a second, thinner line.  Pick "Helix turn" below to see where it comes from.  As an alpha helix coils, residue $i$ hydrogen-bonds to residue $i{+}4$, so every residue in the helix is close to the one four positions ahead.  That fixed offset is what draws the second line.

Now pick "Sheet pairing."  Here the chain folds back on itself, so two strands that are tens of residues apart in the sequence end up lying side by side.  Those contacts show up far from the diagonal.

[Interactive: Contact Map ↔ 3D Structure — Ubiquitin](https://karthikvedula.com/assets/files/protein/contact_map_3d_linked.html) — Cell (i,j) in the contact map shows whether residues i and j are in contact; try "Helix turn" and "Sheet pairing" to see how local and long-range folding patterns show up as bands off the main diagonal.

#### ESM-2 & ESM C: do scaling laws hold for proteins?

ESM-2 is basically ESM-1b's architecture scaled up. It comes in six sizes, from 8M parameters up to 15B.

But does scaling actually work here? Drag the slider through all six real checkpoints and watch what happens to contact precision and structure prediction quality. The published numbers are pretty clear about it: performance shoots up early, then flattens out hard. Going from 3B to 15B (a 5x jump in parameters) barely moves the needle compared to what that same 5x jump did way back at 8M to 35M.

[Interactive: ESM-2 Scaling Laws — 8M to 15B](https://karthikvedula.com/assets/files/protein/esm2_scaling_laws.html) — Drag the slider through ESM-2's six real checkpoints (8M to 15B parameters) to see contact precision and structure quality improve early, then flatten out.
Maybe the 15B ESM-2 model didn't actually hit a limit—it just didn't see enough data. Researchers at BioMap and Tsinghua University [(paper)](https://proceedings.neurips.cc/paper_files/paper/2024/file/8066ae1446b2bbccb5159587cc3b3bcc-Paper-Conference.pdf) tested this. Every ESM-2 size was trained on the same ~1 trillion tokens: roughly 22 billion unique tokens repeated 45 times. Their analysis suggested that compute would've been better spent on a larger model with fresher data. They trained a **10.7B model on ~260B mostly fresh tokens**, which beat ESM-2 3B and matched or beat ESM-2 15B on most benchmarks.

The ESM team later took a similar approach with **ESM C**, released in December 2024, training each size on **6.2T tokens** instead of ESM-2's ~1T. The result is essentially the flattening curve from above, fixed: ESM C 300M matches ESM-2 650M, 600M rivals 3B, and 6B beats every ESM-2 model.  ESM C also deliberately overtrained its smaller models, since spending more on training a cheap-to-run model can be worthwhile in practice.

#### AlphaFold 2: bake priors through architecture 

Now we'll talk about AlphaFold 2 (AF2), the huge breakthrough model in this space.  To understand it best, let me show you how it looks like from a high level.

AlphaFold 2 fundamentally splits the task of protein folding into two steps:

1. Generate a good representation of which residues connect to which (Evoformer)
2. Iteratively generate the protein 3D structure given the representations (Structure module)

Here's the full pipeline.  We'll go through each box in order.

```mermaid
flowchart TD
  SEQ["**Sequence**"]
  SEARCH["**MSA + template search**
  jackhmmer, HHblits"]

  subgraph EVOFORMER [" Evoformer — 48 blocks "]
    direction LR
    MSA["MSA
    row + column attention"]
    PAIR["Pair grid
    triangle update + attention"]
    MSA -->|outer product mean| PAIR
    PAIR -.->|bias| MSA
  end

  STRUCT["**Structure module**
  Invariant Point Attention"]
  FINISH["Side chains + confidence
  χ angles · pLDDT · PAE"]
  OUT["**3D structure**"]

  SEQ --> SEARCH --> EVOFORMER
  EVOFORMER --> STRUCT --> FINISH --> OUT
  OUT -.->|recycled 3×| EVOFORMER
```

Let's first talk about step 1.  This part of AlphaFold is called the **Evoformer**.  It works by keeping two representations of the same protein side by side, and repeatedly updates each one using the other.  There are 48 Evoformer blocks stacked up.  They all have the same design, but each one has its own weights.

The first representation is the **Multiple Sequence Alignment (MSA)**.  MSA has similar protein sequences from different organisms lined up.  This is used by the model to detect evolutionary / coevolutionary patterns (just like what ESM-1b tried in its pretraining).  Essentially, imagine lining up the amino acid sequences for a human, a dog, and a cat.  If positions 1 and 3 mutate together across species, there is a good chance they do so because they are connected.  This is what AlphaFold leverages to enrich its representations.

The second is the **pair grid**, which the paper calls the *pair representation*.  It has one cell per pair of positions.  It starts out holding very little: the two amino acid types and how far apart the positions are in the sequence.  If the search found similar proteins with known structures (called *templates*), their residue distances get added in too.  The pair grid is where AlphaFold writes down what it thinks about each pair of residues, and it later uses this to actually predict how the protein folds.

The rest of the Evoformer is these two representations trading information back and forth.  Take a look at both below.

[Interactive: Two data forms — MSA and pair grid](https://karthikvedula.com/assets/files/protein/intro_two_data_forms.html) — AlphaFold 2's two core representations: the Multiple Sequence Alignment (MSA) and the pair grid, which repeatedly trade information.

##### Row attention

Let's start with the MSA.  A residue's letter on its own doesn't say much.  Knowing position 1 is Methionine doesn't tell you what role it plays.  What matters is how position 1 relates to the other residues in the protein, and some of those relationships matter a lot more than others.

Attention is how the model figures out which ones matter.  **Row attention** runs attention within a single sequence (one row of the MSA).  For one position, it scores how relevant every other position in that row is.  The score has two parts.  One is the usual attention comparison of the two residues' vectors.  The other is a bias term read from the pair grid, so whatever the pair grid has learned about that pair in earlier blocks feeds into the score.

[Interactive: Row attention](https://karthikvedula.com/assets/files/protein/row_attention_why.html) — Row attention scores how relevant each position in a sequence is to a given position, biased by the pair grid's existing opinion about that pair.

##### Column attention

**Column attention** runs along the other axis of the MSA.  It fixes one position and compares what every species has there.  For example, say the dog has a K at position 2.  The useful signal is in what the other species have at that same spot.  If they all agree, this position is probably constrained.  If they vary freely, it probably isn't under much selective pressure.  Column attention lets every species' version of a position look at every other species' version, so the model can pick up on how conserved that position is.

[Interactive: Column attention](https://karthikvedula.com/assets/files/protein/column_attention_why.html) — Column attention compares what every species has at one fixed position, using how much they agree to decide how much each one should inform the rest.

##### Outer product mean

Row and column attention both update the MSA using the MSA.  So far the pair grid has only been read from.  **Outer product mean** is the first step that writes MSA information into it.

The idea comes from coevolution.  If two positions are close together in the folded protein, a mutation at one usually needs a matching mutation at the other to keep the structure intact.  Across many species, that shows up as the two positions varying together.  This signal is spread out over every row of the MSA, and it is weak in any single row.

So for each pair of positions $i$ and $j$, outer product mean takes the vectors for $i$ and $j$ in one species and multiplies them together (an outer product).  It does this for every species and averages the results.  If $i$ and $j$ vary together, the products line up and the average stays large.  If they vary independently, the products point in random directions and the average shrinks toward zero.  The result is written into pair grid cell $(i,j)$.

[Interactive: Outer product mean](https://karthikvedula.com/assets/files/protein/outer_product_why.html) — Outer product mean multiplies each pair of positions' vectors together species by species and averages the results, concentrating scattered coevolutionary signal into the pair grid.

##### Triangle update

Every step so far moves information between the MSA and the pair grid.  None of them let one pair grid cell update another.  The next two steps, triangle update and triangle attention, do exactly that.

The intuition comes from geometry.  If residue $i$ is close to residue $k$, and $k$ is close to $j$, then $i$ can't be very far from $j$.  This is the *triangle inequality*.  So what the pair grid says about $(i,k)$ and $(k,j)$ should be useful when figuring out $(i,j)$.

For a target cell $z_{ij}$, the **triangle update** looks at every possible third residue $k$.  It combines $z_{ik}$ and $z_{kj}$ into a message about $(i,j)$, then sums those messages over all $k$:

$$
z_{ij} \leftarrow z_{ij} + \sum_k f(z_{ik}, z_{kj})
$$

Each $k$ forms a triangle $i$–$k$–$j$, which is where the name comes from.

Explore this below: pick a cell, and see how it is updated through triangle update.

[Interactive: Triangle update — a sweep over the pair grid](https://karthikvedula.com/assets/files/protein/triangle_update_interactive.html) — Pick a pair grid cell (i,j) and see how it's updated by summing messages from every third residue k, forming a triangle i-k-j.

> - Each cell above is one number.  A real pair grid cell is a 128-dimensional vector, and none of it is literally a distance in Ångströms.
> - The triangle inequality is the motivation for this step.  The step itself never checks any distances.  It combines cells $(i,k)$ and $(k,j)$ through learned weights and adds the result to cell $(i,j)$.
{: .prompt-warning}

{% capture triangle_update_math %}
AlphaFold 2 calls this the **triangular multiplicative update**.  It runs two variants, one using "outgoing" edges and one using "incoming" edges.  Here's the outgoing version, for pair grid cell $z_{ij}$:

$$
a_{ik} = \sigma\big(W_{a_1}\,\mathrm{LN}(z_{ik})\big) \odot \big(W_{a_2}\,\mathrm{LN}(z_{ik})\big)
$$

$$
b_{jk} = \sigma\big(W_{b_1}\,\mathrm{LN}(z_{jk})\big) \odot \big(W_{b_2}\,\mathrm{LN}(z_{jk})\big)
$$

$$
\Delta z_{ij} = \sigma\big(W_{g}\,\mathrm{LN}(z_{ij})\big) \;\odot\; W_{\text{out}}\,\mathrm{LN}\!\left(\sum_{k} a_{ik} \odot b_{jk}\right)
$$

$$
z_{ij} \leftarrow z_{ij} + \Delta z_{ij}
$$

where $\mathrm{LN}$ is LayerNorm, $\sigma$ is the sigmoid function, $\odot$ is elementwise multiplication, and every $W$ is a learned linear projection.

How this maps to the interactive above:

- $a_{ik}$ and $b_{jk}$ are gated, projected versions of cells $(i,k)$ and $(j,k)$.  The raw cell values never get combined directly.
- The outgoing version uses $(j,k)$ where the simplified equation above used $(k,j)$.  The pair grid isn't symmetric, so this is a different cell.  The incoming version uses $z_{ki}$ and $z_{kj}$ instead.  Running both covers both directions.
- $\sum_{k} a_{ik} \odot b_{jk}$ is the sweep the widget animates: combine, then sum over every third residue $k$.
- $\sigma(W_g \mathrm{LN}(z_{ij}))$ is a gate computed from the current value of cell $(i,j)$.  It controls how much of the summed update gets added to the cell.
{% endcapture %}

{% include collapsible.html summary="Click here for the real math behind triangle update" content=triangle_update_math mermaid=true %}

##### Triangle attention

Triangle update adds up a message $m_k$ from every third residue $k$, all with equal standing:

$$
m_{ij} = m_1 + m_2 + m_3 + m_4
$$

But some third residues are probably more informative than others.  **Triangle attention** learns a weight for each $k$:

$$
m_{ij} = 0.05\,m_1 + 0.10\,m_2 + 0.80\,m_3 + 0.05\,m_4
$$

Here $k_3$ dominates the update and the others contribute very little.  These weights come from attention.

The target cell $z_{ij}$ is projected into a **query** $q_{ij}$.  Each candidate cell $z_{ik}$ is projected into a **key** $k_{ik}$.  The query and key are compared with a dot product, and the third side of the triangle, $z_{jk}$, adds a bias:

$$
s_{ijk} = q_{ij} \cdot k_{ik} + b_{jk}
$$

A softmax over all $k$ then turns the scores into weights that add up to 1.  So if one $k$ gets more weight, the others get less.

Try it below: pick a cell, and see which triangles get the most weight.  The widget's "q·k" is $q_{ij}\cdot k_{ik}$ and "bias" is $b_{jk}$, so the score building up in each row is $s_{ijk}$ above.

[Interactive: Triangle attention](https://karthikvedula.com/assets/files/protein/triangle_attention_why.html) — Pick a cell and see which candidate triangles get the most weight -- unlike triangle update's plain sum, triangle attention weights each third residue with a softmax.

> - In the real model, q&middot;k is a dot product between projected vectors.  The widget simplifies both to one number, so it's just their product.
> - The query comes from $(i,j)$ itself.  That's why q&middot;k changes when you pick a different target cell, even for the same candidate $k$.
{: .prompt-warning}

{% capture triangle_attention_math %}
AlphaFold 2 calls this **triangular self-attention**.  Like triangle update, it runs two variants: attending around the starting node (row $i$) or the ending node (column $j$).  Here's the starting-node version, for pair grid cell $z_{ij}$ attending over every $k$ in row $i$:

$$
q_{ij} = W_Q\,z_{ij} \qquad k_{ik} = W_K\,z_{ik} \qquad v_{ik} = W_V\,z_{ik} \qquad b_{jk} = W_B\,z_{jk}
$$

$$
s_{ijk} = \frac{q_{ij}^{\top} k_{ik}}{\sqrt{d}} + b_{jk}
$$

$$
\alpha_{ijk} = \operatorname{softmax}_k\big(s_{ijk}\big)
$$

$$
z_{ij}^{\text{new}} = \sum_{k} \alpha_{ijk}\, v_{ik}
$$

where $d$ is the key dimension and every $W$ is a learned linear projection.

How this maps to the interactive above:

- $z_{ij}$ only enters through $q_{ij}$.  The output is built entirely from the $v_{ik}$'s.
- $b_{jk}$ comes from $z_{jk}$, the third side of the triangle.  This bias is what makes it *triangle* attention instead of plain self-attention.
- $\alpha_{ijk}$ is one softmax across every $k$ in the row, so raising one weight lowers the others.  In triangle update, every $k$ is added in with no weighting.
- The ending-node variant has the same shape, attending over column $j$: keys and values come from $z_{kj}$, and the bias comes from $z_{ki}$.

It uses the same three cells as triangle update: $z_{ij}$, $z_{ik}$, $z_{jk}$.  Here they become a query, keys and values, and a bias.
{% endcapture %}

{% include collapsible.html summary="Click here for the real math behind triangle attention" content=triangle_attention_math mermaid=true %}

##### Structure Module and Invariant Point Attention

After 48 Evoformer blocks, AlphaFold has a pair grid full of learned information about every pair of residues.  Now it has to actually place the residues in 3D.  This is step 2, the **Structure Module**.  It takes the pair grid, plus one vector per residue called the *single representation* (taken from the MSA row for the target protein).

The Structure Module gives each residue a **rigid frame**:

$$
T_i = (R_i, t_i)
$$

Think of this as a little coordinate system attached to residue $i$: $R_i$ is a rotation that says which way it's pointing, and $t_i$ says where it is.  Every frame starts at the origin.  The Structure Module then runs 8 times (with shared weights), adjusting the frames a little each time until the protein settles into a 3D arrangement.

Each run uses **Invariant Point Attention (IPA)** to decide which residues each residue should pay attention to.  IPA adds up three terms for each pair of residues $i$ and $j$:

1. Scalar features: do their learned vectors match?
2. Pair information: what does the pair grid say about $(i,j)$?
3. 3D geometry: are their learned points close in space?

The third term is the new part.  Residue $i$ learns a query point $q_i^p$, written in its own local coordinates.  Its frame places that point in the global coordinates of the protein:

$$
T_i(q_i^p) = R_i\,q_i^p + t_i
$$

Residue $j$'s key point is placed the same way, as $T_j(k_j^p)$.  Then the two points are compared by their distance:

$$
\left\lVert T_i(q_i^p)-T_j(k_j^p) \right\rVert
$$

This distance doesn't change if you move or rotate the entire protein.  A translation shifts both points equally, so it cancels out.  A rotation doesn't change distances.

There's a name for this property.  **SE(3)** is the set of every way you can move a rigid object around in 3D: any rotation combined with any shift.  (It stands for the *special Euclidean group* in 3 dimensions.)  Something is **SE(3)-invariant** if it comes out exactly the same no matter which of these moves you apply to the input first.  IPA's attention scores are SE(3)-invariant.  This matters because the protein's position and orientation in space are arbitrary, so the model's prediction shouldn't depend on them.

Step through this on a real structure below.

[Interactive: Real frames on a real backbone](https://karthikvedula.com/assets/files/protein/ipa_real_frames.html) — Step through Invariant Point Attention on an actual protein structure, comparing learned query and key points placed into 3D space via each residue's local frame.

Putting the three terms together gives the attention weight:

$$
a_{ij}
=
\operatorname{softmax}_j
\left(
\underbrace{\frac{q_i\cdot k_j}{\sqrt{c}}}_{\text{scalar attention}}
+
\underbrace{b_{ij}}_{\text{pair grid}}
-
\underbrace{
\frac{\gamma}{2}
\sum_p
\left\lVert
T_i(q_i^p)-T_j(k_j^p)
\right\rVert^2
}_{\text{3D point attention}}
\right)
$$

The distance term is subtracted, so residues whose points are close together get more attention.  This means the current 3D geometry affects which residues attend to each other.

##### Finishing up

A few more pieces complete the pipeline from the diagram at the top of this section:

- **Side chains.**  IPA only moves the backbone frames.  A separate small network predicts each residue's **χ (chi) angles**, the torsion angles that rotate its side chain into place.
- **Confidence.**  The model also outputs the confidence scores from the [metrics section](#model-confidence-plddt-and-pae): **pLDDT** for each residue and **PAE** for each pair.
- **Recycling.**  The whole thing (Evoformer, then Structure Module) runs again with its own output fed back in as input.  By default AF2 recycles 3 times, so there are 4 passes in total.

#### AlphaFold 3: same reasoning, different bets

The biggest change in AlphaFold 3 (AF3) is **what it predicts**.  AF2 was built to predict the structure of a protein.  AF3 predicts structures of **complexes made from many kinds of molecules**: proteins, DNA, RNA, small-molecule ligands, ions, and chemically modified residues.  Most of the other changes follow from that.

The first change is how AF3 breaks its input into **tokens**.  AF2 had one token per residue.  AF3 still uses one token per standard amino acid or nucleotide.  But a ligand or modified residue doesn't fit a fixed vocabulary, so each of its atoms gets its own token.

The second change is that **the Evoformer becomes the Pairformer**.  AF3 still uses an MSA, but much less.  A small MSA module (4 blocks) folds the MSA into the pair grid, and then the MSA is thrown away.  The main trunk is the **Pairformer**, 48 blocks that update only the pair grid and the single representation.  The pair grid still gets the same triangle updates and triangle attention we went through above.  So most of what you learned in the AF2 section carries over.

The third change is that **the Structure Module becomes a diffusion module**.  *Diffusion* is a way of generating data by starting from random noise and removing it a little at a time.  We'll go through how it works in more detail in the [RFdiffusion section](#rfdiffusion).  AF3 starts with every atom at a random position and learns to move them, step by step, into a plausible structure.  It works on all atoms directly, so there are no residue frames and no separate χ-angle step for side chains.

The fourth change is that AF3 **drops built-in invariance**.  IPA was [SE(3)-invariant](#structure-module-and-invariant-point-attention) by design.  AF3's diffusion module isn't.  Instead, during training each structure is randomly rotated and shifted, so the model learns to give the same answer no matter how the input is oriented.

So the pair grid and triangle operations stay at the center of AF3.  The two big changes are the scope (proteins plus DNA, RNA, and small molecules) and how the final 3D coordinates are generated.

#### RFdiffusion + ProteinMPNN: solving inverse folding

So far we've just been talking about protein folding.  But remember, earlier on in the blog post, we outlined the different class of problems in this field.  One of them included **inverse folding**, where we know what kind of shape we want a protein to be, but don't know how to make it -- i.e. the amino acid sequence that works.  If we can do inverse folding, that means we can design new proteins to our liking.  Scientists at the Baker Lab at the University of Washington proposed a solution:

```mermaid
flowchart LR
    A[RFdiffusion] --> B[ProteinMPNN] --> C[AlphaFold 2]
```

1. RFdiffusion generates a new protein backbone/structure.  It essentially is here to "fill in the details" given a general shape of the protein provided by the human.
2. ProteinMPNN takes that backbone and designs an amino-acid sequence that should encode it.
3. AlphaFold 2 then predicts the structure from that sequence to check whether it actually folds back to the intended design.

##### RFdiffusion

RFdiffusion doesn't need a sequence at all.  It generates a new backbone structure from random noise.

It starts from **RoseTTAFold**, the Baker Lab's structure prediction model.  RoseTTAFold processes proteins using three tracks that pass information to each other: a **1D track** for individual residues, a **2D track** for residue pairs (like AF2's pair grid), and a **3D track** for the backbone coordinates.  RFdiffusion takes a trained RoseTTAFold and fine-tunes it to be a diffusion model.

Here's how the diffusion part works.  During training, take a real protein structure $x_0$ and add noise to it, producing a corrupted version $x_t$.  The larger $t$ is, the more noise.  The network is trained to predict the original structure from the noisy one:

$$
x_t \xrightarrow{f_\theta} \hat{x}_0
$$

To generate a new protein, we start from pure noise (random residue positions and orientations) and apply the network over and over.  Each step removes a bit of noise, until we end up with a plausible backbone.

Usually we don't want just any protein.  We want one that satisfies some structural constraint.  For example, suppose we already know a small binding motif that we want the final protein to contain.  The motif residues stay fixed exactly where they need to be, and the rest of the backbone is generated from noise around them:

[Interactive: Diffusion in 3D — noise to helix](https://karthikvedula.com/assets/files/protein/rfdiffusion_motif.html) — A known binding motif stays fixed in place while the rest of the backbone diffuses from noise around it.

We encode the known motif as a condition $c$, containing its structure and position.  The network now receives both the noisy protein and this condition:

$$
\hat{x}_0 = f_\theta(x_t, c)
$$

The conditions for training come from the training set itself.  Take a real protein, pick part of its structure to be the motif, and give the model that part's true coordinates as $c$.  The model has to reconstruct the rest of the protein from noise.  After many examples like this, the model learns how backbones tend to arrange themselves around a fixed piece.  At generation time, we give it the motif we care about, and it builds a new backbone around it.

The result is a designed **3D backbone**, but we still haven't figured out the ordering of amino acids that can make this.  That's the job of **ProteinMPNN**.

##### ProteinMPNN

ProteinMPNN starts from a protein backbone and asks: what amino acid sequence would fold into this structure?

It treats the backbone as a graph.  Each residue is a node.  Each residue is connected by edges to its 48 nearest neighbors in 3D.  Using 3D neighbors matters because two residues can be far apart in the sequence but right next to each other in the folded protein.

Each node has a vector $h_i$ for what the network currently knows about residue $i$.  Each edge has a vector $e_{ij}$ describing the geometry between residues $i$ and $j$, built from the distances between their backbone atoms.

Suppose we're trying to figure out what amino acid belongs at residue $i$.  Each neighbor $j$ sends a message to $i$, computed from both residues' vectors and the geometry between them:

$$
m_{ij}=\phi_\theta(h_i,h_j,e_{ij})
$$

Residue $i$ adds up the messages from all of its neighbors:

$$
m_i=\sum_{j\in N(i)}m_{ij}
$$

and uses the total to update its vector:

$$
h_i'=\psi_\theta(h_i,m_i)
$$

This is the basic idea of a **message-passing neural network (MPNN)**: neighbors send messages, the node adds them up, and the node updates its vector.

Step through it below.  Pick a residue, watch its neighbors send messages, watch those messages get added up, then watch the update.  Click any other node to repeat it somewhere else in the graph.

[Interactive: ProteinMPNN — message passing](https://karthikvedula.com/assets/files/protein/mpnn_message_passing.html) — Pick a residue and watch its neighbors send messages, sum them together, and update its representation -- the basic message-passing idea behind ProteinMPNN.

After several layers of this, each $h_i$ contains information about the 3D environment around position $i$.

Next, ProteinMPNN turns those vectors into actual amino acids.  It does this with an **autoregressive decoder**, which picks the sequence one residue at a time.  Suppose we've already chosen

$$
x_1=A,\qquad x_2=L,\qquad x_3=G
$$

To predict position 4, the decoder uses $h_4$ together with the residues chosen so far:

$$
p(x_4\mid h_4,x_1,x_2,x_3)
$$

For example, it might give $P(x_4=V\mid h_4,A,L,G)=0.42$.  After $V$ is chosen, it becomes part of the context for the next position:

$$
p(x_5\mid h_5,A,L,G,V)
$$

> I've simplified one thing above.  Real ProteinMPNN doesn't decode left to right.  During training, it picks a **random** order every time, so position 4 might be decided before position 1.  The main payoff is flexibility at design time.  If you already know the amino acids at some positions (say, a binding site), you can fix them and let the model fill in everything else around them.
{: .prompt-warning}

So the full sequence probability is a product over whatever order got sampled:

$$
p(x_1,\ldots,x_L \mid X) = \prod_{i=1}^{L} p\big(x_{\sigma(i)} \mid x_{\sigma(1)},\ldots,x_{\sigma(i-1)},\, X\big)
$$

where $X$ is the backbone and $\sigma$ is a random ordering of the positions.

Here's the whole pipeline:

```mermaid
flowchart TD
  A[Backbone] --> B[3D graph] --> C[Message passing] --> D[Structural representations] --> E[Autoregressive decoder] --> F[Amino-acid sequence]
```

#### ESM3: one model, three modalities

Every model so far goes in one direction: sequence to embedding, sequence to structure, or structure to sequence.  ESM3 is the model in the table near the start of this post marked **multimodal, any → any**.  Sequence, structure, and function all go into the same model, and it can predict any of them from the others.

Click through the architecture below.  The sections after it go through each piece in detail.

[Interactive: ESM3 architecture](https://karthikvedula.com/assets/files/protein/esm3_architecture.html) — Click through ESM3's architecture, where sequence, structure, and function all enter the same model and any modality can predict any other.

##### Structure tokenizer

Sequence already comes in discrete tokens, one of 20 amino acids.  Structure is continuous 3D geometry, so ESM3 uses a **learned structure tokenizer** to turn it into tokens.

For each residue, the tokenizer looks at its local neighborhood (its 16 nearest neighbors) and runs that geometry through a learned encoder.  The output is matched to the nearest entry in a learned codebook of **4,096 structure codes**.  This setup is called a *VQ-VAE* (vector-quantized autoencoder).

```mermaid
flowchart LR
    A[local 3D geometry] --> B[learned encoder] --> C[continuous representation] --> D[nearest code] --> E[structure token]
```

So a protein's structure might become

$$
[1832,\;204,\;3991,\;88,\ldots]
$$

Each token stands for a recurring local shape.  The numbers themselves don't mean anything.  They're just indexes into the codebook.

##### Function tokens

Function is handled differently.  There's no obvious fixed vocabulary of "function words" like the 20 amino acids.  ESM3 starts from the protein's **InterPro annotations** (labels from a database of known protein families and domains) and converts those into tokens:

```mermaid
flowchart LR
    A[InterPro annotations] --> B[TF-IDF weighting] --> C[locality-sensitive hashing] --> D[function tokens]
```

**TF-IDF** (term frequency–inverse document frequency) decides which annotations are informative.  If an annotation appears in almost every protein, it doesn't say much about any specific one, so it gets a low weight.  A rare annotation gets a higher weight.

**Locality-sensitive hashing (LSH)** then compresses the weighted annotations into **eight function tokens per residue**.  LSH is a hash where similar inputs tend to get the same output, so proteins with similar functions end up with similar tokens.

Both steps are simple enough to run by hand on a toy example.  Pick a protein below and watch its annotations get reweighted by rarity.  Then switch to the hashing tab and drag a point around to see when its token changes.

[Interactive: ESM3 function tokenizer](https://karthikvedula.com/assets/files/protein/esm3_function_tokenizer.html) — Pick a protein to see its InterPro annotations reweighted by TF-IDF rarity, then switch to the hashing tab to see when locality-sensitive hashing changes a token.

Unlike the structure tokenizer, nothing here is learned.  TF-IDF and LSH are fixed algorithms.  Here's how all three modalities become tokens:

| Modality  | How it becomes tokens               | Learned? |
| --------- | ------------------------------------ | -------- |
| Sequence  | Fixed amino-acid vocabulary         | **No**   |
| Structure | VQ-VAE encoder + learned codebook   | **Yes**  |
| Function  | TF-IDF + locality-sensitive hashing | **No**   |

##### Combining sequence, structure, and function

At each residue position $i$, ESM3 now has a sequence token, a structure token, and function tokens.  Each one is turned into an embedding, and the embeddings are added together:

$$
h_i =
e_i^{\text{sequence}}
+
e_i^{\text{structure}}
+
e_i^{\text{function}}
$$

So position $i$ gets one vector with information from all three.  The sequence stays the same length.  Each position's vector just carries more information:

- **Sequence:** what amino acid is here?
- **Structure:** what does its local 3D environment look like?
- **Function:** what biological role is associated with it?

ESM3 also has a few smaller tracks added in the same way, like secondary structure and how exposed each residue is to water.  I'm leaving those out to keep things simple.

##### Geometric attention

After that, ESM3 is mostly a standard transformer.  Self-attention lets each residue pull in information from other residues, including ones that are far apart in the sequence but close together in the folded protein.

The one exception is the **first transformer block**, which also gets the 3D coordinates directly.  So structure gets into ESM3 two ways:

```mermaid
flowchart LR
    A[coordinates] --> B["structure tokenizer"] --> C[structure embedding]
    A --> D["geometric attention in block 1"]
```

The second path is there because a structure token is a compressed summary.  Some detail in the original geometry gets lost, and block 1 can use it.

Just like in AlphaFold 2, each residue $i$ has a frame $T_i=(R_i,t_i)$, where $R_i$ is its orientation and $t_i$ its position.  For a pair of residues $i,j$, the frames can describe where $j$ is from $i$'s point of view.  Take a point $x$ in $j$'s local coordinates and convert it into $i$'s local coordinates:

$$
x_{j\rightarrow i}
=
R_i^{T}(R_jx+t_j-t_i)
$$

This combines a relative rotation $R_i^{T}R_j$ and a relative translation $R_i^{T}(t_j-t_i)$.  Together they're written as $T_i^{-1}T_j$, the transform that takes $j$'s frame into $i$'s frame.  Attention then uses it alongside the usual query and key:

$$
\text{attention}_{ij}
=
f\left(
q_i,\,
k_j,\,
\underbrace{T_i^{-1}T_j}_{\text{relative geometry}}
\right)
$$

So when updating residue $i$, attention depends on:

* the learned vector of $i$,
* the learned vector of $j$, and
* **where $j$ is, and which way it's facing, relative to $i$**.

Since only relative frames are used, this is SE(3)-invariant, just like IPA: rotating or moving the whole protein doesn't change anything.  After block 1, the geometric information is baked into the residue vectors, and the rest of the blocks are standard transformer blocks.

#### Differing philosophies

> This section is my own interpretation.  It isn't an established taxonomy.
{: .prompt-warning}

Stepping back, the three labs seem to disagree on where domain knowledge should live:

- **AlphaFold** builds geometry into *how attention is computed*.  Triangle updates and triangle attention are designed around the triangle inequality, and IPA builds SE(3)-invariance into the attention score.  The transformer itself is heavily non-standard.  AF3 keeps the triangle operations but drops the built-in invariance.
- **ESM** goes the other way.  It tokenizes sequence, structure, and function so a near-standard transformer can take them in, and lets coevolution and geometry be learned through attention.  ESM3's one exception is geometric attention in block 1, which suggests tokenizing alone loses some structural information.
- **Baker Lab** splits by task.  RoseTTAFold (and RFdiffusion, which is built on it) is close to AlphaFold's approach: multiple tracks, with geometry built into attention.  ProteinMPNN is the outlier.  It has no tokens and no attention.  Its graph edges come straight from which residues are physically close, so the geometry is decided before the network even runs.

### References

{% capture references_content %}

**Representation models**

- Rives, A. et al. ["Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences."](https://www.pnas.org/doi/10.1073/pnas.2016239118) *PNAS* 118(15), 2021. (ESM-1b)
- Rao, R. et al. ["Transformer protein language models are unsupervised structure learners."](https://openreview.net/pdf?id=fylclEqgvgd) *ICLR*, 2021.
- Elnaggar, A. et al. ["ProtTrans: Towards Cracking the Language of Life's Code Through Self-Supervised Deep Learning and High Performance Computing."](https://arxiv.org/abs/2007.06225) *arXiv:2007.06225*, 2021. (ProtBERT)
- Lin, Z. et al. ["Evolutionary-scale prediction of atomic-level protein structure with a language model."](https://www.science.org/doi/10.1126/science.ade2574) *Science* 379(6637), 2023. (ESM-2 / ESMFold)
- EvolutionaryScale. ["ESM Cambrian: Revealing the mysteries of proteins with unsupervised learning."](https://www.evolutionaryscale.ai/blog/esm-cambrian) Dec 4, 2024. (ESM C)
- Cheng, X. et al. ["Training Compute-Optimal Protein Language Models."](https://proceedings.neurips.cc/paper_files/paper/2024/file/8066ae1446b2bbccb5159587cc3b3bcc-Paper-Conference.pdf) *NeurIPS*, 2024. (BioMap/Tsinghua compute-optimal scaling)
- Su, J. et al. ["SaProt: Protein Language Modeling with Structure-Aware Vocabulary."](https://openreview.net/forum?id=6MRm3G4NiU) *ICLR*, 2024.

**Structure prediction**

- Jumper, J. et al. ["Highly accurate protein structure prediction with AlphaFold."](https://www.nature.com/articles/s41586-021-03819-2) *Nature* 596, 2021. (AlphaFold 2)
- Baek, M. et al. ["Accurate prediction of protein structures and interactions using a three-track neural network."](https://www.science.org/doi/10.1126/science.abj8754) *Science* 373(6557), 2021. (RoseTTAFold)
- Abramson, J. et al. ["Accurate structure prediction of biomolecular interactions with AlphaFold 3."](https://www.nature.com/articles/s41586-024-07487-w) *Nature* 630, 2024.

**Design and inverse folding**

- Watson, J. L. et al. ["De novo design of protein structure and function with RFdiffusion."](https://www.nature.com/articles/s41586-023-06415-8) *Nature* 620, 2023.
- Dauparas, J. et al. ["Robust deep learning–based protein sequence design using ProteinMPNN."](https://www.science.org/doi/10.1126/science.add2187) *Science* 378(6615), 2022.
- Nijkamp, E. et al. ["ProGen2: Exploring the Boundaries of Protein Language Models."](https://arxiv.org/abs/2206.13517) *arXiv:2206.13517*, 2022.

**Multimodal**

- Hayes, T. et al. ["Simulating 500 million years of evolution with a language model."](https://www.science.org/doi/10.1126/science.ads0018) *Science*, 2025. (ESM3)

**Metrics**

- Zhang, Y. & Skolnick, J. ["Scoring function for automated assessment of protein structure template quality."](https://pubmed.ncbi.nlm.nih.gov/15476259/) *Proteins* 57(4), 2004. (TM-score)
- Monastyrskyy, B. et al. ["Evaluation of residue-residue contact prediction in CASP10."](https://pmc.ncbi.nlm.nih.gov/articles/PMC3823628/) *Proteins* 82(S2), 2013. (long-range contact, 24-residue cutoff)
- Shen, M-Y. & Sali, A. ["Statistical potential for assessment and prediction of protein structures."](https://onlinelibrary.wiley.com/doi/10.1110/ps.062416606) *Protein Science* 15(11), 2006. (DOPE)
- Chen, V. B. et al. ["MolProbity: all-atom structure validation for macromolecular crystallography."](https://pmc.ncbi.nlm.nih.gov/articles/PMC2803126/) *Acta Cryst D* 66, 2010.
- Ramachandran, G. N., Ramakrishnan, C., & Sasisekharan, V. ["Stereochemistry of polypeptide chain configurations."](https://pubmed.ncbi.nlm.nih.gov/13990617/) *Journal of Molecular Biology* 7(1), 1963. (Ramachandran plot)

**Datasets and infrastructure**

- The UniProt Consortium. ["UniProt: the Universal Protein Knowledgebase in 2025."](https://academic.oup.com/nar/article/53/D1/D609/7902999) *Nucleic Acids Research* 53(D1), 2025.
- Varadi, M. et al. ["AlphaFold Protein Structure Database in 2024: providing structure coverage for over 214 million protein sequences."](https://academic.oup.com/nar/article/52/D1/D368/7337620) *Nucleic Acids Research* 52(D1), 2024.
- RCSB PDB. ["PDB Reaches a New Milestone: 200,000+ Entries."](https://www.rcsb.org/news/639b9e337f8444f313d20414)
- NIGMS. ["More Than 25 Years of Competition and Collaboration Advance the Prediction of Protein Shapes."](https://biobeat.nigms.nih.gov/2021/07/more-than-25-years-of-competition-and-collaboration-advance-the-prediction-of-protein-shapes/) 2021. (CASP)

**Tools**

- Rego, N. & Koes, D. ["3Dmol.js: molecular visualization with WebGL."](https://academic.oup.com/bioinformatics/article/31/8/1322/213186?login=false) *Bioinformatics* 31(8), 2015.
- Elfmann, C. & Stülke, J. ["PAE Viewer."](https://pae-viewer.uni-goettingen.de/) University of Göttingen.

{% endcapture %}

{% include collapsible.html summary="Click here for the full list of references" content=references_content mermaid=true %}

Thanks for reading! This blog post took around 2 months to make, so I really appreciate you getting to the bottom of this page!
