Spaces:
Sleeping
Sleeping
updated model
Browse files- dataset/__init__.py +0 -0
- dataset/ogbn_link_pred_dataset.py +218 -18
- galis_app.py +7 -4
- llm/__init__.py +0 -0
- llm/related_work_generator.py +0 -0
- model/__init__.py +0 -0
- model/cos-sim.py +104 -0
- model/mlp.py +137 -0
- predictor/__init__.py +0 -0
- predictor/link_predictor.py +54 -61
- pyproject.toml +0 -0
dataset/__init__.py
CHANGED
|
File without changes
|
dataset/ogbn_link_pred_dataset.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import torch
|
| 4 |
from ogb.nodeproppred import PygNodePropPredDataset
|
| 5 |
from torch_geometric.transforms import RandomLinkSplit
|
| 6 |
-
from torch_geometric.loader import LinkNeighborLoader
|
| 7 |
from torch_geometric.data import Data
|
| 8 |
|
| 9 |
import requests
|
|
@@ -23,9 +25,8 @@ class OGBNLinkPredDataset:
|
|
| 23 |
self._download_abstracts()
|
| 24 |
self.corpus = self._load_corpus()
|
| 25 |
|
| 26 |
-
self.
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
|
| 30 |
def _download_abstracts(self):
|
| 31 |
target_dir = os.path.join(self.root, "mapping")
|
|
@@ -38,22 +39,17 @@ class OGBNLinkPredDataset:
|
|
| 38 |
os.makedirs(target_dir, exist_ok=True)
|
| 39 |
|
| 40 |
try:
|
| 41 |
-
print(f"Downloading from {url}...")
|
| 42 |
response = requests.get(url, stream=True)
|
| 43 |
response.raise_for_status()
|
| 44 |
with open(gz_path, "wb") as f:
|
| 45 |
for chunk in response.iter_content(chunk_size=8192):
|
| 46 |
f.write(chunk)
|
| 47 |
-
print(f"File downloaded to: {gz_path}")
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
with open(tsv_path, 'wb') as f_out:
|
| 52 |
shutil.copyfileobj(f_in, f_out)
|
| 53 |
-
print(f"File extracted to: {tsv_path}")
|
| 54 |
|
| 55 |
os.remove(gz_path)
|
| 56 |
-
print(f"Removed temporary file: {gz_path}")
|
| 57 |
|
| 58 |
except requests.exceptions.RequestException as e:
|
| 59 |
print(f"Error downloading file: {e}")
|
|
@@ -80,22 +76,226 @@ class OGBNLinkPredDataset:
|
|
| 80 |
+ "\n "
|
| 81 |
+ df_text_aligned["abstract"].fillna("")
|
| 82 |
).tolist()
|
| 83 |
-
print(f"Corpus created with {len(corpus)} documents.")
|
| 84 |
return corpus
|
| 85 |
except FileNotFoundError:
|
| 86 |
print("Error: titleabs.tsv not found. Could not create corpus.")
|
| 87 |
return []
|
| 88 |
|
| 89 |
-
def
|
| 90 |
transform = RandomLinkSplit(
|
| 91 |
-
num_val=val_size,
|
| 92 |
-
num_test=test_size,
|
| 93 |
is_undirected=False,
|
| 94 |
-
add_negative_train_samples=
|
|
|
|
| 95 |
)
|
| 96 |
train_split, val_split, test_split = transform(self.data)
|
| 97 |
-
print("Data successfully split into train, validation, and test sets.")
|
| 98 |
return train_split, val_split, test_split
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
def get_splits(self) -> tuple[Data, Data, Data]:
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import random
|
| 4 |
+
from torch_sparse import SparseTensor
|
| 5 |
import pandas as pd
|
| 6 |
import torch
|
| 7 |
from ogb.nodeproppred import PygNodePropPredDataset
|
| 8 |
from torch_geometric.transforms import RandomLinkSplit
|
|
|
|
| 9 |
from torch_geometric.data import Data
|
| 10 |
|
| 11 |
import requests
|
|
|
|
| 25 |
self._download_abstracts()
|
| 26 |
self.corpus = self._load_corpus()
|
| 27 |
|
| 28 |
+
self.val_size = val_size
|
| 29 |
+
self.test_size = test_size
|
|
|
|
| 30 |
|
| 31 |
def _download_abstracts(self):
|
| 32 |
target_dir = os.path.join(self.root, "mapping")
|
|
|
|
| 39 |
os.makedirs(target_dir, exist_ok=True)
|
| 40 |
|
| 41 |
try:
|
|
|
|
| 42 |
response = requests.get(url, stream=True)
|
| 43 |
response.raise_for_status()
|
| 44 |
with open(gz_path, "wb") as f:
|
| 45 |
for chunk in response.iter_content(chunk_size=8192):
|
| 46 |
f.write(chunk)
|
|
|
|
| 47 |
|
| 48 |
+
with gzip.open(gz_path, "rb") as f_in:
|
| 49 |
+
with open(tsv_path, "wb") as f_out:
|
|
|
|
| 50 |
shutil.copyfileobj(f_in, f_out)
|
|
|
|
| 51 |
|
| 52 |
os.remove(gz_path)
|
|
|
|
| 53 |
|
| 54 |
except requests.exceptions.RequestException as e:
|
| 55 |
print(f"Error downloading file: {e}")
|
|
|
|
| 76 |
+ "\n "
|
| 77 |
+ df_text_aligned["abstract"].fillna("")
|
| 78 |
).tolist()
|
|
|
|
| 79 |
return corpus
|
| 80 |
except FileNotFoundError:
|
| 81 |
print("Error: titleabs.tsv not found. Could not create corpus.")
|
| 82 |
return []
|
| 83 |
|
| 84 |
+
def get_splits(self) -> tuple[Data, Data, Data]:
|
| 85 |
transform = RandomLinkSplit(
|
| 86 |
+
num_val=self.val_size,
|
| 87 |
+
num_test=self.test_size,
|
| 88 |
is_undirected=False,
|
| 89 |
+
add_negative_train_samples=True,
|
| 90 |
+
neg_sampling_ratio=1.0,
|
| 91 |
)
|
| 92 |
train_split, val_split, test_split = transform(self.data)
|
|
|
|
| 93 |
return train_split, val_split, test_split
|
| 94 |
|
| 95 |
+
|
| 96 |
+
class OGBNLinkPredNegDataset(OGBNLinkPredDataset):
|
| 97 |
+
"""Degree similar hard negatives sampling"""
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self, root_dir: str = "data", val_size: float = 0.1, test_size: float = 0.2
|
| 101 |
+
):
|
| 102 |
+
super().__init__(root_dir, val_size, test_size)
|
| 103 |
+
self.degree_tol = 0
|
| 104 |
+
|
| 105 |
def get_splits(self) -> tuple[Data, Data, Data]:
|
| 106 |
+
transform = RandomLinkSplit(
|
| 107 |
+
num_val=self.val_size,
|
| 108 |
+
num_test=self.test_size,
|
| 109 |
+
is_undirected=False,
|
| 110 |
+
add_negative_train_samples=False,
|
| 111 |
+
neg_sampling_ratio=0.0,
|
| 112 |
+
)
|
| 113 |
+
train_split, val_split, test_split = transform(self.data)
|
| 114 |
+
|
| 115 |
+
print("Generating hard negatives...")
|
| 116 |
+
adj_matrix = SparseTensor.from_edge_index(
|
| 117 |
+
train_split.edge_index, # only from train_split
|
| 118 |
+
sparse_sizes=(self.data.num_nodes, self.data.num_nodes),
|
| 119 |
+
)
|
| 120 |
+
self.degrees = adj_matrix.sum(dim=0).to(torch.long)
|
| 121 |
+
# to prevent creating negative edges that are positive in other split
|
| 122 |
+
self.all_edge_set = set(zip(*self.data.edge_index.tolist()))
|
| 123 |
+
train_split = self._add_balanced_negs(train_split)
|
| 124 |
+
val_split = self._add_balanced_negs(val_split)
|
| 125 |
+
test_split = self._add_balanced_negs(test_split)
|
| 126 |
+
return train_split, val_split, test_split
|
| 127 |
+
|
| 128 |
+
def _add_balanced_negs(self, split_data):
|
| 129 |
+
assert (split_data.edge_label == 1).all(), "Expected only positive edges"
|
| 130 |
+
|
| 131 |
+
pos_edges = split_data.edge_label_index
|
| 132 |
+
pos_list = pos_edges.t().tolist()
|
| 133 |
+
num_negs = pos_edges.size(1)
|
| 134 |
+
|
| 135 |
+
negs = []
|
| 136 |
+
for _ in range(num_negs):
|
| 137 |
+
u, v_orig = random.choice(pos_list)
|
| 138 |
+
target_deg = int(self.degrees[v_orig])
|
| 139 |
+
|
| 140 |
+
found = False
|
| 141 |
+
for _ in range(20):
|
| 142 |
+
w = random.randrange(self.data.num_nodes)
|
| 143 |
+
if (
|
| 144 |
+
(u, w) not in self.all_edge_set
|
| 145 |
+
and w != u
|
| 146 |
+
and abs(int(self.degrees[w]) - target_deg) <= self.degree_tol
|
| 147 |
+
):
|
| 148 |
+
negs.append((u, w))
|
| 149 |
+
found = True
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
if not found:
|
| 153 |
+
while True:
|
| 154 |
+
w = random.randrange(self.data.num_nodes)
|
| 155 |
+
if (u, w) not in self.all_edge_set and w != u:
|
| 156 |
+
negs.append((u, w))
|
| 157 |
+
break
|
| 158 |
+
|
| 159 |
+
neg_edges = torch.tensor(negs, dtype=torch.long).t()
|
| 160 |
+
N = pos_edges.size(1)
|
| 161 |
+
|
| 162 |
+
split_data.edge_label_index = torch.cat([pos_edges, neg_edges], dim=1)
|
| 163 |
+
split_data.edge_label = torch.cat(
|
| 164 |
+
[
|
| 165 |
+
torch.ones(N, dtype=torch.long, device=pos_edges.device),
|
| 166 |
+
torch.zeros(N, dtype=torch.long, device=pos_edges.device),
|
| 167 |
+
]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
return split_data
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# class OGBNLinkPredNegDataset2(OGBNLinkPredDataset):
|
| 174 |
+
# """Degree and semantically similar hard negatives sampling"""
|
| 175 |
+
#
|
| 176 |
+
# def __init__(self, root_dir="data", val_size=0.1, test_size=0.2):
|
| 177 |
+
# super().__init__(root_dir, val_size, test_size)
|
| 178 |
+
#
|
| 179 |
+
# def get_splits(self) -> tuple[Data, Data, Data]:
|
| 180 |
+
# transform = RandomLinkSplit(
|
| 181 |
+
# num_val=self.val_size,
|
| 182 |
+
# num_test=self.test_size,
|
| 183 |
+
# is_undirected=False,
|
| 184 |
+
# add_negative_train_samples=False,
|
| 185 |
+
# neg_sampling_ratio=0.0,
|
| 186 |
+
# )
|
| 187 |
+
# train_split, val_split, test_split = transform(self.data)
|
| 188 |
+
#
|
| 189 |
+
# print("Generating semantic hard negatives...")
|
| 190 |
+
# train_split = self._add_balanced_negs(train_split)
|
| 191 |
+
# val_split = self._add_balanced_negs(val_split)
|
| 192 |
+
# test_split = self._add_balanced_negs(test_split)
|
| 193 |
+
# return train_split, val_split, test_split
|
| 194 |
+
#
|
| 195 |
+
# def _add_balanced_negs(self, split_data):
|
| 196 |
+
# assert (split_data.edge_label == 1).all(), "Expected only positive edges"
|
| 197 |
+
#
|
| 198 |
+
# BS = 1_000
|
| 199 |
+
# B = self.data.x.to("cuda", dtype=torch.bfloat16) # (num_nodes, dim)
|
| 200 |
+
# B = F.normalize(B, p=2, dim=1)
|
| 201 |
+
# K = 100
|
| 202 |
+
#
|
| 203 |
+
# pos_edges = split_data.edge_label_index
|
| 204 |
+
# adj_matrix = SparseTensor.from_edge_index(
|
| 205 |
+
# split_data.edge_index,
|
| 206 |
+
# sparse_sizes=(self.data.num_nodes, self.data.num_nodes),
|
| 207 |
+
# )
|
| 208 |
+
# degrees = adj_matrix.sum(dim=0).to("cuda")
|
| 209 |
+
#
|
| 210 |
+
# topk_val = torch.empty((BS, K), dtype=torch.bfloat16, device="cuda")
|
| 211 |
+
# topk_idx = torch.empty((BS, K), dtype=torch.int64, device="cuda")
|
| 212 |
+
#
|
| 213 |
+
# neg_edges = []
|
| 214 |
+
#
|
| 215 |
+
# for i in range(0, pos_edges.shape[1], BS):
|
| 216 |
+
# batch_end = min(i + BS, pos_edges.shape[1])
|
| 217 |
+
# src_idx = pos_edges[0, i:batch_end] # (batch_size,)
|
| 218 |
+
# dst_idx = pos_edges[1, i:batch_end] # (batch_size,)
|
| 219 |
+
#
|
| 220 |
+
# A = B[src_idx] # (batch_size, dim)
|
| 221 |
+
#
|
| 222 |
+
# with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 223 |
+
# sim = torch.mm(A, B.t()) # equivalent to cos-sim
|
| 224 |
+
#
|
| 225 |
+
# # mask for similarity with itself and existing edges
|
| 226 |
+
# sim[torch.arange(len(A)), dst_idx] = -1
|
| 227 |
+
# sim[torch.arange(len(A)), src_idx] = -1
|
| 228 |
+
# # TODO: exclude edges from val&test sets
|
| 229 |
+
#
|
| 230 |
+
# torch.topk(sim, K, out=(topk_val, topk_idx))
|
| 231 |
+
# topk_idx2 = topk_idx[: len(A)]
|
| 232 |
+
#
|
| 233 |
+
# # sample degree matched negs
|
| 234 |
+
# topk_deg = degrees[topk_idx2]
|
| 235 |
+
# src_deg = degrees[src_idx]
|
| 236 |
+
#
|
| 237 |
+
# deg_diffs = torch.abs(topk_deg - src_deg.unsqueeze(1))
|
| 238 |
+
# closest_idx = torch.argmin(deg_diffs, dim=1) # (batch_size,)
|
| 239 |
+
# sampled_negs = topk_idx[
|
| 240 |
+
# torch.arange(len(A), device="cuda"), closest_idx
|
| 241 |
+
# ]
|
| 242 |
+
# neg_edges.append(sampled_negs)
|
| 243 |
+
#
|
| 244 |
+
# neg_dsts = torch.cat(neg_edges, dim=0).to("cpu")
|
| 245 |
+
# neg_edge_index = torch.stack([pos_edges[0].cpu(), neg_dsts], dim=0)
|
| 246 |
+
# edge_label_index = torch.cat([pos_edges.cpu(), neg_edge_index], dim=1)
|
| 247 |
+
# edge_label = torch.cat(
|
| 248 |
+
# [split_data.edge_label, torch.zeros(neg_dsts.shape[0])], dim=0
|
| 249 |
+
# )
|
| 250 |
+
# assert edge_label.shape[0] == edge_label_index.shape[1], (
|
| 251 |
+
# "Label and index shape mismatch"
|
| 252 |
+
# )
|
| 253 |
+
# assert len(neg_dsts) == pos_edges.shape[1], (
|
| 254 |
+
# "Expected same amount of positive and negative edges"
|
| 255 |
+
# )
|
| 256 |
+
# return Data(
|
| 257 |
+
# x=split_data.x,
|
| 258 |
+
# edge_index=edge_label,
|
| 259 |
+
# edge_label_index=edge_label_index,
|
| 260 |
+
# edge_label=edge_label,
|
| 261 |
+
# )
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
dataset = OGBNLinkPredNegDataset()
|
| 266 |
+
train, val, test = dataset.get_splits()
|
| 267 |
+
|
| 268 |
+
def extract_pos_neg_edges(split):
|
| 269 |
+
pos = split.edge_label_index[:, split.edge_label == 1]
|
| 270 |
+
neg = split.edge_label_index[:, split.edge_label == 0]
|
| 271 |
+
return pos, neg
|
| 272 |
+
|
| 273 |
+
for name, split in [("train", train), ("val", val), ("test", test)]:
|
| 274 |
+
assert split.edge_label_index.shape[0] == 2, (
|
| 275 |
+
f"{name}: edge_label_index must have 2 rows"
|
| 276 |
+
)
|
| 277 |
+
assert split.edge_label_index.shape[1] == split.edge_label.shape[0], (
|
| 278 |
+
f"{name}: label/index shape mismatch"
|
| 279 |
+
)
|
| 280 |
+
assert torch.all(0 <= split.edge_label) and torch.all(split.edge_label <= 1), (
|
| 281 |
+
f"{name}: labels not 0/1"
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
pos, neg = extract_pos_neg_edges(split)
|
| 285 |
+
assert pos.size(1) == neg.size(1), f"{name}: pos/neg count mismatch"
|
| 286 |
+
|
| 287 |
+
pos_set = set(tuple(e) for e in pos.t().tolist())
|
| 288 |
+
neg_set = set(tuple(e) for e in neg.t().tolist())
|
| 289 |
+
assert pos_set.isdisjoint(neg_set), f"{name}: pos/neg overlap"
|
| 290 |
+
|
| 291 |
+
assert all(u != v for u, v in pos_set), f"{name}: pos self-loops"
|
| 292 |
+
assert all(u != v for u, v in neg_set), f"{name}: neg self-loops"
|
| 293 |
+
|
| 294 |
+
assert len(pos_set) == pos.size(1), f"{name}: pos duplicates"
|
| 295 |
+
assert len(neg_set) == neg.size(1), f"{name}: neg duplicates"
|
| 296 |
+
|
| 297 |
+
assert pos.size(1) / neg.size(1) == 1.0 if neg.size(1) > 0 else True, (
|
| 298 |
+
f"{name}: ratio not 1.0"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
print("All asserts passed!")
|
galis_app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from pathlib import Path
|
| 2 |
import streamlit as st
|
| 3 |
-
|
| 4 |
from predictor.link_predictor import (
|
| 5 |
prepare_system,
|
| 6 |
get_citation_predictions,
|
|
@@ -9,7 +9,7 @@ from predictor.link_predictor import (
|
|
| 9 |
)
|
| 10 |
from llm.related_work_generator import generate_related_work
|
| 11 |
|
| 12 |
-
MODEL_PATH = Path("
|
| 13 |
|
| 14 |
|
| 15 |
@st.cache_resource
|
|
@@ -94,8 +94,9 @@ def app():
|
|
| 94 |
new_vector = abstract_to_vector(
|
| 95 |
abstract_input, abstract_title, st_model
|
| 96 |
)
|
|
|
|
| 97 |
probabilities = get_citation_predictions(
|
| 98 |
-
vector=new_vector,
|
| 99 |
model=gcn_model,
|
| 100 |
z_all=z_all,
|
| 101 |
num_nodes=dataset.data.num_nodes,
|
|
@@ -112,7 +113,9 @@ def app():
|
|
| 112 |
|
| 113 |
with related_work_placeholder.container():
|
| 114 |
with st.spinner("Generating related work section..."):
|
| 115 |
-
related_work = generate_related_work(
|
|
|
|
|
|
|
| 116 |
st.session_state.related_work = related_work
|
| 117 |
|
| 118 |
if st.session_state.references:
|
|
|
|
| 1 |
from pathlib import Path
|
| 2 |
import streamlit as st
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
from predictor.link_predictor import (
|
| 5 |
prepare_system,
|
| 6 |
get_citation_predictions,
|
|
|
|
| 9 |
)
|
| 10 |
from llm.related_work_generator import generate_related_work
|
| 11 |
|
| 12 |
+
MODEL_PATH = Path("model.pth")
|
| 13 |
|
| 14 |
|
| 15 |
@st.cache_resource
|
|
|
|
| 94 |
new_vector = abstract_to_vector(
|
| 95 |
abstract_input, abstract_title, st_model
|
| 96 |
)
|
| 97 |
+
|
| 98 |
probabilities = get_citation_predictions(
|
| 99 |
+
vector=F.normalize(new_vector.view(1, -1), p=2, dim=1),
|
| 100 |
model=gcn_model,
|
| 101 |
z_all=z_all,
|
| 102 |
num_nodes=dataset.data.num_nodes,
|
|
|
|
| 113 |
|
| 114 |
with related_work_placeholder.container():
|
| 115 |
with st.spinner("Generating related work section..."):
|
| 116 |
+
related_work = generate_related_work(
|
| 117 |
+
st.session_state.references
|
| 118 |
+
)
|
| 119 |
st.session_state.related_work = related_work
|
| 120 |
|
| 121 |
if st.session_state.references:
|
llm/__init__.py
CHANGED
|
File without changes
|
llm/related_work_generator.py
CHANGED
|
File without changes
|
model/__init__.py
CHANGED
|
File without changes
|
model/cos-sim.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from sklearn.metrics import roc_auc_score, average_precision_score
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
import argparse
|
| 8 |
+
from dataset.ogbn_link_pred_dataset import OGBNLinkPredDataset, OGBNLinkPredNegDataset
|
| 9 |
+
|
| 10 |
+
BATCH_SIZE_EDGES = 100_000 # edge batching for scoring
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args():
|
| 14 |
+
parser = argparse.ArgumentParser()
|
| 15 |
+
parser.add_argument(
|
| 16 |
+
"--custom-neg", action=argparse.BooleanOptionalAction, default=False
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--bert-embed", action=argparse.BooleanOptionalAction, default=False
|
| 20 |
+
)
|
| 21 |
+
return parser.parse_args()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@torch.no_grad()
|
| 25 |
+
def eval_edges_cos(global_emb, edge_index, edge_label, batch_size=BATCH_SIZE_EDGES):
|
| 26 |
+
# edge_index shape: [2, M] with GLOBAL node ids; edge_label: [M] in {0,1}
|
| 27 |
+
assert edge_index.dim() == 2 and edge_index.size(0) == 2
|
| 28 |
+
assert edge_index.max() < global_emb.size(0), "Edge node id out of range."
|
| 29 |
+
assert (edge_label == 0).any() and (edge_label == 1).any(), "Need both classes."
|
| 30 |
+
|
| 31 |
+
scores_list, labels_list = [], []
|
| 32 |
+
M = edge_index.size(1)
|
| 33 |
+
for i in range(0, M, batch_size):
|
| 34 |
+
j = min(i + batch_size, M)
|
| 35 |
+
src = edge_index[0, i:j].to(global_emb.device)
|
| 36 |
+
dst = edge_index[1, i:j].to(global_emb.device)
|
| 37 |
+
scores = (global_emb[src] * global_emb[dst]).sum(
|
| 38 |
+
dim=1
|
| 39 |
+
) # cosine (L2-normalized)
|
| 40 |
+
scores_list.append(scores.float().cpu().numpy())
|
| 41 |
+
labels_list.append(edge_label[i:j].cpu().numpy())
|
| 42 |
+
y_scores = np.concatenate(scores_list)
|
| 43 |
+
y_true = np.concatenate(labels_list)
|
| 44 |
+
roc = roc_auc_score(y_true, y_scores)
|
| 45 |
+
ap = average_precision_score(y_true, y_scores)
|
| 46 |
+
return roc, ap
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
args = parse_args()
|
| 51 |
+
USE_CUSTOM_NEG = args.custom_neg
|
| 52 |
+
USE_BERT_EMBED = args.bert_embed
|
| 53 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 54 |
+
|
| 55 |
+
# --- Load dataset + frozen embeddings ---
|
| 56 |
+
if USE_CUSTOM_NEG:
|
| 57 |
+
print("using hard negatives")
|
| 58 |
+
dataset = OGBNLinkPredNegDataset(val_size=0.1, test_size=0.2)
|
| 59 |
+
else:
|
| 60 |
+
print("using random negatives")
|
| 61 |
+
dataset = OGBNLinkPredDataset(val_size=0.1, test_size=0.2)
|
| 62 |
+
if USE_BERT_EMBED:
|
| 63 |
+
print("using BERT embeds")
|
| 64 |
+
if Path("model/embeddings.pth").exists():
|
| 65 |
+
emb = torch.load("model/embeddings.pth", map_location=DEVICE)
|
| 66 |
+
else:
|
| 67 |
+
st = SentenceTransformer("bongsoo/kpf-sbert-128d-v1", device=DEVICE)
|
| 68 |
+
emb = st.encode(
|
| 69 |
+
dataset.corpus, convert_to_tensor=True, show_progress_bar=True
|
| 70 |
+
)
|
| 71 |
+
Path("model").mkdir(parents=True, exist_ok=True)
|
| 72 |
+
torch.save(emb, "model/embeddings.pth")
|
| 73 |
+
emb = F.normalize(emb.to(DEVICE), p=2, dim=1)
|
| 74 |
+
else:
|
| 75 |
+
print("using skipgram embeds")
|
| 76 |
+
emb = dataset.data.x
|
| 77 |
+
|
| 78 |
+
train_data, val_data, test_data = dataset.get_splits()
|
| 79 |
+
|
| 80 |
+
# Sanity checks
|
| 81 |
+
for split_name, data in [
|
| 82 |
+
("train", train_data),
|
| 83 |
+
("val", val_data),
|
| 84 |
+
("test", test_data),
|
| 85 |
+
]:
|
| 86 |
+
assert data.edge_label_index.size(1) == data.edge_label.size(0), (
|
| 87 |
+
f"{split_name} size mismatch"
|
| 88 |
+
)
|
| 89 |
+
assert (data.edge_label == 0).any() and (data.edge_label == 1).any(), (
|
| 90 |
+
f"{split_name} lacks negatives"
|
| 91 |
+
)
|
| 92 |
+
assert data.edge_label_index.max() < emb.size(0), (
|
| 93 |
+
f"{split_name} has node ids >= num_nodes"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
val_roc, val_ap = eval_edges_cos(
|
| 97 |
+
emb, val_data.edge_label_index, val_data.edge_label
|
| 98 |
+
)
|
| 99 |
+
test_roc, test_ap = eval_edges_cos(
|
| 100 |
+
emb, test_data.edge_label_index, test_data.edge_label
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
print(f"Val ROC-AUC: {val_roc:.4f}, Val AP: {val_ap:.4f}")
|
| 104 |
+
print(f"Test ROC-AUC: {test_roc:.4f}, Test AP: {test_ap:.4f}")
|
model/mlp.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from sklearn.metrics import roc_auc_score, average_precision_score
|
| 5 |
+
import numpy as np
|
| 6 |
+
from dataset.ogbn_link_pred_dataset import (
|
| 7 |
+
OGBNLinkPredDataset,
|
| 8 |
+
OGBNLinkPredNegDataset,
|
| 9 |
+
# OGBNLinkPredNegDataset2,
|
| 10 |
+
)
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from sentence_transformers import SentenceTransformer
|
| 13 |
+
import argparse
|
| 14 |
+
|
| 15 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 16 |
+
BATCH_SIZE = 2048
|
| 17 |
+
NUM_EPOCHS = 50
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_args():
|
| 21 |
+
parser = argparse.ArgumentParser()
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--custom-neg", action=argparse.BooleanOptionalAction, default=False
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"--bert-embed", action=argparse.BooleanOptionalAction, default=False
|
| 27 |
+
)
|
| 28 |
+
return parser.parse_args()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# --- Feature builder ---
|
| 32 |
+
def edge_features(emb, ei):
|
| 33 |
+
u, v = ei
|
| 34 |
+
eu, ev = emb[u], emb[v]
|
| 35 |
+
return torch.cat([eu * ev, torch.abs(eu - ev)], dim=1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# --- Simple MLP ---
|
| 39 |
+
class PairMLP(nn.Module):
|
| 40 |
+
def __init__(self, in_dim, hidden=256):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.fc1 = nn.Linear(in_dim, hidden)
|
| 43 |
+
self.fc2 = nn.Linear(hidden, 1)
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
x = F.relu(self.fc1(x))
|
| 47 |
+
return self.fc2(x).squeeze(-1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# --- Training loop ---
|
| 51 |
+
def run_epoch(data, train=True):
|
| 52 |
+
model.train(train)
|
| 53 |
+
total_loss = 0
|
| 54 |
+
idx = (
|
| 55 |
+
torch.randperm(data.edge_label.size(0))
|
| 56 |
+
if train
|
| 57 |
+
else torch.arange(data.edge_label.size(0))
|
| 58 |
+
)
|
| 59 |
+
for i in range(0, len(idx), BATCH_SIZE):
|
| 60 |
+
batch_end = min(i + BATCH_SIZE, data.edge_label.size(0))
|
| 61 |
+
batch_idx = idx[i:batch_end]
|
| 62 |
+
feats = edge_features(emb, data.edge_label_index[:, batch_idx]).to(DEVICE)
|
| 63 |
+
labels = data.edge_label[batch_idx].float().to(DEVICE)
|
| 64 |
+
scores = model(feats)
|
| 65 |
+
loss = F.binary_cross_entropy_with_logits(scores, labels)
|
| 66 |
+
if train:
|
| 67 |
+
opt.zero_grad()
|
| 68 |
+
loss.backward()
|
| 69 |
+
opt.step()
|
| 70 |
+
total_loss += loss.item() * len(batch_idx)
|
| 71 |
+
return total_loss / len(idx)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@torch.no_grad()
|
| 75 |
+
def evaluate(data):
|
| 76 |
+
scores_all, labels_all = [], []
|
| 77 |
+
for i in range(0, data.edge_label.size(0), BATCH_SIZE):
|
| 78 |
+
batch_end = min(i + BATCH_SIZE, data.edge_label.size(0))
|
| 79 |
+
feats = edge_features(emb, data.edge_label_index[:, i:batch_end]).to(DEVICE)
|
| 80 |
+
labels = data.edge_label[i : i + BATCH_SIZE]
|
| 81 |
+
scores = torch.sigmoid(model(feats)).cpu().numpy()
|
| 82 |
+
scores_all.append(scores)
|
| 83 |
+
labels_all.append(labels.numpy())
|
| 84 |
+
y_scores = np.concatenate(scores_all)
|
| 85 |
+
y_true = np.concatenate(labels_all)
|
| 86 |
+
return roc_auc_score(y_true, y_scores), average_precision_score(y_true, y_scores)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
args = parse_args()
|
| 91 |
+
USE_CUSTOM_NEG = args.custom_neg
|
| 92 |
+
USE_BERT_EMBED = args.bert_embed
|
| 93 |
+
|
| 94 |
+
# --- Load dataset + frozen embeddings ---
|
| 95 |
+
if USE_CUSTOM_NEG:
|
| 96 |
+
print("using hard negatives")
|
| 97 |
+
dataset = OGBNLinkPredNegDataset(val_size=0.1, test_size=0.2)
|
| 98 |
+
else:
|
| 99 |
+
print("using random negatives")
|
| 100 |
+
dataset = OGBNLinkPredDataset(val_size=0.1, test_size=0.2)
|
| 101 |
+
if USE_BERT_EMBED:
|
| 102 |
+
print("using BERT embeds")
|
| 103 |
+
if Path("model/embeddings.pth").exists():
|
| 104 |
+
emb = torch.load("model/embeddings.pth", map_location=DEVICE)
|
| 105 |
+
else:
|
| 106 |
+
st = SentenceTransformer("bongsoo/kpf-sbert-128d-v1", device=DEVICE)
|
| 107 |
+
emb = st.encode(
|
| 108 |
+
dataset.corpus, convert_to_tensor=True, show_progress_bar=True
|
| 109 |
+
)
|
| 110 |
+
Path("model").mkdir(parents=True, exist_ok=True)
|
| 111 |
+
torch.save(emb, "model/embeddings.pth")
|
| 112 |
+
emb = emb.to(DEVICE)
|
| 113 |
+
else:
|
| 114 |
+
print("using skipgram embeds")
|
| 115 |
+
emb = dataset.data.x
|
| 116 |
+
|
| 117 |
+
train_data, val_data, test_data = dataset.get_splits()
|
| 118 |
+
|
| 119 |
+
model = PairMLP(emb.size(1) * 2).to(DEVICE)
|
| 120 |
+
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
|
| 121 |
+
|
| 122 |
+
# --- Training ---
|
| 123 |
+
best_roc, best_ap = 0.0, 0.0
|
| 124 |
+
for epoch in range(NUM_EPOCHS):
|
| 125 |
+
loss = run_epoch(train_data, train=True)
|
| 126 |
+
val_roc, val_ap = evaluate(val_data)
|
| 127 |
+
if val_roc > best_roc:
|
| 128 |
+
torch.save(
|
| 129 |
+
model.state_dict(), f"model_roc{str(val_roc)[:4].replace('.', '_')}.pth"
|
| 130 |
+
)
|
| 131 |
+
print(
|
| 132 |
+
f"Epoch {epoch + 1} | Loss {loss:.4f} | Val ROC {val_roc:.4f} | Val AP {val_ap:.4f}"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# --- Final test ---
|
| 136 |
+
test_roc, test_ap = evaluate(test_data)
|
| 137 |
+
print(f"Test ROC {test_roc:.4f} | Test AP {test_ap:.4f}")
|
predictor/__init__.py
CHANGED
|
File without changes
|
predictor/link_predictor.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
from pathlib import Path
|
| 2 |
import torch
|
|
|
|
|
|
|
|
|
|
| 3 |
import structlog
|
| 4 |
-
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
-
from model.
|
| 7 |
-
from dataset.ogbn_link_pred_dataset import OGBNLinkPredDataset
|
| 8 |
|
| 9 |
|
| 10 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -24,50 +24,33 @@ def abstract_to_vector(
|
|
| 24 |
text = title + "\n" + abstract_text
|
| 25 |
with torch.no_grad():
|
| 26 |
vector = st_model.encode(text, convert_to_tensor=True, device=DEVICE)
|
| 27 |
-
return vector
|
| 28 |
|
| 29 |
|
| 30 |
def get_citation_predictions(
|
| 31 |
-
vector: torch.Tensor,
|
|
|
|
|
|
|
|
|
|
| 32 |
) -> torch.Tensor:
|
| 33 |
model.eval()
|
| 34 |
-
with torch.no_grad():
|
| 35 |
-
empty_edge_index = torch.empty(2, 0, dtype=torch.long, device=DEVICE)
|
| 36 |
-
h1_new = model.conv1(vector, edge_index=empty_edge_index).relu()
|
| 37 |
-
z_new = model.conv2(h1_new, edge_index=empty_edge_index)
|
| 38 |
-
|
| 39 |
-
new_node_idx = num_nodes
|
| 40 |
-
row = torch.full((num_nodes,), fill_value=new_node_idx, device=DEVICE)
|
| 41 |
-
col = torch.arange(num_nodes, device=DEVICE)
|
| 42 |
-
edge_label_index_to_check = torch.stack([row, col], dim=0)
|
| 43 |
-
|
| 44 |
-
z_combined = torch.cat([z_all, z_new], dim=0)
|
| 45 |
|
| 46 |
with torch.no_grad():
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def format_top_k_predictions(
|
| 53 |
-
probs: torch.Tensor, dataset: OGBNLinkPredDataset, top_k=10
|
| 54 |
) -> str:
|
| 55 |
-
"""
|
| 56 |
-
Formats the top K predictions into a single string for display.
|
| 57 |
-
|
| 58 |
-
Args:
|
| 59 |
-
probs (torch.Tensor): The tensor of probabilities for all potential links.
|
| 60 |
-
dataset (OGBNLinkPredDataset): The dataset object containing the corpus.
|
| 61 |
-
top_k (int): The number of top predictions to format.
|
| 62 |
-
|
| 63 |
-
Returns:
|
| 64 |
-
str: A formatted string with the top K predictions.
|
| 65 |
-
"""
|
| 66 |
probs = probs.cpu()
|
| 67 |
top_probs, top_indices = torch.topk(probs, k=top_k)
|
| 68 |
-
|
| 69 |
output_lines = []
|
| 70 |
-
|
| 71 |
header = f"Top {top_k} Citation Predictions:"
|
| 72 |
output_lines.append(header)
|
| 73 |
|
|
@@ -86,14 +69,9 @@ def format_top_k_predictions(
|
|
| 86 |
|
| 87 |
|
| 88 |
def prepare_system(model_path: Path):
|
| 89 |
-
"""
|
| 90 |
-
Performs all one-time, expensive operations to prepare the system.
|
| 91 |
-
Initializes models, loads data, and pre-calculates embeddings using structured logging.
|
| 92 |
-
"""
|
| 93 |
logger.info("system_preparation.start")
|
| 94 |
|
| 95 |
dataset = OGBNLinkPredDataset()
|
| 96 |
-
data = dataset.data.to(DEVICE)
|
| 97 |
logger.info("dataset.load.success")
|
| 98 |
|
| 99 |
model_name = "bongsoo/kpf-sbert-128d-v1"
|
|
@@ -103,54 +81,69 @@ def prepare_system(model_path: Path):
|
|
| 103 |
st_model = SentenceTransformer(model_name, device=DEVICE)
|
| 104 |
logger.info("model.load.success", model_type="SentenceTransformer")
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
if model_path.exists():
|
| 111 |
-
|
| 112 |
-
logger.info("model.load.success", model_type="
|
| 113 |
else:
|
| 114 |
logger.warning(
|
| 115 |
"model.load.failure",
|
| 116 |
-
model_type="
|
| 117 |
path=str(model_path),
|
| 118 |
reason="File not found, using random weights.",
|
| 119 |
)
|
| 120 |
-
gcn_model.eval()
|
| 121 |
|
| 122 |
-
|
| 123 |
-
with torch.no_grad():
|
| 124 |
-
z_all = gcn_model(data.x, data.edge_index)
|
| 125 |
|
| 126 |
logger.info(
|
| 127 |
"embeddings.calculation.success",
|
| 128 |
-
embedding_name="
|
| 129 |
-
shape=list(
|
| 130 |
)
|
| 131 |
-
|
| 132 |
logger.info("system_preparation.finish", status="ready_for_predictions")
|
| 133 |
-
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
if __name__ == "__main__":
|
| 137 |
MODEL_PATH = Path("model.pth")
|
| 138 |
-
|
| 139 |
-
gcn_model, st_model, dataset, z_all = prepare_system(MODEL_PATH)
|
| 140 |
|
| 141 |
my_title = "A Survey of Graph Neural Networks for Link Prediction"
|
| 142 |
-
my_abstract = """Link
|
| 143 |
-
|
| 144 |
-
"""
|
| 145 |
|
| 146 |
new_vector = abstract_to_vector(my_title, my_abstract, st_model)
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
probabilities = get_citation_predictions(
|
| 149 |
vector=new_vector,
|
| 150 |
-
model=
|
| 151 |
-
z_all=
|
| 152 |
num_nodes=dataset.data.num_nodes,
|
| 153 |
)
|
| 154 |
|
| 155 |
-
references = format_top_k_predictions(
|
|
|
|
|
|
|
| 156 |
print(references)
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from dataset.ogbn_link_pred_dataset import OGBNLinkPredDataset
|
| 4 |
+
from pathlib import Path
|
| 5 |
import structlog
|
|
|
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
+
from model.mlp import edge_features, PairMLP
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 24 |
text = title + "\n" + abstract_text
|
| 25 |
with torch.no_grad():
|
| 26 |
vector = st_model.encode(text, convert_to_tensor=True, device=DEVICE)
|
| 27 |
+
return vector
|
| 28 |
|
| 29 |
|
| 30 |
def get_citation_predictions(
|
| 31 |
+
vector: torch.Tensor,
|
| 32 |
+
model: PairMLP,
|
| 33 |
+
z_all: torch.Tensor,
|
| 34 |
+
num_nodes: int,
|
| 35 |
) -> torch.Tensor:
|
| 36 |
model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
with torch.no_grad():
|
| 39 |
+
combined_embeddings = torch.cat([vector.view(1, -1), z_all], dim=0)
|
| 40 |
+
edge_index = torch.tensor([[0] * num_nodes, list(range(1, num_nodes + 1))]).to(
|
| 41 |
+
DEVICE
|
| 42 |
+
)
|
| 43 |
+
feat = edge_features(combined_embeddings, edge_index).to(DEVICE)
|
| 44 |
+
scores = torch.sigmoid(model(feat))
|
| 45 |
+
return scores.squeeze()
|
| 46 |
|
| 47 |
|
| 48 |
def format_top_k_predictions(
|
| 49 |
+
probs: torch.Tensor, dataset: OGBNLinkPredDataset, top_k=10, show_prob=False
|
| 50 |
) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
probs = probs.cpu()
|
| 52 |
top_probs, top_indices = torch.topk(probs, k=top_k)
|
|
|
|
| 53 |
output_lines = []
|
|
|
|
| 54 |
header = f"Top {top_k} Citation Predictions:"
|
| 55 |
output_lines.append(header)
|
| 56 |
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
def prepare_system(model_path: Path):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
logger.info("system_preparation.start")
|
| 73 |
|
| 74 |
dataset = OGBNLinkPredDataset()
|
|
|
|
| 75 |
logger.info("dataset.load.success")
|
| 76 |
|
| 77 |
model_name = "bongsoo/kpf-sbert-128d-v1"
|
|
|
|
| 81 |
st_model = SentenceTransformer(model_name, device=DEVICE)
|
| 82 |
logger.info("model.load.success", model_type="SentenceTransformer")
|
| 83 |
|
| 84 |
+
# Load corpus embeddings
|
| 85 |
+
if Path("model/embeddings.pth").exists():
|
| 86 |
+
corpus_embeddings = torch.load("model/embeddings.pth", map_location=DEVICE)
|
| 87 |
+
logger.info("embeddings.load.success")
|
| 88 |
+
else:
|
| 89 |
+
logger.info("embeddings.calculation.start")
|
| 90 |
+
corpus_embeddings = st_model.encode(
|
| 91 |
+
dataset.corpus, convert_to_tensor=True, show_progress_bar=True
|
| 92 |
+
)
|
| 93 |
+
Path("model").mkdir(parents=True, exist_ok=True)
|
| 94 |
+
torch.save(corpus_embeddings, "model/embeddings.pth")
|
| 95 |
+
logger.info("embeddings.calculation.success")
|
| 96 |
+
|
| 97 |
+
corpus_embeddings = F.normalize(corpus_embeddings.to(DEVICE), p=2, dim=1)
|
| 98 |
+
|
| 99 |
+
# Initialize PairMLP
|
| 100 |
+
embedding_dim = corpus_embeddings.size(1)
|
| 101 |
+
pair_mlp = PairMLP(embedding_dim * 2).to(DEVICE)
|
| 102 |
|
| 103 |
if model_path.exists():
|
| 104 |
+
pair_mlp.load_state_dict(torch.load(model_path, map_location=DEVICE))
|
| 105 |
+
logger.info("model.load.success", model_type="PairMLP", path=str(model_path))
|
| 106 |
else:
|
| 107 |
logger.warning(
|
| 108 |
"model.load.failure",
|
| 109 |
+
model_type="PairMLP",
|
| 110 |
path=str(model_path),
|
| 111 |
reason="File not found, using random weights.",
|
| 112 |
)
|
|
|
|
| 113 |
|
| 114 |
+
pair_mlp.eval()
|
|
|
|
|
|
|
| 115 |
|
| 116 |
logger.info(
|
| 117 |
"embeddings.calculation.success",
|
| 118 |
+
embedding_name="corpus_embeddings",
|
| 119 |
+
shape=list(corpus_embeddings.shape),
|
| 120 |
)
|
|
|
|
| 121 |
logger.info("system_preparation.finish", status="ready_for_predictions")
|
| 122 |
+
|
| 123 |
+
return pair_mlp, st_model, dataset, corpus_embeddings
|
| 124 |
|
| 125 |
|
| 126 |
if __name__ == "__main__":
|
| 127 |
MODEL_PATH = Path("model.pth")
|
| 128 |
+
pair_model, st_model, dataset, corpus_embeddings = prepare_system(MODEL_PATH)
|
|
|
|
| 129 |
|
| 130 |
my_title = "A Survey of Graph Neural Networks for Link Prediction"
|
| 131 |
+
my_abstract = """Link prediction is a critical task in graph analysis.
|
| 132 |
+
In this paper, we review various GNN architectures like GCN and GraphSAGE for predicting edges."""
|
|
|
|
| 133 |
|
| 134 |
new_vector = abstract_to_vector(my_title, my_abstract, st_model)
|
| 135 |
+
new_vector = F.normalize(
|
| 136 |
+
new_vector.view(1, -1), p=2, dim=1
|
| 137 |
+
) # Normalize like corpus embeddings
|
| 138 |
|
| 139 |
probabilities = get_citation_predictions(
|
| 140 |
vector=new_vector,
|
| 141 |
+
model=pair_model,
|
| 142 |
+
z_all=corpus_embeddings,
|
| 143 |
num_nodes=dataset.data.num_nodes,
|
| 144 |
)
|
| 145 |
|
| 146 |
+
references = format_top_k_predictions(
|
| 147 |
+
probabilities, dataset, top_k=5, show_prob=True
|
| 148 |
+
)
|
| 149 |
print(references)
|
pyproject.toml
CHANGED
|
File without changes
|