Flipper: extending protein sequence-to-function benchmarks
Published:
Note: this article, as well as flipper, is a collaboration between Stephen Malina and myself. You can find Stephen here!
Over the past few years, the number of benchmarks comparing protein sequence-to-function models has grown a lot. Benchmarks vary on the models and datasets they choose to survey, but one thing we’ve noticed is that reproducing or extending their results can sometimes be daunting. We thought we’d help out by reproducing the Fitness Landscape Inference for Proteins (FLIP) benchmark and making our code even easier1 to use and extend; that project became flipper! Besides it using AAV data, which Stephen is biased towards, FLIP seemed like a good choice because it included a variety of train/test splits and models spanning across vanilla CNNs to pretrained language models.
To ensure we were sticking as close to the original paper as possible, we reproduced its results on a subset of the datasets using both CNN and ESM models (see performance comparison below). To make our work as easy to extend as possible, we built a generic training/testing setup on top of Pytorch Lightning and Hydra. We hope using Pytorch Lightning will make it even easier for users to add more models or modify the existing one, and by using Hydra we hope to make it easy to do hyperparameter optimization.
We compared performance of FLIP models and our reproduced flipper models (specifically CNN and ESM1b) across splits in AAV and GB1 data; results are displayed below. ESM1b models were not tested on AAV data due to compute limitations, and CNN models were trained across five random seeds. FLIP performance largely falls within the range of performance by Flipper counterparts, especially in lower variance training splits (i.e. three_vs_rest, seven_vs_many) with more training data.

