Module contents
Lesson 17 of 30Core 110 min

Link prediction: heuristics, autoencoders and the labeling trick

Frame link prediction under observable information, compare structural heuristics and learned models, and evaluate candidate rankings without leakage.

After this lesson you can

  • Define message graphs, supervision pairs and assumed negatives without leakage.
  • Compute common-neighbor, Adamic-Adar, resource-allocation and Katz scores.
  • Compare graph autoencoders, pair labeling and source-conditioned path models.
  • Interpret AUC, MRR and Hits@K under explicit candidate and tie conventions.
  • Construct and audit temporal and retrospective link prediction experiments.

Before you start

What does a missing edge mean?

Recommending a dependency, anticipating a collaboration or finding a molecular interaction requires scoring pairs, not isolated nodes. But “no edge in the file” can mean it does not exist, has not yet been observed, or will appear later. That choice changes the task and what can be called a negative.

In a temporal collaboration graph, for example, the message graph must contain only information available before the cutoff. If a future edge is used to construct features or neighborhoods, the model can succeed because it has already seen the fact it must predict. In a partially reconstructed static graph, by contrast, the task is to infer hidden edges of a known graph: this is not necessarily an evaluation of future events.

During training also distinguish edges over which messages pass from those used to supervise the objective. If the encoder sees a positive edge the decoder must reconstruct, it may learn a shortcut that will not be present for a test edge. One option is to divide training edges into two disjoint sets; another is to remove the target edge from its subgraph for each query. Declare the convention, since benchmarks do not all use the same one.

InteractiveEdges that are seen and edges that teach
  • Fixed message
  • Visible positive pair
012345
Deliberately vulnerable score: 10 if the pair is in messages, plus common neighbors. Positives and negatives are fixed to illustrate the mechanism, not measured data.
Positive pair
Label use
Held-out positives visible in messages0
Illustrative detector test AUC0.000
Change the destination of each positive pair and decide whether it is in the message graph. The illustrative detector adds ten for a present pair and also counts common neighbors; AUC uses test labels and six fixed negatives. This is an explicit construction, not a measurement of a trained model.

A negative sampled from unobserved pairs is an assumed negative. In incomplete data it may be an unrecorded edge; in temporal prediction it may even appear later. Avoiding known training, validation and test positives when the protocol permits identifying the full graph prevents contaminating them as negatives, but using future knowledge to filter candidates is not necessarily admissible in deployment. Declare what information the sampler uses and what uncertainty remains.

A random split in PyG

RandomLinkSplit can construct positive and negative examples and reserve a disjoint fraction of training edges for supervision. The example checks each target positive is absent from its own message graph. It also shows a choice worth knowing: with this transform the test graph incorporates positive validation edges. That convention is appropriate only if those observations have been revealed before the test decision; if a frozen graph is needed, build it explicitly and recheck exclusions. A random split does not replace a temporal split for future events.

[ ]Inspect RandomLinkSplitLocal GPU
import random
import torch
from torch_geometric.data import Data
from torch_geometric.transforms import RandomLinkSplit

random.seed(8); torch.manual_seed(8)
undirected = torch.tensor([(i, (i + 1) % 12) for i in range(12)] + [(i, (i + 3) % 12) for i in range(12)], dtype=torch.long).T
edge_index = torch.cat([undirected, undirected.flip(0)], dim=1)
data = Data(edge_index=edge_index, num_nodes=12)
splitter = RandomLinkSplit(num_val=.2, num_test=.2, is_undirected=True,
                           split_labels=True, add_negative_train_samples=True,
                           disjoint_train_ratio=.25)
train, valid, test = splitter(data)
for name, part in [('train', train), ('valid', valid), ('test', test)]:
    visible = {tuple(sorted(e)) for e in part.edge_index.T.tolist()}
    positives = {tuple(sorted(e)) for e in part.pos_edge_label_index.T.tolist()}
    negatives = {tuple(sorted(e)) for e in part.neg_edge_label_index.T.tolist()}
    assert not positives & visible
    assert not negatives & visible
    print(name, 'mensajes', len(visible), 'positivos', len(positives), 'negativos', len(negatives))
print('El grafo de test incluye positivas de validación:',
      len({tuple(sorted(e)) for e in valid.pos_edge_label_index.T.tolist()} &
          {tuple(sorted(e)) for e in test.edge_index.T.tolist()}))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Heuristics before networks

Link heuristics summarize structural patterns without training an encoder. For an undirected simple graph, Γ(u)\Gamma(u) is the neighborhood and d(w)=∣Γ(w)∣d(w)=\abs{\Gamma(w)}. Three scores use common neighbors:

sCN(u,v)=∣Γ(u)∩Γ(v)∣,sAA(u,v)=∑w∈Γ(u)∩Γ(v)1log⁡d(w),sRA(u,v)=∑w∈Γ(u)∩Γ(v)1d(w).\begin{aligned} s_{\mathrm{CN}}(u,v)&=\abs{\Gamma(u)\cap\Gamma(v)},\\ s_{\mathrm{AA}}(u,v)&=\sum_{w\in\Gamma(u)\cap\Gamma(v)}\frac1{\log d(w)},\\ s_{\mathrm{RA}}(u,v)&=\sum_{w\in\Gamma(u)\cap\Gamma(v)}\frac1{d(w)}. \end{aligned}

For two distinct endpoints, a common neighbor has degree at least two, so the logarithmic denominator is nonzero. Adamic-Adar (AA) and resource allocation (RA) reduce the weight of a very popular intermediary at different rates. No rule is universal: a bipartite or heterophilous network may have a different link formation mechanism.

The unit of measurement also matters. If nodes are authors and two authors who shared several papers appear only once as neighbors, the preceding formulas use binary adjacency. If the number of collaborations is an intensity, define a weighted extension and do not present its output as the same binary score. An observed interaction edge need not be reciprocal: in a package dependency, endpoint order is part of the question.

Katz sums walks of all lengths, not only two hops. If A\mat{A} is a finite graph’s adjacency and 0≤β<1/ρ(A)0\leq\beta<1/\rho(\mat{A}) when ρ(A)>0\rho(\mat{A})>0,

K=∑k=1∞βkAk=(I−βA)−1−I.\mat{K}=\sum_{k=1}^{\infty}\beta^k\mat{A}^k=(\mat{I}-\beta\mat{A})^{-1}-\mat{I}.

Entry (u,v)(u,v) of Ak\mat{A}^k counts walks of length kk, including those that revisit nodes. The spectral criterion guarantees convergence of the matrix Neumann series; if ρ(A)=0\rho(\mat{A})=0, the matrix is nilpotent and the sum is finite for every β\beta. For large graphs forming the dense inverse is unwise. Personalized PageRank (PPR) also accumulates paths with restart, but uses a normalized transition matrix and therefore answers a different question.

