Skip to content
ImagineWorld

Generating protein structures

node_idnode-book_build-small-language-model_chapter-08-generating-protein-structures
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleGenerating protein structures
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Generating protein structures

Section titled “Chapter 8 — Generating protein structures”

This chapter covers

  • Using LLMs to generate protein structures
  • Using LLMs to generate crystal structures
  • Optimizing LLM inference performance for chemistry

Chapter 7 covered practical examples of domain-specific small language models (SLMs) for Python code generation and how to optimize them to run on commodity hardware, even a laptop. This chapter presents real-world examples of specialized SLMs for drug R&D and chemistry.

In chapter 7, you saw how to overcome inference challenges using the tips and tricks introduced in the first part of this book. Before we move on to more advanced inference optimization and model quantization in the following chapters, we’ll apply these techniques to specialized SLMs in the chemistry domain to show that they aren’t limited to creating coding assistants. If chemistry is new to you, don’t worry—we’ll keep it high level and cover only what you need to follow the model descriptions and inference optimization strategies we’ll apply.

Chemistry is one of the fields that has benefited most from advances in natural language processing (NLP). Researchers have reframed many chemistry tasks as text-sequence problems. Combined with open datasets, this has sparked a wave of work starting with clearly defined fundamental challenges. Early models were single-modal, using molecules as both input and output. More recent work is multimodal, adding data such as spectra from analytical techniques and human language (such as synthesis procedures) to bridge the gap between chemical and natural-language modeling.