What are sequence-to-function models?
Starting from the basics, sequence-to-function models take (protein) sequences and predict one or more scalar properties representing some functional property. In practice, sequence-to-function models are often used as proxies for experimental assays that probe the fitness of proteins. Experimental assays are often lower throughput, which means that it can be infeasible to assess the fitness of a long list of protein candidates within practical time constraints. By approximating these assays, sequence-to-function models can identify higher fitness proteins, ensuring we make good use of our assays and maximizing the chance of finding a valuable novel protein variant.
Let’s illustrate this with an example. Suppose that we’re biofuel engineers, trying to find a protein that breaks down cellulose into simple sugars; this could then be converted into ethanol or other fuels. We already have a protein (represented by an amino acid sequence of length 35, let’s say) that does this, but it needs to be 10x more efficient to generate biofuel at a profitable rate. We might start by looking at all 20 * 35 singles, variants that are one mutation ‘away’ from the wild-type. Assuming we don’t get lucky and find a 10x better hit in the singles, this provides us with a good starting dataset on which we can train our models. Going beyond singles, the full space of potential variants of our enzyme is extremely large: there are 20^35 (nearly 1e45) options available. Even if our assay can process millions of proteins per week (extremely optimistic), we can only examine a small fraction of the space. On the other hand, sequence-to-function models operate at a much higher throughput and are only limited by compute. While still not fast enough to examine the entire 1e45 variant space, sequence-to-function models can examine billions or even trillions of proteins depending on their size and compute available. This allows us to examine a longer list of potential proteins before passing off the highest quality candidates to the assay.
So far, we’ve painted a simple but hopefully informative picture of how protein design works and where sequence-to-function models fit in. Others have written in much more depth covering issues we haven’t even touched on such as how you guide the search process (beyond single and random mutations), using predictive uncertainty, combining generative and predictive models, and much more. A few of our personal favorite reviews on this are:
- A primer on model-guided exploration of fitness landscapes for biological sequence design
- Is novelty predictable?
- Learning the Protein Language: Evolution, Structure and Function
- Adaptive machine learning for protein engineering
- Controllable Protein Design with Language Models
How do sequence-to-function models work?
Sequence-to-function models can work in many different ways, but they often take the amino acid sequence for a protein as input for predicting scalar function(s). In the realm of deep learning, which is what we’re primarily focused on here, models usually translate amino acid sequence input into a representation, which can be as simple as a one-hot encoding or a more complicated embedding function. They then apply a series of nonlinear functions to these embeddings, eventually producing a predicted fitness level.
Following success in NLP, it’s become increasingly popular in the protein space to try and learn embeddings by training very large models with self-supervised learning. For example, FLIP uses a family of models called ESM (Evolutionary Sequence Models), which have been trained on nearly the entire corpus of known protein sequences. In doing this, the models hopefully learn representations that better capture useful properties of proteins such as structure.
What is FLIP?
FLIP compares the performance of different model architectures and setups on fitness prediction tasks across a few different datasets and train-test splits. The benchmark compares three classes of models; ordered in decreasing size: language models (ESM), CNNs, and ridge regression. As mentioned, ESM models generate individual embeddings for each amino acid in the sequence, so there are subcategories of models that merge these individual embeddings in different ways to generate an overall protein embedding. These methods are averaging embeddings over the entire protein sequence, averaging over just the mutation window, and calculating a weighted average based on learned parameters.
There are three fitness prediction tasks in the benchmark: fluorescence, AAV, and thermostability. The fluorescence dataset is the smallest, limited to mutations at four positions of the GFP protein. The AAV dataset is larger, due to a larger search space opened up from a longer mutation window in the protein. And thermostability is the largest, sampled from a diverse set of proteins that share this property. Due to compute constraints, we chose to only reproduce the results of the ESM models and CNNs on the fluorescence and AAV datasets. However, we expect our results to generalize to thermostability and other models based on the agreement we see here and the fact that we use nearly identical architectures and hyperparameters.
The benchmark also includes a variety of train-test splits for each dataset, simulating realistic data availability for model development during the design cycle. Sometimes, such as in the ‘two vs. many’ split, training data only includes a local ‘neighborhood’ of sequences clustered a few mutations away from the wild-type protein, while sequences in the test set all fall outside of this edit distance range. This mirrors the situation where we gather variants with only a few mutations but want to design and assay variants with more mutations in the hope that we’ll find improved variants as we make more mutations.
What did we do differently?
Improvements to the pipeline begin with the use of PyTorch Lightning to reproduce models. By moving the models into LightningModules, training and validation logic is moved outside of for loops and into more legible step functions. Training loop logic for the CNN, with FLIP and Flipper, is included below.
def epoch(model, train, current_step=0):
if train:
model = model.train()
loader = train_iterator
t = 'Training'
n_total = len(train_iterator)
else:
model = model.eval()
loader = val_iterator
t = 'Validating'
n_total = len(val_iterator)
losses = []
outputs = []
tgts = []
n_seen = 0
for i, batch in enumerate(loader):
loss, output, tgt = step(model, batch, train)
losses.append(loss)
outputs.append(output)
tgts.append(tgt)
n_seen += len(batch[0])
if train:
nsteps = current_step + i + 1
else:
nsteps = i
outputs = torch.cat(outputs).numpy()
tgts = torch.cat(tgts).cpu().numpy()
if train:
with torch.no_grad():
_, val_rho = epoch(model, False, current_step=nsteps)
print('epoch: %d loss: %.3f val loss: %.3f' % (e + 1, loss, val_rho))
if not train:
val_rho = spearmanr(tgts, outputs).correlation
mse = mean_squared_error(tgts, outputs)
return i, val_rho
Epoch level code branches off at multiple points based on a train variable. It identifies whether training or validation is being run during that epoch. Meanwhile, the CNN’s LightningModule includes separate functions for training and validation steps/epochs.
class CNN(pl.LightningModule):
...
def training_step(self, batch, batch_idx):
src, tgt, mask, _ = batch
ohe = self.generate_ohe(src).float()
output = self(ohe, mask)
self.training_loss.update(output, tgt)
self.log("training_loss", self.training_loss, on_step=False, on_epoch=True)
return F.mse_loss(output, tgt)
def validation_step(self, batch, batch_idx):
src, tgt, mask, _ = batch
output = self(self.generate_ohe(src).float(), mask)
output = output.flatten()
tgt = tgt.flatten()
self.val_spearman.update(output, tgt)
self.log("val_spearman", self.val_spearman, on_step=False, on_epoch=True)
self.val_loss.update(output, tgt)
self.log("val_loss", self.val_loss, on_step=False, on_epoch=True)
Metrics tracking loss and relevant early stopping variables are also explicitly initialized in the __init__ and regularly saved to a logger for future debugging. Tokenizers are passed into models during initialization, allowing them to be defined outside models and shared according to a user’s discretion or replaced with alternatives. Datasets are all processed through a single DataModule, with dataset specific processing injected via functions, making testing across different datasets (existing or new) much easier.
Setup for training runs and inference is abstracted with Hydra; all config options related to models, datasets, logging and other options are explicitly defined in config files, circumventing the need for a long list of command line args. To simplify scripts for hyperparameter search, users can override specific configs via the command line as well. Training commands for FLIP and Flipper are included below for comparison.
python train_all.py aav_4 cnn
FLIP hardcodes a dictionary that references specific splits in a dataset according to the first argument. With Flipper, the user just runs:
python train.py
This starts a training run based on the configs set in train.yaml and its extensions, included below.
defaults:
- _self_
- data: default.yaml
- model: cnn.yaml
- callbacks: spearman_early_stopping.yaml
- logger: csv.yaml # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
- trainer: gpu.yaml
- paths: default.yaml
- extras: default.yaml
# - hydra: default.yaml
# experiment configs allow for version control of specific hyperparameters
# e.g. best hyperparameters for given model and datamodule
- experiment: null
# config for hyperparameter optimization
- hparams_search: null
# optional local config for machine/user specific settings
# it's optional since it doesn't need to exist and is excluded from version control
- optional local: default.yaml
# debugging config (enable through command line, e.g. `python train.py debug=default)
- debug: null
Specific config options from train.yaml can also be overridden.
python train.py data.split=one_vs_many debug=default
Embedding generation for ESM models was also moved to inside the training cycle, rather than a single pass done during data pre-processing, to enable fine-tuning during the training process.
What if you want to contribute?
We would love to have more contributions to flipper, be it by adding new models (hint: we’re excited about someone training a top model on Ankh to see how it compares to ESM), new datasets, or other quality-of-life improvements. We’re happy to get pull requests out of the blue, but also feel free to reach out to Adithya or post an issue if you want to first chat about potential contributions.
Acknowledgements
We first want to thank the authors of FLIP and the people who produced the datasets included in it for their amazing work. Our reproduction wouldn’t have been possible without them and we want to emphasize how grateful we are to them for making and putting these benchmarks out there.
I (Adithya) entered the field after a brief internship at a biotech startup in the summer of 2022, as a newcomer to both ML and protein engineering. Stephen kindly volunteered to take me under his wing, offering up inspiration for Flipper as a project and providing valuable technical mentorship whenever I hit roadblocks.
Footnotes:
- We want to emphasize that this isn’t intended as a criticism of the original FLIP codebase. We’re extremely grateful to its authors for putting the work out there and think they did a great job sharing their work and documenting it. We view our work as building on theirs to lower the barrier to entry to reproducing even more while also validating their results by reproducing them.