[ ]Common neighbors and Katz on a small graphBrowser
import numpy as np

adj = np.array([[0,1,1,0], [1,0,1,1], [1,1,0,1], [0,1,1,0]], dtype=float)
def scores(A, u, v):
    common = (A[u] > 0) & (A[v] > 0)
    degree = A.sum(axis=1)[common]
    return int(common.sum()), np.sum(1 / np.log(degree)), np.sum(1 / degree)

print('CN, AA, RA para 0 y 3:', scores(adj, 0, 3))
beta = .1
assert beta * max(abs(np.linalg.eigvals(adj))) < 1
katz = np.linalg.solve(np.eye(len(adj)) - beta * adj, np.eye(len(adj))) - np.eye(len(adj))
series = np.zeros_like(adj)
power = np.eye(len(adj))
for k in range(1, 60):
    power = power @ adj
    series += beta**k * power
print('serie y sistema coinciden:', np.allclose(series, katz))
print('Katz(0, 3):', round(katz[0, 3], 6))

Encode nodes and decode pairs

A graph autoencoder (GAE) computes Z=fθ(X,Amsg)\mat{Z}=f_\theta(\mat{X},\mat{A}_{\mathrm{msg}}) and trains a decoder on positive and negative pairs. With dot product, puv=σ(zu⊤zv)p_{uv}=\sigmoid(\vb{z}_u\T\vb{z}_v); binary loss is computed only over chosen supervision pairs. The message graph and loss pair set are different objects.

Dot product is symmetric and its complete logit matrix ZZ⊤\mat{Z}\mat{Z}\T is positive semidefinite. Without modification it cannot represent every directed relation or every arbitrary symmetric matrix. An MLP on zu⊙zv\vb{z}_u\odot\vb{z}_v remains symmetric but removes the restriction of factoring logits as a Gram matrix. For direction one can use an asymmetric bilinear decoder zu⊤Rzv\vb{z}_u\T\mat{R}\vb{z}_v or concatenate endpoints in order.

This difference also affects model serving. Dot product permits precomputing vectors and searching candidates with a similarity index. A head receiving a pair may need to evaluate every proposed pair, though candidates can first be retrieved with a cheaper method. In both cases candidate retrieval and filtering must respect what was known at prediction time: a two-stage system cannot compensate with a good decoder for leakage introduced in the first stage.

The VGAE of Kipf and Welling learns an approximate distribution qθ(Z∣X,Amsg)q_\theta(\mat{Z}\given\mat{X},\mat{A}_{\mathrm{msg}}), usually diagonal Gaussian per node, and optimizes a variational bound with reconstruction and divergence from the prior, as in the VAE objective decomposition. For q(zi)=N(μi,diag⁡(σi2))q(\vb{z}_i)=\Normal(\vb{\mu}_i,\diag(\vb{\sigma}_i^2)) and p(zi)=N(0,I)p(\vb{z}_i)=\Normal(\vb{0},\mat{I}),

KL⁡(qi ∥ pi)=12∑j(μij2+σij2−1−log⁡σij2).\KL(q_i\,\|\,p_i)=\frac12\sum_j(\mu_{ij}^2+\sigma_{ij}^2-1-\log\sigma_{ij}^2).

Reparameterization zi=μi+σi⊙εi\vb{z}_i=\vb{\mu}_i+\vb{\sigma}_i\odot\vb{\eps}_i, with εi∼N(0,I)\vb{\eps}_i\sim\Normal(\vb{0},\mat{I}), allows differentiation with respect to encoder parameters. A loss computed with sampled negatives does not automatically match the likelihood of all pairs: its weighting defines the objective and affects probability calibration.

Comparing GAE and VGAE must fix the split, candidates and training budget. The KL term can be summed over coordinates and averaged per node, but its coefficient relative to reconstruction depends on how pairs are averaged. Writing that coefficient and the specific reduction makes the objective reproducible; changing the number of negatives without adjusting weighting changes the optimized problem. Evaluation can use the posterior mean as a deterministic representation or average several samples, provided the choice is declared.

Metrics and candidates

Link prediction metrics depend on the candidate distribution. AUC is the probability a positive scores higher than a negative, plus half the tie probability. With random negatives from a sparse graph, rejecting very distant pairs may be easy; choosing structurally close negatives can change both the figure and method comparison. HeaRT proposes heuristic-related negatives to study that difficulty; it does not automatically make all those pairs true negatives.

For a query with one positive and associated negatives, a tie convention like the OGB evaluator’s uses

r=1+#{s−>s+}+12#{s−=s+},MRR=1Q∑q=1Q1rq.r=1+\#\{s^- > s^+\}+\tfrac12\#\{s^- = s^+\},\qquad \mathrm{MRR}=\frac1Q\sum_{q=1}^{Q}\frac1{r_q}.

Hits@K is the fraction of queries with rank at least as good as KK, if that is the defined protocol. OGB also has tasks with a global negative list and global Hits@K threshold: do not mix that definition with per-query negatives. Negative count, selection and tie handling are part of the metric. MRR with a hundred candidates is not directly comparable to one with a thousand.

InteractiveRanking depends on negatives
Common neighbors8/13
GAE6/13
Simplified SEAL8/13
Simplified NBF0/13

One split and seed of the Karate social graph. SEAL and NBF models are reduced versions; negatives are filtered using the known full graph. This is neither a temporal evaluation nor a conclusive comparison.

Negatives
2
Best Hits@20.615
Test queries13
Negatives per query4
One run on the Karate social graph, with thirteen test queries and four negatives per query. The message graph is a spanning tree; two-hop negatives are close in that tree. SEAL and NBF are simplified implementations. Retrospective selection excludes known edges of the full graph and does not represent temporal deployment.

Both difficulty and method ordering change here. The sample is small and comparison uses one seed: it does not show one method wins on other graphs. Ten validation edges were reserved without using them for parameter selection and training ran for 80 epochs with predetermined parameters. Random and hard negatives can overlap. For each positive, a tie gets average rank; AUC instead compares positives with the negative set of the chosen variant. In this particular run reduced NBF ranks are all three under both selections; we do not interpret this behavior as a general NBFNet property.

With a global negative list, OGB Hits@K compares each positive with the K-th highest negative score and counts it only if strictly greater. This tie rule differs from the preceding per-query average rank. The figure also depends on how many negatives entered the global list. A run with a sample of that list helps debugging, but does not produce the official full-dataset score. When publishing a table, report protocol alongside metric and time: without them a model difference may come from candidate construction.

A pair is more than two nodes