Some chemistry terms Amino acid—Organic molecule used by living organisms to build proteins Antibody—Immune-system protein that helps fight pathogens such as bacteria and viruses Oligomer—Molecule made of a small number of repeating units called monomers Protein—Molecule made of amino acids that supports growth, tissue repair, and other body functions Reactant—Substance that is changed or consumed in a chemical reaction Reagent—Substance added to trigger a reaction or test for one (or for a specific chemical) SMILES—The Simplified Molecular Input Line Entry System, a chemical notation for representing molecular structures in computer-readable form (https://biocyc.org/help.html?object=smiles)

One early and notable effort is the Molecular Transformer (https://pubs.acs.org/doi/10.1021/acscentsci.9b00576). Organic synthesis is a key building block in medicinal chemistry, and a necessary but still unsolved step in synthesis planning is product prediction: given reactants and reagents, what will the final products be? In this work, reaction prediction is treated as machine translation between SMILES strings for reactants, reagents, and products. The model outperforms earlier methods, achieving top-1 accuracy above 90% on a common benchmark dataset. The Molecular Transformer learns correlations between the presence or absence of chemical motifs in the reactants, reagents, and products in the dataset, and it requires no handcrafted rules.

Drug discovery is the area where adopting language models has delivered the biggest gains so far. As mentioned in chapter 1, because they’re trained mostly on data scraped from the web, large commercial language models underperform on tasks that require specialized knowledge—knowledge that typically requires domain-specific, often proprietary data that isn’t available to tech companies. In other cases, a model needs task-specific tuning, or the data’s structure is too complex for large general-purpose models to be useful. In all these scenarios, the closed nature of large commercial models and the high cost of fine-tuning them make it impossible to achieve the performance needed for drug discovery.

For these reasons, academia and industry have turned to smaller open source pre-trained language models. These models provide full control and make it possible to release production-ready models for a diverse set of drug discovery tasks. Each month brings new specialized models, many under permissive open source licenses that often cover not only the source code and model checkpoints, but also the training and test datasets. I maintain a GitHub repo that tracks major fully open source initiatives in this area (https://github.com/virtualramblas/awesome-deep-learning-4-life-sciences).

This chapter will look at notable examples of domain-specific SLMs for protein and crystal structure generation, along with ML/AI engineering considerations and suggestions for improving inference performance.

8.2 **From natural language to protein structures

Section titled “8.2 **From natural language to protein structures”

The first SLM we’ll explore is ProtGPT2 (https://www.nature.com/articles/s41467-022-32007-7), a model that “speaks” the protein language and can be used for novel protein design and engineering. Sequences generated by ProtGPT2 preserve key features of natural proteins (amino acid propensities, secondary structure content, and globularity) while exploring previously unseen regions of protein space.

ProtGPT2 is a decoder-only GPT-2 model with 738 million parameters. It was pre-trained in a self-supervised fashion to predict the next token (oligomer) in a sequence, using 87,162 raw protein sequences from the UniRef50 database (https://www.uniprot.org/help/uniref) and without including the corresponding annotations. The pre-processed training set is available on the Hugging Face Hub (https://huggingface.co/datasets/nferruz/UR50_2021_04). Given a natural-language prompt, it can generate protein sequences. The pretrained model is available on the Hugging Face Hub (https://huggingface.co/nferruz/ProtGPT2).

Let’s look at how this model works and use it to generate de novo proteins in a zero-shot setting. A companion Colab notebook is provided for this example. Because the model is available on the Hugging Face Hub, we’ll use the Transformers library to download it and set up an inference pipeline:

from transformers import pipeline
protgpt2 = pipeline('text-generation', model="nferruz/ProtGPT2")

After downloading the model, we can use the preceding pipeline to generate protein sequences:

sequences = protgpt2("<|endoftext|>", max_length=100,
do_sample=True, top_k=950,
repetition_penalty=1.2,
num_return_sequences=10,
eos_token_id=0)

This is no different from generating text or code. Here, we asked the model to generate 10 protein sequences; the results look like this:

{'generated_text':
'<|endoftext|>\nMGDIPAEILRNWNYYSNFTLLHITFFLLGTFLHLIQELKGKPKPSKGKKQEESVAE
E\nKVKEEPPIMVQGKAKETKTKKRDIEAEPVPMVEPLPVDELEKLDKEMKKKKDKKK\nEKQEIEQKAV
VEQAPVVEQSAAVEQLPVAEQKPEQEKAKKAKKSEPEKKPEVKLEKKKR\nEKEREETEEKPAEEPQAVED EEH
EEVAKKSKKRRKADVQEPEVEEVKVEAEPKKKKR\nKQSDDDSQEKKGGKKEKSKK'}
{'generated_text':
'<|endoftext|>\nMVQPQSASDPPASPTTDHPLSPLGNRVVVGRCLLLLALLFHTFTYTWAYAAGSLYCV
A\nVCMPTVLIYQCALLLCLTVSRRHHRVSRGGSRWPSRLVWLRSTKWAVVLLLIFFSLFGLA\nTQCFVIFCHP
TAYSQSTMQHHSPAANITTHCGPNAHNDSHHVALSQWVETAVAWAFVASV\nVAWFASVAVVIPRWTGYCRLCCR
DSASSSNDDASGMEDKWDEEEYEDEE'}
{'generated_text':
'<|endoftext|>\nMSRPRNPR TVAGAPVPVAHAHPQIHETHGVR LHYVERGTGPPVVLVHGLGGQIDSMV
G\nALPALPRHRVVALDQRG HESDKPATGYGIAEIAADL DG FIAAXXCPAFGCHGRQGSGR\nGGPGR AAAAG
RSSEPRGLHARSAQPAQGLDHGHRAGPGEVRRRGRRTGCRPSLTPD\nLSTTPRGPA'}
{'generated_text':
'<|endoftext|>\n MHIWGCGPSTIGLINTKNPTIFFILLTPDVSISFAIPPNKSLFSSIKYHVISKK
N\nKFLNISKIGIFLPSFCSCLYRCLIRGTTFTNERPSTQTRSNNHQ'}
{'generated_text':
'<|endoftext|>\nMPHPIALAAIAGAPLALCAVLW SHVALEGQAAWSMAAMSALGTVTALRRTLLGPA A
T\nAAFLAGFGWVALAELAAPPRAAHH LAALG PAPVLRVRE EARADPVRTR YRLVTGDRA D\nGGPGRAW TAP
RPRLLVWRAAGP ERWVPGRAGARL LMTPRGTPNPGALDAELAALRR\nGIAASGLRGPAGVSADPLSWR
RLRGRFERWLD RQAAAGPRGAVAALATGDEAGIPAP\nD WAVFRDTGTAHLMVSG LHIGLVAGLAGALAARLY
G'}
{'generated_text':
'<|endoftext|>\nMKHA WILLLFYAETSAQLYSTHFANPFNPLNMRPAHNSTELFFIPSHSFFGPVISA
Q\nNGFQ QNPTAVNQYPTQTAQYPTYSM YOPSSIPYYQ LTA STTPYNE YTSFPQNTYNTPS\nNYDAYYY PQT
QVYYQYQPSTTQPMNYRSYNTTTHYPP IQPTYEASNAYSMYQQQ TTP\nSQSPYNTQSTTTQPSTFSPQETM
LEVSP TPPASNVPSPVAISPPPPQVPPQSASSP ISTA'}
{'generated_text':
'<|endoftext|>\nMSPIA WFFLASGSIALLGNVPLWG PWRWRLTPLAVVLFATWALQRWEAALFLLV LV
A\nLIGLAGRAARVL RASLFARRLRGAAAEV AEPMDAEAAHAATAAAA GDQP'}
{'generated_text':
'<|endoftext|>\nMSGFVAVLFTATLFC LIPCLAFIYILGNKDLGKDHPLIYLLSLASG TLCGDAFLHLI
P\nHLL ENHETHG TESNGHSMALWVLLG VFFMCEKL FHLITEYKQSHAMK ISKKTMIV\nGDDAKLYDPV
TTRINTSKHCCSSSGSPSYSDTSGETICNNTENG LLSVNNISN DFN\nNANKNNHLNKPNKHGT DNVETN
QNSSETDNKQNKHSHNQKCN GDLEVSSKGNHRSTAS\nSS'}
{'generated_text':
'<|endoftext|>\nMRALILFLLCGCAVTT PATTVRTAQPT LEEPGRSRVWLW STRAPERWL VVRDGTVRG
L\nDPASGRTIWQ LAPGEERWGTEAVGDELLVTRAGTASVELAVRAKDLTGRAQLTVSTVPTS\nVPTPSPEPPL
WVVEGDAAPVDRARWG RAVTLGDQQ LVADPRR RVFAGTPSGGWSLAR\nLDAATGAPLWQTPVAA GQALVAG
AAPGSFVVGYDRLSFA DAASGAE TWAGPVGERGRG\nPAAAPTATVDGT'}
{'generated_text':
'<|endoftext|>\n MRLIWTFLIFFL TIGRAQD SLNNSRIIPLVTLKDFCNSGISIIPNGENEDELYKIKNS
L\nANOFER TKYSLNRLDFEID SIRCD SLNRF DSLVYDTS LFRIDSTFGNLEKSKNDIDNK\nISILEKNLKS
LLKSEHLKFSN VITFIVL IFFIAVLLWILKRSRNKTIINITINSKKIL\nELDRLEYEKKLTTMENELNQKIA
ENRL LMEQTRLKEIFETKTDLS D SQN T LSSSQNEKII\nAENIRFQEEKALLEQKL'}

The model chose to generate sequences that start with the amino acid “M” (we didn’t specify a prompt, so the choice was up to the model, but you can specify any other amino acid, oligomer, fragment, or protein as a starting point). Because the model is compact, generating a batch of 10 sequences takes, on average, less than 2 minutes on Colab’s free tier without hardware acceleration. This is acceptable, since these tasks don’t necessarily need to happen in real time and the model can run on commodity hardware. For this model, it’s probably better to focus on the quality of the generated protein sequences. In the next section, we evaluate a model that, unlike ProtGPT2, needs more attention to inference performance. A widely used metric for assessing the quality of LLM-generated content is the perplexity score, introduced in section 6.2.1. In that section, we also implemented a basic function to calculate perplexity for LLM-generated text. Applying that same function to the 10 generated protein sequen yields the following scores:

275.8756703543678
552.265406680504
222.6862045710289
739.1276632256441
202.7109209811726
449.55308995221174
419.3895659171086
385.7640621074327
404.39583964519915
573.9670349466911

As with text generation, a lower perplexity score is better.

This domain-specific open SLM shows that with the right data, you do not need a large model to solve real-world, nontrivial tasks.

Our second SLM in this chapter is the Antibody Generator (also referred to as AntibodyGPT), a specialized protein generation model for creating therapeutic antibody sequences for use in immunology, vaccine development, and medical treatments. Antibodies are proteins that protect us when a foreign substance (called an antigen) enters the body. Produced by the immune system, antibodies bind to these substances to help eliminate them. The Antibody Generator is based on ProGen2, an advanced language model developed by Salesforce and trained on more than 280 million protein sequences—it was introduced in the paper “ProGen2: Exploring the Boundaries of Protein Language Models” (https://arxiv.org/abs/2206.13517).

The ProGen2 family follows a decoder-only architecture and includes four model sizes: small (151 million parameters), medium (765 million parameters), large (2.7 billion parameters), and extra-large (6.4 billion parameters). The Antibody Generator models were built using the ProGen2 small, medium, and large variants as a baseline and were fine-tuned on 5,000 experimentally resolved crystal structures of antibodies and their antigens (see figure 8.1). All three Antibody Generator model options are available on the Hugging Face Hub.

Let’s run inference with AntibodyGPT, starting with the small model. A companion Colab notebook is provided for this example, and it requires GPU acceleration.

ProGen2 small ProGen2 medium ProGen2 large ProGen2 extra-large
(151M) (764M) (2.7B) (6.4B)
│ │ │
└──────────────────┴─── Fine Tuning ──┴───────┐
│ │
▼ ▼
AntibodyGPT small AntibodyGPT medium AntibodyGPT large
(151M) (764M) (2.7B)
Base model (ProGen2)ParametersFine-tuned counterpart (AntibodyGPT)Parameters
ProGen2 small151MAntibodyGPT small151M
ProGen2 medium764MAntibodyGPT medium764M
ProGen2 large2.7BAntibodyGPT large2.7B
ProGen2 extra-large6.4B— (no fine-tuned counterpart)—

[!visual-conversion] Figure 8.1 — The different options available for the ProGen2 and Antibody Generator model families (p. 160)

To download checkpoints for this model (or either of the other two versions) from the Hugging Face Hub and load them into memory, you’ll need a custom auto class, ProGenForCausalLM. It’s implemented in a public GitHub repo by Joseph Roberts (a coauthor of AntibodyGPT): https://github.com/joethequant/docker_protein_generator. First, clone the repo:

Terminal window
!git clone https://github.com/joethequant/docker_protein_generator.git
%cd ./docker_protein_generator/

We can now download the model and its tokenizer:

import torch
from models.progen.modeling_progen import ProGenForCausalLM
from tokenizers import Tokenizer
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model_id = 'AntibodyGeneration/fine-tuned-progen2-small'
model = ProGenForCausalLM.from_pretrained(model_id)
model = model.to(device)
tokenizer = Tokenizer.from_pretrained(model_id)

After we load the model into GPU memory, we can define a target antigen sequence:

target_sequence =
'MQIPQAPWVWAVLQLGRWPGWFLDSPRPNPPTFSPALLVVTEGNATFTCSFNTSSESFVLNWYRMSPSN
QTDKLAAPEDRSQPGQDCRFVTQLPNGRDFHMSVVRNRNDSGTYLCGAISLAPKAQIKESLRAELRVTERA EVPTAHPSPRPAGQFQLLVGVVGLLGSLVLLWVLAVICSRAAGTIGARRTGQPLKEDPSAVPVFSVDYG ELDFQWREKTPPEPPVCVPEQTEYATIVFPSGMGTSSPARRGSADGPRSAQPLRPEDGHCSWPL'

And we can specify how many antibody sequences to generate:

number_of_sequences = 2

Before passing the prompt to the model and running inference, we need to tokenize the target sequence and convert it to a PyTorch tensor:

tokenized_sequence = tokenizer.encode(target_sequence)
input_tensor = torch.tensor([tokenized_sequence.ids]).to(device)

Now we can start sequence generation (inference):

with torch.no_grad():
output = model.generate(input_tensor, max_length=1024,
pad_token_id=tokenizer.encode('<|pad|>').ids[0],
do_sample=True, top_p=0.9, temperature=0.8,
num_return_sequences=number_of_sequences)

To get the generated sequences, we need to decode the model output as follows:

as_lists = lambda batch: [batch[i, ...].detach().cpu().numpy().tolist()
for i in range(batch.shape[0])]
sequences = tokenizer.decode_batch(as_lists(output))
if len(sequences) > 0:
sequences = [x.replace('2', "'") for x in sequences]

Although this model is smaller than ProtGPT, generating just two target sequences quickly requires a GPU (inference with the same model and settings takes a couple of hours on the Colab free tier without hardware acceleration). Under these conditions, the benchmark shows the following average latency:

('P95 latency (ms) - 137426.0512944001; Average latency (ms)
- 119778.24 +\\\- 27239.48;',
137426.0512944001)

In the CUDA allocator configuration, the expandable-segment allocation is set to false by default. This can fragment the allocator’s memory segments, preventing them from expanding later during inference for reuse. You can test whether changing the CUDA caching allocator improves latency:

%env PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

Rerunning the benchmark after applying the preceding setting achieves a slightly lower average latency:

('P95 latency (ms) - 128515.5656411501; Average latency (ms)
- 103638.09 +\\\- 29278.26;',
128515.5656411501)

Before optimizing this model, let’s look at how we can validate its generated results. Perplexity and similar statistical metrics make little sense on their own in cases like this. A more reliable option is the ANARCI tool (https://opig.stats.ox.ac.uk/webapps/sabdab-sabpred/sabpred/anarci/), developed and maintained by the Oxford Protein Informatics Group (OPIG), for antibody numbering and receptor classification.

ANARCI checks whether generated antibody sequences conform to known patterns and structures, helping us assess structural viability and alignment with established frameworks. The goal is for sequences to be not only novel but also biologically relevant and potentially functional. You can submit a generated antibody sequence to the ANARCI online tool; figure 8.2 shows the results for one of the sequences from our example.

MQIPQAPWVVWAVLQLGWRPGWFLDSPDRPNWPTFSPALLVVTGEONATFTCSNTSESFVLNYRMSPSNQTDKLAAPEDRSQPQQDCRFVTQLPNGR
DFHMSVVRARNDSGTYLCGAISLAPKAQIKESLRAELRTVRAEVPVTAHPSPRPAGQFQTLVGVGGLLGSLVLLVWVLAVICSRAARTIGARRTQOP
LKEDPSAVPVFSVDYGELDFQWREKTPGPPVCVPEQTEYATIVFPSGMTSSPARRGSADGPRSAQPLPEDGHCSWPLCGLLSGCWGIVGQPGDGRSCGL
WLLTOTHGILFNSSLTEVNPFHHGPRAYPGGGSGGGSGGGGSEVKLVEGGDVVQPGSSLKISCASKEYGFTSYDISWVRQHPGGGLEWIGYLP
YDSETRVSKPODLTDVHMONSYNETADTQIDMAVSRKSFFSMSVMRSLYSGTYYCTRGDNWPHWFDPMWGGTLVTYSA AKTPPSVFPALPCSRSTSESTAA
GCLVXDYPPEPVTVSWSGALTSVGHTFP AVLQSSGLYSLSVTVPSSSLGTQTYTCNVNHKPSNTKVDKRVELKTGGGSGGGSGGGGSEIVLTQSPVLS
LSPGERATLSCRASQGYSSYLAWYQOKPGQAPRLLIYDASHNATGIPAHFSGSGGTDFTLTISSEPEDAFYCOQSNWPLTFGGGTKWEIKRTVAAPS
IFPPSDEQLKSGTASVVCCLNNFYPREAKVQWKVDNALQSGNSQESVTEQDSKDSTYSLSSTLTLSKADYEKHKVYACEVTHQGLRSPVTKSFNRGEC
E I V L T Q S P V S L S L S P G E R A T L
Domain No.Assigned SpeciesDomain TypeStart IndexEnd Index
1humanH363496
2humanK612719

Domain 1, scheme = imgt

123456789101112131415161718192021
EVKLVESGG-DVVQPGSSLKI

Domain 2, scheme = imgt

123456789101112131415161718192021
EIVLTQSPVSLSLSPGERATL

Figure 8.2 The output of the online ANARCI tool for one of the antibody sequences generated in our example

In many domains, it’s common to validate generated content with a dedicated tool. Subject matter experts should always review it. You can also perform this validation programmatically using the Python ANARCI API (https://github.com/oxpig/ANARCI/tree/master).

Next, let’s see whether the model benefits from quantization. Using the Bitsandbytes library, we can quantize it to 8-bit. First, we’ll define a quantization configuration:

from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
)

Now we’ll use it via the ProGenForCausalLM auto class:

model_id="AntibodyGeneration/fine-tuned-progen2-small"
model_int8 = ProGenForCausalLM.from_pretrained(model_id,
quantization_config=bnb_config,
)
tokenizer = Tokenizer.from_pretrained(model_id)

As expected, the 8-bit quantized model is smaller than the original (156.73 MB ver 617 MB). Running the same benchmark as for the original model, we can observe following performance:

('P95 latency (ms) - 80453.97859845006; Average latency (ms)
- 61846.30 +\|- 18507.29;',
80453.97859845006)
The average latency is typically about 40% lower than in the vanilla models' benchmarks
after enabling dynamic, expandable segments.

The third SLM we’ll explore is CrystalLLM from the “Crystal Structure Generation with Autoregressive Large Language Modeling” paper (https://arxiv.org/abs/2307.04340). It’s a Transformer-based, decoder-only LLM built to generate crystal structures. Previously , crystal structure-prediction methods—often based on computationally intensive ab initio techniques—typically relied on dedicated tools to optimize candidate structures.

CrystalLLM is the first model trained on textual representations of crystallographic information files (CIFs), rather than traditional chemical representations. The authors argue that symbol sequences can represent complex chemical structures and that LLMs can learn deeper causal relationships beyond simple correlations. Trained on extensive CIF data, the model can generate physically plausible inorganic crystal structures. The authors also added Monte Carlo tree search (MCTS) and a graph-based neural network to improve structural sampling.

During training, the model is given token sequences from a corpus of CIF files and learns to predict the next token. After training, it can generate new CIF files conditioned on a starting token sequence. Generating a CIF file involves repeatedly sampling tokens from the model, conditioning on the accumulated generated content, until a terminating condition is reached.

Figure 8.3 (from the previously cited paper) provides a high-level view of CrystalLLM’s training and inference processes. As you can see, during training, a CIF file is tokenized into a symbol sequence. The model processes the sequence, and it outputs, for each input symbol, a probability distribution over the vocabulary. These predicted distributions are compared with the target distributions (all the probability mass on the correct next token) using the cross-entropy loss metric. The targets are the input tokens

dslm-fig-8.3-the-crystallm-training-process-a.png

[!visual-conversion] Figure 8.3 — The CrystaLLM training process (a) and the generation process with MCTS decoding (b) (p. 164) shifted one position left, since the task is to predict the next token from the preceding tokens (as in many LLM content-generation tasks). The tokens are grouped into CIF tags, atoms, numeric digits, and punctuation. The output tokens (not sampled during training) represent those with the highest assigned probability. Underlined tokens indicate cases where the correct next token receives relatively low probability.

Once the model is trained, it generates a CIF file from a prompt. The prompt is built by concatenating the symbol data with the target cell composition, and it’s then tokenized and fed to the model. At each step, the model samples the next token from the predicted distribution and appends it to the CIF contents. This repeats until a pre-defined stopping condition is reached. The model is based on GPT-2; the model definition, training, and inference code are adapted from Andrej Karpathy’s nanoGPT repository (https://github.com/karpathy/nanoGPT).

CrystaLLM can generate plausible crystal structures for a wide range of inorganic compounds, including ones it didn’t see during training. It generates syntactically valid, physically plausible structures and can predict crystal structures given chemical

composition and symmetry information. It also generalizes to unseen inorganic structures, achieving structural matches in up to 40% of cases, and can extrapolate structural motifs to new compositions. This work is important because it has shown potential to accelerate material discovery by generating candidate crystal structures for downstream optimization.

We’ll skip the remaining training details. In this chapter, we’ll use the pretrained model and focus only on the inference process. A companion Colab notebook is provided for this section.

To set up the environment, we’ll first clone the CrystaLLM GitHub repository:

Terminal window
!git clone https://github.com/lantunes/CrystaLLM.git
%cd CrystaLLM

Next, we’ll make the cloned source code directories part of the Python path:

import sys
import os
sys.path.append('/content/CrystaLLM')
os.environ["PYTHONPATH"] += (":/content/CrystaLLM")

Once you’ve installed the missing requirements, download the pretrained model weights. Two versions of CrystaLLM are available: small (25 million parameters) and large (200 million parameters). These weights aren’t available on the Hugging Face Hub, so download them using the following Python script (here we’re requesting the small version):

Terminal window
!python bin/download.py crystallm_v1_small.tar.gz
!tar xvf crystallm_v1_small.tar.gz

We’re now ready to use it to generate crystal structures. First, we need to create a prompt, which in this case is the partial contents of a preprocessed CIF file. Typically, the prompt contains the cell composition: a formula specifying the total count of each atom type in the unit cell. For example, we can specify Na2Cl2 (disodium dichloride), which indicates four atoms in the unit cell, and use the provided make_prompt_file.py script to prepare and save the prompt for later use:

Terminal window
!python bin/make_prompt_file.py Na2Cl2 my_prompt.txt

To prompt the model with a cell composition, the format should use the data_ prefix and a newline character at the end of the line:

data_<cell_composition>\n

The make_prompt_file.py script handles this formatting convention (and more). In our example, the model is prompted with data_Na2Cl2\n.

We can now generate the CIF files; we’ll use the provided sample.py script:

Terminal window
!python bin/sample.py \
Terminal window
out_dir=crystallm_v1_small \
start=FILE:sample_prompt.txt \
num_samples=2 \
top_k=10 \
max_new_tokens=3000 \
device=cuda \
target=file

This script takes the following arguments:

  • out_dir—The directory containing the downloaded model checkpoints.
  • start—Either a prompt in the required format or the path to a file containing the prompt.
  • num_samples—The number of samples to generate.
  • top_k—The maximum number of most likely tokens to keep.
  • max_new_tokens—The maximum number of tokens to generate per sample.
  • device—Where to offload the model weights: CPU or GPU.
  • target—Where the generated content should be sent. In our example, it’s file. Alternatively, it can be console.

These are some other arguments we haven’t used here:

  • temperature—This has the same meaning as in any Transformer model.
  • seed—Sets the random seed for reproducibility; defaults to 1,337.
  • dtype—Model precision; defaults to bf16.
  • compile—Boolean flag indicating whether to compile the model with PyTorch before CIF generation for faster execution. Defaults to False.

No hardware acceleration is needed for this small model. With the chosen configuration (3,000 tokens max per sequence), generating two CIF files on a Colab CPU VM takes under a minute on average. Here is one of the generated CIF files from this run:

data_Na2Cl2
loop_
_atom_type_symbol
_atom_type_electronegativity
_atom_type_radius
_atom_type_ionic_radius
Na 0.9300 1.8000 1.1600
Cl 3.1600 1.0000 0.7800
_symmetry_space_group_name_H-M P4/nmm
_cell_length_a 4.9038
_cell_length_b 4.9038
_cell_length_c 3.9603
_cell_angle_alpha 90.0000
_cell_angle_beta 90.0000
_cell_angle_gamma 90.0000
_symmetry_Int_Tables_number 129
_chemical_formula_structural NaCl
_chemical_formula_sum 'Na2 Cl2'
_cell_volume 95.2964
_cell_formula_units_Z 2
loop_
_symmetry_equiv_pos_site_id
_symmetry_equiv_pos_as_xyz
1 'x, y, z'
loop_
_atom_site_type_symbol
_atom_site_label
_atom_site_symmetry_multiplicity
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_occupancy
Na Na0 2 0.0000 0.0000 0.0000 1
Cl Cl1 2 0.0000 0.5000 0.9817 1

The model’s output isn’t usable yet: the model produces raw CIF files that require postprocessing . A Python script is provided; you’ll need to run it on the generated files as follows:

Terminal window
!python bin/postprocess.py . colab_processed_cifs

The postprocess.py script takes two arguments: the directory containing the generated raw CIF files and the output directory for the postprocessed files. After postprocessing , the raw CIF file shown previously looks like this:

data_Na2Cl2
_symmetry_space_group_name_H-M P4/nmm
_cell_length_a 4.9038
_cell_length_b 4.9038
_cell_length_c 3.9603
_cell_angle_alpha 90.0000
_cell_angle_beta 90.0000
_cell_angle_gamma 90.0000
_symmetry_Int_Tables_number 129
_chemical_formula_structural NaCl
_chemical_formula_sum 'Na2 Cl2'
_cell_volume 95.2964
_cell_formula_units_Z 2
loop_
_symmetry_equiv_pos_site_id
_symmetry_equiv_pos_as_xyz
1 'x+1/2, y+1/2, -z'
2 '-y, x, -z'
3 '-x, y, z'
4 'y+1/2, -x+1/2, z'
5 'x+1/2, -y+1/2, -z'
6 '-y+1/2, x+1/2, z'
7 '-x, -y, z'
8 'x, y, z'
9 'y, x, -z'
10 '-x+1/2, y+1/2, -z'
11 '-y, -x, -z'
12 '-x+1/2, -y+1/2, -z'
13 'y, -x, -z'
14 '-y+1/2, -x+1/2, z'
15 'x, -y, z'
16 'y+1/2, x+1/2, z'
loop_
_atom_site_type_symbol
_atom_site_label
_atom_site_symmetry_multiplicity
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_occupancy
Na NaO 2 0.0000 0.0000 0.0000 1
Cl Cl1 2 0.0000 0.5000 0.9817 1

Now we need to validate the generated files. A validation script is provided, and it expects the input CIF files in a .tar.gz archive:

Terminal window
!tar -czvf colab_processed_cifs.tar.gz ./colab_processed_cifs/

Trigger the validation as follows:

Terminal window
!python bin/evaluate_cifs.py colab_processed_cifs.tar.gz -o colab_processed_cifs.csv

The evaluate_cifs.py script takes two arguments: the name of the archive containing the CIF files to evaluate and the name of the CSV file where the results should be saved. The results are also printed to standard output at the end:

space group consistent: 2/2 (1.000)
atom site multiplicity consistent: 2/2 (1.000)
avg. bond length reasonableness score: 1.0000 ± 0.0000
bond lengths reasonable: 2/2 (1.000)
num valid: 2/2 (1.000)
longest valid generated length: 631
avg. valid generated length: 560.500 ± 70.500

Among other things, the output’s info and stats show that both generated CIF files are valid.

As described at the start of section 8.4 (see figure 8.3), the CrystaLLM paper proposes a second way to generate CIF files: run the LLM inside an MCTS loop. A script is also provided. You can run MCTS-based decoding as follows:

Terminal window
!python bin/mcts.py \
Terminal window
out_dir=crystallm_v1_small \
device=cuda \
dtype=bfloat16 \
start=FILE:sample_prompt.txt \
tree_width=5 \
max_depth=2000 \
selector=puct \
c=1.0 \
num_simulations=1000 \
reward_k=2.0 \
scorer=random \
top_child_weight_cutoff=0.9999 \
bypass_only_child=True \
mcts_out_dir=colab_mcts_cifs

mcts.py uses the same model, precision, and sample prompt file as standard generation. It also takes MCTS-specific arguments: tree width, maximum depth, number of simulations, and rollouts per simulation.

If you want to upload a CrystalLM pretrained model (or your fine-tuned version) to a Hugging Face Hub repository and use it with the Transformers library, follow these steps. We show the small model here; the large model follows the same steps but uses different configuration values.

First, create a configuration file, config.json, as required by the Transformers auto classes. You can copy most values from config/crystallm_v1_small.yaml in the CrystalLM GitHub repository (there is a similar file for the large model).

crystall_small_config = """{
"bias": true,
"model_type": "gpt2",
"block_size": 1024,
"dropout": 0.1,
"n_embd": 512,
"n_head": 8,
"n_layer": 8,
"vocab_size": 50257
}"""
with open('/content/CrystalLM/crystallm_v1_small/config.json', 'a') as f:
f.write(crystall_small_config)

Next, convert the model checkpoint from .pt to .bin, which is required to load it into an auto class:

import torch
checkpoint = torch.load("/content/CrystalLM/crystallm_v1_small/ckpt.pt",
map_location=torch.device('cpu'))
params = checkpoint["model"]
torch.save(params,
"/content/CrystalLM/crystallm_v1_small/pytorch_model.bin")

Note that instead of accessing the model_state_dict key, we access the model key directly, because this pretrained model stores its weights under that key in the checkpoint dictionary.

Now we can wrap the model in a Model class, provide the generated configuration, and make it available through the Transformers library:

from transformers import AutoConfig, AutoModelForCausalLM
config = AutoConfig.from_pretrained(
'/content/CrystalLM/crystallm_v1_small/config.json')
transformer_model = AutoModelForCausalLM.from_pretrained(
'/content/CrystalLM/crystallm_v1_small', config=config)

Then we save the Model to disk (to generate the remaining files):

transformer_model.save_pretrained
("/content/CrystalLM/crystallm_v1_small_hf")

It can also be uploaded to the Hugging Face Hub if needed. First, in Colab, create a new secret with the name HF_TOKEN. Copy your access token key from your Hugging Face Hub profile settings, and paste it into the Value field of the HF_TOKEN. Then toggle the key icon on the left side of the Colab UI to let the notebook access the secret. Finally, load the token programmatically:

import os
from google.colab import userdata
os.environ["HF_TOKEN"] = userdata.get("HF_TOKEN")

You can then use it to log in to the Hugging Face Hub (this requires the huggingface_hub package to be installed):

from huggingface_hub import login
login(os.environ["HF_TOKEN"])

You can now push the model to the Hub:

transformer_model.push_to_hub("crystallm_v1_small_hf")

That concludes this part of the book showing real-life examples of local, domain-specific models. The chapters in the next part cover more advanced optimization techniques and finally look at deployment on different hardware platforms and integrating small, specialized language models into larger systems.

Summary

  • Chemistry language models use NLP techniques to represent molecular structures as text sequences for drug discovery.
  • ProtGPT2 generates protein sequences with a decoder-only GPT-2 model trained on 87,162 UniRef50 protein sequences.
  • Protein generation uses endoftext prompts to produce amino acid sequences that resemble natural proteins.
  • Perplexity scoring evaluates generated protein sequences, with lower scores indicating higher-quality output.
  • AntibodyGPT fine-tunes ProGen2 on 5,000 experimentally resolved crystal structures for generating therapeutic antibodies.
  • The ProGenForCausalLM class loads ProGen2-based models from custom repositories and runs inference.
  • CUDA memory-allocation settings can reduce inference latency by enabling expandable segments for better memory management.
  • 8-bit quantization shrinks the AntibodyGPT model from 617 MB to 156 MB and improves average latency by 40%.
  • The ANARCI tool validates generated antibody sequences that conform to known antibody structural patterns.
  • CrystalLLM generates crystal structures from text representations of crystallographic information files.
  • CIF file generation involves tokenizing crystallographic data and using autoregressive prediction to complete structures.
  • Monte Carlo tree search improves sampling quality for generating crystal structures.
  • Validating chemical structures requires domain-specific tools rather than standard text-generation metrics.
  • Domain-specific models achieve effective results with smaller parameter counts than generalist language models.
  • Specialized chemistry models require subject-matter experts to validate biological relevance and viability.