niknak33's picture
Upload README.md
41188b5 verified
|
Raw History Blame
27.3 kB
metadata
license: other
license_name: nvidia-open-model-license
license_link: >-
  https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/
library_name: codonfm
language:
  - en
tags:
  - biology
  - genomics
  - rna
  - dna
  - codon
  - encodon
  - codon-optimization
  - synonymous-variants
  - variant-effect-prediction
  - protein-expression
  - translation-efficiency
  - mrna-design
  - foundation-model
  - masked-language-modeling

CodonFM

Reading mRNA in its own language, one codon at a time.
NVIDIA Biological Sciences

Code · Preprint · All CodonFM models · NGC · Blog

Three mRNA strands encoding the same protein, differing only at one leucine codon: CUU, CUC and CUA, highlighted in yellow, tan and blue. Each passes through stylised model layers and emerges as a protein structure tinted to match its codon, showing that synonymous choices change the outcome.

CodonFM-5B

CodonFM is a family of open RNA foundation models that read protein-coding sequences at codon resolution. Most protein models treat synonymous codons (the different three-letter words that encode the same amino acid) as interchangeable, discarding the signal they carry. CodonFM keeps it, learning the context-dependent grammar of codon usage from evolution-scale data.

That grammar is shaped by GC content, tRNA availability, RNA structure and host or tissue context, and it shows up in translation efficiency, RNA stability, protein folding and pathogenic synonymous variants. From coding sequence alone, CodonFM recovers synonymous variant effects, missense pathogenicity and mRNA properties.

CodonFM-5B is the largest member of the family. It is released together with CodonFM-5B-CDWT, which is pretrained with codon-frequency-weighted masking instead of uniform random masking. See the two training objectives below.

A coding sequence tokenised two ways. Amino-acid models collapse the synonymous codons GAA and GAG into a single token E, losing the distinction. CodonFM keeps each codon as its own token, which feeds codon optimization, variant effect prediction and sequence embeddings.

Why codon resolution matters

A synonymous substitution is often called a silent mutation, because the protein it encodes is unchanged. It is rarely silent in practice. Swapping a common leucine codon for a rare one leaves the amino acid sequence identical while changing how the transcript folds, how quickly the ribosome moves along it, and whether the finished protein folds correctly.

A synonymous change from CTA to CTG keeps the same amino acid but triggers three downstream consequences: mRNA structure instability shortens mRNA half-life, affecting how much protein is made; altered translational kinetics disrupt folding rhythm, affecting how fast it is made; protein misfolding and aggregation cause loss of function or toxicity, affecting whether it works at all.

A model that tokenises to amino acids cannot represent the left-hand side of that picture, so it cannot reason about any of the consequences on the right.

The second problem is scale. Because most amino acids have several codons, the same protein can be encoded by an immense number of different coding sequences without altering a single residue. A wet-lab cycle tests a few dozen constructs, so the search has always been settled by frequency tables or expert intuition. Getting it right matters: a major cliff in RNA-based therapeutic design is reaching good protein expression at tolerable doses, and an exceptionally well-designed protein still fails if it cannot be produced in the cell type you need it in.

What makes CodonFM work

Three ingredients make CodonFM work: evolutionary data from over 130 million coding sequences across more than 22,000 species; a codon-level model that captures synonymous codon usage; and downstream validation on protein expression, translation efficiency and variant effect.

Where to start

If you want to Go to
Run something now Quick start
Choose between the two 5B models Which model should I use?
Score variants starting from sequencing data From a sequencer to scored variants
Know exactly what the model takes and returns What goes in, what comes out
See the evidence that scale helps What scaling to 5B buys you

At a glance

