TGraphX › Insights › TGraphX vs PyKEEN: Choosing a Knowledge Graph Embedding Library
← Back to Insights

TGraphX vs PyKEEN: Choosing a Knowledge Graph Embedding Library

Topic: Knowledge graphs

PyKEEN is a dedicated, widely used PyTorch library for knowledge graph (KG) embedding research. TGraphX ships a smaller KG module as one part of a broader graph learning library.

The short version: for KG embedding research and benchmarking, PyKEEN is usually the right choice. TGraphX's KG module makes sense when you already work in TGraphX, or want to wire your own feature encoders into a small multimodal KG model, and can accept Beta and Experimental code.

What was checked. The TGraphX examples were run with TGraphX 1.5.1 on CPU. Statements about PyKEEN come from its documentation and README, checked on 26 November 2026; the optimizer default noted below was also read in the source of PyKEEN 1.11.1 and its class-resolver dependency. PyKEEN was not installed, so its snippets were not executed. No accuracy or speed comparison was made.

What PyKEEN provides

According to its documentation, PyKEEN offers:

  • a large model collection (the README lists 40), including literal models such as ComplExLiteral and DistMultLiteral that use numeric entity attributes
  • representation modules that encode entity text or images
  • hyperparameter optimization built on Optuna (hpo_pipeline) and ablation studies
  • basic, Bernoulli and pseudo-typed negative samplers, with optional filtering of false negatives
  • rank-based evaluation, filtered by default, with optimistic, realistic and pessimistic ranks
  • built-in benchmark datasets such as FB15k-237, WN18RR and Wikidata5M
  • support for reproducing runs: seeded pipelines, saved result directories, replicates, and pykeen experiments reproduce for published settings

What TGraphX 1.5.1 provides

The tgraphx.kg module offers:

  • six scoring models: TransE, DistMult, ComplEx, RotatE, RESCAL and SimplE
  • a KnowledgeGraph container that can carry entity, relation and triple features
  • uniform, Bernoulli, filtered and typed negative samplers
  • KGEvaluator: filtered head and tail ranking, with tied scores given their average rank
  • a trainer (KGTrainer), a one-call helper (kg_completion) and a small search function (run_kg_hpo)
  • MultimodalKGModel, which fuses per-modality encoders into entity vectors
  • Experimental pieces: an R-GCN based completion model, temporal KGs and rule mining

It has no loaders for the public benchmark datasets. It generates synthetic KGs, and you load your own triples with KnowledgeGraph.from_triples (string or integer tuples) or load_tsv (integer IDs). The module's own notes label the data model, the uniform, Bernoulli and filtered samplers, the evaluator, TransE and DistMult as Beta, and ComplEx, RotatE and the trainer as Experimental.

Side by side: TransE on the same split

This TGraphX example runs as written. The synthetic triples are random, so its scores only show that the pieces connect. They are not evenly spread either: in 1.5.1 generate_synthetic_kg sorts the unique triples before truncating to the requested number, so here only entities 0-31 ever appear as heads, while all 60 appear as tails.

python
import torch
import tgraphx as tgx
from tgraphx.kg import (FilteredNegativeSampler, KGEvaluator, KGTrainer,
                        KGTrainingConfig, TransEModel, generate_synthetic_kg)

kg = generate_synthetic_kg(num_entities=60, num_relations=4, num_triples=600, seed=0)
print(int(kg.triples[:, 0].max()), int(kg.triples[:, 2].max()))   # largest head, tail
train, valid, test = kg.train_valid_test_split(0.8, 0.1, 0.1, seed=0)

tgx.set_seed(42)   # seed before building the model: weights are initialised here
model = TransEModel(kg.num_entities, kg.num_relations, embedding_dim=64, norm=1)
config = KGTrainingConfig(num_epochs=20, batch_size=64, lr=1e-2,
                          loss_type="margin", margin=1.0, seed=42)
sampler = FilteredNegativeSampler(kg.num_entities,
                                  positive_set=train.positive_triple_set())
history = KGTrainer(model, config, train.triples, sampler=sampler).train()

evaluator = KGEvaluator(train.triples, valid.triples, test.triples,
                        num_entities=kg.num_entities)
result = evaluator.evaluate(model, triples=test.triples)
print(len(train), len(valid), len(test))
print(round(result.filt_mrr, 3), round(result.filt_hits[10], 3))

A closely matching PyKEEN configuration, reusing the same split:

python
from pykeen.pipeline import pipeline
from pykeen.triples import CoreTriplesFactory

def factory(part):
    return CoreTriplesFactory.create(part.triples, num_entities=kg.num_entities,
                                     num_relations=kg.num_relations)

