CodonTransformer

Model Introduction

CodonTransformer is a deep learning model for multispecies codon optimization. Given an input protein sequence and a target host organism, it generates a host-specific DNA coding sequence.

Because of the degeneracy of the genetic code, the same protein can be encoded by many different DNA sequences, while different hosts have distinct preferences for synonymous codons. CodonTransformer uses a Transformer to model the contextual relationships among proteins, codons, and host organisms, generating DNA sequences that better match the natural codon distribution of the target host while preserving the translated protein sequence as much as possible.

Paper:

CodonTransformer: a multispecies codon optimizer using context-aware neural networks
Nature Communications, 2025

Model Description

CodonTransformer is a Transformer model designed for multispecies codon optimization. Its core network is based on a BigBird masked language model and incorporates the STREAM representation proposed by the authors, which encodes target host information, amino acid information, and codon information into a unified sequence representation.

Unlike traditional optimization methods based on global codon frequencies, CodonTransformer considers not only host preferences for individual codons but also uses the contextual modeling capability of Transformers to learn local dependencies between neighboring codons. This enables it to generate DNA sequences that more closely resemble the natural coding patterns of the target host. The model can be used for multispecies codon optimization, heterologous protein expression sequence design, and further fine-tuning on custom DNA-protein-host datasets.

The official model was trained on more than one million DNA-protein paired samples spanning 164 species, including bacteria, archaea, plants, animals, and fungi.

Use Cases

Scenario Description
Codon optimization Redesign protein-coding DNA for a target host
Heterologous protein expression Generate coding sequences that better match host codon preferences for different hosts
Multispecies sequence design Switch the target organism among multiple supported hosts
Multiple candidate sequence generation Generate multiple distinct DNA candidate sequences through temperature sampling
Batch codon optimization Perform batch inference for multiple protein-host combinations
Model fine-tuning Continue fine-tuning using custom DNA-protein-host data
Model pretraining Train the model from scratch using large-scale processed training data

Usage

1. Using OneCode

You can use the OneCode online environment for intelligent one-click AI4S programming:

Try intelligent one-click AI4S programming

2. Manual Installation and Usage

Hardware Requirements

  • CodonTransformer supports inference on both CPUs and accelerator devices.
  • A CPU can be used for single protein sequence inference.
  • GPU/DCU devices are recommended for batch inference, long-sequence inference, fine-tuning, and pretraining.

Environment Setup

DCU/SCNet Environment

conda create -n onescience311 python=3.11 -y
conda activate onescience311

pip install onescience[bio] \
  -i http://mirrors.onescience.ai:3141/pypi/simple/ \
  --trusted-host mirrors.onescience.ai
  • If you encounter missing dependencies or version incompatibilities during execution, refer to the dependency versions specified in requirements.txt at the repository root and install or adjust the corresponding dependencies as needed.

Model and Data Preparation

1) CodonTransformer Model Weights

The official model is available on Hugging Face:

https://huggingface.co/adibvafa/CodonTransformer

In an online environment, from_pretrained automatically downloads the model weights when they are not available in the local cache. In an offline environment, the weights must be downloaded in advance to the cache directory corresponding to HF_HOME. The recommended cache location is:

/path/to/.cache/huggingface/hub/

Set the following environment variables when running the scripts:

export HF_HOME=/path/to/.cache/huggingface
export HF_HUB_OFFLINE=1
export TRANSFORMERS_OFFLINE=1

The inference and fine-tuning scripts in this repository support using the local cache through HF_HOME and OFFLINE=1.

2) Training Dataset

The official training data can be obtained from Zenodo or Hugging Face Datasets:

https://zenodo.org/records/12509224
https://huggingface.co/datasets/adibvafa/CodonTransformer

It is recommended to place the downloaded raw data in:

scripts/data/raw/

Accordingly, the complete dataset file is recommended to be saved as:

scripts/data/raw/dataset.csv

The processed training JSON files are recommended to be saved in:

scripts/data/processed/

3. Quick Start

Download the Model Package

hf download OneScience-Group/CodonTransformer \
  --local-dir ./CodonTransformer

cd CodonTransformer

Inference Examples

Single-Sequence Codon Optimization

Run the script:

bash scripts/slurm/run_inference_single.sh

The default parameters are:

PROTEIN="MFWY"
ORGANISM="Escherichia coli general"
OFFLINE=1

To change the input protein and host:

