Views
No views yet
bacformer package (see https://github.com/macwiatrak/Bacformer). An end-to-end Python example demonstrating how to embed a genome with Bacformer is provided in the tutorials folder.Bacformer.1import torch
2from transformers import AutoModel
3from bacformer.pp import protein_seqs_to_bacformer_inputs
4
5device = "cuda:0"
6model = AutoModel.from_pretrained("macwiatrak/bacformer-causal-MAG", trust_remote_code=True).to(device).eval().to(torch.bfloat16)
7
8# Example input: a sequence of protein sequences
9# in this case: 4 toy protein sequences
10# Bacformer was trained with a maximum nr of proteins of 6000.
11protein_sequences = [
12 "MGYDLVAGFQKNVRTI",
13 "MKAILVVLLG",
14 "MQLIESRFYKDPWGNVHATC",
15 "MSTNPKPQRFAWL",
16]
17# embed the proteins with ESM-2 to get average protein embeddings
18inputs = protein_seqs_to_bacformer_inputs(
19 protein_sequences,
20 device=device,
21 batch_size=128, # the batch size for computing the protein embeddings
22 max_n_proteins=6000, # the maximum number of proteins Bacformer was trained with
23)
24
25# move the inputs to the device
26inputs = {k: v.to(device) for k, v in inputs.items()}
27# compute contextualized protein embeddings with Bacformer
28with torch.no_grad():
29 outputs = model(**inputs, return_dict=True)
30
31print('last hidden state shape:', outputs["last_hidden_state"].shape) # (batch_size, max_length, hidden_size)
32print('genome embedding:', outputs.last_hidden_state.mean(dim=1).shape) # (batch_size, hidden_size)6,000, which covers whole bacterial genome in >98% of genomes present in out training corpus.50k distinct protein family clusters.
Importantly, the input to Bacformer are exact protein sequence and we only use the discrete protein family label in a final classification layer where predicting
the protein family of masked proteins. This allows the model to work on amino acid level tasks where even single mutations can change the phenotype of a genome.1,024 and the maximum number of proteins in a genome was set to 6,000, which covers whole bacterial genome in >98% of genomes present in our training corpus.
The Adam optimizer [1] was used with a linear warmup learning rate schedule, with the number of warmup steps equal to 7,500. The base learning rate of 0.00015 was used,
scaled by square root of number of GPUs (lr = args.lr * np.sqrt(max(n_gpus, 1))). We monitor the loss on the validation set as the measure of performance during training.D dimensional vector. We embed all of the N proteins present in the whole bacterial genome resulting in a N x D matrix,
where D is the dimension of the base pLM model, here 480. The protein embeddings are added together with the 2) contig embeddings. The contig embeddings
are learnable embeddings which represent the unique contigs present in the genome. As an example, if a genome is made up of K contigs, each containing a number of proteins,
each protein within the same contig will have the same contig embedding, which is different from the embeddings of different contigs.
Contig embeddings have been created to account for the fact that bacterial genomes are often made up of chromosome and plasmid(s) and are frequently collated by combining
multiple contigs together (metagenome assembled genomes).
The contig embeddings are initialised and train from scratch at the beginning of pretraining.[CLS] token
at the start of the sequence, 2) [SEP] token between the contigs or chromosomes(s)/plasmid(s), 3) [END] token at the end of the genome. The example below show how does
the genome representation look like for complete genomes and MAGs.[CLS] [chromosome1_gene1] [chromosome2_gene2] ... [chromosomme1_geneN] [SEP] [plasmid1_gene1] ... [plasmid1_geneM] [END][CLS] [contig1_gene1] ... [contig1_geneN] [SEP] [contig2_gene1] ... [contig2_geneM] [SEP] ... [contigZgeneV] [END]hidden_dim=480 and is trained from scratch. Bacformer leverages the flash attention available in pytorch>=2.2.50k distinct protein family clusters. Importantly, the input to Bacformer are
exact protein sequences present in the whole bacterial genome, rather than protein family tokens. This allows the model to work on amino acid level tasks where even single mutations
can change the phenotype of a genome, while still allowing for pretraining.1@article{Wiatrak2025.07.20.665723,
2 author = {Wiatrak, Maciej and Vi{\~n}as Torn{\'e}, Ramon and Ntemourtsidou, Maria and Dinan, Adam M. and Abelson, David C. and Arora, Divya and Brbi{\'c}, Maria and Weimann, Aaron and Floto, Rodrigo Andres},
3 title = {A contextualised protein language model reveals the functional syntax of bacterial evolution},
4 elocation-id = {2025.07.20.665723},
5 year = {2025},
6 doi = {10.1101/2025.07.20.665723},
7 publisher = {Cold Spring Harbor Laboratory},
8 URL = {https://www.biorxiv.org/content/early/2025/07/20/2025.07.20.665723},
9 eprint = {https://www.biorxiv.org/content/early/2025/07/20/2025.07.20.665723.full.pdf},
10 journal = {bioRxiv}
11}