TGraphX › Insights › Knowledge Graph Tutorial: Tensor Entity Features and Multimodal KGs in TGraphX
← Back to Insights

Knowledge Graph Tutorial: Tensor Entity Features and Multimodal KGs in TGraphX

Topic: Knowledge graphs

Classic knowledge graph embedding gives every entity a learned ID vector. Real entities often come with content as well: product images, profile vectors, sequence or volume data. This tutorial builds a small typed knowledge graph whose entities carry tensors of different shapes, then compares three ways of using it under one training budget and over ten seeds: IDs only, entity features, and entity features with relational message passing (R-GCN). It ends with entity classification.

Examples tested with TGraphX 1.5.1 on CPU; the Python blocks build on each other. The data is synthetic, so the numbers show that the pipeline works, not how good any method is. For the basic training and ranking workflow, see knowledge graph embedding with tensor features.


Prerequisites

  • The TGraphX data model (see what is a TGX graph)
  • Knowledge graph link prediction: scoring triples (head, relation, tail)

Part 1: A Typed Knowledge Graph with Tensor Features

A shop catalogue: 90 items, each with a small image, and 12 shops, each with a 6-number profile. Items are sold_by shops and bought_with other items. Every item has a hidden category (0, 1 or 2) that tints its image and makes it more likely to be linked within the category.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx.kg import KnowledgeGraph

torch.set_num_threads(1)
gen = torch.Generator().manual_seed(0)

ITEMS, SHOPS, CLASSES = 90, 12, 3
NUM_ENTITIES = ITEMS + SHOPS                 # items 0..89, shops 90..101
SOLD_BY, BOUGHT_WITH = 0, 1
item_class = torch.arange(ITEMS) % CLASSES
shop_class = torch.arange(SHOPS) % CLASSES
items, shops = torch.arange(ITEMS), torch.arange(SHOPS)

def linked(pool, same_class, k=2):
    """k distinct targets, each from the same category with probability 0.8."""
    chosen = set()
    while len(chosen) < k:
        source = same_class if torch.rand(1, generator=gen).item() < 0.8 else pool
        chosen.add(int(source[torch.randint(len(source), (1,), generator=gen)]))
    return sorted(chosen)

rows = []
for i in range(ITEMS):
    c = item_class[i]
    rows += [(i, SOLD_BY, ITEMS + s) for s in linked(shops, shops[shop_class == c])]
    others = items != i
    rows += [(i, BOUGHT_WITH, j) for j in linked(items[others], items[(item_class == c) & others])]
triples = torch.tensor(rows)

# One row per entity in every feature tensor; masks say which rows are real
image = torch.zeros(NUM_ENTITIES, 3, 8, 8)
tint = F.one_hot(item_class, 3).float()[:, :, None, None]
image[:ITEMS] = (0.5 * tint + torch.randn(ITEMS, 3, 8, 8, generator=gen)
                 + 0.5 * torch.randn(ITEMS, 3, 1, 1, generator=gen))
profile = torch.zeros(NUM_ENTITIES, 6)
profile[ITEMS:] = torch.randn(SHOPS, 6, generator=gen)

features = {"image": image, "profile": profile}
masks = {"image": torch.arange(NUM_ENTITIES) < ITEMS,
         "profile": torch.arange(NUM_ENTITIES) >= ITEMS}

kg = KnowledgeGraph(triples, num_entities=NUM_ENTITIES, num_relations=2,
                    entity_features=features, entity_feature_masks=masks,
                    entity_types=(torch.arange(NUM_ENTITIES) >= ITEMS).long())
train_kg, valid_kg, test_kg = kg.train_valid_test_split(0.8, 0.1, 0.1, seed=0)

def drop_reversed(split, seen):
    """Remove bought_with triples whose reverse (t, bought_with, h) is in `seen`."""
    keep = torch.tensor([not (r == BOUGHT_WITH and (t, r, h) in seen)
                         for h, r, t in split.triples.tolist()])
    return KnowledgeGraph(split.triples[keep], num_entities=NUM_ENTITIES, num_relations=2)

valid_kg = drop_reversed(valid_kg, train_kg.positive_triple_set())
test_kg = drop_reversed(test_kg, train_kg.positive_triple_set() | valid_kg.positive_triple_set())

print(kg)
print({name: tuple(t.shape) for name, t in kg.entity_features.items()})
print(len(train_kg), len(valid_kg), len(test_kg))
text
KnowledgeGraph(entities=102, relations=2, triples=360)
{'image': (102, 3, 8, 8), 'profile': (102, 6)}
288 35 34