PROTEIN="MALWMRLLPLLALLALWGPDPAAA" \
ORGANISM="Homo sapiens" \
bash scripts/slurm/run_inference_single.sh

Generate Multiple Candidate DNA Sequences

Run:

bash scripts/slurm/run_inference_multiple.sh

By default, multiple candidate DNA sequences are generated for the same protein sequence and saved to:

outputs/multiple_predictions.csv

The main parameters include:

deterministic=False
temperature=0.5
top_p=0.95
num_sequences=5
match_protein=True

where:

  • deterministic=False enables probabilistic sampling.
  • temperature controls sampling diversity, with a typical range of 0.2 ~ 0.8.
  • top_p controls nucleus sampling.
  • num_sequences specifies the number of candidate sequences to generate.
  • match_protein=True constrains the generated DNA to translate to the same input protein sequence.

Change the Target Host

The target host is specified directly through the organism parameter, for example:

organism = "Escherichia coli general"

It can be changed to:

organism = "Homo sapiens"

or:

organism = "Saccharomyces cerevisiae"

Then rerun inference to obtain a codon-optimized DNA sequence for the corresponding host.

Batch Inference

The example data is currently located at:

scripts/demo/sample_dataset.csv

Run directly:

bash scripts/slurm/run_inference_batch.sh

The default output is saved to:

outputs/sample_predictions.csv

The input CSV must contain at least:

protein_sequence
organism

To use a custom CSV:

INPUT_CSV=/path/to/input.csv \
OUTPUT_CSV=/path/to/output.csv \
bash scripts/slurm/run_inference_batch.sh

Training

Fine-Tuning Data Preparation

For custom fine-tuning, first prepare your own CSV file. It is recommended to place it at:

scripts/data/raw/your_data.csv

It must contain at least:

dna
protein
organism

Then run the data preprocessing script provided in the repository:

INPUT_CSV=$PWD/scripts/data/raw/your_data.csv \
OUTPUT_JSON=$PWD/scripts/data/processed/finetune_data.json \
bash scripts/slurm/prepare_finetune_data.sh

CodonTransformer Fine-Tuning

Run the script:

bash scripts/slurm/run_finetune.sh

By default, it reads:

scripts/data/processed/finetune_data.json

and saves checkpoints to:

weight/checkpoints/finetune

To fine-tune using custom data, run:

DATASET_JSON=$PWD/scripts/data/processed/finetune_data.json \
CHECKPOINT_DIR=$PWD/weight/checkpoints/finetune \
CHECKPOINT_FILENAME=finetune.ckpt \
BATCH_SIZE=6 \
MAX_EPOCHS=15 \
NUM_WORKERS=5 \
ACCUMULATE_GRAD_BATCHES=1 \
NUM_GPUS=4 \
LEARNING_RATE=0.00005 \
WARMUP_FRACTION=0.1 \
SAVE_EVERY_N_STEPS=512 \
SEED=123 \
DEBUG=0 \
bash scripts/slurm/run_finetune.sh

Here, NUM_GPUS=4, BATCH_SIZE=6, and MAX_EPOCHS=15 are the default training settings. In practice, these parameters should be adjusted according to the number of allocated GPU/DCU devices, available device memory, and dataset size.

Export the Fine-Tuned Model and Run Inference

After fine-tuning is complete, the following script can be used to export the checkpoint into a model file suitable for inference:

scripts/slurm/export_finetuned_model.sh

Run it as follows:

CHECKPOINT_PATH=/path/to/finetuned_checkpoint.ckpt \
OUTPUT_MODEL_PATH=/path/to/output_finetuned_model.pt \
NUM_ORGANISMS=164 \
bash scripts/slurm/export_finetuned_model.sh

After export, the following script can be used to load the fine-tuned model for inference:

scripts/slurm/run_inference_finetuned.sh

Run it as follows:

PROTEIN="MFWY" \
ORGANISM="Escherichia coli general" \
MODEL_PATH=/path/to/output_finetuned_model.pt \
bash scripts/slurm/run_inference_finetuned.sh

Pretraining

The current pretraining entry point is:

scripts/pretrain.py

Pretraining is a complete model training workflow and requires large-scale processed DNA-protein-host data. Before full pretraining, the complete dataset.csv must first be converted into a JSONL file that can be read by the training script.

The repository provides the following preprocessing script:

scripts/slurm/prepare_pretrain_data.sh

By default, this script reads:

scripts/data/raw/dataset.csv

