Edit model card

ChemFIE-BED (ChemSELFIES Embedding)

ChemFIE-BED is a sentence-transformers based on gbyuvd/chemselfies-base-bertmlm fine-tuned on around (for now) 2 million pairs of valid molecules' SELFIES (Krenn et al. 2020) taken from COCONUTDB (Sorokina et al. 2021) and (Zdrazil et al. 2023). It maps compounds' Self-Referencing Embedded Strings (SELFIES) into a 320-dimensional dense vector space, potentially can be used for chemical similarity, similarity search, classification, clustering, and more.

Although there is more data for the model to train on, the test metrics on unseen data of combined natural products and bioactives are already sufficient for now.

This model is the full implementation of Tom Aarsen's suggestions on previous prototype model, now using my own pre-trained BERT and Matryoshka embeddings. For the latter, the model uses 320, 160, and 80 dimension that you can truncate depending on your needs.

For more informations:

ko-fi

Model Details

Model Description

  • Model Type: Sentence Transformer
  • Base model: gbyuvd/chemselfies-base-bertmlm
  • Maximum Sequence Length: 512 tokens
  • Output Dimensionality: 320 tokens
  • Similarity Function: Cosine Similarity
  • Pooling: Mean pooling
  • Training Dataset: SELFIES pairs generated from COCONUTDB and ChemBL34
  • Language: SELFIES
  • License: CC-BY-NC-SA 4.0

Full Model Architecture

