{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "1517383df6eb646", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T13:13:56.347478Z", "start_time": "2024-12-13T13:13:52.210350Z" } }, "outputs": [], "source": [ "import os\n", "import time\n", "from rdkit import Chem\n", "from rdkit import RDLogger;\n", "from torch.utils.data import Dataset\n", "import torch.nn.functional as F\n", "from tqdm import tqdm\n", "RDLogger.DisableLog('rdApp.*')\n", "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\n", "import pickle\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import math\n", "import dgl\n", "import networkx as nx" ] }, { "cell_type": "code", "execution_count": 3, "id": "697783252f244e50", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:02:54.040212Z", "start_time": "2024-12-13T04:02:54.034215Z" } }, "outputs": [], "source": [ "atom_number_index_dict ={\n", " 1:0, # H\n", " 6:1, # C\n", " 7:2, # N\n", " 8:3, # O\n", " 9:4 # F\n", "} \n", "# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "atom_index_number_dict = {v: k for k, v in atom_number_index_dict.items()}\n", "max_atom_number = max(atom_number_index_dict.keys())\n", "atom_number2index_tensor = torch.full((max_atom_number + 1,), -1)\n", "for k, v in atom_number_index_dict.items():\n", " atom_number2index_tensor[k] = v\n", "\n", "atom_index2number_tensor = torch.tensor([atom_index_number_dict[i] for i in range(len(atom_index_number_dict))])\n", "def atom_number2index(atom_number):\n", " return atom_number_index_dict[atom_number]\n", "def atom_index2number(atom_index):\n", " return atom_index_number_dict[atom_index]" ] }, { "cell_type": "code", "execution_count": 4, "id": "7074f5a11a15ebc6", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:05:20.426859Z", "start_time": "2024-12-13T04:02:57.613812Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 130831/130831 [02:22<00:00, 916.44it/s] \n" ] } ], "source": [ "from dgl.data import QM9Dataset\n", "from torch.utils.data import SubsetRandomSampler\n", "from dgl.dataloading import GraphDataLoader\n", "from multiprocessing import Pool\n", "\n", "dataset = QM9Dataset(label_keys=['mu', 'gap'], cutoff=5.0)\n", "dataset_length = len(dataset)\n", "train_idx = torch.arange(dataset_length)\n", "class PreprocessedQM9Dataset(Dataset):\n", " def __init__(self, dataset):\n", " self.dataset = dataset\n", " self.processed_data = []\n", " self._preprocess()\n", "\n", " def _preprocess(self):\n", " for g, label in tqdm(self.dataset):\n", " g.ndata[\"Z_index\"] = torch.tensor([atom_number2index(z.item()) for z in g.ndata[\"Z\"]])\n", " self.processed_data.append((g, label))\n", "\n", " def __len__(self):\n", " return len(self.processed_data)\n", "\n", " def __getitem__(self, idx):\n", " return self.processed_data[idx]\n", "\n", "# 包装数据集\n", "processed_dataset = PreprocessedQM9Dataset(dataset)" ] }, { "cell_type": "code", "execution_count": 1, "id": "d1f69b7e2e1aa945", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T03:55:50.314260Z", "start_time": "2024-12-13T03:55:50.115978Z" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'processed_dataset' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[1], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mprocessed_dataset\u001b[49m[\u001b[38;5;241m0\u001b[39m])\n", "\u001b[1;31mNameError\u001b[0m: name 'processed_dataset' is not defined" ] } ], "source": [ "print(processed_dataset[0])" ] }, { "cell_type": "code", "execution_count": 5, "id": "d1137deeda269919", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:05:20.442135Z", "start_time": "2024-12-13T04:05:20.428230Z" } }, "outputs": [], "source": [ "myGLoader = GraphDataLoader(processed_dataset,batch_size=4,pin_memory=True)" ] }, { "cell_type": "code", "execution_count": 13, "id": "b44c553b-dc97-445c-b50f-5d8cc58e12c3", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T12:20:46.508536Z", "start_time": "2024-12-13T12:20:20.023147Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 0%| | 138/32708 [00:00<00:23, 1368.45it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "16\n", "21\n", "26\n", "38\n", "42\n", "44\n", "49\n", "50\n", "58\n", "72\n", "80\n", "82\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 2%|▏ | 546/32708 [00:00<00:24, 1307.34it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "84\n", "86\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 5%|▍ | 1633/32708 [00:01<00:23, 1311.41it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "94\n", "96\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 43%|████▎ | 14160/32708 [00:10<00:15, 1224.36it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "98\n", "100\n", "106\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 46%|████▌ | 14903/32708 [00:11<00:14, 1228.66it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "110\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [00:26<00:00, 1235.31it/s]\n" ] } ], "source": [ "max_nodes = 0\n", "for batch in tqdm(myGLoader):\n", " g,label = batch\n", " if g.num_nodes()>max_nodes:\n", " max_nodes = g.num_nodes()\n", " print(g.num_nodes())\n", " # print(g)\n", " # break\n", " " ] }, { "cell_type": "code", "execution_count": 6, "id": "1a5caea191a642bc", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:05:20.457355Z", "start_time": "2024-12-13T04:05:20.443241Z" } }, "outputs": [], "source": [ "from functools import partial\n", "import sys\n", "sys.path.append(\"lib\")\n", "from lib.metrics import sce_loss\n", "\n", "class GMae(nn.Module):\n", " def __init__(self, encoder,decoder,\n", " in_dim,hidden_dim,out_dim,mask_rate=0.3,replace_rate=0.1,alpha_l=2,\n", " embedding_layer_classes=5,embedding_layer_dim=4):\n", " super(GMae, self).__init__()\n", " self.Z_embedding = nn.Embedding(embedding_layer_classes,embedding_layer_dim)\n", " self.encoder = encoder\n", " self.decoder = decoder\n", " self.mask_rate = mask_rate\n", " self.replace_rate = replace_rate\n", " self.alpha_l = alpha_l\n", " self.in_dim = in_dim\n", " self.hidden_dim = hidden_dim\n", " self.out_dim = out_dim\n", " self.embedding_layer_classes = embedding_layer_classes\n", " self.embedding_layer_dim = embedding_layer_dim\n", " self.enc_mask_token = nn.Parameter(torch.zeros(1,in_dim))\n", " self.criterion = partial(sce_loss, alpha=alpha_l)\n", " self.encoder_to_decoder = nn.Linear(hidden_dim, hidden_dim, bias=False)\n", " def encode_atom_index(self,Z_index):\n", " return self.Z_embedding(Z_index)\n", " def encoding_mask_noise(self, g, x, mask_rate=0.3):\n", " num_nodes = g.num_nodes()\n", " perm = torch.randperm(num_nodes, device=x.device)\n", " # random masking\n", " num_mask_nodes = int(mask_rate * num_nodes)\n", " mask_nodes = perm[: num_mask_nodes]\n", " keep_nodes = perm[num_mask_nodes: ]\n", "\n", " if self.replace_rate > 0:\n", " num_noise_nodes = int(self.replace_rate * num_mask_nodes)\n", " perm_mask = torch.randperm(num_mask_nodes, device=x.device)\n", " token_nodes = mask_nodes[perm_mask[: int((1-self.replace_rate) * num_mask_nodes)]]\n", " noise_nodes = mask_nodes[perm_mask[-int(self.replace_rate * num_mask_nodes):]]\n", " noise_to_be_chosen = torch.randperm(num_nodes, device=x.device)[:num_noise_nodes]\n", " out_x = x.clone()\n", " out_x[token_nodes] = 0.0\n", " out_x[noise_nodes] = x[noise_to_be_chosen]\n", " else:\n", " out_x = x.clone()\n", " token_nodes = mask_nodes\n", " out_x[mask_nodes] = 0.0\n", "\n", " out_x[token_nodes] += self.enc_mask_token\n", " use_g = g.clone()\n", "\n", " return use_g, out_x, (mask_nodes, keep_nodes) \n", " def mask_attr_prediction(self, g, x):\n", " use_g, use_x, (mask_nodes, keep_nodes) = self.encoding_mask_noise(g, x, self.mask_rate)\n", " enc_rep = self.encoder(use_g, use_x)\n", " # ---- attribute reconstruction ----\n", " rep = self.encoder_to_decoder(enc_rep)\n", " recon = self.decoder(use_g, rep)\n", " x_init = x[mask_nodes]\n", " x_rec = recon[mask_nodes]\n", " loss = self.criterion(x_rec, x_init)\n", " return loss\n", "\n", " def embed(self, g, x):\n", " rep = self.encoder(g, x)\n", " return rep\n", " " ] }, { "cell_type": "code", "execution_count": 7, "id": "c99cb509ac0f1054", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:05:20.473215Z", "start_time": "2024-12-13T04:05:20.458354Z" } }, "outputs": [], "source": [ "import dgl.nn as dglnn\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "class SimpleGNN(nn.Module):\n", " def __init__(self, in_feats, hid_feats, out_feats):\n", " super().__init__()\n", " self.conv1 = dglnn.SAGEConv(\n", " in_feats=in_feats, out_feats=hid_feats,aggregator_type=\"mean\")\n", " self.conv2 = dglnn.SAGEConv(\n", " in_feats=hid_feats, out_feats=out_feats,aggregator_type=\"mean\")\n", "\n", " def forward(self, graph, inputs):\n", " # 输入是节点的特征\n", " h = self.conv1(graph, inputs)\n", " h = F.relu(h)\n", " h = self.conv2(graph, h)\n", " return h" ] }, { "cell_type": "code", "execution_count": 8, "id": "5a8a4e4dd753b642", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:05:20.707956Z", "start_time": "2024-12-13T04:05:20.474302Z" } }, "outputs": [], "source": [ "sage_enc = SimpleGNN(in_feats=7,hid_feats=4,out_feats=4)\n", "sage_dec = SimpleGNN(in_feats=4,hid_feats=4,out_feats=7)\n", "gmae = GMae(sage_enc,sage_dec,7,4,7,replace_rate=0)\n", "epoches = 5\n", "optimizer = optim.Adam(gmae.parameters(), lr=1e-3)\n", "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')" ] }, { "cell_type": "code", "execution_count": 11, "id": "224529a988b81ef5", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T03:59:44.770215Z", "start_time": "2024-12-13T03:59:11.545931Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epoch 0 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " 10%|▉ | 3262/32708 [00:32<04:55, 99.64it/s] \n", "\n", "KeyboardInterrupt\n", "\n" ] } ], "source": [ "# print(f\"epoch {0} started!\")\n", "# gmae.train()\n", "# gmae.encoder.train()\n", "# gmae.decoder.train()\n", "# gmae.to(device)\n", "# loss_epoch = 0\n", "# import os\n", "# os.environ[\"CUDA_LAUNCH_BLOCKING\"]=\"1\"\n", "# for batch in tqdm(myGLoader):\n", "# optimizer.zero_grad()\n", "# batch_g, _ = batch\n", "# R = batch_g.ndata[\"R\"].to(device)\n", "# Z_index = batch_g.ndata[\"Z_index\"].to(device)\n", "# Z_emb = gmae.encode_atom_index(Z_index)\n", "# feat = torch.cat([R,Z_emb],dim=1)\n", "# batch_g = batch_g.to(device)\n", "# loss = gmae.mask_attr_prediction(batch_g, feat)\n", "# loss.backward()\n", "# optimizer.step()\n", "# loss_epoch+=loss.item()\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "a22599c4e591125b", "metadata": { "ExecuteTime": { "end_time": "2024-12-13T04:30:37.389930Z", "start_time": "2024-12-13T04:05:20.708461Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epoch 0 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [05:11<00:00, 105.09it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "best model saved-loss:470.463-save_path:./experiments/consumption/gmae/12-13@12_05/gmae_epoch-0-470.463.pt\n", "epoch 0: loss 470.46260083183415\n", "epoch 1 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [05:04<00:00, 107.34it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "best model saved-loss:18.848-save_path:./experiments/consumption/gmae/12-13@12_05/gmae_epoch-1-18.848.pt\n", "epoch 1: loss 18.848073385778548\n", "epoch 2 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [04:59<00:00, 109.35it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "best model saved-loss:4.784-save_path:./experiments/consumption/gmae/12-13@12_05/gmae_epoch-2-4.784.pt\n", "epoch 2: loss 4.7842518344823475\n", "epoch 3 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [05:04<00:00, 107.37it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "best model saved-loss:1.336-save_path:./experiments/consumption/gmae/12-13@12_05/gmae_epoch-3-1.336.pt\n", "epoch 3: loss 1.336019518836153\n", "epoch 4 started!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 32708/32708 [04:56<00:00, 110.21it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "best model saved-loss:0.572-save_path:./experiments/consumption/gmae/12-13@12_05/gmae_epoch-4-0.572.pt\n", "epoch 4: loss 0.5721691430861142\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "from datetime import datetime\n", "\n", "current_time = datetime.now().strftime(\"%m-%d@%H_%M\")\n", "best_loss = 10000\n", "for epoch in range(epoches):\n", " print(f\"epoch {epoch} started!\")\n", " gmae.train()\n", " gmae.encoder.train()\n", " gmae.decoder.train()\n", " gmae.to(device)\n", " loss_epoch = 0\n", " for batch in tqdm(myGLoader):\n", " optimizer.zero_grad()\n", " batch_g, _ = batch\n", " R = batch_g.ndata[\"R\"].to(device)\n", " # Z_index = batch_g.ndata[\"Z_index\"].to(device)\n", " Z_index = batch_g.ndata[\"Z_index\"].to(device)\n", " Z_emb = gmae.encode_atom_index(Z_index)\n", " feat = torch.cat([R,Z_emb],dim=1)\n", " batch_g = batch_g.to(device)\n", " loss = gmae.mask_attr_prediction(batch_g, feat)\n", " loss.backward()\n", " optimizer.step()\n", " loss_epoch+=loss.item()\n", " if loss_epoch < best_loss:\n", " formatted_loss_epoch = f\"{loss_epoch:.3f}\"\n", " save_path = f\"./experiments/QM9/gmae/{current_time}/gmae_epoch-{epoch}-{formatted_loss_epoch}.pt\"\n", " save_dir = os.path.dirname(save_path)\n", " if not os.path.exists(save_dir):\n", " os.makedirs(save_dir,exist_ok=True)\n", " torch.save(gmae.state_dict(), save_path)\n", " best_loss = loss_epoch\n", " print(f\"best model saved-loss:{formatted_loss_epoch}-save_path:{save_path}\")\n", " print(f\"epoch {epoch}: loss {loss_epoch}\")" ] } ], "metadata": { "kernelspec": { "display_name": "gnn_course", "language": "python", "name": "gnn_course" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.20" } }, "nbformat": 4, "nbformat_minor": 5 }