and outputs:

scripts/data/processed/pretrain_data.json

Therefore, before full pretraining, first run:

bash scripts/slurm/prepare_pretrain_data.sh

If the raw data or output directory differs from the default path, modify it using environment variables:

INPUT_CSV=$PWD/scripts/data/raw/dataset.csv \
OUTPUT_JSON=$PWD/scripts/data/processed/pretrain_data.json \
bash scripts/slurm/prepare_pretrain_data.sh

The complete generated pretraining data is recommended to be saved as:

scripts/data/processed/pretrain_data.json

Full pretraining can be started with:

TRAIN_DATA_PATH=$PWD/scripts/data/processed/pretrain_data.json \
CHECKPOINT_DIR=$PWD/weight/checkpoints/pretrain \
BATCH_SIZE=6 \
MAX_EPOCHS=5 \
NUM_WORKERS=5 \
ACCUMULATE_GRAD_BATCHES=1 \
NUM_GPUS=16 \
LEARNING_RATE=0.00005 \
WARMUP_FRACTION=0.1 \
SAVE_INTERVAL=5 \
SEED=123 \
DEBUG=0 \
bash scripts/slurm/run_pretrain.sh

Here, NUM_GPUS=16 corresponds to the default multi-device setting in the pretraining script. In practice, adjust NUM_GPUS according to the number of allocated GPU/DCU devices. Pretraining checkpoints are saved by default to:

weight/checkpoints/pretrain

OneScience Official Information

Citation and License

  • The official CodonTransformer source code repository is licensed under the Apache License 2.0. See the LICENSE file in the repository root for details.
  • CodonTransformer model weights are distributed separately through Hugging Face, while the training data is available through Zenodo and Hugging Face Datasets. The model weights, training data, and related third-party resources must each be used in accordance with the licenses and terms of use specified on their respective pages.
  • This repository is the DCU-adapted version of CodonTransformer. The use of the repository code, model weights, and related data remains subject to the licenses and terms of use of their respective original projects.

中文说明

模型简介

CodonTransformer 是一个用于多物种密码子优化的深度学习模型。给定输入的蛋白质序列和目标宿主生物,它会生成宿主特异性的 DNA 编码序列。

由于遗传密码的简并性,同一种蛋白质可以由许多不同的 DNA 序列编码,而不同宿主对同义密码子有着各自不同的偏好。CodonTransformer 使用 Transformer 对蛋白质、密码子和宿主生物之间的上下文关系进行建模,在尽可能保持翻译后蛋白质序列不变的同时,生成更符合目标宿主天然密码子分布的 DNA 序列。

论文:

CodonTransformer: a multispecies codon optimizer using context-aware neural networks
Nature Communications, 2025

模型描述

CodonTransformer 是一个为多物种密码子优化而设计的 Transformer 模型。其核心网络基于 BigBird 掩码语言模型,并引入了作者提出的 STREAM 表示,将目标宿主信息、氨基酸信息和密码子信息编码为统一的序列表示。

与基于全局密码子频率的传统优化方法不同,CodonTransformer 不仅考虑宿主对单个密码子的偏好,还利用 Transformer 的上下文建模能力来学习相邻密码子之间的局部依赖关系。这使其能够生成更接近目标宿主天然编码模式的 DNA 序列。该模型可用于多物种密码子优化、异源蛋白表达序列设计,以及在自定义的 DNA-蛋白质-宿主数据集上进一步微调(fine-tuning)。

官方模型在涵盖细菌、古菌、植物、动物和真菌等 164 个物种的一百多万条 DNA-蛋白质配对样本上训练而成。

应用场景

场景 说明
密码子优化 为目标宿主重新设计蛋白质编码 DNA
异源蛋白表达 为不同宿主生成更符合其密码子偏好的编码序列
多物种序列设计 在多个受支持的宿主之间切换目标生物
多候选序列生成 通过温度采样生成多条不同的 DNA 候选序列
批量密码子优化 对多个蛋白质-宿主组合执行批量推理
模型微调 使用自定义的 DNA-蛋白质-宿主数据继续微调
模型预训练 使用大规模处理后的训练数据从头训练模型

使用方式

1. 使用 OneCode

您可以使用 OneCode 在线环境体验一键智能 AI4S 编程:

体验一键智能 AI4S 编程

2. 手动安装与使用