Details
What it does Predicts masked codons from surrounding codon context; the resulting likelihoods and embeddings drive codon optimization, variant effect prediction and expression modelling
Architecture BERT-style transformer encoder, trained at four scales from 80M to 5B parameters
Input A protein-coding sequence (CDS) as a string of codons, up to 2,046 codons; longer sequences are truncated
Output Per-position codon probabilities, sequence likelihoods, and encoder embeddings
Training objective Masked language modelling over codons, with uniform random masking (5B-CDWT uses frequency-weighted masking)
Training data ~130M coding sequences from >22,000 species across the tree of life, from NCBI RefSeq. Human-affecting pathogen sequences are excluded for biosafety
Who it is for mRNA and cell-therapy design, protein expression and biomanufacturing, clinical variant interpretation, genomics research
License Code: Apache-2.0 · Weights: NVIDIA Open Model License

Which model should I use?

Model Params Masking Use this one if…
CodonFM-5B ★ 5B Random You want the strongest all-round model for mRNA design, expression prediction and somatic variant analysis
CodonFM-5B-CDWT 5B Codon-frequency-weighted You are scoring germline variants. Best in the family on ClinVar synonymous variants; for somatic variants and expression, plain 5B is at least as strong
Encodon-1B 911M Random You need the previous flagship, or 5B does not fit your GPU
Encodon-Cdwt-1B 911M Codon-frequency-weighted You need germline variant scoring at 1B. Its embeddings lean less on simple features like GC content, which makes it weakest in the family on protein expression; use Encodon-1B there
Encodon-600M 609M Random You are trading accuracy for throughput
Encodon-80M 77M Random You are testing a pipeline, not making calls, since it is close to chance on variant interpretation

All CodonFM models are listed in the CodonFM collection.

The two training objectives

Both 5B models are trained by masking 15% of the codons in a sequence and predicting them from context. They differ in how much each prediction counts toward the loss.

CodonFM-5B uses uniform random masking: every codon is weighted equally. Because real coding sequences are dominated by a handful of preferred codons, the model spends most of its training signal on codons it already knows well.

CodonFM-5B-CDWT weights the loss by inverse codon frequency, pushing the model to learn the rare-codon long tail. Leucine shows why that matters: it has six synonymous codons, and human usage is heavily skewed:

Codon Usage in human CDS Cdwt loss weight
CTG 40% 0.3×
CTC 20% 0.6×
CTT 13% 0.9×
TTG 13% 0.9×
TTA 7% 1.7×
CTA 7% 1.7×

A rare CTA therefore contributes roughly 6× more gradient than a common CTG. The result is a model that is more sensitive to species-specific codon preference, which is why 5B-CDWT leads on germline pathogenicity while the uniformly-masked 5B is the better general-purpose choice.

What goes in, what comes out

One input format, three kinds of output. All of it is the same underlying capability, a masked codon language model, consumed three different ways.

Input

A protein-coding sequence (CDS): uppercase A/C/G/T, length divisible by three. Not genomic DNA with introns, not UTR-only sequence, and not protein.

The model tokenises by codon rather than by base, using a 69-token vocabulary covering the 64 codons plus special tokens, with a default context of 2048 tokens including the start and separator tokens. That is roughly 2,000 codons, or about 6,000 nucleotides, in one pass.

Files in

File What it is
One CSV Your sequences. Columns depend on the task
.safetensors + config.json The checkpoint pair, side by side in one folder. A .ckpt also works
An empty output directory The writer scans for .npy files, so leftovers from an earlier run corrupt the merge

For embeddings, the CSV needs id, ref_seq, value, split. For variant scoring it needs id, ref_seq, ref_codon, alt_codon, codon_position. Extra columns are allowed in both.

Files out

Everything returns as NumPy .npy arrays in the predictions directory.

Task Files What they hold
Embeddings embeddings_merged.npy, ids_merged.npy One frozen CLS vector per sequence, width matching the checkpoint's hidden size: 1024 for 80M, 2048 for 600M and 1B, 4096 for 5B
Variant scoring ref_likelihoods_merged.npy, alt_likelihoods_merged.npy, likelihood_ratios_merged.npy, ids_merged.npy Log-likelihood ratio per variant: log p(ref) - log p(alt)

Join results back to your CSV on ids_merged.npy, and do not assume row order survives, because it often does not. Embeddings are a starting point rather than an answer; the public repo's notebooks 4-EnCodon-Downstream-Task-riboNN, 5-EnCodon-Downstream-Task-mRFP-expression and 6-EnCodon-Downstream-Task-mRNA-stability show the downstream regressor step.

