diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a7cdac76c182c2f5bce8533edd496b92e5335d33 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/GraphMAE.iml b/.idea/GraphMAE.iml new file mode 100644 index 0000000000000000000000000000000000000000..ddf0cb9a3f154645817d0c1c626b32fe325ebdb0 --- /dev/null +++ b/.idea/GraphMAE.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/deployment.xml b/.idea/deployment.xml new file mode 100644 index 0000000000000000000000000000000000000000..f5a2601ff07f2817a59e85d237ff328317c43dd1 --- /dev/null +++ b/.idea/deployment.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000000000000000000000000000000000000..7869b569aaa2e01a9dcc58b988bc663371fc5ea2 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,76 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000000000000000000000000000000000000..105ce2da2d6447d11dfe32bfb846c3d5b199fc99 --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/jupyter-settings.xml b/.idea/jupyter-settings.xml new file mode 100644 index 0000000000000000000000000000000000000000..d2ce8f60d3bcec4babe09aaad035c8443e06379e --- /dev/null +++ b/.idea/jupyter-settings.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000000000000000000000000000000000000..2fc8082a4c5f65b55e6891a96d288d8c1353cd06 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000000000000000000000000000000000..afad42e5a3050c9dbff4391fff8fab7b8545b059 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000000000000000000000000000000000000..28ec6c4afa16ada61790bf695adf1fc04f22427c --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,182 @@ + + + + + + + + + + + { + "associatedIndex": 2 +} + + + + { + "keyToString": { + "Python.prepare_QM9_dataset.executor": "Run", + "Python.run.executor": "Run", + "Python.upload_dataset.executor": "Run", + "RunOnceActivity.ShowReadmeOnStart": "true", + "last_opened_file_path": "E:/python/2024.12.11/GraphMAE", + "node.js.detected.package.eslint": "true", + "node.js.detected.package.tslint": "true", + "node.js.selected.package.eslint": "(autodetect)", + "node.js.selected.package.tslint": "(autodetect)", + "nodejs_package_manager_path": "npm", + "settings.editor.selected.configurable": "org.jetbrains.plugins.notebooks.jupyter.connections.configuration.JupyterServerConfigurable", + "vue.rearranger.settings.migration": "true" + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1733919936165 + + + + + + + + + + + \ No newline at end of file diff --git a/.ipynb_checkpoints/DataInspect-checkpoint.ipynb b/.ipynb_checkpoints/DataInspect-checkpoint.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..210b52dab216d1c72f16230040900ecd653d9a7b --- /dev/null +++ b/.ipynb_checkpoints/DataInspect-checkpoint.ipynb @@ -0,0 +1,396 @@ +{ + "cells": [ + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:11:02.453452Z", + "start_time": "2024-12-12T16:10:59.783010Z" + } + }, + "cell_type": "code", + "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", + "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" + ], + "id": "1517383df6eb646", + "outputs": [], + "execution_count": 1 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:11:02.468893Z", + "start_time": "2024-12-12T16:11:02.454576Z" + } + }, + "cell_type": "code", + "source": [ + "atom_number_index_dict ={\n", + " 1:0,\n", + " 6:1,\n", + " 7:2,\n", + " 8:3,\n", + " 9:4\n", + "}\n", + "atom_index_number_dict ={\n", + " 0:1,\n", + " 1:6,\n", + " 2:7,\n", + " 3:8,\n", + " 4:9\n", + "}\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]" + ], + "id": "697783252f244e50", + "outputs": [], + "execution_count": 2 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:11:03.301916Z", + "start_time": "2024-12-12T16:11:03.243204Z" + } + }, + "cell_type": "code", + "source": [ + "from dgl.data import QM9Dataset\n", + "from torch.utils.data import SubsetRandomSampler\n", + "from dgl.dataloading import GraphDataLoader\n", + "\n", + "dataset = QM9Dataset(label_keys=['mu', 'gap'], cutoff=5.0)\n", + "dataset_length = len(dataset)\n", + "train_idx = torch.arange(dataset_length)\n", + "train_sampler = SubsetRandomSampler(train_idx)\n", + "def collate_fn(batch):\n", + " graphs, labels = map(list, zip(*batch))\n", + " for g in graphs:\n", + " # g.ndata[\"R\"]->the coordinates of each atom[num_nodes,3], g.ndata[\"Z\"]->the atomic number(H:1,C:6) [num_nodes]\n", + " g.ndata[\"Z_index\"] = torch.tensor([atom_number2index(z.item()) for z in g.ndata[\"Z\"]])\n", + " batched_graph = dgl.batch(graphs)\n", + " return batched_graph, torch.stack(labels)\n", + "myGLoader = GraphDataLoader(dataset,collate_fn=collate_fn,batch_size=5, pin_memory=True)" + ], + "id": "7074f5a11a15ebc6", + "outputs": [], + "execution_count": 3 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T15:59:44.314049Z", + "start_time": "2024-12-12T15:59:44.299072Z" + } + }, + "cell_type": "code", + "source": [ + "# atom_numbers = []\n", + "# for g,_ in dataset:\n", + "# for atom_z in g.ndata[\"Z\"]:\n", + "# if atom_z not in atom_numbers:\n", + "# atom_numbers.append(atom_z)\n", + "# print(atom_numbers)" + ], + "id": "5758841a1f281514", + "outputs": [], + "execution_count": 12 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:14:46.301537Z", + "start_time": "2024-12-12T16:11:12.606641Z" + } + }, + "cell_type": "code", + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "for batch in myGLoader:\n", + " batch_g,label = batch\n", + " batch_g.to(device)\n", + " " + ], + "id": "13bcff8166b0e35b", + "outputs": [], + "execution_count": 5 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:07:15.834856Z", + "start_time": "2024-12-12T16:07:15.822783Z" + } + }, + "cell_type": "code", + "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=4,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", + " " + ], + "id": "1a5caea191a642bc", + "outputs": [], + "execution_count": 5 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:07:18.136174Z", + "start_time": "2024-12-12T16:07:18.122456Z" + } + }, + "cell_type": "code", + "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" + ], + "id": "c99cb509ac0f1054", + "outputs": [], + "execution_count": 6 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:07:21.516476Z", + "start_time": "2024-12-12T16:07:21.118135Z" + } + }, + "cell_type": "code", + "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 = 20\n", + "optimizer = optim.Adam(gmae.parameters(), lr=1e-3)\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')" + ], + "id": "5a8a4e4dd753b642", + "outputs": [], + "execution_count": 7 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T16:10:52.354863Z", + "start_time": "2024-12-12T16:10:52.311090Z" + } + }, + "cell_type": "code", + "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", + "for batch in 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()" + ], + "id": "224529a988b81ef5", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "epoch 0 started!\n" + ] + }, + { + "ename": "RuntimeError", + "evalue": "CUDA error: device-side assert triggered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n", + "output_type": "error", + "traceback": [ + "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m", + "\u001B[1;31mRuntimeError\u001B[0m Traceback (most recent call last)", + "Cell \u001B[1;32mIn[12], line 10\u001B[0m\n\u001B[0;32m 8\u001B[0m optimizer\u001B[38;5;241m.\u001B[39mzero_grad()\n\u001B[0;32m 9\u001B[0m batch_g, _ \u001B[38;5;241m=\u001B[39m batch\n\u001B[1;32m---> 10\u001B[0m R \u001B[38;5;241m=\u001B[39m \u001B[43mbatch_g\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mndata\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mR\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m]\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mto\u001B[49m\u001B[43m(\u001B[49m\u001B[43mdevice\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m 11\u001B[0m Z_index \u001B[38;5;241m=\u001B[39m batch_g\u001B[38;5;241m.\u001B[39mndata[\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mZ_index\u001B[39m\u001B[38;5;124m\"\u001B[39m]\u001B[38;5;241m.\u001B[39mto(device)\n\u001B[0;32m 12\u001B[0m Z_emb \u001B[38;5;241m=\u001B[39m gmae\u001B[38;5;241m.\u001B[39mencode_atom_index(Z_index)\n", + "\u001B[1;31mRuntimeError\u001B[0m: CUDA error: device-side assert triggered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n" + ] + } + ], + "execution_count": 12 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2024-12-12T15:59:46.502050Z", + "start_time": "2024-12-12T15:59:44.442506Z" + } + }, + "cell_type": "code", + "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 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", + " if loss_epoch < best_loss:\n", + " formatted_loss_epoch = f\"{loss_epoch:.3f}\"\n", + " save_path = f\"./experiments/consumption/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}\")" + ], + "id": "a22599c4e591125b", + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "epoch 0 started!\n" + ] + }, + { + "ename": "RuntimeError", + "evalue": "CUDA error: device-side assert triggered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n", + "output_type": "error", + "traceback": [ + "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m", + "\u001B[1;31mRuntimeError\u001B[0m Traceback (most recent call last)", + "Cell \u001B[1;32mIn[18], line 19\u001B[0m\n\u001B[0;32m 17\u001B[0m Z_emb \u001B[38;5;241m=\u001B[39m gmae\u001B[38;5;241m.\u001B[39mencode_atom_index(Z_index)\n\u001B[0;32m 18\u001B[0m feat \u001B[38;5;241m=\u001B[39m torch\u001B[38;5;241m.\u001B[39mcat([R,Z_emb],dim\u001B[38;5;241m=\u001B[39m\u001B[38;5;241m1\u001B[39m)\n\u001B[1;32m---> 19\u001B[0m batch_g \u001B[38;5;241m=\u001B[39m \u001B[43mbatch_g\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mto\u001B[49m\u001B[43m(\u001B[49m\u001B[43mdevice\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m 20\u001B[0m loss \u001B[38;5;241m=\u001B[39m gmae\u001B[38;5;241m.\u001B[39mmask_attr_prediction(batch_g, feat)\n\u001B[0;32m 21\u001B[0m loss\u001B[38;5;241m.\u001B[39mbackward()\n", + "File \u001B[1;32mE:\\Anaconda\\envs\\gnn_course\\lib\\site-packages\\dgl\\heterograph.py:5730\u001B[0m, in \u001B[0;36mDGLGraph.to\u001B[1;34m(self, device, **kwargs)\u001B[0m\n\u001B[0;32m 5728\u001B[0m \u001B[38;5;66;03m# 2. Copy misc info\u001B[39;00m\n\u001B[0;32m 5729\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_nodes \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[1;32m-> 5730\u001B[0m new_bnn \u001B[38;5;241m=\u001B[39m {\n\u001B[0;32m 5731\u001B[0m k: F\u001B[38;5;241m.\u001B[39mcopy_to(num, device, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mkwargs)\n\u001B[0;32m 5732\u001B[0m \u001B[38;5;28;01mfor\u001B[39;00m k, num \u001B[38;5;129;01min\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_nodes\u001B[38;5;241m.\u001B[39mitems()\n\u001B[0;32m 5733\u001B[0m }\n\u001B[0;32m 5734\u001B[0m ret\u001B[38;5;241m.\u001B[39m_batch_num_nodes \u001B[38;5;241m=\u001B[39m new_bnn\n\u001B[0;32m 5735\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_edges \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n", + "File \u001B[1;32mE:\\Anaconda\\envs\\gnn_course\\lib\\site-packages\\dgl\\heterograph.py:5731\u001B[0m, in \u001B[0;36m\u001B[1;34m(.0)\u001B[0m\n\u001B[0;32m 5728\u001B[0m \u001B[38;5;66;03m# 2. Copy misc info\u001B[39;00m\n\u001B[0;32m 5729\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_nodes \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m 5730\u001B[0m new_bnn \u001B[38;5;241m=\u001B[39m {\n\u001B[1;32m-> 5731\u001B[0m k: \u001B[43mF\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcopy_to\u001B[49m\u001B[43m(\u001B[49m\u001B[43mnum\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mdevice\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m 5732\u001B[0m \u001B[38;5;28;01mfor\u001B[39;00m k, num \u001B[38;5;129;01min\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_nodes\u001B[38;5;241m.\u001B[39mitems()\n\u001B[0;32m 5733\u001B[0m }\n\u001B[0;32m 5734\u001B[0m ret\u001B[38;5;241m.\u001B[39m_batch_num_nodes \u001B[38;5;241m=\u001B[39m new_bnn\n\u001B[0;32m 5735\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_batch_num_edges \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n", + "File \u001B[1;32mE:\\Anaconda\\envs\\gnn_course\\lib\\site-packages\\dgl\\backend\\pytorch\\tensor.py:143\u001B[0m, in \u001B[0;36mcopy_to\u001B[1;34m(input, ctx, **kwargs)\u001B[0m\n\u001B[0;32m 141\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m ctx\u001B[38;5;241m.\u001B[39mindex \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m 142\u001B[0m th\u001B[38;5;241m.\u001B[39mcuda\u001B[38;5;241m.\u001B[39mset_device(ctx\u001B[38;5;241m.\u001B[39mindex)\n\u001B[1;32m--> 143\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43minput\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcuda\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m 144\u001B[0m \u001B[38;5;28;01melse\u001B[39;00m:\n\u001B[0;32m 145\u001B[0m \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mRuntimeError\u001B[39;00m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mInvalid context\u001B[39m\u001B[38;5;124m\"\u001B[39m, ctx)\n", + "\u001B[1;31mRuntimeError\u001B[0m: CUDA error: device-side assert triggered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n" + ] + } + ], + "execution_count": 18 + } + ], + "metadata": { + "kernelspec": { + "name": "gnn_course", + "language": "python", + "display_name": "gnn_course" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..363fcab7ed6e9634e198cf5555ceb88932c9a245 --- /dev/null +++ b/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.virtual_documents/DataInspect.ipynb b/.virtual_documents/DataInspect.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..96dcdcb80552bac110299310c5694a881bcec1ab --- /dev/null +++ b/.virtual_documents/DataInspect.ipynb @@ -0,0 +1,237 @@ +import os +import time +from rdkit import Chem +from rdkit import RDLogger; +from torch.utils.data import Dataset +import torch.nn.functional as F +from tqdm import tqdm +RDLogger.DisableLog('rdApp.*') +import torch +import torch.nn as nn +import torch.optim as optim +import pickle +import numpy as np +import matplotlib.pyplot as plt +import math +import dgl +import networkx as nx + + +atom_number_index_dict ={ + 1:0, # H + 6:1, # C + 7:2, # N + 8:3, # O + 9:4 # F +} +# device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +atom_index_number_dict = {v: k for k, v in atom_number_index_dict.items()} +max_atom_number = max(atom_number_index_dict.keys()) +atom_number2index_tensor = torch.full((max_atom_number + 1,), -1) +for k, v in atom_number_index_dict.items(): + atom_number2index_tensor[k] = v + +atom_index2number_tensor = torch.tensor([atom_index_number_dict[i] for i in range(len(atom_index_number_dict))]) +def atom_number2index(atom_numbers): + return atom_number2index_tensor[atom_numbers] +def atom_index2number(atom_indexes): + return atom_index2number_tensor[atom_indexes] + + +from dgl.data import QM9Dataset +from torch.utils.data import SubsetRandomSampler +from dgl.dataloading import GraphDataLoader +from multiprocessing import Pool + +dataset = QM9Dataset(label_keys=['mu', 'gap'], cutoff=5.0) +dataset_length = len(dataset) +train_idx = torch.arange(dataset_length) +# def preprocess_graph(data): +# g, label = data +# g.ndata["Z_index"] = atom_number2index(g.ndata["Z"]) +# return g, label + +# def preprocess_dataset(dataset): +# with Pool(processes=4) as pool: # 设置进程数 +# with tqdm(total=len(dataset)) as pbar: # 初始化进度条 +# results = [] +# for result in pool.imap(preprocess_graph, dataset): # 使用 imap 逐步处理 +# results.append(result) +# pbar.update(1) # 更新进度条 +# return results + +# # 使用多进程预处理数据集 +# dataset = preprocess_dataset(dataset) + +# def collate_fn(batch): +# # print(batch) +# graphs, labels = map(list, zip(*batch)) +# for g in graphs: +# pass +# # g.ndata["Z_index"] = atom_number2index(g.ndata["Z"]) +# # g.ndata["R"]->the coordinates of each atom[num_nodes,3], g.ndata["Z"]->the atomic number(H:1,C:6) [num_nodes] +# # g.ndata["Z_index"] = torch.tensor([atom_number2index(z.item()) for z in g.ndata["Z"]]) +# batched_graph = dgl.batch(graphs) +# return batched_graph, torch.stack(labels) +myGLoader = GraphDataLoader(dataset,batch_size=32,pin_memory=True,num_workers=8) + + +# for batch in tqdm(myGLoader): +# pass +# # print(batch) + + + +from functools import partial +import sys +sys.path.append("lib") +from lib.metrics import sce_loss + +class GMae(nn.Module): + def __init__(self, encoder,decoder, + in_dim,hidden_dim,out_dim,mask_rate=0.3,replace_rate=0.1,alpha_l=2, + embedding_layer_classes=5,embedding_layer_dim=4): + super(GMae, self).__init__() + self.Z_embedding = nn.Embedding(embedding_layer_classes,embedding_layer_dim) + self.encoder = encoder + self.decoder = decoder + self.mask_rate = mask_rate + self.replace_rate = replace_rate + self.alpha_l = alpha_l + self.in_dim = in_dim + self.hidden_dim = hidden_dim + self.out_dim = out_dim + self.embedding_layer_classes = embedding_layer_classes + self.embedding_layer_dim = embedding_layer_dim + self.enc_mask_token = nn.Parameter(torch.zeros(1,in_dim)) + self.criterion = partial(sce_loss, alpha=alpha_l) + self.encoder_to_decoder = nn.Linear(hidden_dim, hidden_dim, bias=False) + def encode_atom_index(self,Z_index): + return self.Z_embedding(Z_index) + def encoding_mask_noise(self, g, x, mask_rate=0.3): + num_nodes = g.num_nodes() + perm = torch.randperm(num_nodes, device=x.device) + # random masking + num_mask_nodes = int(mask_rate * num_nodes) + mask_nodes = perm[: num_mask_nodes] + keep_nodes = perm[num_mask_nodes: ] + + if self.replace_rate > 0: + num_noise_nodes = int(self.replace_rate * num_mask_nodes) + perm_mask = torch.randperm(num_mask_nodes, device=x.device) + token_nodes = mask_nodes[perm_mask[: int((1-self.replace_rate) * num_mask_nodes)]] + noise_nodes = mask_nodes[perm_mask[-int(self.replace_rate * num_mask_nodes):]] + noise_to_be_chosen = torch.randperm(num_nodes, device=x.device)[:num_noise_nodes] + out_x = x.clone() + out_x[token_nodes] = 0.0 + out_x[noise_nodes] = x[noise_to_be_chosen] + else: + out_x = x.clone() + token_nodes = mask_nodes + out_x[mask_nodes] = 0.0 + + out_x[token_nodes] += self.enc_mask_token + use_g = g.clone() + + return use_g, out_x, (mask_nodes, keep_nodes) + def mask_attr_prediction(self, g, x): + use_g, use_x, (mask_nodes, keep_nodes) = self.encoding_mask_noise(g, x, self.mask_rate) + enc_rep = self.encoder(use_g, use_x) + # ---- attribute reconstruction ---- + rep = self.encoder_to_decoder(enc_rep) + recon = self.decoder(use_g, rep) + x_init = x[mask_nodes] + x_rec = recon[mask_nodes] + loss = self.criterion(x_rec, x_init) + return loss + + def embed(self, g, x): + rep = self.encoder(g, x) + return rep + + + +import dgl.nn as dglnn +import torch.nn as nn +import torch.nn.functional as F +class SimpleGNN(nn.Module): + def __init__(self, in_feats, hid_feats, out_feats): + super().__init__() + self.conv1 = dglnn.SAGEConv( + in_feats=in_feats, out_feats=hid_feats,aggregator_type="mean") + self.conv2 = dglnn.SAGEConv( + in_feats=hid_feats, out_feats=out_feats,aggregator_type="mean") + + def forward(self, graph, inputs): + # 输入是节点的特征 + h = self.conv1(graph, inputs) + h = F.relu(h) + h = self.conv2(graph, h) + return h + + +sage_enc = SimpleGNN(in_feats=7,hid_feats=4,out_feats=4) +sage_dec = SimpleGNN(in_feats=4,hid_feats=4,out_feats=7) +gmae = GMae(sage_enc,sage_dec,7,4,7,replace_rate=0) +epoches = 20 +optimizer = optim.Adam(gmae.parameters(), lr=1e-3) +device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + +print(f"epoch {0} started!") +gmae.train() +gmae.encoder.train() +gmae.decoder.train() +gmae.to(device) +loss_epoch = 0 +import os +os.environ["CUDA_LAUNCH_BLOCKING"]="1" +for batch in tqdm(myGLoader): + optimizer.zero_grad() + batch_g, _ = batch + R = batch_g.ndata["R"].to(device) + Z_index = batch_g.ndata["Z"].to(device) + Z_emb = gmae.encode_atom_index(Z_index) + # feat = torch.cat([R,Z_emb],dim=1) + # batch_g = batch_g.to(device) + # loss = gmae.mask_attr_prediction(batch_g, feat) + # loss.backward() + # optimizer.step() + # loss_epoch+=loss.item() + + + +from datetime import datetime + +current_time = datetime.now().strftime("%m-%d@%H_%M") +best_loss = 10000 +for epoch in range(epoches): + print(f"epoch {epoch} started!") + gmae.train() + gmae.encoder.train() + gmae.decoder.train() + gmae.to(device) + loss_epoch = 0 + for batch in myGLoader: + optimizer.zero_grad() + batch_g, _ = batch + R = batch_g.ndata["R"].to(device) + # Z_index = batch_g.ndata["Z_index"].to(device) + Z_index = batch_g.ndata["Z_index"].to(device) + Z_emb = gmae.encode_atom_index(Z_index) + feat = torch.cat([R,Z_emb],dim=1) + batch_g = batch_g.to(device) + loss = gmae.mask_attr_prediction(batch_g, feat) + loss.backward() + optimizer.step() + loss_epoch+=loss.item() + if loss_epoch < best_loss: + formatted_loss_epoch = f"{loss_epoch:.3f}" + save_path = f"./experiments/consumption/gmae/{current_time}/gmae_epoch-{epoch}-{formatted_loss_epoch}.pt" + save_dir = os.path.dirname(save_path) + if not os.path.exists(save_dir): + os.makedirs(save_dir,exist_ok=True) + torch.save(gmae.state_dict(), save_path) + best_loss = loss_epoch + print(f"best model saved-loss:{formatted_loss_epoch}-save_path:{save_path}") + print(f"epoch {epoch}: loss {loss_epoch}") diff --git a/DataInspect.ipynb b/DataInspect.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a5ca2bcde07949c46853a9b7fb0c5fcab8fadf06 --- /dev/null +++ b/DataInspect.ipynb @@ -0,0 +1,622 @@ +{ + "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 +} diff --git a/README.md b/README.md index bfc343e608feba06483d406db1b0f6abbbd67ac5..0a3b353c53feefca871eea93438e955bd6b7903d 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,43 @@ ---- -license: mit ---- -# 模型训练过程汇总(持续更新中) - -对于已收集的每一个模型,`code` 目录为模型定义、训练和测试的代码和脚本文件,`model` 目录为已收集的 epoch 模型文件,`dataset.zip` 为模型数据集。 - -下表汇总了所有收集的模型训练过程信息: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
模型名称模型简介模型类型Epoch数量数据集信息
Clone-detection-BigCloneBench基于大规模代码克隆基准数据集的代码克隆检测模型,任务是进行二元分类(0/1),其中1代表语义等价,0代表其他情况。代码克隆检测2个epochBigCloneBench数据集
Clone-detection-POJ-104基于POJ-104数据集的代码克隆检测模型,任务是识别不同编程题目中相似的代码实现,给定一段代码和一组候选代码,任务是返回具有相同语义的Top K个代码代码克隆检测2个epoch (0-1)POJ-104编程题目数据集
CodeCompletion-token基于token级别的代码自动补全模型代码补全5个epoch (Java语料库)Java代码token序列数据集
Defect-detection代码缺陷检测模型,通过分析代码来识别潜在的缺陷和错误(进行二元分类(0/1))代码缺陷检测5个epoch包含缺陷标注的C语言代码数据集
code-refinement代码优化模型代码优化/重构34个epoch(small数据集)代码优化前后对数据集(C语言)
code-to-text代码到自然语言的转换模型代码注释生成每种语言10个epoch (支持Python/Java/JavaScript/PHP/Ruby/Go)多语言代码-文本对数据集
NL-code-search-Adv高级自然语言代码搜索模型,通过计算自然语言查询与代码片段之间的相似性来实现代码搜索,代码搜索2个epoch自然语言-(python)代码对数据集
NL-code-search-WebQuery基于Web查询的代码搜索模型,该模型通过编码器处理代码和自然语言输入,并利用多层感知器(MLP)来计算相似性得分代码搜索两个数据集各3个epochWeb查询-代码对数据集(CodeSearchNet数据集和CoSQA数据集(python))
text-to-code自然语言到代码的生成模型代码生成23个epoch文本描述-代码(c语言)对数据集
GraphMAE_MQ9在QM9数据集上训练的图掩码自编码器,通过对分子图中的原子的坐标以及类型进行预测实现自监督训练图自编码器10个epoch分子属性预测数据集
\ No newline at end of file +# Graph Mask AutoEncoder(GraphMAE) on QM9 Dataset +## Overview +We run the **Graph Mask AutoEncoder** on **QM9 Dataset** for pretraining. We use the atom position of each atom and the embedding of their element type as the input feature (dim=7) and predict the input feature by using the GraphSage with 4-dim hidden representation. + +**Total Epochs: 10** +## How to run +### If you do not want to re-train the model again +- **Unzip the model.zip** to get the model weight & embedded graph in each epoch +### If you want to try out the training process +- step1. **Preprocess the dataset** (we have provided the preprocessed as well) + +```bash +python prepare_QM9_dataset.py --label_keys "mu" "gap" +``` +- step2. **Train the Graph Mask AutoEncoder on the preprocessed dataset** +```bash +python run.py [--dataset_path] [--batch_size] [--epochs] [--device] [--save_dir] +``` + +## Model Description +### Overview +Ref:**[GraphMAE](https://arxiv.org/abs/2205.10803)** +>Self-supervised learning (SSL) has been extensively explored in recent years. Particularly, generative SSL has seen emerging success in natural language processing and other AI fields, such as the wide adoption of BERT and GPT. Despite this, contrastive learning-which heavily relies on structural data augmentation and complicated training strategies-has been the dominant approach in graph SSL, while the progress of generative SSL on graphs, especially graph autoencoders (GAEs), has thus far not reached the potential as promised in other fields. In this paper, we identify and examine the issues that negatively impact the development of GAEs, including their reconstruction objective, training robustness, and error metric. We present a masked graph autoencoder GraphMAE that mitigates these issues for generative self-supervised graph pretraining. Instead of reconstructing graph structures, we propose to focus on feature reconstruction with both a masking strategy and scaled cosine error that benefit the robust training of GraphMAE. We conduct extensive experiments on 21 public datasets for three different graph learning tasks. The results manifest that GraphMAE-a simple graph autoencoder with careful designs-can consistently generate outperformance over both contrastive and generative state-of-the-art baselines. This study provides an understanding of graph autoencoders and demonstrates the potential of generative self-supervised pre-training on graphs. + +### Detail +Encoder & Decoder: Two layer [GraphSage](https://docs.dgl.ai/generated/dgl.nn.pytorch.conv.SAGEConv.html) + +Readout Method: Mean + +HiddenDims: 4 (Default) + +MaskRate: 0.3 (Default) + +Training on RTX 4060 + +## Dataset Description +### Overview +Ref: **[QM9](https://docs.dgl.ai/generated/dgl.data.QM9Dataset.html)** +> Type: Molecule property prediction +> +> Sample_num: 130831 +> +> Total Elements: H,C,N,O,F diff --git a/code/QM9_dataset_class.py b/code/QM9_dataset_class.py new file mode 100644 index 0000000000000000000000000000000000000000..684e8cc638dd6913f67d27c2e344f956a85e5807 --- /dev/null +++ b/code/QM9_dataset_class.py @@ -0,0 +1,51 @@ +import os + +from tqdm import tqdm +import networkx as nx +import torch +from torch.utils.data import Dataset + +atom_number_index_dict = { + 1: 0, # H + 6: 1, # C + 7: 2, # N + 8: 3, # O + 9: 4 # F +} +atom_index_number_dict = {v: k for k, v in atom_number_index_dict.items()} +max_atom_number = max(atom_number_index_dict.keys()) + + +def atom_number2index(atom_number): + return atom_number_index_dict[atom_number] + + +def atom_index2number(atom_index): + return atom_index_number_dict[atom_index] + + +class PreprocessedQM9Dataset(Dataset): + def __init__(self, dataset): + self.dataset = dataset + self.processed_data = [] + if dataset is not None: + self._preprocess() + def _preprocess(self): + i = 0 + for g, label in tqdm(self.dataset): + g.ndata["Z_index"] = torch.tensor([atom_number2index(z.item()) for z in g.ndata["Z"]]) + g.ndata["sample_idx"] = i + self.processed_data.append((g, label)) + + def __len__(self): + return len(self.processed_data) + + def __getitem__(self, idx): + return self.processed_data[idx] + + def save_dataset(self, save_dir): + if not os.path.exists(save_dir): + os.makedirs(save_dir) + torch.save(self.processed_data, os.path.join(save_dir,"QM9_dataset_processed.pt")) + def load_dataset(self, dataset_path): + self.processed_data = torch.load(dataset_path) \ No newline at end of file diff --git a/code/lib/__pycache__/metrics.cpython-38.pyc b/code/lib/__pycache__/metrics.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff578d4b141726312380c8e9c8a3a3f5251a329b Binary files /dev/null and b/code/lib/__pycache__/metrics.cpython-38.pyc differ diff --git a/code/lib/metrics.py b/code/lib/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7951435e7706b10522564db46584e418c278b373 --- /dev/null +++ b/code/lib/metrics.py @@ -0,0 +1,95 @@ +# -*- coding:utf-8 -*- + +import numpy as np +import torch +import torch.nn.functional as F + + +def masked_mape_np(y_true, y_pred, null_val=np.nan): + with np.errstate(divide='ignore', invalid='ignore'): + if np.isnan(null_val): + mask = ~np.isnan(y_true) + else: + mask = np.not_equal(y_true, null_val) + mask = mask.astype('float32') + mask /= np.mean(mask) + mape = np.abs(np.divide(np.subtract(y_pred, y_true).astype('float32'), + y_true)) + mape = np.nan_to_num(mask * mape) + return np.mean(mape) + + +def masked_mse(preds, labels, null_val=np.nan): + if np.isnan(null_val): + mask = ~torch.isnan(labels) + else: + mask = (labels != null_val) + mask = mask.float() + # print(mask.sum()) + # print(mask.shape[0]*mask.shape[1]*mask.shape[2]) + mask /= torch.mean((mask)) + mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask) + loss = (preds - labels) ** 2 + loss = loss * mask + loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss) + return torch.mean(loss) + + +def masked_rmse(preds, labels, null_val=np.nan): + return torch.sqrt(masked_mse(preds=preds, labels=labels, + null_val=null_val)) + + +def masked_mae(preds, labels, null_val=np.nan): + if np.isnan(null_val): + mask = ~torch.isnan(labels) + else: + mask = (labels != null_val) + mask = mask.float() + mask /= torch.mean((mask)) + mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask) + loss = torch.abs(preds - labels) + loss = loss * mask + loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss) + return torch.mean(loss) + + +def masked_mae_test(y_true, y_pred, null_val=np.nan): + with np.errstate(divide='ignore', invalid='ignore'): + if np.isnan(null_val): + mask = ~np.isnan(y_true) + else: + mask = np.not_equal(y_true, null_val) + mask = mask.astype('float32') + mask /= np.mean(mask) + mae = np.abs(np.subtract(y_pred, y_true).astype('float32'), + ) + mae = np.nan_to_num(mask * mae) + return np.mean(mae) + + +def masked_rmse_test(y_true, y_pred, null_val=np.nan): + with np.errstate(divide='ignore', invalid='ignore'): + if np.isnan(null_val): + mask = ~np.isnan(y_true) + else: + # null_val=null_val + mask = np.not_equal(y_true, null_val) + mask = mask.astype('float32') + mask /= np.mean(mask) + mse = ((y_pred - y_true) ** 2) + mse = np.nan_to_num(mask * mse) + return np.sqrt(np.mean(mse)) + + +def sce_loss(x, y, alpha=3): + x = F.normalize(x, p=2, dim=-1) + y = F.normalize(y, p=2, dim=-1) + + # loss = - (x * y).sum(dim=-1) + # loss = (x_h - y_h).norm(dim=1).pow(alpha) + + loss = (1 - (x * y).sum(dim=-1)).pow_(alpha) + + loss = loss.mean() + return loss diff --git a/code/lib/utils.py b/code/lib/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c8572f255479e7a0ef389579d60b736f150cdfae --- /dev/null +++ b/code/lib/utils.py @@ -0,0 +1,397 @@ +import os +import numpy as np +import torch +import torch.utils.data +from sklearn.metrics import mean_absolute_error +from sklearn.metrics import mean_squared_error +import sys +project_path = "/content/gdrive//My Drive/CS5248_project" +sys.path.append(project_path + '/lib') +from metrics import masked_mape_np +from scipy.sparse.linalg import eigs +from metrics import masked_mape_np, masked_mae,masked_mse,masked_rmse,masked_mae_test,masked_rmse_test + + +def re_normalization(x, mean, std): + x = x * std + mean + return x + + +def max_min_normalization(x, _max, _min): + x = 1. * (x - _min)/(_max - _min) + x = x * 2. - 1. + return x + + +def re_max_min_normalization(x, _max, _min): + x = (x + 1.) / 2. + x = 1. * x * (_max - _min) + _min + return x + + +def get_adjacency_matrix(distance_df_filename, num_of_vertices, id_filename=None): + ''' + Parameters + ---------- + distance_df_filename: str, path of the csv file contains edges information + + num_of_vertices: int, the number of vertices + + Returns + ---------- + A: np.ndarray, adjacency matrix + + ''' + if 'npy' in distance_df_filename: + + adj_mx = np.load(distance_df_filename) + + return adj_mx, None + + else: + + import csv + + A = np.zeros((int(num_of_vertices), int(num_of_vertices)), + dtype=np.float32) + + distaneA = np.zeros((int(num_of_vertices), int(num_of_vertices)), + dtype=np.float32) + + if id_filename: + + with open(id_filename, 'r') as f: + id_dict = {int(i): idx for idx, i in enumerate(f.read().strip().split('\n'))} # 把节点id(idx)映射成从0开始的索引 + + with open(distance_df_filename, 'r') as f: + f.readline() + reader = csv.reader(f) + for row in reader: + if len(row) != 3: + continue + i, j, distance = int(row[0]), int(row[1]), float(row[2]) + A[id_dict[i], id_dict[j]] = 1 + distaneA[id_dict[i], id_dict[j]] = distance + return A, distaneA + + else: + + with open(distance_df_filename, 'r') as f: + f.readline() + reader = csv.reader(f) + for row in reader: + if len(row) != 3: + continue + i, j, distance = int(row[0]), int(row[1]), float(row[2]) + A[i, j] = 1 + distaneA[i, j] = distance + return A, distaneA + + +def scaled_Laplacian(W): + ''' + compute \tilde{L} + + Parameters + ---------- + W: np.ndarray, shape is (N, N), N is the num of vertices + + Returns + ---------- + scaled_Laplacian: np.ndarray, shape (N, N) + + ''' + + assert W.shape[0] == W.shape[1] + + D = np.diag(np.sum(W, axis=1)) + + L = D - W + + lambda_max = eigs(L, k=1, which='LR')[0].real + + return (2 * L) / lambda_max - np.identity(W.shape[0]) + + +def cheb_polynomial(L_tilde, K): + ''' + compute a list of chebyshev polynomials from T_0 to T_{K-1} + + Parameters + ---------- + L_tilde: scaled Laplacian, np.ndarray, shape (N, N) + + K: the maximum order of chebyshev polynomials + + Returns + ---------- + cheb_polynomials: list(np.ndarray), length: K, from T_0 to T_{K-1} + + ''' + + N = L_tilde.shape[0] + + cheb_polynomials = [np.identity(N), L_tilde.copy()] + + for i in range(2, K): + cheb_polynomials.append(2 * L_tilde * cheb_polynomials[i - 1] - cheb_polynomials[i - 2]) + + return cheb_polynomials + + +def load_graphdata_channel1(graph_signal_matrix_filename, num_of_indices, DEVICE, batch_size, shuffle=True): + ''' + 这个是为PEMS的数据准备的函数 + 将x,y都处理成归一化到[-1,1]之前的数据; + 每个样本同时包含所有监测点的数据,所以本函数构造的数据输入时空序列预测模型; + 该函数会把hour, day, week的时间串起来; + 注: 从文件读入的数据,x是最大最小归一化的,但是y是真实值 + 这个函数转为mstgcn,astgcn设计,返回的数据x都是通过减均值除方差进行归一化的,y都是真实值 + :param graph_signal_matrix_filename: str + :param num_of_hours: int + :param num_of_days: int + :param num_of_weeks: int + :param DEVICE: + :param batch_size: int + :return: + three DataLoaders, each dataloader contains: + test_x_tensor: (B, N_nodes, in_feature, T_input) + test_decoder_input_tensor: (B, N_nodes, T_output) + test_target_tensor: (B, N_nodes, T_output) + + ''' + + file = os.path.basename(graph_signal_matrix_filename).split('.')[0] + + dirpath = os.path.dirname(graph_signal_matrix_filename) + + filename = os.path.join(dirpath, + file) +'_astcgn' + + print('load file:', filename) + + file_data = np.load(filename + '.npz') + train_x = file_data['train_x'] # (10181, 307, 3, 12) + train_x = train_x[:, :, 0:5, :] + train_target = file_data['train_target'] # (10181, 307, 12) + + val_x = file_data['val_x'] + val_x = val_x[:, :, 0:5, :] + val_target = file_data['val_target'] + + test_x = file_data['test_x'] + test_x = test_x[:, :, 0:5, :] + test_target = file_data['test_target'] + + mean = file_data['mean'][:, :, 0:5, :] # (1, 1, 3, 1) + std = file_data['std'][:, :, 0:5, :] # (1, 1, 3, 1) + + # ------- train_loader ------- + train_x_tensor = torch.from_numpy(train_x).type(torch.FloatTensor).to(DEVICE) # (B, N, F, T) + train_target_tensor = torch.from_numpy(train_target).type(torch.FloatTensor).to(DEVICE) # (B, N, T) + + train_dataset = torch.utils.data.TensorDataset(train_x_tensor, train_target_tensor) + + train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=shuffle) + + # ------- val_loader ------- + val_x_tensor = torch.from_numpy(val_x).type(torch.FloatTensor).to(DEVICE) # (B, N, F, T) + val_target_tensor = torch.from_numpy(val_target).type(torch.FloatTensor).to(DEVICE) # (B, N, T) + + val_dataset = torch.utils.data.TensorDataset(val_x_tensor, val_target_tensor) + + val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False) + + # ------- test_loader ------- + test_x_tensor = torch.from_numpy(test_x).type(torch.FloatTensor).to(DEVICE) # (B, N, F, T) + test_target_tensor = torch.from_numpy(test_target).type(torch.FloatTensor).to(DEVICE) # (B, N, T) + + test_dataset = torch.utils.data.TensorDataset(test_x_tensor, test_target_tensor) + + test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False) + + # print + print('train:', train_x_tensor.size(), train_target_tensor.size()) + print('val:', val_x_tensor.size(), val_target_tensor.size()) + print('test:', test_x_tensor.size(), test_target_tensor.size()) + + return train_loader, train_target_tensor, val_loader, val_target_tensor, test_loader, test_target_tensor, mean, std + + +def compute_val_loss_mstgcn(net, val_loader, criterion, masked_flag,missing_value,sw, epoch, limit=None): + ''' + for rnn, compute mean loss on validation set + :param net: model + :param val_loader: torch.utils.data.utils.DataLoader + :param criterion: torch.nn.MSELoss + :param sw: tensorboardX.SummaryWriter + :param global_step: int, current global_step + :param limit: int, + :return: val_loss + ''' + + net.train(False) # ensure dropout layers are in evaluation mode + + with torch.no_grad(): + + val_loader_length = len(val_loader) # nb of batch + + tmp = [] # 记录了所有batch的loss + + for batch_index, batch_data in enumerate(val_loader): + encoder_inputs, labels = batch_data + outputs = net(encoder_inputs) + if masked_flag: + loss = criterion(outputs, labels, missing_value) + else: + loss = criterion(outputs, labels) + + tmp.append(loss.item()) + if batch_index % 100 == 0: + print('validation batch %s / %s, loss: %.2f' % (batch_index + 1, val_loader_length, loss.item())) + if (limit is not None) and batch_index >= limit: + break + + validation_loss = sum(tmp) / len(tmp) + sw.add_scalar('validation_loss', validation_loss, epoch) + return validation_loss + + +# def evaluate_on_test_mstgcn(net, test_loader, test_target_tensor, sw, epoch, _mean, _std): +# ''' +# for rnn, compute MAE, RMSE, MAPE scores of the prediction for every time step on testing set. +# +# :param net: model +# :param test_loader: torch.utils.data.utils.DataLoader +# :param test_target_tensor: torch.tensor (B, N_nodes, T_output, out_feature)=(B, N_nodes, T_output, 1) +# :param sw: +# :param epoch: int, current epoch +# :param _mean: (1, 1, 3(features), 1) +# :param _std: (1, 1, 3(features), 1) +# ''' +# +# net.train(False) # ensure dropout layers are in test mode +# +# with torch.no_grad(): +# +# test_loader_length = len(test_loader) +# +# test_target_tensor = test_target_tensor.cpu().numpy() +# +# prediction = [] # 存储所有batch的output +# +# for batch_index, batch_data in enumerate(test_loader): +# +# encoder_inputs, labels = batch_data +# +# outputs = net(encoder_inputs) +# +# prediction.append(outputs.detach().cpu().numpy()) +# +# if batch_index % 100 == 0: +# print('predicting testing set batch %s / %s' % (batch_index + 1, test_loader_length)) +# +# prediction = np.concatenate(prediction, 0) # (batch, T', 1) +# prediction_length = prediction.shape[2] +# +# for i in range(prediction_length): +# assert test_target_tensor.shape[0] == prediction.shape[0] +# print('current epoch: %s, predict %s points' % (epoch, i)) +# mae = mean_absolute_error(test_target_tensor[:, :, i], prediction[:, :, i]) +# rmse = mean_squared_error(test_target_tensor[:, :, i], prediction[:, :, i]) ** 0.5 +# mape = masked_mape_np(test_target_tensor[:, :, i], prediction[:, :, i], 0) +# print('MAE: %.2f' % (mae)) +# print('RMSE: %.2f' % (rmse)) +# print('MAPE: %.2f' % (mape)) +# print() +# if sw: +# sw.add_scalar('MAE_%s_points' % (i), mae, epoch) +# sw.add_scalar('RMSE_%s_points' % (i), rmse, epoch) +# sw.add_scalar('MAPE_%s_points' % (i), mape, epoch) + + +def predict_and_save_results_mstgcn(net, data_loader, data_target_tensor, global_step, metric_method,_mean, _std, params_path, type): + ''' + + :param net: nn.Module + :param data_loader: torch.utils.data.utils.DataLoader + :param data_target_tensor: tensor + :param epoch: int + :param _mean: (1, 1, 3, 1) + :param _std: (1, 1, 3, 1) + :param params_path: the path for saving the results + :return: + ''' + net.train(False) # ensure dropout layers are in test mode + + with torch.no_grad(): + + data_target_tensor = data_target_tensor.cpu().numpy() + + loader_length = len(data_loader) # nb of batch + + prediction = [] # 存储所有batch的output + + input = [] # 存储所有batch的input + + for batch_index, batch_data in enumerate(data_loader): + + encoder_inputs, labels = batch_data + + input.append(encoder_inputs[:, :, 0:1].cpu().numpy()) # (batch, T', 1) + + outputs = net(encoder_inputs) + + prediction.append(outputs.detach().cpu().numpy()) + + if batch_index % 100 == 0: + print('predicting data set batch %s / %s' % (batch_index + 1, loader_length)) + + input = np.concatenate(input, 0) + + input = re_normalization(input, _mean, _std) + + prediction = np.concatenate(prediction, 0) # (batch, T', 1) + + print('input:', input.shape) + print('prediction:', prediction.shape) + print('data_target_tensor:', data_target_tensor.shape) + output_filename = os.path.join(params_path, 'output_epoch_%s_%s' % (global_step, type)) + np.savez(output_filename, input=input, prediction=prediction, data_target_tensor=data_target_tensor) + + # 计算误差 + excel_list = [] + prediction_length = prediction.shape[2] + + for i in range(prediction_length): + assert data_target_tensor.shape[0] == prediction.shape[0] + print('current epoch: %s, predict %s points' % (global_step, i)) + if metric_method == 'mask': + mae = masked_mae_test(data_target_tensor[:, :, i], prediction[:, :, i],0.0) + rmse = masked_rmse_test(data_target_tensor[:, :, i], prediction[:, :, i],0.0) + mape = masked_mape_np(data_target_tensor[:, :, i], prediction[:, :, i], 0) + else : + mae = mean_absolute_error(data_target_tensor[:, :, i], prediction[:, :, i]) + rmse = mean_squared_error(data_target_tensor[:, :, i], prediction[:, :, i]) ** 0.5 + mape = masked_mape_np(data_target_tensor[:, :, i], prediction[:, :, i], 0) + print('MAE: %.2f' % (mae)) + print('RMSE: %.2f' % (rmse)) + print('MAPE: %.2f' % (mape)) + excel_list.extend([mae, rmse, mape]) + + # print overall results + if metric_method == 'mask': + mae = masked_mae_test(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1), 0.0) + rmse = masked_rmse_test(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1), 0.0) + mape = masked_mape_np(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1), 0) + else : + mae = mean_absolute_error(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1)) + rmse = mean_squared_error(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1)) ** 0.5 + mape = masked_mape_np(data_target_tensor.reshape(-1, 1), prediction.reshape(-1, 1), 0) + print('all MAE: %.2f' % (mae)) + print('all RMSE: %.2f' % (rmse)) + print('all MAPE: %.2f' % (mape)) + excel_list.extend([mae, rmse, mape]) + print(excel_list) + + diff --git a/code/model.py b/code/model.py new file mode 100644 index 0000000000000000000000000000000000000000..68551eb7a927d89834dc67fec275654f19ed4db2 --- /dev/null +++ b/code/model.py @@ -0,0 +1,90 @@ +from functools import partial +import sys + +sys.path.append("lib") +from lib.metrics import sce_loss +import torch +import torch.nn as nn +import torch.nn.functional as F +import dgl.nn as dglnn + + +class GMae(nn.Module): + def __init__(self, encoder, decoder, + in_dim, hidden_dim, out_dim, mask_rate=0.3, replace_rate=0.1, alpha_l=2, + embedding_layer_classes=5, embedding_layer_dim=4): + super(GMae, self).__init__() + self.Z_embedding = nn.Embedding(embedding_layer_classes, embedding_layer_dim) + self.encoder = encoder + self.decoder = decoder + self.mask_rate = mask_rate + self.replace_rate = replace_rate + self.alpha_l = alpha_l + self.in_dim = in_dim + self.hidden_dim = hidden_dim + self.out_dim = out_dim + self.embedding_layer_classes = embedding_layer_classes + self.embedding_layer_dim = embedding_layer_dim + self.enc_mask_token = nn.Parameter(torch.zeros(1, in_dim)) + self.criterion = partial(sce_loss, alpha=alpha_l) + self.encoder_to_decoder = nn.Linear(hidden_dim, hidden_dim, bias=False) + + def encode_atom_index(self, Z_index): + return self.Z_embedding(Z_index) + + def encoding_mask_noise(self, g, x, mask_rate=0.3): + num_nodes = g.num_nodes() + perm = torch.randperm(num_nodes, device=x.device) + # random masking + num_mask_nodes = int(mask_rate * num_nodes) + mask_nodes = perm[: num_mask_nodes] + keep_nodes = perm[num_mask_nodes:] + + if self.replace_rate > 0: + num_noise_nodes = int(self.replace_rate * num_mask_nodes) + perm_mask = torch.randperm(num_mask_nodes, device=x.device) + token_nodes = mask_nodes[perm_mask[: int((1 - self.replace_rate) * num_mask_nodes)]] + noise_nodes = mask_nodes[perm_mask[-int(self.replace_rate * num_mask_nodes):]] + noise_to_be_chosen = torch.randperm(num_nodes, device=x.device)[:num_noise_nodes] + out_x = x.clone() + out_x[token_nodes] = 0.0 + out_x[noise_nodes] = x[noise_to_be_chosen] + else: + out_x = x.clone() + token_nodes = mask_nodes + out_x[mask_nodes] = 0.0 + + out_x[token_nodes] += self.enc_mask_token + use_g = g.clone() + + return use_g, out_x, (mask_nodes, keep_nodes) + + def mask_attr_prediction(self, g, x): + use_g, use_x, (mask_nodes, keep_nodes) = self.encoding_mask_noise(g, x, self.mask_rate) + enc_rep = self.encoder(use_g, use_x) + # ---- attribute reconstruction ---- + rep = self.encoder_to_decoder(enc_rep) + recon = self.decoder(use_g, rep) + x_init = x[mask_nodes] + x_rec = recon[mask_nodes] + loss = self.criterion(x_rec, x_init) + return loss + + def embed(self, g, x): + rep = self.encoder(g, x) + return rep + + +class SimpleGnn(nn.Module): + def __init__(self, in_feats, hid_feats, out_feats): + super().__init__() + self.conv1 = dglnn.SAGEConv( + in_feats=in_feats, out_feats=hid_feats, aggregator_type="mean") + self.conv2 = dglnn.SAGEConv( + in_feats=hid_feats, out_feats=out_feats, aggregator_type="mean") + + def forward(self, graph, inputs): + h = self.conv1(graph, inputs) + h = F.relu(h) + h = self.conv2(graph, h) + return h diff --git a/code/prepare_QM9_dataset.py b/code/prepare_QM9_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..a4119fd70c5ddb3dcdc9636baf635675aa66ee4e --- /dev/null +++ b/code/prepare_QM9_dataset.py @@ -0,0 +1,48 @@ +import argparse +import os +import time + +from dgl.data import QM9Dataset +from dgl.dataloading import GraphDataLoader +from rdkit import Chem +from rdkit import RDLogger; +from torch.utils.data import Dataset +import torch.nn.functional as F +from tqdm import tqdm +import ast + +from QM9_dataset_class import PreprocessedQM9Dataset + +RDLogger.DisableLog('rdApp.*') +import torch +import torch.nn as nn +import torch.optim as optim + + +QM9_label_keys = ['mu','alpha','homo','lumo','gap','r2','zpve','U0','U','H','G','Cv'] + + + +def prepare_main(label_keys=None, cutoff=5.0,save_path="dataset"): + assert save_path !="","save_path shouldn't be empty" + if label_keys is None: + raise ValueError('label_keys cannot be None') + for label_key in label_keys: + if label_key not in QM9_label_keys: + raise ValueError('label_key must be in QM9_label_keys,refer:https://docs.dgl.ai/en/0.8.x/generated/dgl.data.QM9Dataset.html') + dataset = QM9Dataset(label_keys=label_keys, cutoff=5.0) + dataset_processed = PreprocessedQM9Dataset(dataset) + print("Store processed QM9 dataset:",save_path) + dataset_processed.save_dataset("dataset") + return dataset_processed + +def main(): + parser = argparse.ArgumentParser(description="Prepare QM9 dataset") + parser.add_argument('--label_keys', nargs='+', help="label keys in QM9 dataset,like 'mu' 'gap'....") + parser.add_argument('--cutoff', type=float, default=5.0, help="cutoff for atom number") + parser.add_argument('--save_path', type=str, default="dataset", help="processed_dataset save path") + args = parser.parse_args() + prepare_main(label_keys=args.label_keys, cutoff=args.cutoff) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/code/run.py b/code/run.py new file mode 100644 index 0000000000000000000000000000000000000000..540310bba841b3da956db24260d6c14348eed14c --- /dev/null +++ b/code/run.py @@ -0,0 +1,94 @@ +import argparse +import os + +import dgl +import torch.utils.data +from dgl.dataloading import GraphDataLoader +from torch import optim +from tqdm import tqdm +from QM9_dataset_class import PreprocessedQM9Dataset +from model import SimpleGnn, GMae +import torch.nn as nn + +def train_epoch(epoch, graphLoader: torch.utils.data.DataLoader, + model: nn.Module,device, optimizer:torch.optim.Optimizer, + save_dir:str + ): + print(f"epoch {epoch} started!") + model.train() + model.encoder.train() + model.decoder.train() + model.to(device) + loss_epoch = 0 + for batch in tqdm(graphLoader): + optimizer.zero_grad() + batch_g, _ = batch + R = batch_g.ndata["R"].to(device) + # Z_index = batch_g.ndata["Z_index"].to(device) + Z_index = batch_g.ndata["Z_index"].to(device) + Z_emb = model.encode_atom_index(Z_index) + feat = torch.cat([R, Z_emb], dim=1) + batch_g = batch_g.to(device) + loss = model.mask_attr_prediction(batch_g, feat) + loss.backward() + optimizer.step() + loss_epoch += loss.item() + return loss_epoch + + +def train_loop(dataset_path, epochs, batch_size,device,save_dir): + device = torch.device(device) + dataset = PreprocessedQM9Dataset(None) + dataset.load_dataset(dataset_path) + print("Dataset loaded:", dataset_path, "Total samples:", len(dataset)) + print("Initializing dataloader") + myGLoader = GraphDataLoader(dataset, batch_size=batch_size, pin_memory=True,shuffle=False) + sage_enc = SimpleGnn(in_feats=7, hid_feats=4, out_feats=4) # 7 = R_dim(3)+Z_embedding_dim(4) + sage_dec = SimpleGnn(in_feats=4, hid_feats=4, out_feats=7) + gmae = GMae(sage_enc, sage_dec, 7, 4, 7, replace_rate=0) + optimizer = optim.Adam(gmae.parameters(), lr=1e-3) + print("Start training", "epochs:", epochs, "batch_size:", batch_size) + for epoch in range(epochs): + loss_epoch = train_epoch(epoch, myGLoader,gmae,device,optimizer,save_dir) + formatted_loss_epoch = f"{loss_epoch:.3f}" + save_path = os.path.join(save_dir,f"epoch_{epoch}",f"gmae_{formatted_loss_epoch}.pt") + save_subdir = os.path.dirname(save_path) + if not os.path.exists(save_subdir): + os.makedirs(save_subdir, exist_ok=True) + torch.save(gmae.state_dict(), save_path) + print(f"Epoch:{epoch},loss:{loss_epoch},Model saved:{save_path}") + with torch.no_grad(): + embedded_graphs = [] + print(f"Epoch:{epoch},start embedding") + gmae.eval() + gmae.encoder.eval() + for batch in tqdm(myGLoader): + batch_g, _ = batch + R = batch_g.ndata["R"].to(device) + Z_index = batch_g.ndata["Z_index"].to(device) + Z_emb = gmae.encode_atom_index(Z_index) + feat = torch.cat([R, Z_emb], dim=1) + batch_g = batch_g.to(device) + batch_g.ndata["embedding"] = gmae.embed(batch_g,feat) + unbatched_graphs = dgl.unbatch(batch_g) + embedded_graphs.extend(unbatched_graphs) + for idx,embedded_graph in enumerate(embedded_graphs): + embeddings_save_path = os.path.join(save_dir, f"epoch_{epoch}", f"embedding_{idx}.dgl") + dgl.save_graphs(embeddings_save_path, [embedded_graph]) + print(f"epoch:{epoch},embedding saved:{embeddings_save_path},total_graphs:{len(embedded_graphs)}") + + + +def main(): + parser = argparse.ArgumentParser(description="Prepare QM9 dataset") + parser.add_argument('--dataset_path', type=str, default='dataset/QM9_dataset_processed.pt') + parser.add_argument('--batch_size', type=int, default=4) + parser.add_argument('--epochs', type=int, default=10, help='number of epochs') + parser.add_argument("--device", type=str, default='cuda:0') + parser.add_argument("--save_dir", type=str, default='./model') + args = parser.parse_args() + train_loop(args.dataset_path, args.epochs, args.batch_size,args.device,args.save_dir) + + +if __name__ == '__main__': + main() diff --git a/model/epoch_0/embedding_0.dgl b/model/epoch_0/embedding_0.dgl new file mode 100644 index 0000000000000000000000000000000000000000..959f65361438434ce93b1fc38d546695a865dc4a Binary files /dev/null and b/model/epoch_0/embedding_0.dgl differ diff --git a/model/epoch_0/embedding_1.dgl b/model/epoch_0/embedding_1.dgl new file mode 100644 index 0000000000000000000000000000000000000000..3b9e6bf82de8112fcd9ba004c1d6773bfd57c303 Binary files /dev/null and b/model/epoch_0/embedding_1.dgl differ diff --git a/model/epoch_0/embedding_10.dgl b/model/epoch_0/embedding_10.dgl new file mode 100644 index 0000000000000000000000000000000000000000..d72e7fa98895a360ab5e3806a70f4755584b9a28 Binary files /dev/null and b/model/epoch_0/embedding_10.dgl differ diff --git a/model/epoch_0/embedding_100.dgl b/model/epoch_0/embedding_100.dgl new file mode 100644 index 0000000000000000000000000000000000000000..8aadbae60a33820f694180edb9cf4be5477e2d66 Binary files /dev/null and b/model/epoch_0/embedding_100.dgl differ diff --git a/model/epoch_0/embedding_1000.dgl b/model/epoch_0/embedding_1000.dgl new file mode 100644 index 0000000000000000000000000000000000000000..ddf6c3048073b2554ffa7921ca7f474a3e2977c1 Binary files /dev/null and b/model/epoch_0/embedding_1000.dgl differ diff --git a/model/epoch_0/embedding_10000.dgl b/model/epoch_0/embedding_10000.dgl new file mode 100644 index 0000000000000000000000000000000000000000..0df012c64888ae3ab3ad53386735ea2cc14c890a Binary files /dev/null and b/model/epoch_0/embedding_10000.dgl differ diff --git a/model/epoch_0/embedding_100000.dgl b/model/epoch_0/embedding_100000.dgl new file mode 100644 index 0000000000000000000000000000000000000000..72afc700cf0938198e641d057c804b4f837b99df Binary files /dev/null and b/model/epoch_0/embedding_100000.dgl differ diff --git a/model/epoch_0/embedding_100001.dgl b/model/epoch_0/embedding_100001.dgl new file mode 100644 index 0000000000000000000000000000000000000000..1b917af3b8b3ba2486b29c988c688a52bfbf0fe0 Binary files /dev/null and b/model/epoch_0/embedding_100001.dgl differ diff --git a/model/epoch_0/embedding_100002.dgl b/model/epoch_0/embedding_100002.dgl new file mode 100644 index 0000000000000000000000000000000000000000..f4d59a92b35beb95bb6526bfe6dfc50f1e065865 Binary files /dev/null and b/model/epoch_0/embedding_100002.dgl differ diff --git a/model/epoch_0/embedding_100003.dgl b/model/epoch_0/embedding_100003.dgl new file mode 100644 index 0000000000000000000000000000000000000000..7198c7c3031fd16c3a19e2628d3dd95e52c82f78 Binary files /dev/null and b/model/epoch_0/embedding_100003.dgl differ diff --git a/model/epoch_0/embedding_100004.dgl b/model/epoch_0/embedding_100004.dgl new file mode 100644 index 0000000000000000000000000000000000000000..06ba06f10b23c0d80016c23a39d8b7185ebbd881 Binary files /dev/null and b/model/epoch_0/embedding_100004.dgl differ diff --git a/model/epoch_0/embedding_100005.dgl b/model/epoch_0/embedding_100005.dgl new file mode 100644 index 0000000000000000000000000000000000000000..5a1a446b7d6b555597b7637dbc202c63ab60df3a Binary files /dev/null and b/model/epoch_0/embedding_100005.dgl differ diff --git a/model/epoch_0/embedding_100006.dgl b/model/epoch_0/embedding_100006.dgl new file mode 100644 index 0000000000000000000000000000000000000000..2abcbb1d5394d21a494b336417e58aae2d563010 Binary files /dev/null and b/model/epoch_0/embedding_100006.dgl differ diff --git a/model/epoch_0/embedding_100007.dgl b/model/epoch_0/embedding_100007.dgl new file mode 100644 index 0000000000000000000000000000000000000000..083613db7573f6571e087c1c673c67873fe1776a Binary files /dev/null and b/model/epoch_0/embedding_100007.dgl differ diff --git a/model/epoch_0/embedding_100008.dgl b/model/epoch_0/embedding_100008.dgl new file mode 100644 index 0000000000000000000000000000000000000000..15f023a5b4938baf47323b5d484c3d39be49075e Binary files /dev/null and b/model/epoch_0/embedding_100008.dgl differ diff --git a/model/epoch_0/embedding_100009.dgl b/model/epoch_0/embedding_100009.dgl new file mode 100644 index 0000000000000000000000000000000000000000..11a4b471a1ea6a84253319446cb3429925aeb013 Binary files /dev/null and b/model/epoch_0/embedding_100009.dgl differ diff --git a/model/epoch_0/embedding_10001.dgl b/model/epoch_0/embedding_10001.dgl new file mode 100644 index 0000000000000000000000000000000000000000..3d8cc9d634260eeb0652ab24f6d511074dab38ba Binary files /dev/null and b/model/epoch_0/embedding_10001.dgl differ diff --git a/model/epoch_0/embedding_100010.dgl b/model/epoch_0/embedding_100010.dgl new file mode 100644 index 0000000000000000000000000000000000000000..6ce97be8c5a8304cc20b3d701db78f6bec1dc050 Binary files /dev/null and b/model/epoch_0/embedding_100010.dgl differ diff --git a/model/epoch_0/embedding_100011.dgl b/model/epoch_0/embedding_100011.dgl new file mode 100644 index 0000000000000000000000000000000000000000..d9515cdda469bbaff35a445ea2e5b94966554454 Binary files /dev/null and b/model/epoch_0/embedding_100011.dgl differ diff --git a/model/epoch_0/embedding_100012.dgl b/model/epoch_0/embedding_100012.dgl new file mode 100644 index 0000000000000000000000000000000000000000..ba409c5cee90ae6d52b3b97591ca8f1073599694 Binary files /dev/null and b/model/epoch_0/embedding_100012.dgl differ diff --git a/model/epoch_0/embedding_100013.dgl b/model/epoch_0/embedding_100013.dgl new file mode 100644 index 0000000000000000000000000000000000000000..edd9da1a7eb038ee04b1757ceb6bd038379b162d Binary files /dev/null and b/model/epoch_0/embedding_100013.dgl differ diff --git a/model/epoch_0/embedding_100014.dgl b/model/epoch_0/embedding_100014.dgl new file mode 100644 index 0000000000000000000000000000000000000000..ec4b251ed2df65316702c53dea55f37aed4bea60 Binary files /dev/null and b/model/epoch_0/embedding_100014.dgl differ diff --git a/model/epoch_0/embedding_100015.dgl b/model/epoch_0/embedding_100015.dgl new file mode 100644 index 0000000000000000000000000000000000000000..bf1562d36a966978f387beae02ed2213c2e7e75f Binary files /dev/null and b/model/epoch_0/embedding_100015.dgl differ diff --git a/model/epoch_0/embedding_100016.dgl b/model/epoch_0/embedding_100016.dgl new file mode 100644 index 0000000000000000000000000000000000000000..53235bdf6a61011bd7d606e678b21075dd64de7d Binary files /dev/null and b/model/epoch_0/embedding_100016.dgl differ diff --git a/model/epoch_0/embedding_100017.dgl b/model/epoch_0/embedding_100017.dgl new file mode 100644 index 0000000000000000000000000000000000000000..57edd3831af49fd02b4a3f3369943e00258d564f Binary files /dev/null and b/model/epoch_0/embedding_100017.dgl differ diff --git a/model/epoch_0/embedding_100018.dgl b/model/epoch_0/embedding_100018.dgl new file mode 100644 index 0000000000000000000000000000000000000000..d645f60dc4823426e9c859a6fb3e32cd3c99d410 Binary files /dev/null and b/model/epoch_0/embedding_100018.dgl differ diff --git a/model/epoch_0/embedding_100019.dgl b/model/epoch_0/embedding_100019.dgl new file mode 100644 index 0000000000000000000000000000000000000000..437dd4d5d0a5f1f9eea63699915d53ed86606b8a Binary files /dev/null and b/model/epoch_0/embedding_100019.dgl differ diff --git a/model/epoch_0/embedding_10002.dgl b/model/epoch_0/embedding_10002.dgl new file mode 100644 index 0000000000000000000000000000000000000000..add4734bb855829bcf984dea71b4047701a2e9e0 Binary files /dev/null and b/model/epoch_0/embedding_10002.dgl differ diff --git a/model/epoch_0/embedding_100020.dgl b/model/epoch_0/embedding_100020.dgl new file mode 100644 index 0000000000000000000000000000000000000000..2f5bc9174d6580e0e48e72c4c4347efe65fb2aa0 Binary files /dev/null and b/model/epoch_0/embedding_100020.dgl differ diff --git a/model/epoch_0/embedding_100021.dgl b/model/epoch_0/embedding_100021.dgl new file mode 100644 index 0000000000000000000000000000000000000000..53589daacad6cfbd1d58ee5fe1515e7127e57ab9 Binary files /dev/null and b/model/epoch_0/embedding_100021.dgl differ diff --git a/model/epoch_0/embedding_100022.dgl b/model/epoch_0/embedding_100022.dgl new file mode 100644 index 0000000000000000000000000000000000000000..7ea86fc53b8b394d422434ee9e29813a8a243239 Binary files /dev/null and b/model/epoch_0/embedding_100022.dgl differ diff --git a/model/epoch_0/embedding_100023.dgl b/model/epoch_0/embedding_100023.dgl new file mode 100644 index 0000000000000000000000000000000000000000..886496f770cc965b432e31ddb0062bdca5321d7f Binary files /dev/null and b/model/epoch_0/embedding_100023.dgl differ diff --git a/model/epoch_0/embedding_100024.dgl b/model/epoch_0/embedding_100024.dgl new file mode 100644 index 0000000000000000000000000000000000000000..2a541498e739b1c725fdba618c096cf32580ba11 Binary files /dev/null and b/model/epoch_0/embedding_100024.dgl differ diff --git a/model/epoch_0/embedding_100025.dgl b/model/epoch_0/embedding_100025.dgl new file mode 100644 index 0000000000000000000000000000000000000000..85940d9778e686a407ec5c3d417c38ce4c72c700 Binary files /dev/null and b/model/epoch_0/embedding_100025.dgl differ diff --git a/model/epoch_0/embedding_100031.dgl b/model/epoch_0/embedding_100031.dgl new file mode 100644 index 0000000000000000000000000000000000000000..262681d685f4973740599d14d6307731305fcc19 Binary files /dev/null and b/model/epoch_0/embedding_100031.dgl differ diff --git a/model/epoch_0/embedding_100036.dgl b/model/epoch_0/embedding_100036.dgl new file mode 100644 index 0000000000000000000000000000000000000000..7d625a3fa7009ad2c804dea8e60617375134232b Binary files /dev/null and b/model/epoch_0/embedding_100036.dgl differ diff --git a/model/epoch_0/embedding_100037.dgl b/model/epoch_0/embedding_100037.dgl new file mode 100644 index 0000000000000000000000000000000000000000..c6f4c98b7487ce55170347159009ef5b775fec1a Binary files /dev/null and b/model/epoch_0/embedding_100037.dgl differ diff --git a/model/epoch_0/embedding_100038.dgl b/model/epoch_0/embedding_100038.dgl new file mode 100644 index 0000000000000000000000000000000000000000..55498ab8bf215dde05a42c190f611dadae19d682 Binary files /dev/null and b/model/epoch_0/embedding_100038.dgl differ diff --git a/model/epoch_0/embedding_100039.dgl b/model/epoch_0/embedding_100039.dgl new file mode 100644 index 0000000000000000000000000000000000000000..eea92bfaafd6ee2a0192ef9a1ff207752b2119c6 Binary files /dev/null and b/model/epoch_0/embedding_100039.dgl differ diff --git a/model/epoch_0/embedding_10004.dgl b/model/epoch_0/embedding_10004.dgl new file mode 100644 index 0000000000000000000000000000000000000000..48b7bc264a6340d2f801f86b344976fcb4fd9024 Binary files /dev/null and b/model/epoch_0/embedding_10004.dgl differ diff --git a/model/epoch_0/embedding_100040.dgl b/model/epoch_0/embedding_100040.dgl new file mode 100644 index 0000000000000000000000000000000000000000..9568920224f5a2c36223f9c84d33f2414011f5ca Binary files /dev/null and b/model/epoch_0/embedding_100040.dgl differ diff --git a/model/epoch_0/embedding_100041.dgl b/model/epoch_0/embedding_100041.dgl new file mode 100644 index 0000000000000000000000000000000000000000..ac38f82b3f306de87f9bba112be6ea493286cdfd Binary files /dev/null and b/model/epoch_0/embedding_100041.dgl differ diff --git a/model/epoch_0/embedding_100042.dgl b/model/epoch_0/embedding_100042.dgl new file mode 100644 index 0000000000000000000000000000000000000000..75564268985f27d27f1e9f31f636b184687636c3 Binary files /dev/null and b/model/epoch_0/embedding_100042.dgl differ diff --git a/model/epoch_0/embedding_100044.dgl b/model/epoch_0/embedding_100044.dgl new file mode 100644 index 0000000000000000000000000000000000000000..84bc7b4b26ed4ccbe6c99f916731824a932c22e2 Binary files /dev/null and b/model/epoch_0/embedding_100044.dgl differ diff --git a/model/epoch_0/embedding_100080.dgl b/model/epoch_0/embedding_100080.dgl new file mode 100644 index 0000000000000000000000000000000000000000..90bd9ffee35d9167a8d149936616eb7fdf278e58 Binary files /dev/null and b/model/epoch_0/embedding_100080.dgl differ diff --git a/model/epoch_0/embedding_100081.dgl b/model/epoch_0/embedding_100081.dgl new file mode 100644 index 0000000000000000000000000000000000000000..777599d46ee66f4b9a280b634bade97a77d0e5d4 Binary files /dev/null and b/model/epoch_0/embedding_100081.dgl differ diff --git a/model/epoch_0/embedding_100082.dgl b/model/epoch_0/embedding_100082.dgl new file mode 100644 index 0000000000000000000000000000000000000000..7020a9d24cb324770452a0466324e65065edf6d2 Binary files /dev/null and b/model/epoch_0/embedding_100082.dgl differ diff --git a/model/epoch_0/embedding_100083.dgl b/model/epoch_0/embedding_100083.dgl new file mode 100644 index 0000000000000000000000000000000000000000..89a45a8212004fa83c462fb464bcbbe54af5c9b3 Binary files /dev/null and b/model/epoch_0/embedding_100083.dgl differ diff --git a/model/epoch_0/embedding_100084.dgl b/model/epoch_0/embedding_100084.dgl new file mode 100644 index 0000000000000000000000000000000000000000..cb4a350961454e19eadfc71e910fd67337b7b627 Binary files /dev/null and b/model/epoch_0/embedding_100084.dgl differ diff --git a/model/epoch_0/embedding_100085.dgl b/model/epoch_0/embedding_100085.dgl new file mode 100644 index 0000000000000000000000000000000000000000..fea242daffb48a91d162768e0f58e2307e048f84 Binary files /dev/null and b/model/epoch_0/embedding_100085.dgl differ diff --git a/model/epoch_0/embedding_100086.dgl b/model/epoch_0/embedding_100086.dgl new file mode 100644 index 0000000000000000000000000000000000000000..aa79f819e19cc04f440f85263c767e6fd0c039d4 Binary files /dev/null and b/model/epoch_0/embedding_100086.dgl differ diff --git a/model/epoch_0/embedding_100087.dgl b/model/epoch_0/embedding_100087.dgl new file mode 100644 index 0000000000000000000000000000000000000000..d583821abba2abc25eda9e8382873ea69e3d3b11 Binary files /dev/null and b/model/epoch_0/embedding_100087.dgl differ diff --git a/model/epoch_0/embedding_100088.dgl b/model/epoch_0/embedding_100088.dgl new file mode 100644 index 0000000000000000000000000000000000000000..d5f880ab81a5fd627eb34823337f24652f711dce Binary files /dev/null and b/model/epoch_0/embedding_100088.dgl differ diff --git a/model/epoch_0/embedding_100089.dgl b/model/epoch_0/embedding_100089.dgl new file mode 100644 index 0000000000000000000000000000000000000000..c4a98eff7cc0c352dc20293ef53bcab647f9f80e Binary files /dev/null and b/model/epoch_0/embedding_100089.dgl differ