Knowledge Graph Embedding in TGraphX: Train and Rank TransE, DistMult, ComplEx, RotatE
Topic: Knowledge graphs
Knowledge graph (KG) embedding models learn representations of entities and relations so that true triples (head, relation, tail) score higher than false ones. tgraphx.kg implements six classic scoring models (TransE, DistMult, ComplEx, RotatE, RESCAL, SimplE) together with negative samplers, a trainer and filtered ranking. It can also compute entity representations from tensor features, such as an image per movie, with MultimodalKGModel.
This tutorial runs the whole workflow on a small synthetic movie graph. The numbers it prints only show that the pipeline works; they are not a benchmark. Examples tested with TGraphX 1.5.1.
The KG subsystem is young. tgx.api_status("TransEModel") and tgx.api_status("DistMultModel") return 'beta', while tgx.api_status("ComplExModel") and tgx.api_status("RotatEModel") return 'experimental'. The module docstrings also mark KGTrainer, MultimodalKGModel, its feature projectors and TypedNegativeSampler as experimental. For KGTrainer the two sources disagree (tgx.api_status("KGTrainer") returns 'beta'), so plan for the more cautious label.
Setup
pip install tgraphx
TGraphX 1.5.1 needs Python 3.10 or newer.
Step 1: Build a knowledge graph and split the triples
Triples are a [num_triples, 3] integer tensor in (head, relation, tail) order. The graph below has 40 users, 30 movies and 3 genres. Each user likes movies from one preferred genre, so there is a pattern to learn.
import torch
import torch.nn as nn
import tgraphx as tgx
from tgraphx.kg import KnowledgeGraph
torch.manual_seed(0)
NUM_USERS, NUM_MOVIES, NUM_GENRES = 40, 30, 3
NUM_ENTITIES = NUM_USERS + NUM_MOVIES + NUM_GENRES
LIKES, HAS_GENRE = 0, 1
movie_ids = torch.arange(NUM_USERS, NUM_USERS + NUM_MOVIES)
genre_ids = torch.arange(NUM_USERS + NUM_MOVIES, NUM_ENTITIES)
movie_genre = torch.arange(NUM_MOVIES) % NUM_GENRES
rows = []
for user in range(NUM_USERS):
same_genre = movie_ids[movie_genre == user % NUM_GENRES]
for movie in same_genre[torch.randperm(len(same_genre))[:6]].tolist():
rows.append((user, LIKES, movie))
for movie, genre in zip(movie_ids.tolist(), movie_genre.tolist()):
rows.append((movie, HAS_GENRE, int(genre_ids[genre])))
kg = KnowledgeGraph(torch.tensor(rows), num_entities=NUM_ENTITIES, num_relations=2)
train_kg, valid_kg, test_kg = kg.train_valid_test_split(0.8, 0.1, 0.1, seed=0)
print(kg)
print(len(train_kg), len(valid_kg), len(test_kg))
Pass num_entities and num_relations explicitly when you know them; otherwise they are inferred as the largest ID plus one. train_valid_test_split shuffles triples at random. For time-stamped facts use a chronological split instead.
If your data uses names, from_triples builds the ID mappings for you (KnowledgeGraph.from_hrt takes three separate 1-D tensors):
named = KnowledgeGraph.from_triples([
("inception", "directed_by", "nolan"),
("nolan", "born_in", "london"),
])
print(named.entity_to_id)
print(named.relation_to_id)
Step 2: Train TransE with KGTrainer
Build the model, a training config and a negative sampler, then hand the training triples to KGTrainer. KGEvaluator computes filtered ranking metrics.
from tgraphx.kg import (TransEModel, KGTrainer, KGTrainingConfig,
KGEvaluator, UniformNegativeSampler)
NEGATIVES = 4
def train(model_cls, loss_type="softplus"):
torch.manual_seed(0)
model = model_cls(kg.num_entities, kg.num_relations, embedding_dim=32)
config = KGTrainingConfig(num_epochs=60, batch_size=64, lr=1e-2,
loss_type=loss_type, seed=0)
sampler = UniformNegativeSampler(kg.num_entities, num_negatives=NEGATIVES)
history = KGTrainer(model, config, train_kg.triples, sampler=sampler).train()
return model, history
transe, history = train(TransEModel, loss_type="margin")
print(f"final training loss: {history['final_loss']:.3f}")
evaluator = KGEvaluator(train_kg.triples, valid_kg.triples, test_kg.triples,
num_entities=kg.num_entities)
val = evaluator.evaluate(transe, triples=valid_kg.triples)
print(f"validation MRR={val.filt_mrr:.3f} Hits@10={val.filt_hits[10]:.3f}")
Three details matter here:
- Negatives per positive come from the sampler. When you pass
sampler=,KGTrainingConfig.num_negativesis ignored in 1.5.1. - Loss choice. The default is
"softplus". TransE scores are negative distances and therefore never positive, so the margin loss is the usual choice for it. - No early stopping.
train()returns a history dict and updates the model you passed in place; the model is left as it is after the last epoch. If you need the best validation epoch, keep acopy.deepcopyofmodel.state_dict()in theon_epoch_endcallback.
Step 3: Compare scoring functions
All scoring classes share the same constructor and score_triples interface, so the training function from Step 2 works for each of them. Choose with the validation split and report the test split once.
from tgraphx.kg import (DistMultModel, ComplExModel, RotatEModel,
RESCALModel, SimplEModel)
models = {"TransE": transe}
for cls in (DistMultModel, ComplExModel, RotatEModel, RESCALModel, SimplEModel):
models[cls.__name__.removesuffix("Model")] = train(cls)[0]
val_mrr = {name: evaluator.evaluate(m, triples=valid_kg.triples).filt_mrr
for name, m in models.items()}
for name, score in val_mrr.items():
print(f"{name:9s} validation MRR {score:.3f}")
best = max(val_mrr, key=val_mrr.get)
test = evaluator.evaluate(models[best], triples=test_kg.triples)
print(f"selected {best}: test MRR={test.filt_mrr:.3f} Hits@1={test.filt_hits[1]:.3f} "
f"Hits@10={test.filt_hits[10]:.3f}")
On a graph this small the ordering is mostly noise. On real data, choose with relation patterns in mind:
| Model | Score (higher is more plausible) | Symmetry | Antisymmetry | Inversion | Composition |
|---|---|---|---|---|---|
| TransE | −‖h + r − t‖ | no | yes | yes | yes |
| DistMult | ⟨h, r, t⟩ | yes, always | no | no | no |
| ComplEx | Re ⟨h, r, conj(t)⟩ | yes | yes | yes | no |
| RotatE | margin − ‖h ∘ r − t‖, each rᵢ of modulus 1 | yes | yes | yes | yes |
The pattern columns follow the comparison in Sun et al., "RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space" (ICLR 2019). RESCAL scores with a full matrix per relation, hᵀ Mᵣ t, so its relation parameters grow with the square of the embedding size. SimplE keeps separate head and tail embeddings per entity plus an inverse relation embedding; it is not restricted to symmetric relations, and Kazemi and Poole (NeurIPS 2018) show it is fully expressive. TransE is also known to struggle with one-to-many and many-to-one relations.
Two implementation notes if you compare with published numbers: TransEModel L2-normalizes entity embeddings inside the score, and RotatEModel normalizes every complex coordinate of the entity embeddings to unit modulus, a constraint the RotatE paper does not place on entities.
For the mathematics behind these choices, see how TransE, DistMult, ComplEx and RotatE score triples.
Step 4: Entity representations from tensor features
So far each entity is only an ID with a learned embedding. Entities often have content of their own: movies have posters, users have profile vectors.
KnowledgeGraph(entity_features=...) stores such tensors at any rank, but storing them changes nothing about training: KGTrainer and tgx.kg_completion() do not read them. To use them, build a MultimodalKGModel. It projects each modality to out_dim, fuses the projections, adds a learned per-entity embedding and scores with a DistMult decoder.
Each feature tensor needs one row per entity. A boolean mask says which rows are real.
from tgraphx.kg import MultimodalKGModel, VectorEntityProjector, SoftplusKGLoss
# KGTrainer re-seeded PyTorch's global generator with config.seed (0), the seed that chose the likes.
# Draw the stand-in features from an unrelated generator so they cannot encode those triples.
feature_rng = torch.Generator().manual_seed(1_000_003)
posters = torch.randn(NUM_ENTITIES, 3, 16, 16, generator=feature_rng) # real only for movie rows
profiles = torch.randn(NUM_ENTITIES, 8, generator=feature_rng) # real only for user rows
is_movie = torch.zeros(NUM_ENTITIES, dtype=torch.bool)
is_movie[movie_ids] = True
is_user = torch.arange(NUM_ENTITIES) < NUM_USERS
features = {"poster": posters, "profile": profiles}
masks = {"poster": is_movie, "profile": is_user}
class PosterEncoder(nn.Module):
"""[N, 3, H, W] -> [N, out_dim], keeping local spatial patterns."""
def __init__(self, out_dim):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(16, out_dim))
def forward(self, x):
return self.net(x)
torch.manual_seed(0)
mm = MultimodalKGModel(
NUM_ENTITIES, kg.num_relations, out_dim=32,
projectors={"poster": PosterEncoder(32), "profile": VectorEntityProjector(8, 32)},
fusion_mode="gated",
)
print(mm.score_triples(train_kg.triples[:4], mm.encode_entities(features, masks)).shape)
TGraphX also ships ImageEntityProjector(3, out_dim). It averages over height and width before its linear layer, so only per-channel means survive. Use it for global color or intensity statistics. When spatial layout matters, pass your own nn.Module that maps [N, ...] to [N, out_dim], like the convolutional encoder above.
KGTrainer calls score_triples(batch) without entity embeddings, which this model rejects, so write the loop yourself:
sampler = UniformNegativeSampler(NUM_ENTITIES, num_negatives=NEGATIVES)
loss_fn = SoftplusKGLoss()
optimizer = torch.optim.Adam(mm.parameters(), lr=1e-2)
gen = torch.Generator().manual_seed(0)
for epoch in range(40):
for idx in torch.randperm(len(train_kg), generator=gen).split(64):
positive = train_kg.triples[idx]
negative = sampler.sample(positive, generator=gen).view(-1, 3)
entities = mm.encode_entities(features, masks) # recomputed: encoders are learning
loss = loss_fn(mm.score_triples(positive, entities),
mm.score_triples(negative, entities))
optimizer.zero_grad()
loss.backward()
optimizer.step()
class EncodedKG(nn.Module):
"""Encode once, then expose score_triples(triples) for KGEvaluator."""
def __init__(self, model):
super().__init__()
self.model = model.eval()
with torch.no_grad():
self.register_buffer("entities", model.encode_entities(features, masks))
def score_triples(self, triples):
return self.model.score_triples(triples, self.entities)
mm_val = evaluator.evaluate(EncodedKG(mm), triples=valid_kg.triples)
print(f"multimodal validation MRR {mm_val.filt_mrr:.3f} "
f"(ID-only DistMult: {val_mrr['DistMult']:.3f})")
The two numbers are not evidence for or against features: the posters and profiles here are random noise, and the two models were not trained alike. On your data, run the ID-only and feature-based models on the same split, tune both on validation and compare over several seeds. Also keep in mind:
- The DistMult decoder is symmetric in head and tail, so it cannot express direction between two entities of the same type.
- Every training step re-encodes all entities. With large images or many entities, precompute features with a frozen encoder or write a model that encodes only the entities in the batch.
TransEModelacceptsentity_feature_dimfor vector features, butKGTrainerandKGEvaluatornever pass features to it.DistMultModel(entity_feature_dim=...)creates a projector that itsscore_triplesdoes not call. Neither is a working shortcut in 1.5.1.
Step 5: Choose a negative sampler
Training contrasts each true triple with corrupted ones, in which the head or the tail is replaced. All KG samplers return a [batch, K, 3] tensor.
from tgraphx.kg import (BernoulliNegativeSampler, FilteredNegativeSampler,
TypedNegativeSampler)
batch = train_kg.triples[:5]
user_range = torch.arange(NUM_USERS)
samplers = {
"uniform": UniformNegativeSampler(NUM_ENTITIES, num_negatives=4),
"bernoulli": BernoulliNegativeSampler(NUM_ENTITIES, num_negatives=4,
train_triples=train_kg.triples),
"filtered": FilteredNegativeSampler(NUM_ENTITIES, num_negatives=4,
positive_set=train_kg.positive_triple_set()),
"typed": TypedNegativeSampler(NUM_ENTITIES, num_negatives=4,
domains={LIKES: user_range, HAS_GENRE: movie_ids},
ranges={LIKES: movie_ids, HAS_GENRE: genre_ids}),
}
for name, s in samplers.items():
print(name, tuple(s.sample(batch, generator=torch.Generator().manual_seed(0)).shape))
- Uniform replaces head or tail with any entity; some draws are in fact true triples.
- Bernoulli chooses which side to corrupt per relation, based on how one-to-many it is.
- Filtered rejects draws found in
positive_set. Give it the training positives only, so test facts do not influence training. - Typed keeps replacements within the allowed heads and tails of each relation, so a
likesnegative stays a (user, movie) pair.
Pass any of them as KGTrainer(..., sampler=...). Schema-aware neural architectures for structured data builds on such relation signatures and shows a 1.5.1 trap: passing entity_types alone does not restrict the typed sampler. The filtered and typed samplers loop in Python and are slower on large graphs. Do not confuse them with tgx.negative_sampling(), which samples non-edges of an ordinary [2, E] graph and knows nothing about relations.
Step 6: Read the ranking metrics
For each evaluated triple (h, r, t), KGEvaluator ranks t against every entity as a tail, and h against every entity as a head. In the filtered setting, other candidates that form a known true triple (train, validation or test) are removed first, so a model is not penalized for ranking another correct answer higher.
The result provides filt_mrr (mean reciprocal rank), filt_mr (mean rank) and filt_hits[1], filt_hits[3], filt_hits[10], each averaged over head and tail prediction; to_dict() also breaks them down by side. Candidates are not restricted by entity type, so users compete for the movie slot too.
The one-call shortcut: kg_completion
tgx.kg_completion() is convenient for a quick smoke run:
result = tgx.kg_completion(
train_kg.triples, kg.num_entities, kg.num_relations,
model="transe", embedding_dim=32, epochs=20, device="cpu",
val_triples=valid_kg.triples, test_triples=test_kg.triples,
)
print(result.metrics)
Know its limits in 1.5.1:
mrrandhits_at_10appear only when you passval_triples, and they are computed on the validation triples.test_triplesis used for filtering only. If evaluation raises an error, the keys are silently missing.- It returns metrics, not the trained model, and has no argument for learning rate, loss or sampler.
- The default
embedding_dimis 32, and withoutepochsit trains for 3 epochs (20 withfast_mode=False). model="complex","rotate"and"simple"fail withValueError: num_entities must be >= 2; got 1. Train those withKGTrainerand an explicit sampler, as in Step 3.
Save the graph and reuse the embeddings
tgx.save writes a .tgx bundle that keeps entity feature tensors of any rank:
stored = KnowledgeGraph(kg.triples, kg.num_entities, kg.num_relations,
entity_features=features, entity_feature_masks=masks)
tgx.save(stored, "runs/kg_exp/graph.tgx")
loaded = tgx.load("runs/kg_exp/graph.tgx")
assert torch.equal(loaded.entity_features["poster"], posters)
print(loaded, "| masks kept:", bool(loaded.entity_feature_masks)) # False
torch.save({"masks": masks, "transe": transe.state_dict()}, "runs/kg_exp/extras.pt")
In 1.5.1 the bundle holds the triples, the entity and relation counts, the three feature dictionaries and metadata. It does not keep entity_to_id, relation_to_id, entity types, feature masks, edge weights or confidences (or timestamps of a temporal KG). Store those yourself, and load .tgx files only from sources you trust, because loading unpickles data.
To use the learned embeddings in a GNN, make them node features. TransEModel L2-normalizes entity embeddings inside its score, so the length of a raw row in entity_emb.weight has no effect on any score; normalize the rows so that those arbitrary lengths do not reach the GNN. Build the message-passing graph from training triples only, otherwise held-out facts leak into the representation:
edge_index, edge_type = train_kg.to_edge_index()
entity_vectors = torch.nn.functional.normalize(transe.entity_emb.weight.detach(), dim=-1)
gnn_graph = tgx.Graph(node_features=entity_vectors, edge_index=edge_index)
hidden = tgx.GCNConv(32, 16)(gnn_graph.x, gnn_graph.edge_index)
print(hidden.shape)
This drops the relation types; use a relational layer if they matter. TransE, DistMult and RESCAL expose entity_emb (only TransE normalizes it inside the score); ComplEx and RotatE use entity_re / entity_im, and SimplE uses entity_head / entity_tail.
A step-by-step knowledge graph tutorial compares ID-only embeddings, MultimodalKGModel and an R-GCN encoder on one graph with image and vector entity features, and ends with entity classification.
Honest limitations
- This tutorial does not benchmark these models on FB15k-237, WN18RR or other standard datasets, and makes no claim that they reproduce published scores. For benchmark work, PyKEEN offers a much wider range of models, training options, evaluation tools and hyperparameter search; see TGraphX vs PyKEEN.
- Entity features are not guaranteed to help. Treat it as a hypothesis and test it.
- Ranking is a Python loop over the evaluated triples, which becomes slow for large test sets.
TemporalKnowledgeGraphexists, but temporal KG support is experimental.
The scope question is discussed in where TGraphX stops and knowledge graph toolkits begin.
When TGraphX's KG module is the right fit
- You want one PyTorch library for KG embeddings and other graph workflows (the MovieLens recommendation example applies TransE to a real dataset).
- Your entities have tensor features and you want to experiment with your own encoders.
- You are prototyping and are prepared to write a training loop where the built-in one is too narrow.
If your goal is a comparable benchmark number, start with a dedicated KG embedding library.
FAQ
Q: What is the default embedding_dim?
A: 32 in tgx.kg_completion(). The model classes themselves default to 64 (RESCALModel to 32).
Q: How do I implement a custom scoring function?
A: Subclass tgraphx.kg.models.KGScoringModel, define score_triples, and train it with KGTrainer. Pass a sampler explicitly. kg_completion accepts only the built-in model names.
from tgraphx.kg.models import KGScoringModel
class WeightedL1(KGScoringModel):
"""-sum_i w_i * |h_i + r_i - t_i| with a positive weight per relation."""
def __init__(self, num_entities, num_relations, dim=32):
super().__init__()
self.entity = nn.Embedding(num_entities, dim)
self.relation = nn.Embedding(num_relations, dim)
self.log_weight = nn.Embedding(num_relations, dim)
nn.init.zeros_(self.log_weight.weight)
def score_triples(self, triples):
h = self.entity(triples[:, 0])
r = self.relation(triples[:, 1])
t = self.entity(triples[:, 2])
w = self.log_weight(triples[:, 1]).exp()
return -(w * (h + r - t).abs()).sum(-1)
torch.manual_seed(0)
custom = WeightedL1(NUM_ENTITIES, kg.num_relations)
KGTrainer(custom, KGTrainingConfig(num_epochs=40, batch_size=64, lr=1e-2, loss_type="margin"),
train_kg.triples, sampler=UniformNegativeSampler(NUM_ENTITIES, num_negatives=4)).train()
print(f"{evaluator.evaluate(custom, triples=valid_kg.triples).filt_mrr:.3f}")
Q: Are temporal knowledge graphs supported?
A: There is tgraphx.kg.TemporalKnowledgeGraph with per-triple timestamps and a chronological_split method. It is experimental, so test it carefully.