Views
No views yet
1pip install torch
2pip install safetensors
3pip install huggingface_hub
4pip install esm==3.1.41import os
2import torch
3from huggingface_hub import hf_hub_download
4from esm.tokenization import get_esmc_model_tokenizers
5from esm.models.esmc import ESMC
6from safetensors import safe_open
7
8# Configuration
9REPO_ID = "NOC-Lab/AbCDR-ESMC"
10device = "cuda" if torch.cuda.is_available() else "cpu"
11
12# Load tokenizer and base model
13tokenizer = get_esmc_model_tokenizers()
14model = ESMC.from_pretrained("esmc_600m").to(device)
15
16# Download fine-tuned weights
17local_ckpt_path = hf_hub_download(
18 repo_id=REPO_ID,
19 filename="model.safetensors",
20 token=os.getenv("HF_TOKEN", None) # For private repos
21)
22
23# Load and rename state dict
24original_state_dict = {}
25with safe_open(local_ckpt_path, framework="pt") as sf:
26 for key in sf.keys():
27 original_state_dict[key] = sf.get_tensor(key)
28
29# Remove "esmC_model." prefix
30renamed_state_dict = {}
31for key, value in original_state_dict.items():
32 new_key = key.replace("esmC_model.", "") if key.startswith("esmC_model.") else key
33 renamed_state_dict[new_key] = value
34
35# Load weights
36model.load_state_dict(renamed_state_dict, strict=False)
37model.eval()1from esm.sdk.api import ESMProtein, LogitsConfig
2
3SEP_TOKEN = "-"
4
5# Example sequences
6heavy_chain = (
7 "EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYAMSWVRQAPGKGLEWVAVISYDGSNKYYADSVKGRF"
8 "TISADTSKNTAYLQMNSLRAEDTAVYYCAREGYYGSSYWYFDYWGQGTLVTVSS"
9)
10light_chain = (
11 "DIQMTQSPSSLSASVGDRVTITCRASQSISSYLNWYQQKPGKAPKLLIYAASSLQSGVPSRFSGSGS"
12 "GTDFTLTISSLQPEDFATYYCQQSYSTPLTFGGGTKVEIK"
13)
14
15# Combine with separator
16paired_sequence = f"{heavy_chain}{SEP_TOKEN}{light_chain}"
17
18# Create protein object and encode
19protein = ESMProtein(sequence=paired_sequence)
20protein_tensor = model.encode(protein)
21
22# Get embeddings
23logits_output = model.logits(
24 protein_tensor,
25 LogitsConfig(sequence=True, return_embeddings=True)
26)
27
28embeddings = logits_output.embeddings # Shape: (1, seq_len, 1152)
29logits = logits_output.logits.sequence # Shape: (1, seq_len, 64)
30
31print(f"Embeddings shape: {embeddings.shape}") # (1, L, 1152)
32print(f"Embeddings dtype: {embeddings.dtype}") # float321# Tokenize sequence
2seq_encoded = tokenizer(paired_sequence, return_tensors="pt")
3seq_input_ids = seq_encoded["input_ids"].to(device)
4
5# Forward pass
6with torch.no_grad():
7 outputs = model(sequence_tokens=seq_input_ids)
8
9embeddings_direct = outputs.embeddings # Shape: (1, seq_len, 1152)
10logits_direct = outputs.sequence_logits # Shape: (1, seq_len, 64)
11
12print(f"Embeddings shape: {embeddings_direct.shape}") # (1, L, 1152)
13print(f"Embeddings dtype: {embeddings_direct.dtype}") # bfloat161# Mean pooling over sequence length
2sequence_representation = embeddings_direct.mean(dim=1) # (1, 1152)
3print(f"Pooled embedding shape: {sequence_representation.shape}")
4
5# Get interface embedding (at separator position)
6separator_pos = len(heavy_chain)
7interface_embedding = embeddings_direct[0, separator_pos, :] # (1152,)1# Multiple sequences
2sequences = [
3 f"{heavy_chain}{SEP_TOKEN}{light_chain}",
4 f"{heavy_chain[:100]}{SEP_TOKEN}{light_chain[:100]}",
5]
6
7# Tokenize with padding
8batch_encoded = tokenizer(sequences, return_tensors="pt", padding=True)
9batch_input_ids = batch_encoded["input_ids"].to(device)
10
11# Forward pass
12with torch.no_grad():
13 batch_outputs = model(sequence_tokens=batch_input_ids)
14
15batch_embeddings = batch_outputs.embeddings # (batch_size, max_seq_len, 1152)
16print(f"Batch embeddings shape: {batch_embeddings.shape}")HEAVY_CHAIN-LIGHT_CHAIN-)sequence = "EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYAMS...-DIQMTQSPSSLSASVGDRVTITCRASQSISS..."1@article{Talaei2026,
2 author = {Talaei, Mahtab and Walker, Kenji C. and Hao, Boran and Jolley, Eliot and Jin, Yeping and Kozakov, Dima and Misasi, John and Vajda, Sandor and Paschalidis, Ioannis Ch. and Joseph-McCarthy, Diane},
3 title = {Preferential {CDR} masking in paired antibody language models improves binding affinity prediction},
4 journal = {Communications AI \& Computing},
5 volume = {1},
6 pages = {7},
7 year = {2026},
8 doi = {10.1038/s44488-026-00010-2}
9}
10
11@article{hayes2025simulating,
12 title={Simulating 500 million years of evolution with a language model},
13 author={Hayes, Thomas and Rao, Roshan and Akin, Halil and Sofroniew, Nicholas J. and Oktay, Deniz and Lin, Zeming and Verkuil, Robert and Tran, Vincent Q. and Deaton, Jonathan and Wiggert, Marius and Badkundri, Rohil and Shafkat, Irhum and Gong, Jun and Derry, Alexander and Molina, Raul S. and Thomas, Neil and Khan, Yousuf A. and Mishra, Chetan and Kim, Carolyn and Bartie, Liam J. and Nemeth, Matthew and Hsu, Patrick D. and Sercu, Tom and Candido, Salvatore and Rives, Alexander},
14 journal={Science},
15 volume={387},
16 number={6736},
17 pages={850--858},
18 year={2025},
19 doi={10.1126/science.ads0018}
20}
21
22@misc{esm2024cambrian,
23 author={{ESM Team}},
24 title={ESM Cambrian: Revealing the mysteries of proteins with unsupervised learning},
25 year={2024},
26 publisher={EvolutionaryScale},
27 url={https://evolutionaryscale.ai/blog/esm-cambrian}
28}1# Option 1: CLI login
2huggingface-cli login
3
4# Option 2: Environment variable
5export HF_TOKEN="your_token_here"