pykeen_result = pipeline(
    training=factory(train),
    validation=factory(valid),
    testing=factory(test),
    model="TransE",
    model_kwargs={"embedding_dim": 64, "scoring_fct_norm": 1},
    loss="MarginRankingLoss",
    loss_kwargs={"margin": 1.0},
    optimizer="Adam",
    optimizer_kwargs={"lr": 1e-2},
    negative_sampler="basic",
    negative_sampler_kwargs={"filtered": True},
    training_kwargs={"num_epochs": 20, "batch_size": 64},
    random_seed=42,
)
print(pykeen_result.get_metric("mrr"), pykeen_result.get_metric("hits@10"))

Check the defaults before comparing; the examples set these three explicitly:

  • TransE distance: PyKEEN defaults to the L1 norm, TGraphX to L2.
  • Loss: KGTrainingConfig defaults to softplus, not a margin loss.
  • Optimizer: the PyKEEN 1.11.1 docstring names Adagrad as the pipeline default, but its code resolves an unset optimizer to Adam (read in the source, not run). KGTrainer uses Adam.

Even with these aligned, initialisation, embedding constraints and sampling code differ, so expect different numbers. Report results from the framework and configuration you actually used.

The one-call helper and its limits

kg_completion is convenient for a smoke test:

python
quick = tgx.kg_completion(train.triples, kg.num_entities, kg.num_relations,
                          model="transe", val_triples=valid.triples, device="cpu")
print(sorted(quick.metrics))

Know what it does before relying on it (TGraphX 1.5.1):

  • It trains for only 3 epochs by default; pass epochs=. It has no learning-rate argument.
  • mrr and hits_at_10 appear only when you pass val_triples, and they are computed on those validation triples. If evaluation fails, the error is swallowed and the metrics are missing.
  • It accepts entity_features, but the models it builds ignore them.
  • model="complex", "rotate" and "simple" raise ValueError: num_entities must be >= 2; got 1.

For those three models, use KGTrainer and pass a sampler explicitly:

python
from tgraphx.kg import ComplExModel, UniformNegativeSampler

tgx.set_seed(42)
complex_model = ComplExModel(kg.num_entities, kg.num_relations, embedding_dim=32)
KGTrainer(complex_model, config, train.triples,
          sampler=UniformNegativeSampler(kg.num_entities)).train()
print(round(evaluator.evaluate(complex_model, triples=valid.triples).filt_mrr, 3))

Hyperparameter search

TGraphX includes run_kg_hpo, a grid or random search over embedding_dim, lr and margin. Treat it as a quick screen, not as a model selection protocol. In 1.5.1:

  • each trial makes its own random 80/20 split of the triples you pass, so trials are scored on different holdouts
  • its training loop is minimal: one full-batch step per epoch, corrupting tails only
  • ComplEx and RotatE trials fail

Never pass it test triples. For a comparison you can defend, keep one fixed validation split and loop yourself (or put the same steps in an Optuna objective):

python
# Filter with training and validation triples only; keep test out of selection
valid_eval = KGEvaluator(train.triples, valid.triples, test.triples[:0],
                         num_entities=kg.num_entities)
scores = {}
for lr in (1e-2, 1e-3):
    tgx.set_seed(42)
    candidate = TransEModel(kg.num_entities, kg.num_relations, embedding_dim=64)
    trial = KGTrainingConfig(num_epochs=10, batch_size=64, lr=lr,
                             loss_type="margin", seed=42)
    KGTrainer(candidate, trial, train.triples, sampler=sampler).train()
    scores[lr] = valid_eval.evaluate(candidate, triples=valid.triples).filt_mrr
print("best lr:", max(scores, key=scores.get))

Multimodal entity features

Both libraries can use information about entities beyond their IDs. PyKEEN has literal models for numeric attributes and representation modules for text and images. TGraphX takes a different packaging: MultimodalKGModel holds one projector per modality, fuses them ("gated", "add" or "concat_project") and scores with a DistMult decoder.

Three things to know. By default (add_learnable_bias=True) the model adds a learnable vector for each entity ID to every fused vector, so it does not score from features alone; pass add_learnable_bias=False for that. ImageEntityProjector averages each channel over height and width before a linear layer, so for real images run a CNN encoder first. And neither KGTrainer nor kg_completion trains this model; you write the loop:

python
import torch.nn.functional as F
from tgraphx.kg import ImageEntityProjector, MultimodalKGModel, VectorEntityProjector

features = {"image": torch.randn(kg.num_entities, 3, 16, 16),     # placeholders
            "tabular": torch.randn(kg.num_entities, 8)}