硬件要求

  • CodonTransformer 支持在 CPU 和加速器设备上进行推理。
  • CPU 可用于单条蛋白质序列的推理。
  • 批量推理、长序列推理、微调和预训练推荐使用 GPU/DCU 设备。

环境配置

DCU/SCNet 环境
conda create -n onescience311 python=3.11 -y
conda activate onescience311

pip install onescience[bio] \
  -i http://mirrors.onescience.ai:3141/pypi/simple/ \
  --trusted-host mirrors.onescience.ai
  • 如果执行过程中遇到依赖缺失或版本不兼容的问题,请参考仓库根目录 requirements.txt 中指定的依赖版本,并按需安装或调整相应的依赖。

模型与数据准备

1)CodonTransformer 模型权重

官方模型可在 Hugging Face 上获取:

https://huggingface.co/adibvafa/CodonTransformer

在联网环境中,当本地缓存中没有模型权重时,from_pretrained 会自动下载。在离线环境中,必须提前将权重下载到 HF_HOME 对应的缓存目录。推荐的缓存位置为:

/path/to/.cache/huggingface/hub/

运行脚本时设置以下环境变量:

export HF_HOME=/path/to/.cache/huggingface
export HF_HUB_OFFLINE=1
export TRANSFORMERS_OFFLINE=1

本仓库中的推理和微调脚本支持通过 HF_HOME 和 OFFLINE=1 使用本地缓存。

2)训练数据集

官方训练数据可以从 Zenodo 或 Hugging Face Datasets 获取:

https://zenodo.org/records/12509224
https://huggingface.co/datasets/adibvafa/CodonTransformer

建议将下载的原始数据放在:

scripts/data/raw/

相应地,建议将完整的数据集文件保存为:

scripts/data/raw/dataset.csv

建议将处理后的训练 JSON 文件保存在:

scripts/data/processed/

3. 快速开始

下载模型包

hf download OneScience-Group/CodonTransformer \
  --local-dir ./CodonTransformer

cd CodonTransformer

推理示例

单序列密码子优化

运行脚本:

bash scripts/slurm/run_inference_single.sh

默认参数为:

PROTEIN="MFWY"
ORGANISM="Escherichia coli general"
OFFLINE=1

更改输入蛋白质和宿主:

PROTEIN="MALWMRLLPLLALLALWGPDPAAA" \
ORGANISM="Homo sapiens" \
bash scripts/slurm/run_inference_single.sh

生成多条候选 DNA 序列

运行:

bash scripts/slurm/run_inference_multiple.sh

默认情况下,会为同一条蛋白质序列生成多条候选 DNA 序列,并保存到:

outputs/multiple_predictions.csv

主要参数包括:

deterministic=False
temperature=0.5
top_p=0.95
num_sequences=5
match_protein=True

其中:

  • deterministic=False 启用概率采样。
  • temperature 控制采样多样性,典型取值范围为 0.2 ~ 0.8。
  • top_p 控制核采样。
  • num_sequences 指定要生成的候选序列数量。
  • match_protein=True 约束生成的 DNA 翻译后与输入蛋白质序列一致。

更改目标宿主

目标宿主直接通过 organism 参数指定,例如:

organism = "Escherichia coli general"

可以改为:

organism = "Homo sapiens"

或者:

organism = "Saccharomyces cerevisiae"

然后重新运行推理,即可获得相应宿主的密码子优化 DNA 序列。

批量推理

示例数据当前位于:

scripts/demo/sample_dataset.csv

直接运行:

bash scripts/slurm/run_inference_batch.sh

默认输出保存到:

outputs/sample_predictions.csv

输入的 CSV 至少必须包含:

protein_sequence
organism

使用自定义 CSV:

INPUT_CSV=/path/to/input.csv \
OUTPUT_CSV=/path/to/output.csv \
bash scripts/slurm/run_inference_batch.sh

训练

微调数据准备

如需自定义微调,请先准备您自己的 CSV 文件。建议将其放在:

scripts/data/raw/your_data.csv

它至少必须包含:

dna
protein
organism

然后运行仓库中提供的数据预处理脚本:

INPUT_CSV=$PWD/scripts/data/raw/your_data.csv \
OUTPUT_JSON=$PWD/scripts/data/processed/finetune_data.json \
bash scripts/slurm/prepare_finetune_data.sh

CodonTransformer 微调

运行脚本:

bash scripts/slurm/run_finetune.sh

默认情况下,它读取:

scripts/data/processed/finetune_data.json

