{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# look data_example" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pickle, h5py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "with open('./LINCS2020/idx2smi.pickle', 'rb') as f:\n", " idx2smi = pickle.load(f)\\\n", " \n", "smiles_list = list(idx2smi.values()) # 假设idx2smi是一个字典,其值为SMILES字符串\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8316 BrC1C(Br)C(Br)C(Br)C(Br)C1Br\n" ] } ], "source": [ "print(len(idx2smi), idx2smi[0])" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'BrC1C(Br)C(Br)C(Br)C(Br)C1Br'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "idx2smi[0] # to path_to_input_smiles.csv" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SMILES已成功保存到LINCS2020_smiles.csv文件中。\n" ] } ], "source": [ "import pickle\n", "import csv\n", "\n", "# 将SMILES字符串写入CSV文件\n", "with open('./LINCS2020/LINCS2020_smiles.csv', 'w', newline='') as csvfile:\n", " writer = csv.writer(csvfile)\n", " # 写入标题行(可选)\n", " writer.writerow(['SMILES'])\n", " # 遍历字典,写入SMILES\n", " for idx, smi in idx2smi.items():\n", " writer.writerow([smi])\n", "\n", "print(\"SMILES已成功保存到LINCS2020_smiles.csv文件中。\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate ECFP4 embedding for all smiles\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rdkit import Chem\n", "from rdkit.Chem import AllChem\n", "import numpy as np\n", "import pickle\n", "\n", "def smiles_to_ecfp4(smiles_list, radius=2, n_bits=2048):\n", " \"\"\"\n", " 将SMILES列表转换为ECFP4特征向量。\n", "\n", " 参数:\n", " smiles_list (list): SMILES字符串列表。\n", " radius (int): ECFP的半径,默认为2(即ECFP4)。\n", " n_bits (int): 特征向量的长度,默认为2048。\n", "\n", " 返回:\n", " dict: 一个字典,键为SMILES字符串,值为对应的ECFP4特征向量。\n", " \"\"\"\n", " ecfp4_dict = {}\n", " \n", " for smiles in smiles_list:\n", " mol = Chem.MolFromSmiles(smiles)\n", " if mol is not None:\n", " # 替换编码器\n", " ecfp4 = AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=n_bits)\n", " ecfp4_dict[smiles] = np.array(ecfp4, dtype=np.float32)\n", " else:\n", " print(\"Error in \", smiles)\n", " # 如果SMILES无法解析为分子,则填充一个全零的向量\n", " ecfp4_dict[smiles] = np.zeros(n_bits, dtype=np.float32)\n", " \n", " return ecfp4_dict\n", "\n", "# 从字典中提取SMILES列表\n", "smiles_list = list(idx2smi.values()) # 假设idx2smi是一个字典,其值为SMILES字符串\n", "\n", "# 计算ECFP4特征\n", "ecfp4_features_dict = smiles_to_ecfp4(smiles_list)\n", "\n", "# ecfp4_features_dict\n" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8316 8316\n" ] } ], "source": [ "print(len(smiles_list), len(ecfp4_features_dict))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ecfp4_features_dict\n", "\n", "# np.str_('BrC1C(Br)C(Br)C(Br)C(Br)C1Br'): array([0., 0., 0., ..., 0., 0., 0.], dtype=float32)," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 保存为 pickle 文件\n", "with open('./LINCS2020/ECFP4_emb2048.pickle', 'wb') as f:\n", " pickle.dump(ecfp4_features_dict, f)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2048,)" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ecfp4_features_dict['CN1CCN(CCCN2c3ccccc3Sc3ccc(cc23)C(F)(F)F)CC1'].shape" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# import pickle, h5py\n", "# import numpy as np\n", "# import pandas as pd\n", "\n", "# with open('./embeddings/ChemBERTa2_emb384.pickle', 'rb') as f:\n", "# KPGT_emb2304 = pickle.load(f)\n", "# KPGT_emb2304" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(300,)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# KPGT_emb2304['BrC1C(Br)C(Br)C(Br)C(Br)C1Br'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate KGPT embedding for all smiles" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pickle, h5py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "with open('./embeddings/KPGT_emb2304.pickle', 'rb') as f:\n", " KPGT_emb2304 = pickle.load(f)\n", "KPGT_emb2304" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "预训练权重总参数量: 111,755,936\n", "111.8 M\n" ] } ], "source": [ "import torch\n", "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/KPGT/base.pth', map_location='cpu')\n", "total = sum(v.numel() for v in state_dict.values())\n", "print(f'预训练权重总参数量: {total:,}')\n", "print(f'{total/1e6:.1f} M')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate InfoAlign embedding for all smiles" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# pip install infoalign\n", "\n", "# infoalign_predict --input LINCS2020/LINCS2020_smiles.csv \\\n", "# --output InfoAlign_output.npy \\\n", "# --output-to-input-column # Adds the representation as an additional column in the input CSV\n", "\n", "# 是否存在数据泄露,因为这个是基于表征学习的" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "预训练权重总参数量: 13,808,553\n", "13.8 M\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_1948954/1463163983.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/infoalign_model/pretrain.pt', map_location='cpu')\n" ] } ], "source": [ "import torch\n", "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/infoalign_model/pretrain.pt', map_location='cpu')\n", "total = sum(v.numel() for v in state_dict.values())\n", "print(f'预训练权重总参数量: {total:,}')\n", "print(f'{total/1e6:.1f} M') # → 21.2 M" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "import csv\n", "import numpy as np\n", "import pickle\n", "\n", "# CSV文件路径\n", "csv_path = 'infoalign_model/LINCS2020_smiles.csv'\n", "# NPY文件路径\n", "npy_path = 'infoalign_model/InfoAlign_output.npy'\n", "\n", "# 初始化一个空字典来存储SMILES和对应的表征\n", "smiles_to_representation = {}\n", "\n", "# 读取NPY文件\n", "info_align_output = np.load(npy_path)\n", "\n", "# 读取CSV文件并同时替换字典中的值\n", "with open(csv_path, mode='r', newline='', encoding='utf-8') as csvfile:\n", " reader = csv.DictReader(csvfile)\n", " for idx, row in enumerate(reader):\n", " smiles = row['SMILES']\n", " # 直接从info_align_output中获取对应的数值\n", " representation = info_align_output[idx]\n", " smiles_to_representation[smiles] = representation\n" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8316" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(smiles_to_representation)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "字典已成功保存到 embeddings/InfoAlign_emb300.pickle\n" ] } ], "source": [ "# 保存字典为pickle文件\n", "pickle_path = 'embeddings/InfoAlign_emb300.pickle'\n", "with open(pickle_path, 'wb') as pickle_file:\n", " pickle.dump(smiles_to_representation, pickle_file)\n", "\n", "print(f\"字典已成功保存到 {pickle_path}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate ChemBERTa-2 embedding for all smiles" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] } ], "source": [ "from transformers import AutoModel, AutoTokenizer\n", "model = AutoModel.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\") # 77M SMILES(完整PubChem数据集)\n", "tokenizer = AutoTokenizer.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\")\n", "inputs = tokenizer(\"CCO\", return_tensors=\"pt\")\n", "outputs = model(**inputs) # 嵌入位于 outputs.last_hidden_state" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "torch.Size([1, 5, 384])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "outputs.last_hidden_state.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "ChemBERTa-77M 可训练参数量: 3,427,440\n", "3.4 M\n" ] } ], "source": [ "# from transformers import AutoModel\n", "\n", "# model = AutoModel.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\")\n", "\n", "# trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", "# print(f\"ChemBERTa-77M 可训练参数量: {trainable:,}\")\n", "# print(f\"{trainable/1e6:.1f} M\") # → 85.7 M" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] } ], "source": [ "# from transformers import AutoModel, AutoTokenizer\n", "# import torch, os, shutil\n", "\n", "# repo_id = \"DeepChem/ChemBERTa-77M-MLM\"\n", "\n", "# # 1. 磁盘大小:下载后统计整个 snapshot 目录\n", "# tmp_dir = \"./tmp_snapshot\" # 临时目录,用完即删\n", "# model = AutoModel.from_pretrained(repo_id, cache_dir=tmp_dir)\n", "# tokenizer = AutoTokenizer.from_pretrained(repo_id, cache_dir=tmp_dir)\n", "\n", "# disk_mb = sum(\n", "# os.path.getsize(os.path.join(root, f))\n", "# for root, _, files in os.walk(tmp_dir)\n", "# for f in files\n", "# ) / 1024 ** 2\n", "\n", "# print(f\"权重文件磁盘占用:{disk_mb:.1f} MB\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n", "100%|██████████| 260/260 [00:01<00:00, 168.25it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "总分子数 : 8316\n", "总耗时 : 2.82 s\n", "平均推理 : 0.34 ms / molecule\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "import pickle\n", "import time\n", "from transformers import AutoModel, AutoTokenizer\n", "import torch\n", "import numpy as np\n", "from rdkit import Chem\n", "from tqdm import tqdm # 可选:用于进度条\n", "\n", "def smiles_to_chemberta2(smiles_list, model_name=\"DeepChem/ChemBERTa-77M-MLM\", batch_size=32):\n", " \"\"\"\n", " 将SMILES列表转换为ChemBERTa-2的嵌入向量(CLS token的隐藏状态)。\n", " \n", " 参数:\n", " smiles_list (list): SMILES字符串列表\n", " model_name (str): Hugging Face模型ID,默认为ChemBERTa-2的MLM版本\n", " batch_size (int): 批处理大小,根据GPU内存调整\n", " \n", " 返回:\n", " dict: 键为SMILES,值为768维嵌入向量(numpy数组)\n", " \"\"\"\n", " # 加载模型和tokenizer\n", " tokenizer = AutoTokenizer.from_pretrained(model_name)\n", " model = AutoModel.from_pretrained(model_name)\n", " model.eval() # 切换到推理模式\n", " \n", " # 检查CUDA可用性\n", " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", " model.to(device)\n", " \n", " chemberta2_dict = {}\n", " \n", " # 分批处理SMILES\n", " for i in tqdm(range(0, len(smiles_list), batch_size)):\n", " batch_smiles = smiles_list[i:i+batch_size]\n", " valid_indices = []\n", " batch_inputs = []\n", " \n", " # 过滤无效SMILES并生成输入\n", " for idx, smiles in enumerate(batch_smiles):\n", " mol = Chem.MolFromSmiles(smiles)\n", " if mol is not None:\n", " valid_indices.append(idx)\n", " batch_inputs.append(smiles)\n", " else:\n", " print(f\"Invalid SMILES: {smiles}\")\n", " \n", " if not batch_inputs:\n", " continue\n", " \n", " # Tokenize并移动到设备\n", " inputs = tokenizer(\n", " batch_inputs, \n", " return_tensors=\"pt\", \n", " padding=True, \n", " truncation=True, \n", " max_length=512\n", " ).to(device)\n", " \n", " # 生成嵌入\n", " with torch.no_grad():\n", " outputs = model(**inputs)\n", " embeddings = outputs.last_hidden_state[:, 0, :] # 取CLS token的嵌入\n", " \n", " # 将有效结果存入字典\n", " for j, idx in enumerate(valid_indices):\n", " chemberta2_dict[batch_smiles[idx]] = embeddings[j].cpu().numpy()\n", " \n", " # 处理无效SMILES(填充零向量)\n", " for idx, smiles in enumerate(batch_smiles):\n", " if idx not in valid_indices:\n", " chemberta2_dict[smiles] = np.zeros(768, dtype=np.float32)\n", " \n", " return chemberta2_dict\n", "\n", "# 使用示例\n", "import time\n", "# ----- 计时开始 -----\n", "t0 = time.perf_counter()\n", "smiles_list = list(idx2smi.values()) # 假设idx2smi是SMILES字典\n", "chemberta2_features_dict = smiles_to_chemberta2(smiles_list)\n", "\n", "t1 = time.perf_counter()\n", "# ----- 计时结束 -----\n", "\n", "# 基本统计\n", "total_mols = len(chemberta2_features_dict)\n", "avg_time_ms = (t1 - t0) / total_mols * 1000\n", "\n", "print(f\"总分子数 : {total_mols}\")\n", "print(f\"总耗时 : {t1 - t0:.2f} s\")\n", "print(f\"平均推理 : {avg_time_ms:.2f} ms / molecule\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8316 384\n" ] } ], "source": [ "print(len(chemberta2_features_dict), len(chemberta2_features_dict['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chemberta2_features_dict['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "字典已成功保存到 embeddings/ChemBERTa2_emb384.pickle\n" ] } ], "source": [ "# 保存字典为pickle文件\n", "pickle_path = 'embeddings/ChemBERTa2_emb384.pickle'\n", "with open(pickle_path, 'wb') as pickle_file:\n", " pickle.dump(chemberta2_features_dict, pickle_file)\n", "\n", "print(f\"字典已成功保存到 {pickle_path}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate MolT5 embedding for all smiles" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "torch.Size([1, 768])\n" ] } ], "source": [ "from transformers import T5ForConditionalGeneration, AutoTokenizer\n", "model = T5ForConditionalGeneration.from_pretrained(\"laituan245/molt5-base\")\n", "tokenizer = AutoTokenizer.from_pretrained(\"laituan245/molt5-base\")\n", "inputs = tokenizer(\"CCO\", return_tensors=\"pt\")\n", "embeddings = model.encoder(**inputs).last_hidden_state.mean(dim=1) # 平均池化\n", "print(embeddings.shape)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "MolT5-base 可训练参数量: 247.6 M\n" ] } ], "source": [ "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", "print(f'MolT5-base 可训练参数量: {trainable/1e6:.1f} M')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "已缓存权重磁盘占用:3784.1 MB\n" ] } ], "source": [ "# molt5_disk_usage.py\n", "from transformers import AutoModel, AutoTokenizer\n", "import os, pathlib\n", "\n", "repo_id = \"laituan245/molt5-base\"\n", "\n", "# 让 transformers 只走本地缓存,不会触发下载\n", "model = AutoModel.from_pretrained(repo_id, local_files_only=True)\n", "tokenizer = AutoTokenizer.from_pretrained(repo_id, local_files_only=True)\n", "\n", "# 找到缓存目录\n", "cache_root = pathlib.Path.home() / \".cache/huggingface/hub\"\n", "# 仓库目录名格式:models--{user}--{repo}\n", "repo_dir = cache_root / f\"models--{repo_id.replace('/', '--')}\"\n", "\n", "disk_bytes = sum(f.stat().st_size for f in repo_dir.rglob(\"*\") if f.is_file())\n", "disk_mb = disk_bytes / 1024 ** 2\n", "\n", "print(f\"已缓存权重磁盘占用:{disk_mb:.1f} MB\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 130/130 [00:09<00:00, 13.90it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "总分子数 : 8316\n", "总耗时 : 11.55 s\n", "平均推理 : 1.39 ms / molecule\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "import pickle\n", "from transformers import T5ForConditionalGeneration, AutoTokenizer\n", "import torch\n", "import numpy as np\n", "from rdkit import Chem\n", "from tqdm import tqdm\n", "\n", "def smiles_to_molt5(smiles_list, model_name=\"laituan245/molt5-base\", batch_size=32, pooling=\"mean\"):\n", " \"\"\"\n", " 使用 MolT5 生成 SMILES 的嵌入向量(基于 encoder 的隐藏状态)\n", " \n", " 参数:\n", " smiles_list (list): SMILES 字符串列表\n", " model_name (str): Hugging Face 模型 ID,默认为 MolT5-base\n", " batch_size (int): 批处理大小,根据 GPU 内存调整\n", " pooling (str): 池化方法,可选 \"mean\"(平均池化)或 \"cls\"(取 CLS token)\n", " \n", " 返回:\n", " dict: 键为 SMILES,值为嵌入向量(numpy 数组)\n", " \"\"\"\n", " # 加载 MolT5 的 tokenizer 和模型\n", " model = T5ForConditionalGeneration.from_pretrained(model_name)\n", " tokenizer = AutoTokenizer.from_pretrained(model_name)\n", " model.eval()\n", " \n", " # 设备设置\n", " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", " model.to(device)\n", " \n", " molt5_dict = {}\n", " \n", " # 分批处理\n", " for i in tqdm(range(0, len(smiles_list), batch_size)):\n", " batch_smiles = smiles_list[i:i+batch_size]\n", " valid_indices = []\n", " batch_inputs = []\n", " \n", " # 过滤无效 SMILES\n", " for idx, smiles in enumerate(batch_smiles):\n", " mol = Chem.MolFromSmiles(smiles)\n", " if mol is not None:\n", " valid_indices.append(idx)\n", " batch_inputs.append(smiles)\n", " else:\n", " print(f\"Invalid SMILES: {smiles}\")\n", " molt5_dict[smiles] = np.zeros(model.config.d_model, dtype=np.float32) # 填充零向量\n", " \n", " if not batch_inputs:\n", " continue\n", " \n", " # Tokenize 并生成嵌入\n", " inputs = tokenizer(\n", " batch_inputs,\n", " return_tensors=\"pt\",\n", " padding=True,\n", " truncation=True,\n", " max_length=512\n", " ).to(device)\n", " \n", " with torch.no_grad():\n", " # 获取 encoder 的隐藏状态(形状: [batch_size, seq_len, hidden_dim])\n", " encoder_outputs = model.encoder(**inputs)\n", " hidden_states = encoder_outputs.last_hidden_state\n", " \n", " # 池化策略\n", " if pooling == \"mean\":\n", " embeddings = hidden_states.mean(dim=1) # 平均池化\n", " elif pooling == \"cls\":\n", " embeddings = hidden_states[:, 0, :] # CLS token\n", " else:\n", " raise ValueError(\"pooling 必须是 'mean' 或 'cls'\")\n", " \n", " # 存储结果\n", " for j, idx in enumerate(valid_indices):\n", " molt5_dict[batch_smiles[idx]] = embeddings[j].cpu().numpy()\n", " \n", " return molt5_dict\n", "\n", "\n", "import time\n", "# ----- 计时开始 -----\n", "smiles_list = list(idx2smi.values()) # 假设 idx2smi 是 SMILES 字典\n", "\n", "t0 = time.perf_counter()\n", "molt5_embeddings = smiles_to_molt5(smiles_list, batch_size=64, pooling=\"mean\")\n", "\n", "t1 = time.perf_counter()\n", "# ----- 计时结束 -----\n", "\n", "# 基本统计\n", "total_mols = len(molt5_embeddings)\n", "avg_time_ms = (t1 - t0) / total_mols * 1000\n", "\n", "print(f\"总分子数 : {total_mols}\")\n", "print(f\"总耗时 : {t1 - t0:.2f} s\")\n", "print(f\"平均推理 : {avg_time_ms:.2f} ms / molecule\")\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8316 768\n" ] } ], "source": [ "print(len(molt5_embeddings), len(molt5_embeddings['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "molt5_embeddings['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "字典已成功保存到 embeddings/molt5_emb768.pickle\n" ] } ], "source": [ "# 保存字典为pickle文件\n", "pickle_path = 'embeddings/molt5_emb768.pickle'\n", "with open(pickle_path, 'wb') as pickle_file:\n", " pickle.dump(molt5_embeddings, pickle_file)\n", "\n", "print(f\"字典已成功保存到 {pickle_path}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate Chemprop embedding for all smiles" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# git clone https://github.com/chemprop/chemprop.git\n", "# https://chemprop.readthedocs.io/en/main/installation.html\n", "# https://chemprop.readthedocs.io/en/main/tutorial/cli/fingerprint.html#fingerprint \n", "\n", "# chemprop fingerprint --test-path ./embeddings/LINCS2020_smiles.csv --model-path chemprop/tests/data/example_model_v2_regression_mol.ckpt --output embeddings/fps.csv --ffn-block-index -2" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "预训练权重总参数量: 319,505\n", "0.3 M\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_1948954/3140832406.py:3: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " ckpt = torch.load('/home/bob/boom/VCBench/Molecule_encoder/chemprop/tests/data/example_model_v2_regression_mol.ckpt',\n" ] } ], "source": [ "import torch\n", "\n", "ckpt = torch.load('/home/bob/boom/VCBench/Molecule_encoder/chemprop/tests/data/example_model_v2_regression_mol.ckpt',\n", " map_location='cpu')\n", "\n", "# 取出模型参数部分\n", "model_state = ckpt['state_dict']\n", "\n", "total = sum(v.numel() for v in model_state.values() if isinstance(v, torch.Tensor))\n", "print(f'预训练权重总参数量: {total:,}')\n", "print(f'{total/1e6:.1f} M')" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8316" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import csv\n", "import numpy as np\n", "\n", "# CSV文件路径\n", "csv1_path = 'infoalign_model/LINCS2020_smiles.csv'\n", "csv2_path = 'embeddings/fps_0.csv'\n", "\n", "# 初始化一个空字典来存储SMILES和对应的表征\n", "smiles_to_representation = {}\n", "\n", "# 读取第一个CSV文件(SMILES信息)\n", "smiles_list = []\n", "with open(csv1_path, mode='r', newline='', encoding='utf-8') as csvfile:\n", " reader = csv.DictReader(csvfile)\n", " for row in reader:\n", " smiles = row['SMILES'] # 假设CSV文件中列名为'SMILES'\n", " smiles_list.append(smiles)\n", "\n", "# 读取第二个CSV文件(表征信息),跳过第一行\n", "representation_list = []\n", "with open(csv2_path, mode='r', newline='', encoding='utf-8') as csvfile:\n", " reader = csv.reader(csvfile)\n", " next(reader) # 跳过第一行\n", " for row in reader:\n", " # 将字符串转换为浮点数\n", " representation = [np.float32(x) for x in row] # 假设表征信息是整行数据\n", " representation_list.append(representation)\n", "\n", "# 将列表转换为numpy数组\n", "representation_array = np.array(representation_list)\n", "\n", "# 将SMILES和对应的表征合并到字典中\n", "for smiles, representation in zip(smiles_list, representation_array):\n", " smiles_to_representation[smiles] = representation\n", "\n", "len(smiles_to_representation)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "300 \n" ] }, { "data": { "text/plain": [ "dtype('float32')" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(len(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']), type(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))\n", "\n", "smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br'].dtype" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "300\n", "字典已成功保存到 embeddings/Chemprop_emb300.pickle\n" ] } ], "source": [ "print(len(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))\n", "\n", "import pickle\n", "# 保存字典为pickle文件\n", "pickle_path = 'embeddings/Chemprop_emb300.pickle'\n", "with open(pickle_path, 'wb') as pickle_file:\n", " pickle.dump(smiles_to_representation, pickle_file)\n", "\n", "print(f\"字典已成功保存到 {pickle_path}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate MolCLR embedding for all smiles\n", "\n", "## see /home/bob/boom/DrugIM/TranSiGen/data/MolCLR/Get_emd.ipynb\n", "\n", "### We use GIN model, which has a better performance in their paper" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "预训练权重总参数量: 2,407,201\n", "2.4 M\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_1948954/3871607093.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/MolCLR/ckpt/pretrained_gin/checkpoints/model.pth', map_location='cpu')\n" ] } ], "source": [ "import torch\n", "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/MolCLR/ckpt/pretrained_gin/checkpoints/model.pth', map_location='cpu')\n", "total = sum(v.numel() for v in state_dict.values())\n", "print(f'预训练权重总参数量: {total:,}')\n", "print(f'{total/1e6:.1f} M') # → 21.2 M" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generate Mole-BERT embedding for all smiles\n", "\n", "## see /home/bob/boom/DrugIM/TranSiGen/data/Mole-BERT/Get_emd.ipynb\n", "\n", "### We use GNN_graphpred model, which has a better performance in their paper" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "预训练权重总参数量: 1,860,905\n", "1.9 M\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_1948954/2103728332.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/Mole-BERT/model_gin/Mole-BERT.pth', map_location='cpu')\n" ] } ], "source": [ "import torch\n", "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/Mole-BERT/model_gin/Mole-BERT.pth', map_location='cpu')\n", "total = sum(v.numel() for v in state_dict.values())\n", "print(f'预训练权重总参数量: {total:,}')\n", "print(f'{total/1e6:.1f} M') # → 21.2 M" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3D UniMol" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8316" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pickle, h5py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "with open('./LINCS2020/idx2smi.pickle', 'rb') as f:\n", " idx2smi = pickle.load(f)\\\n", "\n", "unique_smiles = list(idx2smi.values()) # 假设idx2smi是一个字典,其值为SMILES字符串\n", "len(unique_smiles)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2025-09-15 11:17:31 | unimol_tools/models/unimolv2.py | 161 | INFO | Uni-Mol Tools | Loading pretrained weights from /home/bob/anaconda3/envs/boom/lib/python3.11/site-packages/unimol_tools/weights/modelzoo/310M/checkpoint.pt\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "开始生成32个SMILES的嵌入表示...\n", "开始\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "处理批次: 0%| | 0/1 [00:00