/ Модель

Характеристики

Контекст
512 токенов
Параметры
14,1 млн
Лицензия
CC BY-NC-SA 4.0
Архитектура
bert · dense
Базовая модель
chemselfies-base-bertmlm
Библиотека
sentence-transformers
Опубликована
23 июл 2024

chemembed-chemselfies

ЭмбеддингиТекст → embedding3 профессии

ChemFIE-BED преобразует молекулы в формате SELFIES в эмбеддинги для поиска и оценки химического сходства.

131скачиваний за 30 дней1лайквеса обновлены2 ноя 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Эмбеддинги» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

ChemFIE-BED (ChemSELFIES Embedding) — модель эмбеддингов на базе Sentence Transformers, разработанная автором репозитория и дообученная на gbyuvd/chemselfies-base-bertmlm. Она преобразует молекулы, записанные в формате SELFIES, в плотные векторы для поиска и сравнения химических соединений. Обучение проводилось на парах молекул из COCONUTDB и ChemBL34 с метками сходства, рассчитанными по MACCS-отпечаткам.

Модель использует архитектуру BERT с усреднением токенных представлений и косинусной мерой сходства. Размер эмбеддинга — 320 измерений; матричные эмбеддинги позволяют при необходимости сократить его до 160 или 80 измерений. Максимальная длина входа — 512 токенов. Модель предназначена для поиска химически похожих соединений, кластеризации и классификации молекул по их векторам.

Входной язык модели — SELFIES, а не естественный язык; обучение охватывало природные продукты и биоактивные соединения. Качество на тестовых данных автор считает достаточным для текущего применения, но в README не приведены численные метрики. Лицензия CC-BY-NC-SA 4.0 требует указания авторства и ограничивает коммерческое использование.

Сценарии применения

  • поиск структурно похожих молекул в коллекции соединений
  • поиск кандидатов среди природных продуктов и биоактивных соединений
  • кластеризация молекул по эмбеддингам
  • подготовка векторных признаков молекул для классификации
  • сравнение молекул по косинусному сходству

Ограничения

Модель принимает молекулы в формате SELFIES, ограниченные длиной 512 токенов, и не предназначена для обработки естественного языка. В README не приведены численные тестовые метрики; лицензия CC-BY-NC-SA 4.0 запрещает коммерческое использование.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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 ChemBL34 (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:

image

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

Demo for Fast Molecular Similarity Search on SuperNatural3 dataset

See this JupyterNotebook demo for an example of using the above model to perform fast searches for structurally similar compounds within a pre-embedded SELFIES-converted SuperNatural3 dataset (Gallo et al. 2023) (~1 million molecules) using Meta's FAISS.

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

DatasetReferenceTotal 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

MetricValue
pearson_cosine0.9605
spearman_cosine0.9520
pearson_manhattan0.8788
spearman_manhattan0.8587
pearson_euclidean0.8802
spearman_euclidean0.8612
pearson_dot0.8414
spearman_dot0.8421
pearson_max0.9605
spearman_max0.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

EpochStepTraining LosslossNPiso-base-test_spearman_cosine
0.277140990.0243--
0.554381980.0099--
0.8314122970.0083--
1.014790-0.00740.9548

Combined I

EpochStepTraining LosslossAll-base-test_spearman_cosine
0.273740990.0111--
0.547481980.0086--
0.8212122970.0077--
1.014975-0.00720.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

RankCosine Similarity (%)MW (Da)NameSMILES
192.23212.13SN0325329c1cc2c3c(c[nH]c3c1)CC1NCCCC21
291.39267.17SN0232374c1ccc2c3c([nH]c2c1)C1CCN2CCCC2N1CC3
391.36212.13SN0325329-01c1cc2c3c(c[nH]c3c1)C[C@H]1NCCC[C@H]21
491.35226.15SN0275712-02c1ccc2c3c([nH]c2c1)[C@H]1CCCCN1CC3
591.33226.15SN0275712c1ccc2c3c([nH]c2c1)C1CCCCN1CC3
691.27184.10SN0027447CC1=C2N=c3ccccc3=C2CCN1
790.93226.15SN0275712-01c1ccc2c3c([nH]c2c1)[C@@H]1CCCCN1CC3
890.66240.16SN0048348c1ccc2c(c1)N1CCC[N+]=C1C21CCCCC1
990.59267.17'SN0232374-01c1ccc2c3c([nH]c2c1)[C@H]1CCN2CCC[C@@H]2N1CC3
1090.57267.17'SN0232374-02c1ccc2c3c([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

RankCosine Similarity (%)MW (Da)NameSMILES
189.37219.10SN0171732CN1C(=O)c2cccnc2OC2CNCC21
289.07219.10SN0171732-01CN1C(=O)c2cccnc2O[C@H]2CNC[C@H]21
388.75218.14SN0181055-02CCN1C[C@@H]2CC@@Hc1cccc(=O)n1C2
488.74226.15SN0157407-02Cc1ccc2c(c1)c1c3n2CCN[C@H]3CCC1
588.65218.14SN0181055-01CCN1C[C@H]2CC@@Hc1cccc(=O)n1C2
688.62226.15SN0157407-01Cc1ccc2c(c1)c1c3n2CCN[C@@H]3CCC1
788.51218.14SN0181055-03CCN1C[C@@H]2C[C@H](C1)c1cccc(=O)n1C2
888.50294.17SN0126266-01C/C=C1/CN2CC[C@]34C=C(CO)[C@@H]1C[C@]23Nc1ccccc14
988.35294.17SN0126266-04C/C=C1\CN2CC[C@]34C=C(CO)[C@H]1C[C@]23Nc1ccccc14
1088.19242.14SN0095524-01OCc1ccc2c(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

image

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

image

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 (gbyuvd@proton.me)

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.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · sentence-transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
BertModel
Ревизия весов
f9bf7a6

0 моделей