Link prediction and knowledge graphs
Implement TransE, DistMult, and RotatE on FB15k-237 with self-adversarial negative sampling and filtered-ranking evaluation. Study how edge splits and evaluation protocol can inflate results and compare a graph autoencoder for link prediction on a homogeneous graph.
After this lesson you can
- Implement TransE, DistMult, and RotatE scoring functions and contrastive training.
- Implement uniform and self-adversarial negative sampling.
- Evaluate with filtered MRR and Hits@K without edge leakage.
- Compare own results with published ones and explain protocol differences.
Before you start
An unknown link is not necessarily false
A knowledge base stores facts as triples : head entity, relation, and tail entity. Prediction asks which entity is missing in or . Absence of a triple from the record does not prove it false: a sampled negative can be an unobserved true fact. This open-world assumption affects both loss and evaluation.
In a link GNN, the message graph and edges supervising prediction must be separated. If a test edge remains in the message graph, the encoder can directly observe the connection it must predict. In an undirected graph remove both directions and all copies of that edge. If a temporal protocol allows previously observed edges to be added later, state exactly what information was available at prediction.
Three relation geometries
Knowledge-graph embeddings assign learnable vectors to entities and relations. A score gives an ordering, not a calibrated probability. Three models illustrate different tradeoffs: TransE translates vectors, DistMult uses a diagonal product, and RotatE rotates each complex component:
The abbreviation refers to RotatE. In that model entities are complex and each relation component has unit modulus. An inverse relation changes the phase sign, and composing two rotations adds phases modulo . The figure fixes an initial entity at 1 and uses one complex coordinate, so you can verify identities without confusing them with training results.
RotatE’s symmetric error is : it vanishes at phase 0 or 180 degrees. For TransE take ; also requiring leaves error ; requiring both exact equalities forces . DistMult assigns the same score when swapping head and tail because real scalar products commute. In the figure both relation components are 1 and both scores equal . These constraints describe exact fits; a loss can approximate them without perfect satisfaction.
In TransE an inverse relation can be represented by and a chain of two translations by . But if the same head and relation must lead exactly to two different tails, equations and force both representations to coincide. In practice distances, not rigid equalities, are optimized, but the example shows why one-to-many relations can be difficult for a simple translation.
RotatE preserves each component’s modulus when applying a relation: . Angle describes a transformation and distance measures how far it is from reaching the tail. Zero phase represents identity and phase is its own inverse; other phases can describe a relation whose reverse uses another phase. A zero embedding trivially satisfies many equalities, so separating positive and negative facts remains necessary to learn useful representations.
In DistMult, fixing head and relation produces query vector and scoring tails is equivalent to dot products with their embeddings. This can be efficient, but the same commutativity that simplifies computation imposes symmetry when swapping endpoints for a fixed relation. An inverse relation modeled as a different identifier can have other parameters; that does not remove score symmetry when reversing endpoints while retaining the same identifier.
Geometric composition does not establish a universal logical rule over data. Two phases adding to another relation’s phase permits representing a regularity when facts and embeddings support it; it does not prove every pair of observed edges implies a third. Exceptions, incomplete relations, or entities with multiple roles can exist. A high score is a proposal for inspection or retrieval and must be checked against external evidence when the application requires reliable facts.
Negatives and self-adversarial loss
Negative sampling strategies corrupt the head or tail of a positive. Uniform sampling among entities is cheap, but many negatives are easy. RotatE weights batch negatives by their current score:
The implementation stops the gradient of : the model learns from weighted negatives without differentiating through the weighting rule. If , weights are uniform; with , higher-scoring negatives receive more weight. Corruptions present among training triples are discarded, but unknown false negatives can remain. Filtering with validation or test during training would incorporate future information; retrospective evaluation uses another filter for a different purpose.
The negative candidate set also defines task difficulty. Randomly corrupting a head or tail does not necessarily respect type constraints: a wrong-type entity may be trivial to discard. Restricting candidates to compatible types can create more informative negatives, but changes the loss distribution and must be disclosed in comparisons. A corrupted entity matching the original positive is removed if that triple is already in training. In an extremely dense graph, repeatedly sampling until finding a valid negative can be slow; a practical system must also handle that edge case.
Adversarial weighting does not turn scores into probabilities that a fact is false. Softmax normalizes only within the batch’s particular negatives; changing the batch changes the distribution. Stopping gradient on those weights is a loss choice, not a numerical approximation to the gradient obtained by differentiating softmax. When comparing uniform and adversarial sampling, hold dataset, number of negatives, steps, and selection method fixed for a clear interpretation of the difference.
The derivative shows the weight’s effect. For a negative, has derivative . With stopped, its gradient contribution with respect to is : a high-scoring negative receives both a larger sigmoid factor and normally a larger weight. The derivative of the positive part is , so minimizing loss pushes its score upward. If an unobserved true fact is treated as negative, the same rule can push it the wrong way.
Calculating 256 negatives per positive and complex dimension 1000 can produce large activations. The program first obtains all negative scores without retaining their gradient graph and calculates one softmax distribution. It then rescores subsets and accumulates gradient contributions using the same stopped weights. Since negative loss is a sum of terms with fixed weights, this preserves the declared rule’s gradient; a different softmax in each block would not. The effective batch can also be divided into microbatches with --microbatch: first sample all positives and corruptions, normalize their weights over the full batch, and accumulate gradients before one Adam update. Each row retains its softmax over 256 negatives; summation order may cause small rounding differences. In a synthetic test of seven positives versus microbatches of 3, 3, and 1, all three models, both sampling methods, and both directions agreed in gradient to at most 4.47×10⁻⁸ and in parameters after Adam to 7.45×10⁻⁹. The test verifies CPU numerical equivalence for that case, not benchmark performance.
Ranking and filtering
Link-prediction evaluation compares the true answer against all candidate entities. For filtered test rank, other known train, validation, or test answers are removed while retaining the evaluated answer. To select checkpoints on validation, the laboratory filters using only train and validation facts; this avoids reserved test facts during selection. Thus a model is not penalized for ranking another documented answer higher. That retrospective filter is the benchmark protocol: a historical system cannot use facts it did not yet know.
Here we handle ties with average rank:
MRR is the mean reciprocal of head and tail ranks; Hits@K is the fraction of queries with rank . Average rank avoids resolving all ties in the target’s favor but can be fractional. State this convention, candidate entities, and filter before comparing another report. Raw ranking retains other known truths and can therefore be worse; difference magnitude depends on data and model.
For example, with ranks 1, 2, and 10, MRR is , while Hits@3 is . MRR strongly rewards moving an answer from rank 2 to 1; the same one-position improvement near the bottom changes its reciprocal much less. Hits@K changes only on crossing cutoff K. Neither metric indicates whether the first result is a true answer still absent from the graph: evaluation only knows available labels.
The filter is applied per query. When evaluating , remove other known tails for that same pair ; when evaluating , remove other known heads for . Do not indiscriminately filter entities appearing in another relation. The target answer is retained even if in the known-fact set. Tie convention affects MRR and Hits when scores are identical; a benchmark using optimistic or pessimistic rank can produce a different figure without model weights changing.
If candidates are strictly better and candidates other than the target tie it, optimistic rank is and pessimistic rank is . Average rank averages both. For example, two better candidates and three additional ties give 3, 6, and 4.5 under the three conventions. Fractional rank is a tie convention, not a returned half-entity. Hits@K must use the chosen convention, especially when a tie crosses the cutoff.
import numpy as np
def filtered_rank(scores,true_idx,known_mask):
valid = ~np.asarray(known_mask,dtype=bool).copy()
valid[true_idx] = False
target = scores[true_idx]
return 1 + np.sum(scores[valid] > target) + 0.5*np.sum(scores[valid] == target)
scores = np.array([0.9,1.0,0.8,0.9])
known = np.array([True,True,False,False])
print('rango filtrado',filtered_rank(scores,0,known))
assert filtered_rank(scores,0,known)==1.5Laboratory on FB15k-237
FB15k-237 removes relations selected for inverse redundancy in FB15k, but does not prove all shortcuts or biases are gone. Laboratory files come from the RotatE authors’ repository pinned to commit 2e440e0f9c687314d5ff67ead68ce985dc446e3a. RotatE reports filtered MRR 0.338 and Hits@10 0.533 for FB15k-237; its hyperparameter table uses complex dimension 1000, batch 1024, 256 negatives, margin 9, and adversarial temperature 1. The configuration script specifies 100000 steps and initial rate 0.00005 for that configuration.
The pinned files contain 14541 entities and 237 relations, with 272115 training, 17535 validation, and 20466 test triples. Each evaluated triple generates one head and one tail query: full test evaluation includes 40932 ranks, each against all entities before filtering. These figures characterize the files, not the number of true facts in the world or independent queries when several share entities or relations.
Download the embedding experiment. It requires PyTorch and NumPy; if data are missing it obtains them from that commit. It implements all three scores, uniform or self-adversarial sampling, training-negative filtering, and raw and filtered head and tail ranking. It processes negatives in blocks to reduce peak activations without changing softmax weights: first calculate scores without gradient, then accumulate gradients with those fixed weights. Checkpoints save parameters, optimizer, and generator state; --resume requires the same configuration. --pause-after pauses without changing total steps. With --resume --evaluate-checkpoint --validation-only you can evaluate the checkpoint on validation without training or calculating test metrics.
python kg_experiment.py --model rotate --sampler adversarial --steps 100000 --checkpoint rotate.pt --output rotate.json
python kg_experiment.py --model rotate --sampler uniform --steps 100000 --checkpoint rotate-uniforme.pt --output rotate-uniforme.json
python kg_experiment.py --model transe --sampler adversarial --steps 100000 --checkpoint transe.pt --output transe.json
python kg_experiment.py --model distmult --sampler adversarial --steps 100000 --checkpoint distmult.pt --output distmult.json
The script fixes rate reduction halfway through steps, frequency weights, and full candidates. Its complex norm uses a small constant inside the square root to avoid a singular derivative at zero. Random positive selection, validation filter, implementation details, and regularization can differ from original code; closeness to the paper must be measured, not assumed. --eval-limit greater than zero only diagnoses a workflow on a test sample and must be identified as such; default zero evaluates all triples. Full ranking of thousands of queries against every entity and training at this budget can take many hours. A short test is not full reproduction.
We trained all three models from scratch on the same RTX 3060, with one seed and a budget fixed before test: 10000 updates, dimension 256, 1024 positives per batch, microbatches of 128, 64 negatives, and initial rate 0.00005. All three use self-adversarial sampling; we add RotatE with uniform weights to compare sampling. Other parameters, split, and evaluation remain as in the script. Each test result uses all 40932 queries, each over 14541 entities before filtering and with average rank for ties.
| Model and sampling | Raw MRR | Filtered MRR | Filtered Hits@10 |
|---|---|---|---|
| TransE, self-adversarial | 0.1248 | 0.1938 | 0.3456 |
| DistMult, self-adversarial | 0.0663 | 0.1327 | 0.2155 |
| RotatE, self-adversarial | 0.0519 | 0.0862 | 0.1617 |
| RotatE, uniform | 0.0425 | 0.0604 | 0.1205 |
Filtering increases MRR in all four runs because it removes other known answers to the same query. With this seed and budget, self-adversarial RotatE exceeds uniform by 0.0258 filtered MRR; no additional seeds were run to estimate variation. TransE ranked first in this particular comparison. The result does not establish a universal architecture ordering: the same rate and dimension are not necessarily optimal for each, and RotatE has more real parameters due to complex entities.
Our RotatE is far from the published 0.338. Our run uses 10000 steps, dimension 256, and 64 negatives, versus 100000, 1000, and 256 in the published recipe, plus the implementation differences already noted. There is no validation curve across checkpoints to establish convergence or identify which difference explains the gap. A ten-step test with the large recipe and microbatches 128 reserved its own peak of 799 MB and took 18.0 s on a shared GPU; it is not a 100000-step model. The full summary retains MRR, Hits@1/3/10, both rankings, checkpoint hashes, and shared training times. Weights are our own but are not distributed with the lesson; the script allows them to be regenerated.
To reproduce the measured comparison, add --dimension 256 --batch-size 1024 --microbatch 128 --negatives 64 --steps 10000 to each of the four preceding commands and change checkpoint and output names. The adversarial RotatE run was deliberately interrupted after ten steps and resumed with the same state and configuration; times were summed. The GPU was shared with other work, so documented seconds describe those runs’ cost, not isolated latencies.
Evaluation batches queries and traverses candidate entities in blocks: it still compares every entity, but need not store a complete query-by-entity matrix. --eval-batch changes grouping, not the filter or candidate count. One batch versus several was checked in an example with ties and three entity blocks; reproducing the benchmark also requires running full ranking on trained weights and recording results.
At dimension 1000, RotatE retains two real coordinates per complex entity component. For the sizes above this is scalar embedding parameters; TransE and DistMult use each. In float32 RotatE weights alone occupy 117276000 bytes, before gradients, Adam moments, and activations. Equal nominal dimension does not equalize parameter count or compute cost; a quality comparison with those commands must declare that difference.
This program’s optimizer is recreated halfway through the budget with a tenfold lower rate, also resetting its moments. That choice is part of the experiment and is not equivalent to lowering the rate while retaining Adam state. For resumption, the checkpoint saves step, weights, optimizer, and generator; on reaching the same rate change it follows the fixed rule. Comparing another training plan requires declaring the change and not selecting its variant by looking at test.
Aggregate MRR weights every dataset query equally. A frequent relation or an entity appearing many times can dominate the mean, while improvement on a rare relation barely moves it. Breakdown by relation and query type helps detect this, always showing denominators. A split by time or new entities asks a different question from the fixed FB15k-237 split, which alone does not show the model generalizes to future facts or entities without trained embeddings.
A graph autoencoder as a contrast
A graph autoencoder uses a node encoder and pair decoder, for example . It suits a homogeneous undirected graph, whereas the previous models score typed relations. The cell uses Cora, separates positive and negative edges, and removes supervision, validation, and test positives from the message graph. Epoch selection uses validation ROC-AUC; that ROC-AUC is not compared to FB15k-237 MRR as if they measured the same task.
import copy
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures, RandomLinkSplit
from torch_geometric.nn import GCNConv
from sklearn.metrics import roc_auc_score
torch.manual_seed(15)
root=Path.home()/'.cache'/'oryon'/'datasets'/'Planetoid'
graph=Planetoid(str(root),'Cora',transform=NormalizeFeatures())[0]
splitter=RandomLinkSplit(num_val=.05,num_test=.1,is_undirected=True,add_negative_train_samples=True,disjoint_train_ratio=.2)
train,val,test=splitter(graph)
def pairs(edges):
return {tuple(sorted((int(a),int(b)))) for a,b in edges.T.tolist()}
message_pairs=pairs(train.edge_index)
for part in (train,val,test):
positives=part.edge_label_index[:,part.edge_label>0]
assert not (pairs(positives) & message_pairs)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train=train.to(device); val=val.to(device); test=test.to(device)
class Encoder(nn.Module):
def __init__(self):
super().__init__(); self.a=GCNConv(graph.num_node_features,32); self.b=GCNConv(32,16)
def forward(self,x,edges): return self.b(F.relu(self.a(x,edges)),edges)
def decode(z,pairs): return (z[pairs[0]]*z[pairs[1]]).sum(-1)
def auc(model,part):
model.eval()
with torch.no_grad():
z=model(train.x,train.edge_index); scores=decode(z,part.edge_label_index)
return roc_auc_score(part.edge_label.cpu().numpy(),scores.cpu().numpy())
model=Encoder().to(device); opt=torch.optim.Adam(model.parameters(),lr=.01)
best=-1.; state=None
for epoch in range(1,101):
model.train(); opt.zero_grad(); z=model(train.x,train.edge_index)
loss=F.binary_cross_entropy_with_logits(decode(z,train.edge_label_index),train.edge_label.float())
loss.backward(); opt.step(); v=auc(model,val)
if v>best: best=v; state=copy.deepcopy(model.state_dict()); best_epoch=epoch
model.load_state_dict(state)
print('época',best_epoch,'validación ROC-AUC',round(best,4),'test ROC-AUC',round(auc(model,test),4))npm run lab and open the connection link.In a local CPU run, the best validation epoch was 48, with ROC-AUC 0.7565 on validation and 0.7170 on test. This is one split and initialization, not an uncertainty interval or a result comparable with knowledge-graph MRR. The edge-separation assertion passed in that run.
The dot product is symmetric: it does not represent different directions for and . The GCN uses all Cora features and only training-graph edges. This example does not evaluate new entities, typed relations, or temporal deployment; it demonstrates a reproducible split and a specific decoder.
In this split, some training edges are reserved to supervise the decoder and do not appear in the message graph; both directions of validation and test positives are also removed. The assertion makes that condition an explicit check. For all three evaluations the encoder uses the same train.edge_index graph, so reserved edges are not incorporated when building test embeddings. Features of all nodes remain available: this is a transductive link experiment, not an inductive test on unknown nodes.
Training negatives are generated when building the split and remain fixed in this cell. This makes epoch comparison reproducible, but the model can adapt to that particular set of negative pairs. Resampling each epoch would be another experimental choice and require fixing the seed and avoiding known positive pairs. The decoder’s dot product transforms each pair into a logit; ROC-AUC evaluates ranking of split positives and negatives without claiming their sigmoids are calibrated future-link probabilities.
Exercises
Step 1 of 2. What happens when head and tail are swapped?
import numpy as np
def filtered_rank(scores,true_idx,known_mask):
...