tgx.set_seed(42)
mm = MultimodalKGModel(kg.num_entities, kg.num_relations, out_dim=32,
                       projectors={"image": ImageEntityProjector(3, 32),
                                   "tabular": VectorEntityProjector(8, 32)},
                       fusion_mode="gated")
opt = torch.optim.Adam(mm.parameters(), lr=1e-2)
negatives = UniformNegativeSampler(kg.num_entities)
gen = torch.Generator().manual_seed(0)

for epoch in range(3):
    for idx in torch.randperm(len(train), generator=gen).split(64):
        pos = train.triples[idx]
        neg = negatives.sample(pos, generator=gen).view(-1, 3)
        entities = mm.encode_entities(features)          # recompute every step
        loss = (F.softplus(-mm.score_triples(pos, entities)).mean()
                + F.softplus(mm.score_triples(neg, entities)).mean())
        opt.zero_grad()
        loss.backward()
        opt.step()

class FrozenEntities(torch.nn.Module):
    """Gives the evaluator the score_triples(triples) signature it expects."""
    def __init__(self, model, features):
        super().__init__()
        self.model = model.eval()
        with torch.no_grad():
            self.entities = model.encode_entities(features)

    def score_triples(self, triples):
        return self.model.score_triples(triples, self.entities)

mm_result = evaluator.evaluate(FrozenEntities(mm, features), triples=valid.triples)
print(round(mm_result.filt_mrr, 3))       # random features: not meaningful

Whether side features help is an empirical question for your data. Compare against the same decoder without them: with the default per-entity vector, DistMultModel is the natural ID-only baseline.

Feature comparison

Question PyKEEN (per its docs) TGraphX 1.5.1
Scoring models 40 listed in the README 6, plus multimodal and R-GCN variants
Negative samplers Basic, Bernoulli, pseudo-typed; optional filtering Uniform, Bernoulli, filtered, typed
Hyperparameter search Optuna-based Small grid/random search with the limits above
Evaluation Filtered ranking, three rank types Filtered ranking, average rank for ties
Entity side information Literal models, text and image representations Multimodal model with projectors; DistMult decoder
Benchmark datasets Many built in Synthetic only; load your own
Temporal KGs No temporal model in its model list Container and filtered evaluation, Experimental
Reproducing runs Saved configurations and results, replicates Seeds and report writers; you assemble the record
Maturity Established dedicated library Beta and Experimental parts

Which to choose

Choose PyKEEN if:

  • you compare against published KG completion numbers
  • you need a model outside TGraphX's six
  • you want hyperparameter search and ablation tooling
  • you work with the standard benchmark datasets or very large graphs

Choose TGraphX KG if:

  • your project already uses TGraphX and the KG part is modest
  • you want to plug your own nn.Module encoders into a small multimodal model
  • you are prototyping or teaching and have checked the limits listed above

Using both

The libraries can sit in one project. For example, train embeddings in one and use them as node features in a TGraphX graph. PyKEEN exposes trained entity embeddings through its representation modules:

python
entity_vectors = pykeen_result.model.entity_representations[0](indices=None).detach().cpu()

With TGraphX's TransE the table is model.entity_emb. Build the graph from training triples only, so that validation and test links do not leak into message passing:

python
from tgraphx import Graph

edge_index, edge_type = train.to_edge_index()
entity_graph = Graph(node_features=F.normalize(model.entity_emb.weight.detach(), dim=1),
                     edge_index=edge_index, edge_labels=edge_type)
print(entity_graph.num_nodes, entity_graph.num_edges, entity_graph.feature_shape)

For the wider picture, see TGraphX vs knowledge graph toolkits and knowledge graph embedding with tensor features.


FAQ

Q: Can I load PyKEEN models into TGraphX?
A: Not directly; the model classes differ. Embedding tables are ordinary tensors and can be copied, but the scoring conventions (norms, complex-valued layout) must match if you want identical scores.

Q: Does TGraphX have hyperparameter optimization?
A: A small one, run_kg_hpo, with the limits described above.

Q: How do I model inverse relations?
A: KnowledgeGraph.add_inverse_relations() returns a new graph with (t, r + R, h) added and 2R relations. Split first and add inverses to the training triples only; adding them before a random split puts inverses of test triples into training. Build the model with the doubled relation count.

Q: What about very large graphs such as Wikidata?
A: This article did not test TGraphX KG at that scale. PyKEEN ships a Wikidata5M dataset loader. Measure runtime and memory on your own data before committing.

Q: Are there more TGraphX KG examples?
A: The GitHub repository at tag v1.5.1 has several, for example examples/kg_training_pipeline_demo.py. The examples are not part of the pip package.