并将模型权重(检查点)保存到:

weight/checkpoints/finetune

要使用自定义数据进行微调,请运行:

DATASET_JSON=$PWD/scripts/data/processed/finetune_data.json \
CHECKPOINT_DIR=$PWD/weight/checkpoints/finetune \
CHECKPOINT_FILENAME=finetune.ckpt \
BATCH_SIZE=6 \
MAX_EPOCHS=15 \
NUM_WORKERS=5 \
ACCUMULATE_GRAD_BATCHES=1 \
NUM_GPUS=4 \
LEARNING_RATE=0.00005 \
WARMUP_FRACTION=0.1 \
SAVE_EVERY_N_STEPS=512 \
SEED=123 \
DEBUG=0 \
bash scripts/slurm/run_finetune.sh

这里的 NUM_GPUS=4、BATCH_SIZE=6 和 MAX_EPOCHS=15 是默认的训练设置。在实际使用中,应根据分配到的 GPU/DCU 设备数量、可用显存和数据集规模来调整这些参数。

导出微调后的模型并运行推理

微调完成后,可以使用以下脚本将检查点导出为适合推理的模型文件:

scripts/slurm/export_finetuned_model.sh

按如下方式运行:

CHECKPOINT_PATH=/path/to/finetuned_checkpoint.ckpt \
OUTPUT_MODEL_PATH=/path/to/output_finetuned_model.pt \
NUM_ORGANISMS=164 \
bash scripts/slurm/export_finetuned_model.sh

导出后,可以使用以下脚本加载微调后的模型进行推理:

scripts/slurm/run_inference_finetuned.sh

按如下方式运行:

PROTEIN="MFWY" \
ORGANISM="Escherichia coli general" \
MODEL_PATH=/path/to/output_finetuned_model.pt \
bash scripts/slurm/run_inference_finetuned.sh

预训练

当前的预训练入口为:

scripts/pretrain.py

预训练是一个完整的模型训练流程,需要大规模处理后的 DNA-蛋白质-宿主数据。在进行完整预训练之前,必须先将完整的 dataset.csv 转换为训练脚本可读取的 JSONL 文件。

仓库提供了以下预处理脚本:

scripts/slurm/prepare_pretrain_data.sh

默认情况下,该脚本读取:

scripts/data/raw/dataset.csv

并输出:

scripts/data/processed/pretrain_data.json

因此,在完整预训练之前,请先运行:

bash scripts/slurm/prepare_pretrain_data.sh

如果原始数据或输出目录与默认路径不同,请使用环境变量进行修改:

INPUT_CSV=$PWD/scripts/data/raw/dataset.csv \
OUTPUT_JSON=$PWD/scripts/data/processed/pretrain_data.json \
bash scripts/slurm/prepare_pretrain_data.sh

建议将生成的完整预训练数据保存为:

scripts/data/processed/pretrain_data.json

可以使用以下命令启动完整预训练:

TRAIN_DATA_PATH=$PWD/scripts/data/processed/pretrain_data.json \
CHECKPOINT_DIR=$PWD/weight/checkpoints/pretrain \
BATCH_SIZE=6 \
MAX_EPOCHS=5 \
NUM_WORKERS=5 \
ACCUMULATE_GRAD_BATCHES=1 \
NUM_GPUS=16 \
LEARNING_RATE=0.00005 \
WARMUP_FRACTION=0.1 \
SAVE_INTERVAL=5 \
SEED=123 \
DEBUG=0 \
bash scripts/slurm/run_pretrain.sh

这里的 NUM_GPUS=16 对应预训练脚本中的默认多设备设置。在实际使用中,请根据分配到的 GPU/DCU 设备数量调整 NUM_GPUS。预训练的检查点默认保存到:

weight/checkpoints/pretrain

OneScience 官方信息

引用与许可

  • CodonTransformer 官方源代码仓库基于 Apache License 2.0 许可发布。详见仓库根目录中的 LICENSE 文件。
  • CodonTransformer 模型权重通过 Hugging Face 单独分发,训练数据则可通过 Zenodo 和 Hugging Face Datasets 获取。模型权重、训练数据及相关第三方资源各自必须按照其对应页面上规定的许可和使用条款使用。
  • 本仓库是 CodonTransformer 的 DCU 适配版本。仓库代码、模型权重和相关数据的使用仍需遵守其各自原始项目的许可和使用条款。
Downloads last month
10
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support