Three things that will bite you

The split column filters silently. Only rows whose split value is exactly test are processed. Blank or any other value is dropped without an error, so fewer rows come back than you sent and nothing says why.

Duplicate IDs are not rejected. They pass validation and then make the join back to your CSV ambiguous. Assign unique IDs and keep your own mapping to the original rows.

ref_codon must match the sequence. The extractor asserts that the three bases at codon_position in ref_seq equal ref_codon, and halts the job if they do not. Validating the CSV costs nothing; the failure costs a queue slot.

What a variant score does not tell you

The likelihood ratio says how probable the alternate codon is in context, and a larger positive value means the model finds it less plausible. It does not predict whether expression goes up or down, and it is a research signal rather than a clinical call.

Quick start

1. Set up the environment

git clone https://github.com/NVIDIA-BioNeMo/CodonFM
cd CodonFM
bash run_dev.sh

run_dev.sh builds the development image from the repository's Dockerfile and drops you into a shell, with GPU access and your local code mounted at /workspace. It needs Docker and the NVIDIA container toolkit. Pass --data-dir and --checkpoints-dir to mount your own paths.

2. Download the weights

hf download nvidia/CodonFM-Encodon-5B-v1 --local-dir ./encodon_5b

That gives you CodonFM-Encodon-5B-v1.safetensors and config.json. Point model_path at the .safetensors file itself, not at the directory: the loader rejects a directory, and it reads config.json from alongside the file.

3. Score a synonymous variant

Does a silent mutation matter? This scores a GAA → GAG substitution, where both codons encode glutamate, by the ratio of the model's likelihoods for the two codons in context.

import torch
from src.inference.encodon import EncodonInference
from src.data.preprocess.mutation_pred import mlm_process_item

model = EncodonInference(
    model_path="./encodon_5b/CodonFM-Encodon-5B-v1.safetensors",
    task_type="mutation_prediction",
)
model.configure_model()
model = model.to("cuda").eval()

cds = "ATGGAATTTTAA"
variant = mlm_process_item(
    ref_seq=cds,
    codon_position=1,          # Zero-based codon index.
    ref_codon="GAA",
    alt_codon="GAG",
    context_length=2048,
    tokenizer=model.tokenizer,
    mask_mutation=True,
)
batch = {
    k: torch.as_tensor(v, device="cuda").unsqueeze(0)
    for k, v in variant.items()
}

with torch.inference_mode():
    score = model.predict_mutation(batch).likelihood_ratios.item()

print(f"Synonymous variant score: {score:.6f}")

4. Extract embeddings

The third thing the model gives you is a vector per sequence: the [CLS] representation from the final layer. These are the input to your own regressor when you have assay data of your own and want to predict translation efficiency, expression or stability from sequence.

import numpy as np
import torch
from src.inference.encodon import EncodonInference
from src.data.preprocess.codon_sequence import process_item

model = EncodonInference(
    model_path="./encodon_5b/CodonFM-Encodon-5B-v1.safetensors",
    task_type="embedding_prediction",
)
model.configure_model()
model = model.to("cuda").eval()

sequences = ["ATGGAATTTTAA", "ATGGAGTTTTAA"]
items = [process_item(s, context_length=2048, tokenizer=model.tokenizer)
         for s in sequences]
batch = {k: torch.as_tensor(np.stack([it[k] for it in items]), device="cuda")
         for k in items[0]}

with torch.inference_mode():
    embeddings = model.extract_embeddings(batch).embeddings

print(embeddings.shape)        # (2, 4096): one 4096-wide vector per sequence

Extracting them is only half the job. The repository's notebooks 4-EnCodon-Downstream-Task-riboNN, 5-EnCodon-Downstream-Task-mRFP-expression and 6-EnCodon-Downstream-Task-mRNA-stability show the other half: fitting a light regressor on frozen embeddings, which is how the benchmarks above were produced.