The random split treats every triple separately, so it can put (j, bought_with, i) in training and (i, bought_with, j) in validation or test. DistMult, the decoder used below, gives both the same score, so the held-out triple would be as good as seen. drop_reversed removes such cases (here one validation and two test triples). Test triples are also checked against validation, because validation is used to choose the setup.

entity_features is a dictionary of named tensors of any rank, each with num_entities as its first dimension. Nothing is flattened. If your IDs are already in three separate tensors, KnowledgeGraph.from_hrt(heads, relations, tails, ...) takes them directly.


Part 2: Which Models Read the Features?

Storing features on the graph does not make a model use them:

Component Reads entity features?
KGTrainer, tgx.kg_completion No
TransEModel(entity_feature_dim=F) Only if you call score_triples(triples, entity_features=X) yourself; vectors only
DistMultModel(entity_feature_dim=F) No: it creates a projector that its score_triples never uses
MultimodalKGModel Yes, through one projector per modality; any shape your projector accepts
KGRGCNModel.encode(...) Yes, as one [num_entities, in_dim] vector table

For TransE the effect is easy to see:

python
from tgraphx.kg import TransEModel

transe = TransEModel(NUM_ENTITIES, 2, embedding_dim=16, entity_feature_dim=6)
sold = train_kg.triples[train_kg.triples[:, 1] == SOLD_BY][:4]
with_features = transe.score_triples(sold, entity_features=profile)
print(torch.allclose(transe.score_triples(sold), with_features))    # False: features changed the score
text
False

Part 3: One Training Loop and the ID-Only Baseline

Always measure what structure alone achieves. TransE (Bordes et al., 2013) is the classic choice; DistMult is used here because the other two models below also decode with DistMult, which keeps the comparison focused on the entity representation. DistMult scores a triple as the sum over dimensions of e_h · r · e_t.

The training budget has to match too. KGTrainer can train DistMultModel directly, but it cannot train the feature models of Parts 4 and 5, because it calls score_triples without the entity table they need. So all three go through one full-batch loop with the same loss, negative sampler, learning rate and 200 optimizer steps. One seed says little on a graph this small, so each setup is trained with ten seeds:

python
from tgraphx.kg import DistMultModel, KGEvaluator, UniformNegativeSampler, SoftplusKGLoss

# KGEvaluator filters every triple found in its three arguments. Passing all of
# kg.triples first keeps the dropped triples filtered too: they are still true facts.
evaluator = KGEvaluator(kg.triples, valid_kg.triples, test_kg.triples,
                        num_entities=NUM_ENTITIES)

class Frozen(nn.Module):
    """A fixed entity table behind the score_triples(triples) signature."""
    def __init__(self, model, table):
        super().__init__()
        self.model, self.table = model, table

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

def train_link_prediction(model, encode, parameters, seed, steps=200):
    optimizer = torch.optim.Adam(parameters, lr=1e-2)
    sampler = UniformNegativeSampler(NUM_ENTITIES, num_negatives=4)
    loss_fn, rng = SoftplusKGLoss(), torch.Generator().manual_seed(seed)
    positive = train_kg.triples
    for step in range(steps):
        table = encode()                                   # [num_entities, dim]
        negative = sampler.sample(positive, generator=rng).view(-1, 3)
        loss = loss_fn(model.score_triples(positive, table),
                       model.score_triples(negative, table))
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    with torch.no_grad():
        return Frozen(model, encode())

def run_seeds(name, build, seeds=range(10)):
    """Train one model per seed and score each on the validation triples."""
    models, scores = [], []
    for seed in seeds:
        torch.manual_seed(seed)                            # initial weights
        model, encode, parameters = build()
        models.append(train_link_prediction(model, encode, parameters, seed))
        scores.append(evaluator.evaluate(models[-1], triples=valid_kg.triples).filt_mrr)
    scores = torch.tensor(scores)
    print(f"{name:11s}validation MRR: mean {scores.mean():.3f}, std {scores.std():.3f}, "
          f"range {scores.min():.3f} to {scores.max():.3f}")
    return models, scores

class TableDistMult(DistMultModel):
    """DistMult that reads entity vectors from the table the loop passes in."""
    def score_triples(self, triples, table):
        head, relation, tail = triples.T
        return (table[head] * self.relation_emb(relation) * table[tail]).sum(-1)

def build_id_only():
    model = TableDistMult(NUM_ENTITIES, 2, embedding_dim=32)
    return model, lambda: model.entity_emb.weight, model.parameters()

id_models, id_val = run_seeds("ID-only", build_id_only)
text
ID-only    validation MRR: mean 0.068, std 0.015, range 0.038 to 0.091

Part 4: Multimodal Entities with MultimodalKGModel