Suppose an equivariant encoder ff and an automorphism π\pi of the input graph preserving features. Then hπ(u)=hu\vb{h}_{\pi(u)}=\vb{h}_u. If also π(v)=v\pi(v)=v, any deterministic decoder g(hu,hv)g(\vb{h}_u,\vb{h}_v) gives the same score to (u,v)(u,v) and (π(u),v)(\pi(u),v). The proof simply substitutes the two equalities into gg; it does not depend on gg being a dot product.

There is a subtlety: in an unmodified graph, an automorphism fixing vv also preserves adjacency to vv. It cannot turn a visible edge into a visible non-edge. The link prediction limitation arises when pair labels are hidden or endpoints are individually indistinguishable even though pairs do not belong to the same joint orbit. In a cycle, for example, all nodes are individually equivalent, but a distance-two pair and a distance-three pair have different relations.

InteractiveTwo pairs of a cycle
  • Source 0
  • Candidate
012345
Without a mark, an equivariant encoder with equal features assigns the same vector to every node. The example takes scalar 1 for that vector. With a mark, the candidate entry of A²e₀ is shown: it is a structural feature, not a probability.
Candidate from 0
Distance from source2
Equal-embedding score1
Compare candidates from source 0. The pair with 1 is a visible edge and illustrates symmetry, not prediction evaluation. Pairs with 2 and 3 are non-edges; the source mark distinguishes their two-step relations. The score is an explicit model, not a trained result.

The labeling trick adds query-dependent marks to input before running the GNN. A representation can thus express pair relations instead of combining only embeddings computed once per node. Not every labeled GNN distinguishes every pair: the theoretical result of Zhang et al. requires expressivity and specific labeling conditions.

SEAL extracts an enclosing subgraph for each pair, removes the candidate edge if present and labels nodes by distance to endpoints. In DRNL both endpoints receive label 1; a node unreachable from either endpoint under the defined distances receives 0. For the others, let du,dvd_u,d_v be distances computed removing the other endpoint and d=du+dvd=d_u+d_v. The label is

1+min⁡(du,dv)+⌊d2⌋(⌊d2⌋+(d mod 2)−1).1+\min(d_u,d_v)+\left\lfloor\frac d2\right\rfloor\left(\left\lfloor\frac d2\right\rfloor+(d\bmod 2)-1\right).

Extracting a subgraph per candidate is expensive and may repeat work. BUDDY uses sketches and precomputation to approximate structural pair features without materializing each subgraph. That saving does not mean an approximation is identical to SEAL or eliminates evaluation tradeoffs.

Edge removal is applied before computing distances and labels. Otherwise subgraph features themselves can directly signal the target, even if the GNN does not receive that edge. The chosen radius controls what information reaches each example and its cost. A small radius misses long paths; a large one can yield unmanageable neighborhoods around high-degree nodes. Limiting or sampling neighbors helps run the experiment but changes the input and must be declared when comparing with an unlimited method.

Paths conditioned on the source

Path-based models can propagate a state initialized at the source. NBFNet combines an initial condition (INDICATOR), a message function (MESSAGE) and aggregation (AGGREGATE), inspired by generalized Bellman-Ford. With LL iterations and a source-specific state, each destination’s result may depend on paths up to that length; learned operators are not necessarily ordinary sum and product and do not guarantee a shortest path.

Conditioning separates queries that independent node embeddings treat alike, but requires propagation for sources or queries. In multi-relation graphs, relation representations enter messages. Remove the target edge according to protocol and compare memory, time, split and candidates as well as metric; architecture does not fix leakage.

Consider propagation initialized only at the source: after one iteration a state can reach its neighbors; after two it can reach nodes two edges away, and so on. If message function and aggregation are learnable, the model can weight different routes according to parameters. This does not mean it automatically recovers simple paths: it can combine states from walks revisiting nodes. The connection with Bellman-Ford is the iterative form of combining path information, not a shortest-distance guarantee for every parameterization.

Lab: construct and evaluate pairs

The following preparation incorporates the previous lesson’s message-passing framework. Its copy corresponds to SHA-256 722eb1df61bde98ee9a7770777bd4ab4646c8094144f4165d9e979f468252587. We then construct a retrospective split of a collaboration sample from ogbl-collab: the 34 identifiers come from the official training split and local cell indices follow that order. The first highest-degree node examined whose first 33 neighbors by identifier supplied at least 45 additional edges was selected; a BFS tree and the first 45 remaining sorted edges were retained. The resulting 78 edges are a deliberately biased selection, not a representative benchmark sample.

A BFS-generated tree provides messages; the remaining 45 edges are split into supervision, validation and test. To avoid treating edges omitted from that selection as negatives, the 147 known edges within those 34 nodes in the original training split are excluded. Even so, an unrecorded pair may be positive or appear in the future. This retrospective filtering uses more information than the message graph and does not simulate a real temporal decision. Validation is reserved without hyperparameter selection. Random node features make this GAE transductive and seed-dependent. The official train.pt file used to extract data has SHA-256 eb1a1deb3a40fa870fcef21c1f19809ab1806c6395061ef4fbc899fc320e16a1.

The sparse implementation computes CN, AA, RA and Katz. GAE trains its dot product with manual framework gradients. The SEAL variant extracts two hops, removes the target edge, computes DRNL and trains a message layer followed by per-subgraph mean and a linear head; it is a pedagogical version, not a full paper reproduction. Figures are computed when running the cell and refer only to this split. Hits@50 compares the 15 test positives with a global threshold of 100 assumed negatives; these are not official OGB scores.

[ ]Heuristics, GAE and labeled subgraphsBrowser
import numpy as np
import networkx as nx
from scipy.sparse import csr_matrix, eye
from scipy.sparse.linalg import spsolve