For variant scoring at scale and the downstream expression tasks, see the notebooks in the repository.

From a sequencer to scored variants

The quick start above begins with a coding sequence, which assumes you already have one. Most work starts further back, with reads off a sequencer, and getting from there to a CDS is the bulk of the job.

The variant effect prediction notebook in the Genomic Analysis Blueprint, written by Gary Burnett and Fan Cao, covers that whole span on GPU:

Stage What happens
1. Variant calling Raw Illumina FASTQ reads aligned to the human reference with Parabricks BWA, then variants called with DeepVariant
2. Gene annotation GENCODE processed to pull out protein-coding sequences, and the called variants mapped onto genes and transcripts
3. Effect prediction Each variant scored with CodonFM, synonymous ones included

Stage three is what this page documents. Stages one and two are what make it usable on data you actually have, rather than on a coding sequence you were already holding.

It needs a GPU and the Parabricks container, so it is not a browser-only demo. The dataset it ships with is small on purpose: the pipeline is the point, and it scales to real cohorts.

What scaling to 5B buys you

Scale buys comprehension

Validation loss keeps falling with model size, and the 5B models separate clearly from the rest of the family rather than converging with them.

Validation loss against training samples seen, for EnCodon 80M, 600M, 1B, 1B CDWT, 5B and 5B CDWT. Every model's loss falls as training continues, and the 5B models sit lowest throughout, reaching about 1.95 against roughly 2.25 for 1B and 2.9 for 80M.

Figure 1. Larger EnCodon models achieve lower validation loss as training continues.

That shows up directly as fewer synonymous mix-ups. Codon confusion, how often the model mispredicts one synonymous codon for another, falls steadily with scale across almost every amino acid.

Heatmap of synonymous codon confusion by amino acid for each EnCodon model size. Darker green means less confusion. Rows grow darker from EnCodon 80M at the top through to 5B and 5B CDWT at the bottom.

Figure 2. Synonymous codon confusion across model scales. Darker green is a lower confusion score, so larger models show a firmer grip on codon usage.

Variant interpretation

Across 129,384 synonymous variants in ClinVar, the 5B models give the highest AUROC for separating pathogenic from benign, and 5B-CDWT leads, so the rare-codon weighting earns its place on this germline task.

Box plot of AUROC for distinguishing pathogenic from benign matched synonymous variants. EnCodon 5B CDWT is highest at about 0.67, followed by 5B, then 1B CDWT and 1B near 0.62, with SOTA-Best-1 at about 0.61 and EnCodon 80M lowest at about 0.51.

Figure 3. CodonFM 5B CDWT and 5B achieve the highest AUROC for separating pathogenic from benign synonymous variants in ClinVar.

The same holds for somatic mutations. Across 1,471 cancer-observed synonymous variants matched between COSMIC and gnomAD, the larger models beat both the PhyloP conservation score and the best published model on this benchmark. CodonFM also recovers known loss-of-function synonymous mutations in KRAS.

Two box plots comparing COSMIC synonymous mutations against matched gnomAD common variants. On the Mann-Whitney U test the 5B models reach about 10 on the negative log-10 p scale against roughly 6 for 1B, 2 for PhyloP and 1.5 for SOTA-Best-2. The AUROC panel shows the same ordering.

Figure 4. Across 1,471 curated cancer-observed synonymous variants, larger EnCodon models outperform the PhyloP conservation score and the best state-of-the-art model on this test.

Separately, on de novo variant prioritization across three trio-sequenced disease cohorts, including 42,607 autism cases and 2,871 congenital heart disease probands, CodonFM gives the best separation of disease from control, from coding sequence alone.

mRNA design

Random forests trained on frozen 5B embeddings beat the strongest published nucleotide models on both translation efficiency (>140 human and mouse cell types drawn from 3,819 ribosome profiling datasets) and protein expression (1,459 synonymous CDS variants with an E. coli readout), with no fine-tuning.