MultimodalKGModel projects each modality to out_dim, fuses the projections, adds a learned per-entity embedding and scores with a DistMult decoder (there is no TransE option). KGTrainer cannot train it, for the reason given above; the loop from Part 3 passes the entity table in:

python
from tgraphx.kg import MultimodalKGModel, ImageEntityProjector, VectorEntityProjector

def build_multimodal():
    model = MultimodalKGModel(
        NUM_ENTITIES, 2, out_dim=32,
        projectors={"image": ImageEntityProjector(3, 32),
                    "profile": VectorEntityProjector(6, 32)},
        fusion_mode="gated",
    )
    return model, lambda: model.encode_entities(features, masks), model.parameters()

mm_models, mm_val = run_seeds("multimodal", build_multimodal)
text
multimodal validation MRR: mean 0.088, std 0.016, range 0.065 to 0.116

ImageEntityProjector averages each channel over height and width before its linear layer. That is enough for a colour tint; where spatial layout matters, pass your own nn.Module that maps [num_entities, C, H, W] to [num_entities, out_dim]. Training this model end to end, with a custom image encoder and a cold-start test, is covered in the multimodal knowledge graph tutorial.


Part 5: KG + R-GCN for Relational Graph Convolution

An R-GCN (Schlichtkrull et al., 2018) gives each relation its own weight matrix and aggregates neighbours' vectors, so an entity's representation depends on its surroundings (see also RGCN and other heterogeneous layers). KGRGCNModel stacks R-GCN layers and decodes with DistMult. Three things to get right:

  1. Input. encode takes one vector per entity, so fuse the modalities first.
  2. Direction. Messages flow from head to tail only. Add inverse relations, or shops send nothing back to items.
  3. Leakage. Build the message-passing graph from training triples only. For symmetric or inverse relations, the reversed pair of a held-out triple must not be in training or in the message-passing graph either (see Part 1).
python
from tgraphx.kg import KGRGCNModel

class FeatureTable(nn.Module):
    """Fuse the modalities into one [num_entities, dim] table."""
    def __init__(self, dim=16):
        super().__init__()
        self.image = ImageEntityProjector(3, dim, activation=False)
        self.profile = VectorEntityProjector(6, dim, activation=False)

    def forward(self):
        return (self.image(image) * masks["image"][:, None]
                + self.profile(profile) * masks["profile"][:, None])

def edges_by_relation(source):
    """{relation_id: edge_index [2, E]} with inverse relations added."""
    both = source.add_inverse_relations()          # relations 0..3
    edge_index, edge_type = both.to_edge_index()
    return {r: edge_index[:, edge_type == r] for r in range(both.num_relations)}

message_edges = edges_by_relation(train_kg)

def build_rgcn():
    inputs = FeatureTable()
    model = KGRGCNModel(NUM_ENTITIES, num_relations=4, in_dim=16, embedding_dim=32,
                        num_rgcn_layers=2)
    return (model, lambda: model.encode(message_edges, inputs()),
            list(model.parameters()) + list(inputs.parameters()))

rgcn_models, rgcn_val = run_seeds("R-GCN", build_rgcn)
text
R-GCN      validation MRR: mean 0.141, std 0.038, range 0.106 to 0.214

KGRGCNModel.encode applies ReLU after the last layer too, so entity embeddings are non-negative and only the relation vector can make a score negative. If that is too restrictive, stack tgraphx.layers.rgcn.RGCNConv yourself. Training triples are also message edges here, so a positive triple can see itself. The R-GCN paper regularises its encoder with edge dropout, which also weakens that shortcut; KGRGCNModel does not do it for you.

Do not hand KGRGCNModel to KGTrainer. With in_dim set, as here, training raises ValueError. With the default in_dim=None the failure is silent: training runs, but the trainer calls score_triples(triples), which reads the raw entity embeddings, so encode is never called and the R-GCN weights never change. Use a loop that passes the result of encode to score_triples, as in Part 3, and evaluate through Frozen, because KGEvaluator calls score_triples(triples) too and behaves the same way.


Part 6: Link Prediction Evaluation

KGEvaluator computes filtered ranking: for each triple it ranks the true tail among all entities and the true head among all entities, after removing other known true triples. Choose the setup by mean validation MRR, then evaluate only that setup's ten models on the test split:

python
candidates = {"ID-only": (id_models, id_val), "multimodal": (mm_models, mm_val),
              "R-GCN": (rgcn_models, rgcn_val)}
for name in ("multimodal", "R-GCN"):
    wins = int((candidates[name][1] > id_val).sum())
    print(f"{name} beats ID-only on {wins} of {len(id_val)} seeds")