rng = np.random.default_rng(5)
ogb_nodes = [132972,63,910,3236,4201,5055,5234,5528,5767,6821,6834,7069,8061,8950,9531,9631,10859,11184,11675,11834,11866,12696,13110,13749,15265,17514,17744,18050,18365,18462,19306,21418,21631,21822]
selected_edges = [
    [0,1], [0,2], [0,3], [0,4], [0,5], [0,6], [0,7], [0,8], [0,9], [0,10], 
    [0,11], [0,12], [0,13], [0,14], [0,15], [0,16], [0,17], [0,18], [0,19], [0,20], 
    [0,21], [0,22], [0,23], [0,24], [0,25], [0,26], [0,27], [0,28], [0,29], [0,30], 
    [0,31], [0,32], [0,33], [3,5], [3,8], [3,9], [3,10], [3,15], [3,16], [3,17], 
    [3,18], [3,20], [3,25], [3,26], [3,27], [3,31], [4,6], [4,10], [4,27], [5,8], 
    [5,9], [5,10], [5,11], [5,14], [5,15], [5,16], [5,17], [5,18], [5,20], [5,21], 
    [5,25], [5,26], [5,27], [5,29], [5,31], [5,33], [6,12], [6,22], [6,24], [7,9], 
    [8,9], [8,15], [8,16], [8,17], [8,20], [8,26], [8,27], [9,10] 
]
observed_edges = [
    [0,1], [0,2], [0,3], [0,4], [0,5], [0,6], [0,7], [0,8], [0,9], [0,10], 
    [0,11], [0,12], [0,13], [0,14], [0,15], [0,16], [0,17], [0,18], [0,19], [0,20], 
    [0,21], [0,22], [0,23], [0,24], [0,25], [0,26], [0,27], [0,28], [0,29], [0,30], 
    [0,31], [0,32], [0,33], [3,5], [3,8], [3,9], [3,10], [3,15], [3,16], [3,17], 
    [3,18], [3,20], [3,25], [3,26], [3,27], [3,31], [4,6], [4,10], [4,27], [5,8], 
    [5,9], [5,10], [5,11], [5,14], [5,15], [5,16], [5,17], [5,18], [5,20], [5,21], 
    [5,25], [5,26], [5,27], [5,29], [5,31], [5,33], [6,12], [6,22], [6,24], [7,9], 
    [8,9], [8,15], [8,16], [8,17], [8,20], [8,26], [8,27], [9,10], [9,12], [9,15], 
    [9,16], [9,17], [9,18], [9,20], [9,24], [9,25], [9,26], [9,27], [9,31], [10,15], 
    [10,16], [10,17], [10,18], [10,20], [10,25], [10,27], [10,31], [11,14], [11,15], [11,21], 
    [11,29], [11,33], [12,22], [14,15], [14,21], [14,29], [14,33], [15,16], [15,17], [15,18], 
    [15,20], [15,21], [15,25], [15,26], [15,27], [15,29], [15,31], [15,33], [16,17], [16,18], 
    [16,20], [16,25], [16,26], [16,27], [16,31], [17,18], [17,20], [17,25], [17,26], [17,27], 
    [17,31], [18,20], [18,25], [18,27], [18,31], [20,25], [20,26], [20,27], [20,31], [21,29], 
    [21,33], [25,27], [25,31], [26,27], [27,31], [28,32], [29,33] 
]
graph = nx.Graph(); graph.add_nodes_from(range(len(ogb_nodes))); graph.add_edges_from(selected_edges)
observed = {tuple(sorted(e)) for e in observed_edges}
message = nx.Graph(nx.bfs_edges(graph, 0))
known = {tuple(sorted(e)) for e in graph.edges}
others = sorted(known - {tuple(sorted(e)) for e in message.edges})
rng.shuffle(others)
train_pos, valid_pos, test_pos = others[:20], others[20:30], others[30:]
nonedges = sorted(tuple(sorted(e)) for e in nx.non_edges(graph) if tuple(sorted(e)) not in observed)
rng.shuffle(nonedges)
train_neg, valid_neg, test_neg = nonedges[:20], nonedges[20:30], nonedges[30:130]
assert not (set(train_neg + valid_neg + test_neg) & observed)
assert len(set(train_pos + valid_pos + test_pos)) == len(others)
assert not (set(train_pos + valid_pos + test_pos) & {tuple(sorted(e)) for e in message.edges})

n = len(graph)
A = csr_matrix(nx.to_scipy_sparse_array(message, nodelist=range(n), dtype=float, format='csr'))
degree = np.asarray(A.sum(axis=1)).ravel()
invlog = np.zeros(n); invlog[degree > 1] = 1 / np.log(degree[degree > 1])
invdeg = np.divide(1., degree, out=np.zeros(n), where=degree > 0)
def heuristics(u, v, beta=.05):
    common = A[u, :].multiply(A[v, :])
    cn = float(common.sum())
    aa = float((common @ invlog).item())
    ra = float((common @ invdeg).item())
    rhs = np.zeros(n); rhs[v] = 1
    katz = float(spsolve(eye(n, format='csr') - beta * A, rhs)[u] - (u == v))
    return cn, aa, ra, katz
assert .05 * max(abs(np.linalg.eigvalsh(A.toarray()))) < 1

edges = np.array([(u, v) for a, b in message.edges for u, v in ((a, b), (b, a))], dtype=int).T
features = np.column_stack([np.ones(n), degree / max(degree), [nx.clustering(message, i) for i in range(n)], rng.normal(0, .1, n)])
train = np.asarray(train_pos + train_neg)
labels = np.r_[np.ones(len(train_pos)), np.zeros(len(train_neg))]
test = np.asarray(test_pos + test_neg)
test_y = np.r_[np.ones(len(test_pos)), np.zeros(len(test_neg))]
def sigmoid(x): return 1 / (1 + np.exp(-np.clip(x, -30, 30)))

gae = MPLayer(4, 8, aggregation='mean', seed=2)
for epoch in range(200):
    z, cache = gae.forward(features, edges, return_cache=True)
    u, v = train.T
    logits = (z[u] * z[v]).sum(axis=1)
    delta = (sigmoid(logits) - labels) / len(labels)
    grad = np.zeros_like(z)
    np.add.at(grad, u, delta[:, None] * z[v]); np.add.at(grad, v, delta[:, None] * z[u])
    gae.step(gae.backward(grad, cache), .03)
z = gae.forward(features, edges)
gae_scores = (z[test[:, 0]] * z[test[:, 1]]).sum(axis=1)