SentenceTransformer(
  (0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: BertModel 
  (1): Pooling({'word_embedding_dimension': 320, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': False})
)

Usage

Direct Usage (Sentence Transformers)

First install the Sentence Transformers library:

pip install -U sentence-transformers

Then you can load this model and run inference.

from sentence_transformers import SentenceTransformer

# Specify preffered dimensions
# 320, 160, or 80
dimensions = 320

# Download the model from the 🤗 Hub
model = SentenceTransformer("gbyuvd/chembed-chemselfies-bed", truncate_dim=dimensions)

# Run inference
sentences = [
    '[C]  [C]  [=C]  [C]  [=C]  [Branch2]  [Ring2]  [S]  [C]  [C]  [N]  [C]  [=Branch1]  [C]  [=O]  [C]  [=C]  [N]  [Branch1]  [C]  [C]  [C]  [=C]  [C]  [=C]  [Branch2]  [Ring1]  [Ring1]  [S]  [=Branch1]  [C]  [=O]  [=Branch1]  [C]  [=O]  [N]  [C]  [C]  [C]  [Branch1]  [C]  [C]  [C]  [C]  [Ring1]  [#Branch1]  [C]  [=C]  [Ring1]  [S]  [C]  [Ring2]  [Ring1]  [Branch1]  [=O]  [C]  [=C]  [Ring2]  [Ring1]  [P]',
    '[O]  [=C]  [Branch1]  [C]  [O]  [C]  [C]  [C]  [C]  [=C]  [C]  [=C]  [C]  [=C]  [C]  [=C]  [C]  [=C]',
    '[C]  [N]  [C]  [=N]  [C]  [Branch2]  [Branch1]  [C]  [S]  [=Branch1]  [C]  [=O]  [=Branch1]  [C]  [=O]  [N]  [Branch1]  [#Branch2]  [C]  [C]  [C]  [C]  [N]  [C]  [C]  [Ring1]  [=Branch1]  [C]  [C]  [C]  [=C]  [C]  [Branch1]  [Ring1]  [C]  [#N]  [=C]  [C]  [=C]  [Ring1]  [Branch2]  [N]  [Branch1]  [#Branch2]  [C]  [C]  [=C]  [N]  [=C]  [N]  [Ring1]  [Branch1]  [C]  [C]  [Ring2]  [Ring1]  [Ring1]  [=C]  [Ring2]  [Ring2]  [Ring1]',
]

"""
0: CHEMBL1885710
1: CID78383937
2: CHEMBL234161
"""

embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 320]

# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities.shape)
# [3, 3]

Dataset

Dataset Reference Total Number of Pairs
COCONUTDB (Sorokina et al. 2021) 1,183,186
ChemBL34 (Part I) (Zdrazil et al. 2023) 1,064,858

Data Preparation and Labeling

The dataset was prepared using various methods to create informative molecule pairs and labels for training a SELFIES-based sentence transformer. The process involved the following steps:

  1. Data Collection: Raw data was gathered from COCONUTDB and ChemBL34.

  2. Data Preprocessing:

    • Internal duplicates were removed.
    • Molecules were converted to SELFIES representation.
    • Molecules were filtered to ensure token length ≤ 510 (512 - 2 special tokens)
    • SELFIES were converted back to SMILES.
  3. Data Merging:

    • The processed datasets were merged into a combined dataset.
    • Duplicates were removed again.
  4. Tokenization and Encoding:

    • A custom tokenizer was trained on the SELFIES representations.
    • SELFIES were encoded into numerical vectors.
  5. Complexity Score Calculation:

    • A ratio was calculated for each molecule: sum of encoded IDs / length of SELFIES.
    • This ratio serves as a simple complexity score (similar to what was done in the base model)
  6. Binning:

    • The complexity scores were log-transformed to reduce skewness.
    • Sturges' formula was used to determine the optimal number of bins.
    • Molecules were assigned to bins based on their log-transformed complexity scores.
  7. Pair Generation:

    • A target size for each bin was calculated based on the average bin size.
    • For in-strata pairs:
      • Molecules from the same bin were paired.
      • Bins larger than the target size were undersampled.
      • Bins smaller than the target size were oversampled.
    • For inter-strata pairs:
      • Pairs were created between bins with an absolute difference > 3.
    • The pairing process aimed to balance the distribution across complexity levels.
    • Empty subsets were handled to ensure robust processing.
  8. Similarity Labeling:

    • MACCS fingerprints were generated for each molecule using RDKit.
    • Cosine similarity between the MACCS fingerprints was calculated using CuPy for GPU acceleration.
    • Error handling was implemented for cases where molecules couldn't be processed.
    • The labels were resampled to ensure a balanced range of examples ([0,1])
    • The similarity scores were rounded to two decimal places for training.
  9. Splitting:

    • The dataset was split into 80% for training, 10% for validation, and 10% for testing.
    • For the Natural Products set (NP), the test set is labeled "NP-iso-base" because the SMILES strings were not canonicalized (isomeric forms were retained).
    • The test set from ChemBL34 was then combined with the NP test set, and this combined set is referred to as "combined."

This methodology aims to provide a diverse set of molecule pairs with labels indicating structural similarity. The combination of complexity binning, balanced inter- and intra-strata sampling, and MACCS fingerprint similarity labeling is intended to capture a range of molecular complexities while providing chemically relevant labels for model training.

Evaluation

Metrics

Semantic Similarity

Metric Value
pearson_cosine 0.9605
spearman_cosine 0.9520
pearson_manhattan 0.8788
spearman_manhattan 0.8587
pearson_euclidean 0.8802
spearman_euclidean 0.8612
pearson_dot 0.8414
spearman_dot 0.8421
pearson_max 0.9605
spearman_max 0.9520

Recommendations

To fully utilize the model capabitilities on a large dataset for similarity search, I'd recommend using Meta's FAISS for rapid results or any of your preferred document retrieval framework.

Training Details

Training Hyperparameters

  • optimizer : AdamW
  • eval_strategy: epoch
  • per_device_train_batch_size: 64
  • per_device_eval_batch_size: 32
  • weight_decay: 0.01
  • num_train_epochs: 1
  • warmup_ratio: 0.1
  • dataloader_num_workers: 8
  • Loss: MatryoshkaLoss with these parameters:
    {
        "loss": "CosineSimilarityLoss",
        "matryoshka_dims": [
            320,
            160,
            80
        ],
        "matryoshka_weights": [
            1,
            1,
            1
        ],
        "n_dims_per_step": -1
    }
    

Training Logs

Natural Products

Epoch Step Training Loss loss NPiso-base-test_spearman_cosine
0.2771 4099 0.0243 - -
0.5543 8198 0.0099 - -
0.8314 12297 0.0083 - -
1.0 14790 - 0.0074 0.9548

Combined I

Epoch Step Training Loss loss All-base-test_spearman_cosine
0.2737 4099 0.0111 - -
0.5474 8198 0.0086 - -
0.8212 12297 0.0077 - -
1.0 14975 - 0.0072 0.9516

Testing The Generated Embedding to Find Similar Molecules

Using Cosine Similarity

Single Input

Using Varenicline (CID5310966), a nAChR α4β2 partial agonist, as the query molecule, I conducted a similarity search to find structurally related compounds. The search utilized Varenicline's canonical SMILES representation (though isomeric SMILES could also be used) as the input.

I employed FAISS (Facebook AI Similarity Search) to identify the top 10 most similar molecules from a set of 1 million compounds in the Supernatural3 database (Gallo et al. 2023). The search was based on cosine similarities of pre-embedded SELFIES representations of these molecules.

The embeddings for the Supernatural3 database subset were generated using my laptop's NVIDIA GeForce 930M GPU, with a batch size of 64, so do for search.

Varenicline:

image/png

top 10 (returned in 7.7s with visualization):

image/png

Rank Cosine Similarity (%) MW (Da) Name SMILES
1 92.23 212.13 SN0325329 c1cc2c3c(c[nH]c3c1)CC1NCCCC21
2 91.39 267.17 SN0232374 c1ccc2c3c([nH]c2c1)C1CCN2CCCC2N1CC3
3 91.36 212.13 SN0325329-01 c1cc2c3c(c[nH]c3c1)C[C@H]1NCCC[C@H]21
4 91.35 226.15 SN0275712-02 c1ccc2c3c([nH]c2c1)[C@H]1CCCCN1CC3
5 91.33 226.15 SN0275712 c1ccc2c3c([nH]c2c1)C1CCCCN1CC3
6 91.27 184.10 SN0027447 CC1=C2N=c3ccccc3=C2CCN1
7 90.93 226.15 SN0275712-01 c1ccc2c3c([nH]c2c1)[C@@H]1CCCCN1CC3
8 90.66 240.16 SN0048348 c1ccc2c(c1)N1CCC[N+]=C1C21CCCCC1
9 90.59 267.17 'SN0232374-01 c1ccc2c3c([nH]c2c1)[C@H]1CCN2CCC[C@@H]2N1CC3
10 90.57 267.17 'SN0232374-02 c1ccc2c3c([nH]c2c1)[C@@H]1CCN2CCC[C@@H]2N1CC3

Multiple Inputs by Averaging Embeddings

You can take multiple inputs then average their embeddings to find those most similar. For example, using 3 known nAChR α4β2 partial agonists: varenicline, SW4 (Zhang et al. 2012), and cytisine (using their isomeric SMILES)

image/png

then query similars based on the average embeddings (returned in 3.5s):

image/png

Rank Cosine Similarity (%) MW (Da) Name SMILES
1 89.37 219.10 SN0171732 CN1C(=O)c2cccnc2OC2CNCC21
2 89.07 219.10 SN0171732-01 CN1C(=O)c2cccnc2O[C@H]2CNC[C@H]21
3 88.75 218.14 SN0181055-02 CCN1C[C@@H]2CC@@Hc1cccc(=O)n1C2
4 88.74 226.15 SN0157407-02 Cc1ccc2c(c1)c1c3n2CCN[C@H]3CCC1
5 88.65 218.14 SN0181055-01 CCN1C[C@H]2CC@@Hc1cccc(=O)n1C2
6 88.62 226.15 SN0157407-01 Cc1ccc2c(c1)c1c3n2CCN[C@@H]3CCC1
7 88.51 218.14 SN0181055-03 CCN1C[C@@H]2CC@Hc1cccc(=O)n1C2
8 88.50 294.17 SN0126266-01 C/C=C1/CN2CC[C@]34C=C(CO)[C@@H]1C[C@]23Nc1ccccc14
9 88.35 294.17 SN0126266-04 C/C=C1\CN2CC[C@]34C=C(CO)[C@H]1C[C@]23Nc1ccccc14
10 88.19 242.14 SN0095524-01 OCc1ccc2c(c1)c1c3n2CCN[C@@H]3CCC1

Using L2 Distance

(WIP)

Validation by Docking-based Virtual Screening

Validation by Docking-based Virtual Screening (DBVS) is finished, showing promising hit rates — ranging from 26% to 58% within the top 100 similar compounds from SuperNatural3 using the averaged embeddings of nAChR α4β2 partial agonists, depending on the threshold applied. However, some of the methods used are adapted from my undergraduate thesis, which is still in progress and pending publication. Detailed results and methodologies will be fully disclosed after the thesis is published.

Testing Generated Embeddings' Clusters

The plot below shows how the model's embeddings (at this stage) cluster different classes of compounds, compared to using MACCS fingerprints.

Using perplexity of 20 over 5500 iterations. 2D:

image/png

image/png

3D:

image/png

image/png

For a more simple separation between two classes, for example active natural nAChR-α4β2 agonists vs anticoagulants (perplexity = 5):

image/png

And for more data points and classes (perplexity = 7):

image/png

Framework Versions

  • Python: 3.9.13
  • Sentence Transformers: 3.0.1
  • Transformers: 4.42.4
  • PyTorch: 2.3.1+cu121
  • Accelerate: 0.33.0
  • Datasets: 2.20.0
  • Tokenizers: 0.19.1
  • RDKit: 2024.3.3

Citation

BibTeX

ChemFIE-Base

@software{chemfie_basebertmlm,
  author = {GP Bayu},
  title = {{ChemFIE Base}: Pretraining A Lightweight BERT-like model on Molecular SELFIES},
  url = {https://huggingface.co./gbyuvd/chemselfies-base-bertmlm},
  version = {1.0},
  year = {2024},
}

Sentence Transformers

@inproceedings{reimers-2019-sentence-bert,
    title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
    author = "Reimers, Nils and Gurevych, Iryna",
    booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
    month = "11",
    year = "2019",
    publisher = "Association for Computational Linguistics",
    url = "https://arxiv.org/abs/1908.10084",
}

MatryoshkaLoss

@misc{kusupati2024matryoshka,
    title={Matryoshka Representation Learning}, 
    author={Aditya Kusupati and Gantavya Bhatt and Aniket Rege and Matthew Wallingford and Aditya Sinha and Vivek Ramanujan and William Howard-Snyder and Kaifeng Chen and Sham Kakade and Prateek Jain and Ali Farhadi},
    year={2024},
    eprint={2205.13147},
    archivePrefix={arXiv},
    primaryClass={cs.LG}
}

COCONUTDB

@article{sorokina2021coconut,
  title={COCONUT online: Collection of Open Natural Products database},
  author={Sorokina, Maria and Merseburger, Peter and Rajan, Kohulan and Yirik, Mehmet Aziz and Steinbeck, Christoph},
  journal={Journal of Cheminformatics},
  volume={13},
  number={1},
  pages={2},
  year={2021},
  doi={10.1186/s13321-020-00478-9}
}

ChemBL34

@article{zdrazil2023chembl,
  title={The ChEMBL Database in 2023: a drug discovery platform spanning multiple bioactivity data types and time periods},
  author={Zdrazil, Barbara and Felix, Eloy and Hunter, Fiona and Manners, Emma J and Blackshaw, James and Corbett, Sybilla and de Veij, Marleen and Ioannidis, Harris and Lopez, David Mendez and Mosquera, Juan F and Magarinos, Maria Paula and Bosc, Nicolas and Arcila, Ricardo and Kizil{\"o}ren, Tevfik and Gaulton, Anna and Bento, A Patr{\'i}cia and Adasme, Melissa F and Monecke, Peter and Landrum, Gregory A and Leach, Andrew R},
  journal={Nucleic Acids Research},
  year={2023},
  volume={gkad1004},
  doi={10.1093/nar/gkad1004}
}

@misc{chembl34,
  title={ChemBL34},
  year={2023},
  doi={10.6019/CHEMBL.database.34}
}

SuperNatural3

@article{Gallo2023,
  author = {Gallo, K and Kemmler, E and Goede, A and Becker, F and Dunkel, M and Preissner, R and Banerjee, P},
  title = {{SuperNatural 3.0-a database of natural products and natural product-based derivatives}},
  journal = {Nucleic Acids Research},
  year = {2023},
  month = jan,
  day = {6},
  volume = {51},
  number = {D1},
  pages = {D654-D659},
  doi = {10.1093/nar/gkac1008}
}

Partial Agonism of SW4

@article{Zhang2012,
  author = {Zhang, H. and Eaton, J. B. and Yu, L. and Nys, M. and Mazzolari, A. and Van Elk, R. and Smit, A. B. and Alexandrov, V. and Hanania, T. and Sabath, E. and Fedolak, A. and Brunner, D. and Lukas, R. J. and Vistoli, G. and Ulens, C. and Kozikowski, A. P.},
  title = {Insights Into the Structural Determinants Required for High-Affinity Binding of Chiral Cyclopropane-Containing Ligands to Alpha4Beta2-Nicotinic Acetylcholine Receptors: An Integrated Approach to Behaviorally Active Nicotinic Ligands},
  journal = {Journal of Medicinal Chemistry},
  year = {2012},
  volume = {55},
  pages = {8028},
  doi = {10.1021/jm3008739}
}

Contact & Support My Work

G Bayu ([email protected])

This project has been quiet a journey for me, I’ve dedicated hours on this and I would like to improve myself, this model, and future projects. However, financial and computational constraints can be challenging.

If you find my work valuable and would like to support my journey, please consider supporting me here. Your support will help me cover costs for computational resources, data acquisition, and further development of this project. Any amount, big or small, is greatly appreciated and will enable me to continue learning and explore more.

Thank you for checking out this model, I am more than happy to receive any feedback, so that I can improve myself and the future model/projects I will be working on.

Downloads last month
35
Safetensors
Model size
11.1M params
Tensor type
F32
·
Inference Examples
This model does not have enough activity to be deployed to Inference API (serverless) yet. Increase its social visibility and check back later, or deploy to Inference Endpoints (dedicated) instead.

Model tree for gbyuvd/chemembed-chemselfies

Finetuned
(3)
this model

Collection including gbyuvd/chemembed-chemselfies

Evaluation results