best = max(candidates, key=lambda name: candidates[name][1].mean())
results = [evaluator.evaluate(m, triples=test_kg.triples) for m in candidates[best][0]]
test_mrr = torch.tensor([r.filt_mrr for r in results])
hits10 = torch.tensor([r.filt_hits[10] for r in results])
print(f"selected {best}: test MRR mean {test_mrr.mean():.3f} (std {test_mrr.std():.3f}), "
      f"Hits@10 mean {hits10.mean():.3f}")
text
multimodal beats ID-only on 7 of 10 seeds
R-GCN beats ID-only on 10 of 10 seeds
selected R-GCN: test MRR mean 0.131 (std 0.024), Hits@10 mean 0.331

The absolute values are low: which item of a category gets linked is random in this data. Random scores get an MRR of about 0.05 through the same evaluator, so the ID-only models are only slightly above chance. The multimodal mean is above the ID-only mean, but the two ranges overlap and ID-only wins on 3 of the 10 seeds, so here features without message passing give a modest gain that does not appear on every seed. The R-GCN setup is ahead of ID-only on every seed. The seeds change only the initial weights and the negative samples: the dataset, the split and the 35 validation triples stay the same. Nothing was tuned and the models differ in size, so this is not a ranking of methods.


Part 7: Entity Classification

KGRGCNModel is a link prediction model; it has no class output. For entity classification, use its encoder and add a head. The category is not a fact in the graph, so message passing may use all triples. (If a relation is derived from your label, remove it first.) Items are split into 30 training, 30 validation and 30 test nodes, with early stopping on validation loss:

python
from tgraphx.estimators import EarlyStopping

full_edges = edges_by_relation(kg)
order = torch.randperm(ITEMS, generator=torch.Generator().manual_seed(0))
train_ids, val_ids, test_ids = order[:30], order[30:60], order[60:]

def classify(use_graph, seed):
    torch.manual_seed(seed)
    inputs = FeatureTable()
    modules = nn.ModuleDict({"inputs": inputs,
                             "head": nn.Linear(32 if use_graph else 16, CLASSES)})
    if use_graph:
        modules["rgcn"] = KGRGCNModel(NUM_ENTITIES, num_relations=4, in_dim=16,
                                      embedding_dim=32, num_rgcn_layers=2)

    def logits():
        table = inputs()
        hidden = modules["rgcn"].encode(full_edges, table) if use_graph else F.relu(table)
        return modules["head"](hidden)[:ITEMS]

    optimizer = torch.optim.Adam(modules.parameters(), lr=1e-2)
    stopper, best_state = EarlyStopping(patience=30, mode="min"), None
    for epoch in range(200):
        optimizer.zero_grad()
        F.cross_entropy(logits()[train_ids], item_class[train_ids]).backward()
        optimizer.step()
        with torch.no_grad():
            val_loss = F.cross_entropy(logits()[val_ids], item_class[val_ids]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:
            best_state = {k: v.clone() for k, v in modules.state_dict().items()}
        if stop:
            break
    modules.load_state_dict(best_state)
    with torch.no_grad():
        return (logits()[test_ids].argmax(1) == item_class[test_ids]).float().mean().item()

for seed in range(3):
    print(f"seed {seed}: features only {classify(False, seed):.2f}, "
          f"features + R-GCN {classify(True, seed):.2f}")
text
seed 0: features only 0.53, features + R-GCN 0.93
seed 1: features only 0.47, features + R-GCN 0.90
seed 2: features only 0.30, features + R-GCN 0.90

Chance is 0.33. The noisy images alone are weak, and the graph helps because it was generated to link items within a category. On real data, check that assumption by running both.


Limitations

  • Experimental components. MultimodalKGModel and KGRGCNModel may change between releases; pin your version.
  • Full-batch encoding. Both feature models above re-encode every entity at every step. Large images or large graphs need precomputed features or sampled encoding.
  • Small-scale ranking. The evaluator loops over test triples in Python, so large test sets are slow.
  • Basic hyperparameter search. tgraphx.kg.hpo.run_kg_hpo does a small grid or random search over the ID-only models, with limits described in TGraphX vs PyKEEN.
  • Temporal KGs (TemporalKnowledgeGraph) are Experimental and not covered here.
  • No benchmark claims. Nothing here was run on FB15k-237, WN18RR or other standard datasets; see TGraphX benchmark disclaimers.

References

  • Bordes et al., "Translating Embeddings for Modeling Multi-relational Data", NeurIPS 2013.
  • Schlichtkrull et al., "Modeling Relational Data with Graph Convolutional Networks", ESWC 2018.

Related Articles