Multimodal Knowledge Graph with Vision and Text Entities: End-to-End Tutorial
Topic: Knowledge graphs
Most knowledge graph tutorials give each entity nothing but a learned ID embedding. Real knowledge bases are rarely this bare. An e-commerce catalog has product images, a medical ontology has clinical notes, and a scientific database has paper abstracts and figures. This tutorial builds a small knowledge graph whose entities carry images and text embeddings, trains a link prediction model on it, and evaluates it with filtered ranking, including on entities the model never saw during training.
TGraphX 1.5.1 provides the pieces in tgraphx.kg: a KnowledgeGraph container that stores entity feature tensors without flattening them, MultimodalKGModel (one projector per modality, with a DistMult decoder), negative samplers and filtered ranking. MultimodalKGModel is labelled Experimental, and you write the training loop yourself.
What Multimodal Knowledge Graphs Add
A knowledge graph represents facts as triples (head, relation, tail). TransE, DistMult and similar embedding models learn one vector per entity and relation and score each triple from those vectors. They learn from graph structure alone and ignore side information attached to entities.
Multimodal methods compute part of an entity's representation from its content: an encoder for its image, an embedding of its description, and so on. The main promise is the cold-start case. A newly added entity with rich content but no connections has an untrained vector in a pure ID model, while a feature encoder can still place it sensibly. Whether it does depends on the features, so it needs to be measured.
Prerequisites
This tutorial assumes familiarity with:
- PyTorch tensors and training loops
- Knowledge graph basics (entities, relations, triples), as covered in knowledge graph embedding with TGraphX
- Tensor-valued features, as in MNIST as a graph
pip install tgraphx
Examples tested with TGraphX 1.5.1 on CPU. The full script trains three small models and takes a few minutes at most on an ordinary machine.
Data Layout: One Row per Entity
The example is a synthetic publication graph with 50 papers (ids 0-49), 30 authors (50-79) and 10 venues (80-89). Papers have a figure image, authors have a biography embedding, venues have a description embedding.
Each modality tensor has one row for every entity, not one per entity of that type. Entities without the modality get a zero row, and a boolean mask records who really has it. Every entity secretly belongs to one of five topics that shapes both its content and its links, so there is something real to learn.
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx.kg import KnowledgeGraph
torch.manual_seed(0)
NUM_TOPICS = 5
PAPERS, AUTHORS, VENUES = range(0, 50), range(50, 80), range(80, 90)
NUM_ENTITIES = 90
topic = torch.arange(NUM_ENTITIES) % NUM_TOPICS # hidden ground truth
# Figures: the topic is a stripe or checker texture, so channel means carry no signal.
yy, xx = torch.meshgrid(torch.arange(16), torch.arange(16), indexing="ij")
textures = torch.stack([yy % 4 < 2, xx % 4 < 2, (xx + yy) % 4 < 2,
(xx // 2 + yy // 2) % 2 == 0, xx % 8 < 4]).float() - 0.5
figure = torch.zeros(NUM_ENTITIES, 3, 16, 16)
for p in PAPERS:
figure[p] = textures[topic[p]] + 0.3 * torch.randn(3, 16, 16)
def fake_text_embeddings(ids, dim):
"""Stand-in for a sentence encoder: topic centre plus noise, unit length."""
centres = torch.randn(NUM_TOPICS, dim)
out = torch.zeros(NUM_ENTITIES, dim)
ids = list(ids)
out[ids] = F.normalize(centres[topic[ids]] + torch.randn(len(ids), dim), dim=1)
return out
features = {
"figure": figure, # [90, 3, 16, 16]
"bio": fake_text_embeddings(AUTHORS, 768), # [90, 768]
"venue_text": fake_text_embeddings(VENUES, 384), # [90, 384]
}
masks = {name: torch.zeros(NUM_ENTITIES, dtype=torch.bool) for name in features}
masks["figure"][list(PAPERS)] = True
masks["figure"][[3, 17, 29, 41, 48]] = False # papers without a figure
masks["bio"][list(AUTHORS)] = True
masks["venue_text"][list(VENUES)] = True
Building the Knowledge Graph
Three relations connect the entities: authored_by, published_at and cites. Each paper gets two authors and one venue from its topic, and cites up to three older papers from the same topic.
AUTHORED_BY, PUBLISHED_AT, CITES = 0, 1, 2
gen = torch.Generator().manual_seed(1)
def pick(candidates, k):
order = torch.randperm(len(candidates), generator=gen)[:k]
return [candidates[i] for i in order.tolist()]
rows = []
for p in PAPERS:
same_topic = lambda ids: [i for i in ids if topic[i] == topic[p]]
rows += [(p, AUTHORED_BY, a) for a in pick(same_topic(AUTHORS), 2)]
rows += [(p, PUBLISHED_AT, v) for v in pick(same_topic(VENUES), 1)]
rows += [(p, CITES, q) for q in pick(same_topic(range(p)), 3)] # older papers only
triples = torch.tensor(rows) # [num_triples, 3]
kg = KnowledgeGraph(
triples, num_entities=NUM_ENTITIES, num_relations=3,
entity_features=features, entity_feature_masks=masks,
entity_types=torch.tensor([0] * 50 + [1] * 30 + [2] * 10),
)
print(kg) # KnowledgeGraph(entities=90, relations=3, triples=270)
Splitting: Warm Triples and Cold Entities
Two questions need two test sets. A random split of triples tests missing links between known entities. For cold start, ten papers (40-49) are removed from training completely: every triple that mentions them is held back.
import tgraphx as tgx
COLD = torch.arange(40, 50)
is_cold = torch.isin(triples[:, 0], COLD) | torch.isin(triples[:, 2], COLD)
cold_triples = triples[is_cold]
warm = KnowledgeGraph(triples[~is_cold], num_entities=NUM_ENTITIES, num_relations=3)
train_kg, valid_kg, test_kg = warm.train_valid_test_split(0.8, 0.1, 0.1, seed=0)
print(len(train_kg), len(valid_kg), len(test_kg), len(cold_triples)) # 168 21 21 60
report = tgx.leakage_report(train_triples=train_kg.triples,
val_triples=valid_kg.triples,
test_triples=torch.cat([test_kg.triples, cold_triples]))
print(report["ok"]) # True
print(torch.isin(train_kg.triples[:, [0, 2]], COLD).any().item()) # False
leakage_report only detects identical triples shared between splits. In your own data, also look for inverse or near-duplicate relations, which can give test answers away.
What the Built-in Image Projector Sees
tgraphx.kg ships ImageEntityProjector, but it is deliberately light: it averages each channel over all pixels, then applies one linear layer (with a ReLU by default). Shuffling the pixels changes nothing:
from tgraphx.kg import ImageEntityProjector
projector = ImageEntityProjector(in_channels=3, out_dim=8)
images = features["figure"][:4]
shuffled = images.flatten(2)[:, :, torch.randperm(256)].reshape(images.shape)
print(torch.allclose(projector(images), projector(shuffled), atol=1e-6)) # True
If the information is in shapes or texture, either precompute features with a pretrained vision encoder and project those vectors, or plug in your own module. Any nn.Module that maps [num_entities, ...] to [num_entities, out_dim] works as a projector.
The Multimodal Model
Here the figure branch is a small CNN. The text branches use TextEntityProjector, which is a linear layer for precomputed vectors, not a language model. Each branch ends in LayerNorm so the modalities are on a comparable scale.
from tgraphx.kg import MultimodalKGModel, TextEntityProjector
class FigureCNN(nn.Module):
def __init__(self, out_dim):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(),
nn.Conv2d(16, 16, 3, stride=2, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Linear(16, out_dim), nn.LayerNorm(out_dim))
def forward(self, x): # [N, 3, H, W] -> [N, out_dim]
return self.net(x)
def text_branch(in_dim, out_dim):
return nn.Sequential(TextEntityProjector(in_dim, out_dim, activation=False),
nn.LayerNorm(out_dim))
def multimodal_model(per_entity_vector, dim=32):
return MultimodalKGModel(
num_entities=NUM_ENTITIES, num_relations=3, out_dim=dim,
projectors={"figure": FigureCNN(dim),
"bio": text_branch(768, dim),
"venue_text": text_branch(384, dim)},
fusion_mode="gated",
add_learnable_bias=per_entity_vector,
)
model = multimodal_model(per_entity_vector=True)
with torch.no_grad():
entities = model.encode_entities(kg.entity_features, kg.entity_feature_masks)
scores = model.score_triples(triples[:4], entities)
print(tuple(entities.shape), tuple(scores.shape)) # (90, 32) (4,)
Three details of the fusion are worth knowing:
- Each projector output is multiplied by its mask, so missing rows contribute nothing.
"gated"fusion learns one weight per modality, not per entity.- With
add_learnable_bias=True(the default), a learned per-entity vector is added to every entity, not only to those without features. It plays the role of the structural embedding. WithFalse, the representation comes from features alone.
The score is DistMult: the sum over dimensions of z_head * e_relation * z_tail.
Negative Sampling
Training needs false triples. A negative replaces the head or the tail of a true triple, and filtering rejects replacements that happen to be true. The candidate pool matters: the evaluation below ranks the true answer against all entities, so negatives are drawn from all entities that exist at training time.
from tgraphx.kg import FilteredNegativeSampler, TypedNegativeSampler
# Candidate pool: every entity except the cold papers, for every relation.
seen = set(range(NUM_ENTITIES)) - set(COLD.tolist())
proposals = TypedNegativeSampler(
NUM_ENTITIES,
domains={r: seen for r in range(3)}, # allowed corrupted heads per relation
ranges={r: seen for r in range(3)}, # allowed corrupted tails per relation
)
sampler = FilteredNegativeSampler(
NUM_ENTITIES, num_negatives=5,
positive_set=train_kg.positive_triple_set(), base_sampler=proposals,
)
negatives = sampler.sample(train_kg.triples[:64], generator=torch.Generator().manual_seed(0))
print(tuple(negatives.shape)) # (64, 5, 3)
Type-constrained negatives (only authors as corrupted tails of authored_by) are a common alternative, but they never teach the model that a venue is not an author. Use them together with type-constrained ranking, or mix them with unconstrained ones. In five initialisation seeds of this script, switching to type-correct negatives while still ranking all entities lowered the features-only model's validation MRR from 0.38-0.44 to 0.15-0.31.
In 1.5.1, TypedNegativeSampler constrains sampling only through domains and ranges (relation id to allowed entity ids); passing entity_types alone has no effect. The filter uses training triples only, so test triples play no part in training.
Training Loop
KGTrainer in 1.5.1 is meant for the ID-embedding models. It cannot drive MultimodalKGModel, because it calls score_triples without entity embeddings. The loop below encodes the entities once per step and scores positives and negatives against them. Model selection uses validation MRR only.
from tgraphx.kg import DistMultModel, SoftplusKGLoss, evaluate_filtered_ranking
ALL_TRUE = kg.positive_triple_set() # used only to filter rankings
def triple_scorer(model):
"""Return a function that scores LongTensor[B, 3] triples."""
if isinstance(model, MultimodalKGModel):
entities = model.encode_entities(kg.entity_features, kg.entity_feature_masks)
return lambda t: model.score_triples(t, entities)
return model.score_triples
class FrozenScorer(nn.Module):
"""Entity embeddings computed once, in eval mode, for ranking."""
def __init__(self, model):
super().__init__()
model.eval()
with torch.no_grad():
self.fn = triple_scorer(model)
def score_triples(self, t):
return self.fn(t)
def evaluate(model, split):
return evaluate_filtered_ranking(FrozenScorer(model), split, ALL_TRUE, NUM_ENTITIES)
def train(model, epochs=60, lr=3e-3):
optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-3)
loss_fn = SoftplusKGLoss()
gen = torch.Generator().manual_seed(0)
best_mrr, best_state = -1.0, None
for epoch in range(1, epochs + 1):
model.train()
for idx in torch.randperm(len(train_kg), generator=gen).split(64):
batch = train_kg.triples[idx]
negatives = sampler.sample(batch, generator=gen).reshape(-1, 3)
score = triple_scorer(model) # encodes entities once per step
loss = loss_fn(score(batch), score(negatives))
optimiser.zero_grad()
loss.backward()
optimiser.step()
if epoch % 5 == 0:
mrr = evaluate(model, valid_kg.triples).filt_mrr
if mrr > best_mrr:
best_mrr = mrr
best_state = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
return best_mrr
Evaluation
Filtered ranking asks, for each test triple, where the true answer ranks among all entities. All other known true answers, from any split, are removed from the candidate list first, so the model is not penalised for ranking them highly. evaluate_filtered_ranking does this for head and tail queries and averages tied ranks.
Always compare with a model that has no features. For cold papers the number reported below is the tail query: given a new paper, which author, venue or cited paper?
builders = {
"IDs only": lambda: DistMultModel(NUM_ENTITIES, 3, embedding_dim=32),
"features + entity vector": lambda: multimodal_model(per_entity_vector=True),
"features only": lambda: multimodal_model(per_entity_vector=False),
}
trained = {}
for name, build in builders.items():
torch.manual_seed(0)
trained[name] = build()
train(trained[name])
warm_res = evaluate(trained[name], test_kg.triples)
cold_res = evaluate(trained[name], cold_triples)
print(f"{name:25s} warm MRR {warm_res.filt_mrr:.3f} Hits@10 {warm_res.filt_hits[10]:.3f}"
f" | cold tail MRR {cold_res.filt_mrr_tail:.3f}"
f" Hits@10 {cold_res.filt_hits_tail[10]:.3f}")
Output from one CPU run (exact values depend on hardware and library versions):
IDs only warm MRR 0.333 Hits@10 0.976 | cold tail MRR 0.116 Hits@10 0.183
features + entity vector warm MRR 0.432 Hits@10 1.000 | cold tail MRR 0.323 Hits@10 0.767
features only warm MRR 0.444 Hits@10 0.929 | cold tail MRR 0.314 Hits@10 0.800
The cold column is where features matter. The ID-only model has never updated a cold paper's vector from any triple, so it has nothing to go on, while both feature models rank sensibly. A random ranking over 90 candidates gives an MRR of roughly 0.06.
One run is not enough to compare models. Over five initialisation seeds in our runs, cold tail MRR ranged from 0.28 to 0.35 for the two feature models and from 0.02 to 0.12 for the ID-only model, while on warm test triples the ranges overlapped (0.31-0.44 with features, 0.33-0.40 without). So the cold-start gap is consistent here and the warm differences are not.
Do not expect scores near 1 on this data even from a perfect model: content reveals only the topic, and several candidates share each topic. The data is also synthetic and built so that content predicts links. The result shows how to run the comparison, not what to expect on your data.
Handling Missing Modalities
Not every entity has every modality: here five papers lack a figure. With a mask, such an entity gets only what remains. In the features-only model a paper without a figure has nothing at all:
with torch.no_grad():
z = trained["features only"].eval().encode_entities(kg.entity_features,
kg.entity_feature_masks)
print(z[41].abs().sum().item()) # 0.0: cold paper without a figure
print(z[42].abs().sum().item() > 0) # True: cold paper with a figure
Every tail candidate for paper 41 then scores 0, so they all tie. Options are to add a second modality that is almost always present (a title or abstract embedding), to keep the per-entity vector (which is only trained for entities that occur in training triples), or to report such entities separately. Do not fill the gap with random or all-zero images and leave the mask set to True: the model would treat them as real content.
Adding Another Modality
Add one entity-aligned tensor, one mask and one projector under the same name:
talk_audio = torch.zeros(NUM_ENTITIES, 1024) # e.g. from an external audio encoder
talk_mask = torch.zeros(NUM_ENTITIES, dtype=torch.bool)
talk_mask[:10] = True
talk_audio[talk_mask] = torch.randn(10, 1024)
extended = MultimodalKGModel(
num_entities=NUM_ENTITIES, num_relations=3, out_dim=32,
projectors={"figure": FigureCNN(32), "bio": text_branch(768, 32),
"venue_text": text_branch(384, 32), "talk_audio": text_branch(1024, 32)},
)
with torch.no_grad():
z = extended.encode_entities({**features, "talk_audio": talk_audio},
{**masks, "talk_audio": talk_mask})
print(tuple(z.shape)) # (90, 32)
Limitations and Honest Notes
- Memory. Image tensors of shape
[num_entities, 3, 224, 224]grow quickly: 50,000 rows offloat32need about 30 GB. For large graphs, precompute image features once with a frozen encoder and store vectors. - Whole-graph encoding.
encode_entitiesencodes every entity on every call. That is fine for hundreds of entities and not for millions. - Encoders are external. TGraphX does not ship a text encoder or pretrained vision model for this. Poor features give poor cold-start behaviour.
- DistMult is symmetric. Swapping head and tail leaves the score unchanged, so it cannot tell "a cites b" from "b cites a".
ComplExModelandRotatEModelintgraphx.kgcan model asymmetric relations, but they score ID embeddings. For asymmetric relations over features, write your own decoder on the output ofencode_entities. - Scale of this example. Ninety entities and a few hundred triples demonstrate the mechanics only.
When tuning, change embedding size, learning rate, number of epochs and negatives per positive based on validation MRR, never on test results. Optimiser parameter groups let you give an image encoder its own learning rate.
What This Tutorial Builds On
For TransE, DistMult, ComplEx and RotatE on ID embeddings, with KGTrainer, see the knowledge graph embedding tutorial and the scoring functions guide. The knowledge graph tutorial with tensor entity features covers a wider set of models. For image and text features in node-level GNNs, see multimodal vision graph learning.
See the articles hub for the full index of TGraphX guides.
References
- Bordes, Usunier, Garcia-Durán, Weston and Yakhnenko (2013). Translating embeddings for modeling multi-relational data. NeurIPS.
- Yang, Yih, He, Gao and Deng (2015). Embedding entities and relations for learning and inference in knowledge bases. ICLR.
- Trouillon, Welbl, Riedel, Gaussier and Bouchard (2016). Complex embeddings for simple link prediction. ICML.
- Sun, Deng, Nie and Tang (2019). RotatE: knowledge graph embedding by relational rotation in complex space. ICLR.