def subgraph(u, v):
    nodes = sorted(set(nx.single_source_shortest_path_length(message, u, cutoff=2)) | set(nx.single_source_shortest_path_length(message, v, cutoff=2)))
    sub = message.subgraph(nodes).copy()
    if sub.has_edge(u, v): sub.remove_edge(u, v)
    a, b = sub.copy(), sub.copy(); a.remove_node(v); b.remove_node(u)
    du = nx.single_source_shortest_path_length(a, u)
    dv = nx.single_source_shortest_path_length(b, v)
    x = []
    for w in nodes:
        if w in (u, v): label = 1
        elif w not in du or w not in dv: label = 0
        else:
            d = du[w] + dv[w]
            label = 1 + min(du[w], dv[w]) + (d // 2) * (d // 2 + d % 2 - 1)
        x.append([float(w in (u, v)), np.log1p(label), sub.degree[w] / n, 1.])
    index = {w: i for i, w in enumerate(nodes)}
    e = np.array([(index[a], index[b]) for p, q in sub.edges for a, b in ((p, q), (q, p))], dtype=int).reshape(-1, 2).T
    return np.asarray(x), e

def batch(pairs): return collate([subgraph(*pair) for pair in pairs])
sx, se, batch_ids = batch(train)
seal = MPLayer(4, 8, aggregation='mean', seed=3)
w = rng.normal(0, .1, 4); b = 0.
for epoch in range(200):
    h, cache = seal.forward(sx, se, return_cache=True)
    pooled = readout(h, batch_ids, len(train), mode='mean')
    delta = (sigmoid(pooled @ w + b) - labels) / len(labels)
    counts = np.bincount(batch_ids)
    gh = delta[batch_ids, None] * w[None, :] / counts[batch_ids, None]
    grads = seal.backward(gh, cache)
    gw = pooled.T @ delta; gb = delta.sum()
    seal.step(grads, .03); w -= .03 * gw; b -= .03 * gb
tx, te, tb = batch(test)
seal_scores = readout(seal.forward(tx, te), tb, len(test), mode='mean') @ w + b
cn_scores = np.array([heuristics(u, v)[0] for u, v in test])
for name, scores in [('CN', cn_scores), ('GAE', gae_scores), ('SEAL reducido', seal_scores)]:
    pos, neg = scores[test_y == 1], scores[test_y == 0]
    auc = np.mean((pos[:, None] > neg) + .5 * (pos[:, None] == neg))
    threshold = np.partition(neg, -50)[-50]
    hits50 = np.mean(pos > threshold)  # convención global y estricta de OGB
    print(name, 'AUC', round(float(auc), 4), 'Hits@50', round(float(hits50), 4))
print('Partición:', len(message.edges), len(train_pos), len(valid_pos), len(test_pos))

The following local program reproduces the fixed selection of identifiers and edges from the preceding lab from train.pt, after downloading ogbl-collab with the next cell. Output includes all known edges among those nodes to check the negative filter.

[ ]Extract the small collaboration sampleLocal GPU
import hashlib, json, os
from pathlib import Path
import numpy as np
import networkx as nx
import torch

path = Path(os.environ.get('OGB_ROOT', 'dataset')) / 'ogbl_collab' / 'split' / 'time' / 'train.pt'
assert hashlib.sha256(path.read_bytes()).hexdigest() == 'eb1a1deb3a40fa870fcef21c1f19809ab1806c6395061ef4fbc899fc320e16a1'
data = torch.load(path, weights_only=False)
g = nx.Graph()
g.add_edges_from(np.asarray(data['edge'], dtype=np.int64).tolist())
for center, degree in sorted(g.degree, key=lambda x: (-x[1], x[0]))[:100]:
    nodes = [center] + sorted(g.neighbors(center))[:33]
    # Conserva el orden centro + vecinos, independientemente del orden interno de NetworkX.
    sub = nx.relabel_nodes(g.subgraph(nodes), {old: i for i, old in enumerate(nodes)}, copy=True)
    tree = nx.Graph(nx.bfs_edges(sub, 0))
    rest = sorted({tuple(sorted(e)) for e in sub.edges} - {tuple(sorted(e)) for e in tree.edges})
    if len(rest) >= 45:
        selected = sorted({tuple(sorted(e)) for e in tree.edges}) + rest[:45]
        print(json.dumps({'center': center, 'degree': degree, 'node_ids': nodes, 'edges': selected, 'known_edges': sorted(tuple(sorted(e)) for e in sub.edges)}, separators=(',',':')))
        break
else:
    raise RuntimeError('No se encontró muestra con suficientes aristas')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

A temporal ogbl-collab sample

ogbl-collab records author collaborations and provides a temporal split and evaluator with global negatives. The next cell downloads official data if missing and runs a bounded test, not the full benchmark: it uses 128 positive supervision edges, 64 test positives and the first 128 official test negatives. Supervision edges are removed from the message graph along with all repetitions. Positive test edges can represent new collaborations of previously observed pairs; the cell counts how many already appeared in the message graph. In this sample run there were 26 of 64. That differs from discovering a never-observed pair.

The alternative set contains up to two two-hop negatives per source. Negative filtering also consults the validation and test edge list: this retrospective control avoids labeling a known positive negative, but uses future knowledge. It is a candidate comparison, not a pure temporal deployment evaluation. Official splits remain intact; validation does not select parameters. Each Hits@50 uses the OGB evaluator’s global threshold with the specified list, so sample figures are not comparable with the full official table.

CN runs on CPU. GAE and VGAE test dot product and Hadamard with MLP, five epochs and per-node mean KL with coefficient 0.01. Reduced SEAL and NBF use one-hop subgraphs with at most twelve neighbors per endpoint and fifteen epochs. Truncation, binary edge handling and lack of temporal edge features are decisions of this test, not original implementations. OGB-provided node features are used as given; before historical deployment their availability dates should be checked. Times include training and inference, and extraction for pair models, but not download or adjacency construction; initial GAE graph transfer to GPU is also excluded. Peak is PyTorch-allocated memory in this process, not total GPU memory. Each pair method builds its own cache and thus does not inherit prior extraction.

For compatibility with recent PyTorch, the three split files are loaded with weights_only=False only after verifying their SHA-256 hashes against official files. If a future version changes them, the program stops and requires reverifying origin and content. The experiment requires ogb, torch, torch-geometric, scipy and scikit-learn; without CUDA it uses CPU and reports zero MiB of CUDA memory.

If the program is run as a standalone file with environment variable COLLAB_FULL=1, all official test positives and negatives are evaluated in bounded batches. This can take a long time, especially for per-pair subgraph extraction; it retains 128 supervision examples and other example limits. Full test has not been run here, so its result must be measured on your machine and cannot be inferred from the sample.

[ ]Bounded test on ogbl-collabLocal GPU
"""Comparación acotada, no puntuación oficial completa de ogbl-collab."""
import hashlib, os, time
from pathlib import Path
import numpy as np
import torch
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import shortest_path
from sklearn.metrics import roc_auc_score
from torch import nn
import torch.nn.functional as F
from torch_geometric.data import Data, Batch
from torch_geometric.data.data import DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.nn import GCNConv, global_mean_pool
from ogb.linkproppred import PygLinkPropPredDataset, Evaluator

torch.set_num_threads(2)
torch.manual_seed(13)
rng = np.random.default_rng(13)
root = Path(os.environ.get('OGB_ROOT', 'dataset'))  # descarga desde OGB si no existe
with torch.serialization.safe_globals([Data, DataEdgeAttr, DataTensorAttr, GlobalStorage]):
    dataset = PygLinkPropPredDataset(name='ogbl-collab', root=str(root))
    data = dataset[0]
splitdir = root / 'ogbl_collab' / 'split' / 'time'
# El pickle solo se abre después de comprobar el hash de cada archivo oficial.
hashes = {'train':'eb1a1deb3a40fa870fcef21c1f19809ab1806c6395061ef4fbc899fc320e16a1',
          'valid':'aaf6fdbd3a3783c4a0e2b337de8f0cff8e42351a9216fecff2a6b8b056cc01ac',
          'test':'75315d4e3f3d73fe5cc1079758adecf1a87d17bd4dc4466701b5cbdfcbcac006'}
split = {}
for name, expected in hashes.items():
    path = splitdir / f'{name}.pt'
    assert hashlib.sha256(path.read_bytes()).hexdigest() == expected, f'hash inesperado: {path}'
    split[name] = torch.load(path, map_location='cpu', weights_only=False)
    split[name] = {k: torch.as_tensor(v) for k, v in split[name].items()}
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
n = data.num_nodes
known_pairs = np.concatenate([split[p]['edge'].numpy() for p in ('train', 'valid', 'test')])
def key(u, v): return min(int(u), int(v)) * n + max(int(u), int(v))
known = {key(u, v) for u, v in known_pairs}
train_edges = split['train']['edge'].numpy()
chosen = rng.choice(len(train_edges), size=128, replace=False)
supervision = train_edges[chosen]
all_keys = np.minimum(train_edges[:,0], train_edges[:,1]) * n + np.maximum(train_edges[:,0], train_edges[:,1])
supervision_keys = np.minimum(supervision[:,0], supervision[:,1]) * n + np.maximum(supervision[:,0], supervision[:,1])
mask = ~np.isin(all_keys, supervision_keys)  # retira todas las repeticiones del par
msg = train_edges[mask]
A = coo_matrix((np.ones(len(msg)*2), (np.r_[msg[:,0],msg[:,1]], np.r_[msg[:,1],msg[:,0]])), shape=(n,n)).tocsr()
A.data[:] = 1.; A.eliminate_zeros()
full = os.environ.get('COLLAB_FULL') == '1'
positive = split['test']['edge'].numpy() if full else split['test']['edge'].numpy()[:64]
official_negative = split['test']['edge_neg'].numpy() if full else split['test']['edge_neg'].numpy()[:128]
print('Test positivo ya observado en mensajes:', sum(bool(A[int(u),int(v)]) for u,v in positive), 'de', len(positive), flush=True)
reserved = {key(u,v) for u,v in official_negative}
negative = []
while len(negative) < len(supervision):
    u, v = rng.integers(n, size=2)
    k = key(u,v)
    if u != v and k not in known and k not in reserved:
        negative.append((u,v)); reserved.add(k)
train_pairs = np.concatenate([supervision, np.array(negative)])
train_y = torch.tensor([1.] * len(supervision) + [0.] * len(negative), device=device)

# Dos saltos desde fuentes de test; filtra con todas las aristas conocidas.
hard = []
for u, _ in positive:
    before = len(hard)
    nbr = A.indices[A.indptr[u]:A.indptr[u+1]].copy(); rng.shuffle(nbr)
    for mid in nbr:
        second = A.indices[A.indptr[mid]:A.indptr[mid+1]].copy(); rng.shuffle(second)
        for v in second:
            if u != v and key(u,v) not in known and key(u,v) not in reserved:
                hard.append((u,v)); reserved.add(key(u,v))
                if len(hard) - before == 2: break
        if len(hard) - before == 2: break
if len(hard) < 50: raise RuntimeError('No hay suficientes negativos difíciles para Hits@50')
hard = np.array(hard)
evaluator = Evaluator(name='ogbl-collab')
def metrics(pos, neg):
    p, q = np.asarray(pos), np.asarray(neg)
    auc = roc_auc_score(np.r_[np.ones(len(p)),np.zeros(len(q))], np.r_[p,q])
    hits = evaluator.eval({'y_pred_pos':torch.tensor(p), 'y_pred_neg':torch.tensor(q)})['hits@50']
    return {'auc':round(float(auc), 4), 'hits@50':round(float(hits), 4)}
def report(name, predict, start):
    pos = predict(positive); off = predict(official_negative); diff = predict(hard)
    if device.type == 'cuda': torch.cuda.synchronize()
    peak = torch.cuda.max_memory_allocated() / 2**20 if device.type == 'cuda' else 0
    print(name, 'oficial parcial', metrics(pos, off), 'difícil', metrics(pos, diff),
          'segundos', round(time.perf_counter()-start, 2), 'pico CUDA MiB', round(peak, 1), flush=True)
def tic():
    if device.type == 'cuda': torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
    return time.perf_counter()

start = tic()
def cn(pairs): return np.array([A[u].multiply(A[v]).sum() for u,v in pairs]).ravel()
report('CN CPU', cn, start)

edge_index = torch.tensor(np.vstack([np.r_[msg[:,0],msg[:,1]], np.r_[msg[:,1],msg[:,0]]]), dtype=torch.long, device=device)
x = data.x.to(device)
class GAE(nn.Module):
    def __init__(self, variational=False, hadamard=False):
        super().__init__(); self.g1 = GCNConv(x.shape[1], 16); self.g2 = GCNConv(16, 16)
        self.variational = variational
        self.logstd = GCNConv(16, 16) if variational else None
        self.decoder = nn.Sequential(nn.Linear(16,16), nn.ReLU(), nn.Linear(16,1)) if hadamard else None
    def embed(self):
        h=F.relu(self.g1(x, edge_index)); mu=self.g2(h, edge_index)
        if self.logstd is None: return mu, mu.new_zeros(())
        logstd=self.logstd(h, edge_index).clamp(-5, 3)
        kl=.5 * (mu.square()+torch.exp(2*logstd)-1-2*logstd).sum(dim=1).mean()
        return (mu + torch.randn_like(mu)*logstd.exp() if self.training else mu), kl
    def score(self, z, pairs):
        pairs = torch.as_tensor(pairs, dtype=torch.long, device=device)
        product = z[pairs[:,0]] * z[pairs[:,1]]
        return self.decoder(product).view(-1) if self.decoder is not None else product.sum(-1)
for name, variational, hadamard in [('GAE producto',False,False), ('GAE Hadamard-MLP',False,True), ('VGAE producto',True,False), ('VGAE Hadamard-MLP',True,True)]:
    start = tic(); model = GAE(variational,hadamard).to(device); optimizer = torch.optim.Adam(model.parameters(), lr=.01)
    for _ in range(5):
        optimizer.zero_grad(); z, kl = model.embed()
        loss = F.binary_cross_entropy_with_logits(model.score(z, train_pairs), train_y) + .01 * kl
        loss.backward(); optimizer.step()
    model.eval()
    with torch.no_grad(): z, _ = model.embed()
    def gae_predict(pairs):
        with torch.no_grad(): return model.score(z, pairs).cpu().numpy()
    report(name, gae_predict, start)
    del model, z, optimizer
del x, edge_index
if device.type == 'cuda': torch.cuda.empty_cache()

def local_graph(u, v):
    # Se limita cada vecindad a 12 nodos por coste; no es SEAL/NBFNet completo.
    nodes = {int(u),int(v)}
    for endpoint, opposite in ((u,v),(v,u)):
        neighbors = A.indices[A.indptr[endpoint]:A.indptr[endpoint+1]]
        nodes.update(int(w) for w in neighbors[neighbors != opposite][:12])
    nodes = sorted(nodes); idx = {node:i for i,node in enumerate(nodes)}
    sub = A[nodes][:,nodes].toarray(); i, j = idx[int(u)], idx[int(v)]
    sub[i,j] = sub[j,i] = 0
    # DRNL excluye el otro extremo de cada cálculo de distancias.
    left, right = sub.copy(), sub.copy(); left[j,:]=left[:,j]=0; right[i,:]=right[:,i]=0
    du = shortest_path(left, directed=False, indices=i, unweighted=True)
    dv = shortest_path(right, directed=False, indices=j, unweighted=True)
    label = np.zeros(len(nodes))
    for k in range(len(nodes)):
        if k in (i,j): label[k] = 1
        elif np.isfinite(du[k]) and np.isfinite(dv[k]):
            a, b = int(du[k]), int(dv[k]); d=a+b
            label[k] = 1 + min(a,b) + (d//2)*(d//2+d%2-1)
    row, col = np.nonzero(sub)
    features = np.column_stack([np.log1p(label), np.arange(len(nodes)) == i, np.arange(len(nodes)) == j, np.ones(len(nodes))])
    return Data(x=torch.tensor(features, dtype=torch.float), edge_index=torch.tensor(np.vstack([row,col]), dtype=torch.long), target=torch.tensor([j]))
cache = {}
def batches(pairs):
    graphs=[]
    for u,v in pairs:
        pair=(int(u),int(v))
        if pair not in cache: cache[pair] = local_graph(*pair)
        graphs.append(cache[pair])
    return Batch.from_data_list(graphs).to(device)

class PairModel(nn.Module):
    def __init__(self, mode):
        super().__init__(); self.mode=mode
        self.conv1=GCNConv(4, 16); self.conv2=GCNConv(16, 16); self.head=nn.Linear(16,1)
    def forward(self, batch):
        if self.mode == 'SEAL reducido':
            h = F.relu(self.conv1(batch.x, batch.edge_index)); h = F.relu(self.conv2(h,batch.edge_index))
            return self.head(global_mean_pool(h,batch.batch)).view(-1)
        # Tres pasos condicionados a la fuente y lectura en el destino local.
        initial = torch.zeros_like(batch.x); initial[:,1] = batch.x[:,1]
        h = F.relu(self.conv1(initial,batch.edge_index))
        h = F.relu(self.conv2(h,batch.edge_index)); h = F.relu(self.conv2(h,batch.edge_index))
        return self.head(h[batch.ptr[:-1] + batch.target]).view(-1)

for name in ('SEAL reducido', 'NBF reducido'):
    cache.clear()  # cada método paga su propia extracción de subgrafos
    start=tic(); model=PairModel(name).to(device); optimizer=torch.optim.Adam(model.parameters(),lr=.01)
    batch=batches(train_pairs)
    for _ in range(15):
        optimizer.zero_grad(); loss=F.binary_cross_entropy_with_logits(model(batch),train_y); loss.backward(); optimizer.step()
    model.eval()
    def predict(pairs):
        values = []
        with torch.no_grad():
            for begin in range(0, len(pairs), 128):
                values.append(model(batches(pairs[begin:begin+128])).cpu().numpy())
                cache.clear()  # memoria acotada también al recorrer todo el test
        return np.concatenate(values)
    report(name,predict,start)
    del model,optimizer,batch
    if device.type == 'cuda': torch.cuda.empty_cache()
print('Alcance: 128 supervisiones positivas,',len(positive),'positivas de test,',len(official_negative),'negativos oficiales,',len(hard),'difíciles; 5 o 15 épocas. Validación no utilizada.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Reproduce the candidate comparison

The preceding figure was obtained with the following local program using numpy, networkx, scikit-learn and torch. Download mini_mp.py from the message passing from scratch lesson and place it beside the program. The GAE encoder and subgraph classifier GNN use its PyTorch adapter. Reduced NBF propagates a source mark for three steps; it omits the original method’s multiple relations and generalized operators. All methods use the same queries and two negative sets.

[ ]Reproducible comparison on KarateLocal GPU
import json
import networkx as nx
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score
from mini_mp import MPLayer, torch_layer_from_numpy

torch.set_num_threads(2)
torch.manual_seed(7)
rng = np.random.default_rng(5)
graph = nx.karate_club_graph()
message = nx.Graph(nx.bfs_edges(graph, 0))
all_edges = {tuple(sorted(e)) for e in graph.edges}
remaining = sorted(all_edges - {tuple(sorted(e)) for e in message.edges})
rng.shuffle(remaining)
train_pos, valid_pos, test_pos = remaining[:20], remaining[20:30], remaining[30:]
queries = []
for u, v in test_pos:
    distances = nx.single_source_shortest_path_length(message, u)
    pool = [w for w in graph if w != u and tuple(sorted((u, w))) not in all_edges]
    hard = sorted(w for w in pool if distances[w] == 2)
    if len(hard) < 4: continue
    random_neg = rng.choice(sorted(pool), size=4, replace=False).tolist()
    hard_neg = rng.choice(hard, size=4, replace=False).tolist()
    queries.append({'pos': [u, v], 'random': [[u, w] for w in random_neg], 'hard': [[u, w] for w in hard_neg]})
reserved = {tuple(sorted(e)) for q in queries for group in ['random', 'hard'] for e in q[group]}
nonedges = sorted(tuple(sorted(e)) for e in nx.non_edges(graph) if tuple(sorted(e)) not in reserved)
train_neg = [nonedges[j] for j in rng.choice(len(nonedges), size=len(train_pos), replace=False)]
train_pairs = [list(e) for e in train_pos] + [list(e) for e in train_neg]
targets = torch.tensor([1.] * len(train_pos) + [0.] * len(train_neg))
directed = [(u, v) for u, v in message.edges for u, v in [(u, v), (v, u)]]
edge_index = torch.tensor(directed, dtype=torch.long).T
n = graph.number_of_nodes()
A = torch.zeros(n, n)
for u, v in message.edges: A[u, v] = A[v, u] = 1

class GAE(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb = nn.Parameter(torch.randn(n, 8) * .1)
        self.encoder = torch_layer_from_numpy(MPLayer(8, 12, aggregation='mean', seed=2)).float()
    def forward(self, pairs):
        z = self.encoder(self.emb, edge_index)
        p = torch.as_tensor(pairs, dtype=torch.long)
        return (z[p[:, 0]] * z[p[:, 1]]).sum(-1)

def subgraph_pair(u, v):
    nodes = set(nx.single_source_shortest_path_length(message, u, cutoff=2)) | set(nx.single_source_shortest_path_length(message, v, cutoff=2))
    nodes = sorted(nodes)
    sub = message.subgraph(nodes).copy()
    if sub.has_edge(u, v): sub.remove_edge(u, v)
    without_v, without_u = sub.copy(), sub.copy()
    without_v.remove_node(v); without_u.remove_node(u)
    du = nx.single_source_shortest_path_length(without_v, u)
    dv = nx.single_source_shortest_path_length(without_u, v)
    features = []
    for node in nodes:
        if node in (u, v): label = 1
        elif node not in du or node not in dv: label = 0
        else:
            a, b = du[node], dv[node]
            total = a + b
            label = 1 + min(a, b) + (total // 2) * (total // 2 + total % 2 - 1)
        features.append([float(node in (u, v)), np.log1p(label), sub.degree[node] / n, 1.])
    idx = {node: i for i, node in enumerate(nodes)}
    edges = [(idx[a], idx[b]) for a, b in sub.edges for a, b in [(a, b), (b, a)]]
    return np.array(features), np.asarray(edges, dtype=np.int64).reshape(-1, 2).T

cache = {}
def seal_batch(pairs):
    xs, edges, group = [], [], []
    offset = 0
    for i, pair in enumerate(pairs):
        key = tuple(sorted(pair))
        if key not in cache: cache[key] = subgraph_pair(*key)
        x, e = cache[key]
        xs.append(x); edges.append(e + offset); group.extend([i] * len(x)); offset += len(x)
    return torch.tensor(np.concatenate(xs), dtype=torch.float32), torch.tensor(np.concatenate(edges, axis=1)), torch.tensor(group)

class SEALSmall(nn.Module):
    def __init__(self):
        super().__init__()
        self.encoder = torch_layer_from_numpy(MPLayer(4, 8, aggregation='mean', seed=3)).float()
        self.head = nn.Linear(4, 1)
    def forward(self, pairs):
        x, e, group = seal_batch(pairs)
        h = torch.relu(self.encoder(x, e))
        pooled = torch.zeros(len(pairs), 4).index_add(0, group, h)
        return self.head(pooled).view(-1)

class PathNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.start = nn.Parameter(torch.randn(8) * .1)
        self.encoder = torch_layer_from_numpy(MPLayer(8, 12, aggregation='mean', seed=4)).float()
        self.head = nn.Linear(8, 1)
    def forward(self, pairs):
        p = torch.as_tensor(pairs, dtype=torch.long)
        indicator = F.one_hot(p[:, 0], n).float().unsqueeze(-1) * self.start
        batched_edges = (edge_index.unsqueeze(0) + torch.arange(len(p))[:, None, None] * n).permute(1, 0, 2).reshape(2, -1)
        initial = indicator.reshape(-1, 8)
        h = initial
        for _ in range(3):
            h = torch.relu(self.encoder(h, batched_edges) + initial)
        h = h.reshape(len(p), n, 8)
        return self.head(h[torch.arange(len(p)), p[:, 1]]).view(-1)

def train(model):
    optimizer = torch.optim.Adam(model.parameters(), lr=.01)
    for _ in range(80):
        model.train(); optimizer.zero_grad()
        loss = F.binary_cross_entropy_with_logits(model(train_pairs), targets)
        loss.backward(); optimizer.step()
    model.eval()
    return model

def cn(pairs):
    return np.array([len(set(message.neighbors(u)) & set(message.neighbors(v))) for u, v in pairs], dtype=float)

models = {'CN': None, 'GAE': train(GAE()), 'SEAL simplificado': train(SEALSmall()), 'NBF simplificado': train(PathNet())}
results = {}
for kind, model in models.items():
    def predict(pairs):
        if model is None: return cn(pairs)
        with torch.no_grad(): return model(pairs).numpy()
    pos = predict([q['pos'] for q in queries])
    per = {}
    for group in ['random', 'hard']:
        neg = predict([edge for q in queries for edge in q[group]]).reshape(len(queries), 4)
        ranks = 1 + (neg > pos[:, None]).sum(1) + .5 * (neg == pos[:, None]).sum(1)
        auc = roc_auc_score(np.r_[np.ones(len(pos)), np.zeros(neg.size)], np.r_[pos, neg.ravel()])
        per[group] = {'auc': float(auc), 'hits': [float(np.mean(ranks <= k)) for k in [1, 2, 3, 4]], 'mrr': float(np.mean(1 / ranks))}
    results[kind] = per
print('consultas', len(queries), 'train', len(train_pos), 'validación reservada', len(valid_pos), 'test total', len(test_pos))
print(json.dumps(results, ensure_ascii=False), flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
Two nodes have three common neighbors of degrees 2, 3 and 10. Calculate Adamic-Adar using natural logarithms.
Numeric
For the same three intermediaries of degrees 2, 3 and 10, calculate the common-neighbor score.
Numeric
For the three intermediaries of degrees 2, 3 and 10, calculate the resource-allocation score.
Quiz
You want to predict dependencies a project will add next month. Which split matches that question?
Proof
Prove: If an equivariant MPNN sees a graph with features preserved by an automorphism π mapping u to u' and fixing v, any deterministic decoder of the two embeddings assigns equal scores to (u,v) and (u',v).
0
Let H be the MPNN output and P the permutation matrix of π.

Step 1 of 3. What does the automorphism do to the input?

Proof
Prove: If βρ(A) < 1, the Katz series converges to (I − βA)⁻¹ − I.
0
Let B = βA be a finite square matrix with spectral radius less than one.

Step 1 of 3. What happens to powers of B?

Code
Implement mrr(pos_scores, neg_scores). pos_scores has shape (Q,) and neg_scores (Q, M), with M equal for each query. Use OGB average rank for ties: 1 + number of strictly greater negatives + half the tied negatives. Return the mean reciprocal. Reject incompatible shapes or nonfinite inputs with ValueError.
import numpy as np
def mrr(pos_scores, neg_scores):
  pass
Shift+Enter to run

In the test’s tie example, the OGB 1.3.6 Evaluator('ogbl-citation2') evaluator receives PyTorch tensors and returns reciprocals [0.4, 0.5]; their mean is 0.45. This exercise’s shape check also accepts zero negatives per query, an edge case defined here and not a claim about benchmark candidate sizes.

Key idea
The learning unit is the pair under specific observable information and candidate distribution. The message graph, query labeling and metric determine what a score can demonstrate.