Two bar charts of Spearman correlation. On mRNA translation efficiency, EnCodon 5B CDWT and 5B lead at about 0.72, ahead of SOTA-Best-1 at roughly 0.69 and SOTA-Best-3 at 0.52. On mRFP expression, EnCodon 5B and 5B CDWT lead at about 0.73, ahead of SOTA-Best-3 at 0.68 and SOTA-Best-1 at 0.55.

Figure 5. Random forest performance on frozen zero-shot embeddings, for translation efficiency (RiboNN Spearman ρ) and mRFP protein expression (Spearman ρ on a held-out test set). The 5B models lead on both.

Where it gets used

Optimized coding sequences from CodonFM feed CAR-T immunotherapy, tumour profiling, vaccine efficacy and peptide manufacturing.

In the lab

Benchmarks are one thing; wet-lab validation is another. Working with the Arc Institute and Ansa Bio, CodonFM-designed sequences raised GFP expression nearly 4× over wild type in the A549 human epithelial line, and luciferase roughly 2× in the same cells, from changing codon usage alone, leaving both proteins untouched. Two targets rather than one is the point: it is the difference between a method that transfers and a single lucky sequence.

Two bar charts of protein expression in A549 cells relative to wild type. For luciferase, wild type sits at 1.0, SOTA-A at about 0.4, SOTA-B at about 1.3 and the CodonFM design at about 1.95, marked significant with p equal to 6.3e-05. For GFP, wild type sits at 1.0, SOTA-A at about 0.4, SOTA-B at about 1.15 and the CodonFM design at about 3.95, with p equal to 7.8e-05.

Figure 6. Protein expression in A549 human epithelial cells, relative to wild type. CodonFM-designed sequences reach roughly 2× for luciferase (p = 6.3 × 10⁻⁵) and 4× for GFP (p = 7.8 × 10⁻⁵), outperforming two current state-of-the-art RNA language models on both.

Collaborations with further partners, including Therna Biosciences, have achieved or exceeded these gains in therapeutic design work.

Where to go next

If you want to Go here
Run CodonFM on your own sequencing data From a sequencer to scored variants, above
Reproduce the benchmarks above The evaluation notebooks: zero-shot variant scoring, translation efficiency, expression and stability
Understand the method The preprint
Use a smaller or earlier model The CodonFM collection
Read the background The original CodonFM blog

Hardware and software

GPU memory [TODO: confirm with Ankit]
Tested on [TODO: confirm with Ankit. A100 is listed for 1B; add the 5B list and Blackwell status]
Base image nvcr.io/nvidia/pytorch:26.09-py3, pinned by digest in the repository's Dockerfile. Python 3.12
OS Linux

Limitations

  • CodonFM models protein-coding sequences only. It does not model UTRs, introns or non-coding RNA, so regulatory effects outside the CDS are out of scope.
  • Context is capped at 2,046 codons; longer transcripts are truncated.
  • Predictions are computational hypotheses. Designed sequences and variant calls need experimental validation before use in research or clinical decisions.
  • Training data excludes human-affecting pathogen sequences, for biosafety.

The formal model card, with the full Model Card++ bias, explainability, safety and privacy subcards, is on NGC.

License

Code is released under Apache-2.0. Model weights are governed by the NVIDIA Open Model License Agreement. Ready for commercial and non-commercial use.

Citation

@article{codonfm_2025,
  author = {Darabi+, Sajad and Cao+, Fan and Naghipourfar+, Mohsen and Rabhi, Sara and
            Sethia, Ankit and Gion, Kyle and Grewal, Jasleen and Cohen, Jonathan and
            Greenleaf, William and Goodarzi*, Hani and Sundaram*, Laksshman},
  title  = {{Learning the language of codon translation with CodonFM}},
  url    = {https://research.nvidia.com/labs/dbr/assets/data/manuscripts/nv-codonfm-preprint.pdf},
  year   = {2025}
}

Sajad Darabi, Fan Cao and Mohsen Naghipourfar are equal contributing first authors. Corresponding authors: Hani Goodarzi and Laksshman Sundaram.

Contact

Questions and correspondence: nv-codonfm@nvidia.com