DistMult Scoring Function: Formula, Gradients, Symmetry
Topic: Knowledge graphs
DistMult scores a knowledge graph triple (head, relation, tail) with one vector per symbol:
f(h, r, t) = h^T diag(r) t = Σ_i h_i · r_i · t_i
h and t are the head and tail entity embeddings, r is the relation embedding, all in R^d, and a higher score means a more plausible triple. Because multiplication of real numbers commutes, f(h, r, t) = f(t, r, h) for every choice of parameters: DistMult cannot score one direction of a relation differently from the other. Reciprocal relations add a second relation vector for the reversed direction, which removes the conflict between head queries and tail queries, but each individual score stays symmetric.
This page works the formula by hand, derives the gradients, proves the symmetry limit, and measures what reciprocal relations change on two small graphs where the answer can be predicted in advance. For how DistMult sits next to TransE, ComplEx and RotatE, see knowledge graph scoring functions.
The formula as a bilinear form
Yang et al. (2015) start from the bilinear score h^T M_r t, where M_r is a d × d matrix for relation r, and obtain what is now called DistMult by restricting M_r to a diagonal matrix. The restriction changes the parameter count:
| Model | Relation parameters | Total, with |E| entities and |R| relations |
|---|---|---|
| Full bilinear (RESCAL) | a d × d matrix per relation |
|E|·d + |R|·d² |
| DistMult | a d-vector per relation |
|E|·d + |R|·d |
With 200-dimensional embeddings a relation costs 40,000 numbers in the full form and 200 in the diagonal form. The price is that each coordinate i of the head interacts only with coordinate i of the tail.
A worked example with three dimensions
Take
h = ( 2, -1, 0.5) r = (1, 2, 4)
t = (0.5, 1, 2)
Multiply the three vectors element by element, then add:
| dimension | h_i | r_i | t_i | h_i r_i t_i |
|---|---|---|---|---|
| 1 | 2 | 1 | 0.5 | 1 |
| 2 | -1 | 2 | 1 | -2 |
| 3 | 0.5 | 4 | 2 | 4 |
| sum | 3 |
A score means nothing on its own; it is compared with the scores of other candidates. For the query (h, r, ?) with two further candidate tails u = (1, 0.5, -1) and v = (-1, -1, 1), the same arithmetic gives f = -1 for u and f = 2 for v, so the ranking is t (3), then v (2), then u (-1).
DistMult multiplies head, relation and tail dimension by dimension
A table of the products head times relation times tail for the worked three dimensional example, with their sum of 3, and the same sum with head and tail swapped.
Triple: (h = h, r = r, t = t). DistMult score = Σk hk rk tk
| k | h | r | t | h·r·t | t·r·h |
|---|---|---|---|---|---|
| 0 | 1 | 1 | |||
| 1 | -2 | -2 | |||
| 2 | 4 | 4 | |||
| sum | score | 3 | 3 | ||
Swapping head and tail: products are equal in every dimension. DistMult therefore cannot score a relation differently in its two directions.
DistMult: score(h, r, t) = 3 and score(t, r, h) = 3.
The Python snippets on this page were executed on CPU against TGraphX 1.5.1 and build on one another. First, the same numbers come out of tgraphx.kg.DistMultModel once its two embedding tables are filled by hand:
import torch
import torch.nn.functional as F
from tgraphx.kg import DistMultModel
torch.set_num_threads(1) # tiny tensors: one thread is fastest and repeatable
# entities: 0 = h, 1 = t, 2 = u, 3 = v
model = DistMultModel(num_entities=4, num_relations=1, embedding_dim=3)
with torch.no_grad():
model.entity_emb.weight.copy_(torch.tensor(
[[2.0, -1.0, 0.5], [0.5, 1.0, 2.0], [1.0, 0.5, -1.0], [-1.0, -1.0, 1.0]]))
model.relation_emb.weight.copy_(torch.tensor([[1.0, 2.0, 4.0]]))
tail_query = torch.tensor([[0, 0, 1], [0, 0, 2], [0, 0, 3]])
head_swapped = tail_query[:, [2, 1, 0]]
print("score(h, r, x):", model.score_triples(tail_query).tolist())
print("score(x, r, h):", model.score_triples(head_swapped).tolist())
score(h, r, x): [3.0, -1.0, 2.0]
score(x, r, h): [3.0, -1.0, 2.0]
Gradients
The score is linear in each argument separately, so the three partial derivatives are elementwise products of the other two vectors:
∂f/∂h = r ⊙ t ∂f/∂r = h ⊙ t ∂f/∂t = h ⊙ r
For the example, r ⊙ t = (0.5, 2, 8), h ⊙ t = (1, -1, 1) and h ⊙ r = (2, -2, 2).
During training the score goes through a loss. With the logistic (softplus) loss for a label y ∈ {+1, -1}, L = log(1 + exp(-y f)), the chain rule gives
∂L/∂f = -y · σ(-y f)
∂L/∂h = -y · σ(-y f) · (r ⊙ t)
where σ is the logistic function. For our positive triple, σ(-3) ≈ 0.0474: the example already scores 3, so the push on it is small. Autograd agrees:
h = model.entity_emb.weight[0].detach().clone().requires_grad_(True)
r = model.relation_emb.weight[0].detach().clone().requires_grad_(True)
t = model.entity_emb.weight[1].detach().clone().requires_grad_(True)
f = (h * r * t).sum()
loss = F.softplus(-f) # positive triple, y = +1
loss.backward()
scale = -torch.sigmoid(-f).item()
print("dL/df =", round(scale, 4))
for name, grad, other in (("h", h.grad, r * t), ("r", r.grad, h * t), ("t", t.grad, h * r)):
assert torch.allclose(grad, scale * other.detach())
print(f"dL/d{name} = {[round(g, 4) for g in grad.tolist()]}")
dL/df = -0.0474
dL/dh = [-0.0237, -0.0949, -0.3794]
dL/dr = [-0.0474, 0.0474, -0.0474]
dL/dt = [-0.0949, 0.0949, -0.0949]
Two consequences follow from the product form. Dimensions never mix: the gradient for coordinate i depends only on coordinate i of the other two vectors (and on the total score through σ). And a relation coordinate near zero switches that dimension off for the relation, both in the score and in the entity gradients it sends.
Why DistMult is symmetric
The proof is one line:
f(h, r, t) = Σ_i h_i r_i t_i = Σ_i t_i r_i h_i = f(t, r, h)
The code below compares with a tolerance: h*r*t is evaluated left to right, so swapping head and tail can change the last bit of a float even though the two expressions are equal as numbers.
In matrix terms, stack all entity embeddings into E of shape [|E|, d]. The scores of relation r for every (head, tail) pair form S_r = E diag(r) E^T, which is a symmetric matrix of rank at most d. Training cannot leave the set of symmetric matrices, because no parameter value produces anything else.
Three practical consequences:
- Antisymmetric facts are not separable. If
(a, parent_of, b)is true and(b, parent_of, a)is false, both get the same number. No threshold can accept one and reject the other. - Head and tail queries are the same query. Ranking heads for
(?, r, x)and ranking tails for(x, r, ?)use one identical score vector over all entities. - Training on a triple trains its reverse. The loss of
(a, r, b)and of(b, r, a)are the same function, so they send the same gradients.
torch.manual_seed(0)
m = DistMultModel(num_entities=6, num_relations=1, embedding_dim=8)
entities = torch.arange(6)
x = 2
tails_of_x = m.score_triples(torch.stack([torch.full((6,), x), torch.zeros(6, dtype=torch.long), entities], 1))
heads_of_x = m.score_triples(torch.stack([entities, torch.zeros(6, dtype=torch.long), torch.full((6,), x)], 1))
print("(x, r, ?) equals (?, r, x):", torch.allclose(tails_of_x, heads_of_x))
def grads(triple):
m.zero_grad()
F.softplus(-m.score_triples(torch.tensor([triple]))).sum().backward()
return m.entity_emb.weight.grad.clone(), m.relation_emb.weight.grad.clone()
forward, backward = grads([0, 0, 1]), grads([1, 0, 0])
print("same gradients:", all(torch.allclose(a, b) for a, b in zip(forward, backward)))
(x, r, ?) equals (?, r, x): True
same gradients: True
How much this matters depends on the queries, not only on the relation names. Lacroix, Usunier and Obozinski (2018) point out that the symmetry becomes a problem when one evaluates (i, j, ?) and also (?, j, i) for a non-symmetric relation j; by their count such queries are about 4% of the FB15k test set and 60% of the WN18 test set. They also argue, in an appendix, that DistMult can still be expected to reach a high filtered MRR on a large hierarchy, because most queries about it can be answered correctly even though some cannot.
DistMult is ComplEx without the imaginary part
ComplEx (Trouillon et al., 2016) scores Re(Σ_i h_i r_i conj(t_i)) with complex embeddings. If every imaginary part is zero, the conjugate does nothing and the expression is the DistMult sum. The general ComplEx score is antisymmetric in the part that comes from the imaginary component of r, which is exactly what DistMult lacks. You can confirm the reduction on the two package classes by copying the real tables and zeroing the others:
from tgraphx.kg import ComplExModel
torch.manual_seed(0)
real = DistMultModel(num_entities=5, num_relations=2, embedding_dim=6)
cplx = ComplExModel(num_entities=5, num_relations=2, embedding_dim=6)
with torch.no_grad():
cplx.entity_re.weight.copy_(real.entity_emb.weight)
cplx.relation_re.weight.copy_(real.relation_emb.weight)
cplx.entity_im.weight.zero_()
cplx.relation_im.weight.zero_()
triples = torch.tensor([[0, 0, 1], [2, 1, 3], [4, 0, 2]])
print("same scores:", torch.allclose(real.score_triples(triples), cplx.score_triples(triples)))
same scores: True
A comparison between the two on your data therefore also measures the value of the imaginary parts, provided the dimensions and training recipe are matched fairly: ComplEx at dimension d stores twice as many numbers as DistMult at dimension d.
Reciprocal relations
The reciprocal setting gives every relation r a partner r' for the reversed direction:
- for each training triple
(h, r, t), also train on(t, r', h); - answer a tail query
(h, r, ?)withf(h, r, e)over all entitiese; - answer a head query
(?, r, t)as the tail query(t, r', ?), withf(t, r', e).
Lacroix et al. use this construction with a full multiclass log-loss over candidate entities. Kazemi and Poole (2018) use inverse relations for a different purpose in SimplE, which also keeps two embeddings per entity. For DistMult the cost is |R|·d extra parameters.
The head query now has its own relation vector, so the model is no longer forced to give (x, r, ?) and (?, r, x) the same ranking. KnowledgeGraph.add_inverse_relations() builds the extra triples: relation r gets the partner r + |R|. Call it on the training split only. Calling it before splitting can put the reversed copy of a test triple into training. An exact-match leakage check does not see that.
The evaluator does not use r' by itself
KGEvaluator and evaluate_filtered_ranking rank heads for (h, r, t) by scoring (e, r, t) with the original relation. A model trained with reciprocal triples therefore needs a small change of protocol: evaluate the test triples together with their reversed copies, and read only the tail metrics. The tail query of a reversed triple is exactly the reciprocal head query. The filter set must also contain the reversed copies of all known facts.
An experiment with a predictable answer
Two relations, each on its own graph, both fully used for training so that the question is what the scoring function can represent, not what it can predict:
- a binary tree of 31 nodes, edges pointing from parent to child (acyclic);
- ten separate directed 3-cycles
a → b → c → aon 30 nodes.
Both models are trained with full softmax (cross-entropy) over all entities, not the logistic loss of the Gradients section, using Adam with weight decay; the plain model averages tail and head queries.
from tgraphx.kg import KnowledgeGraph, evaluate_filtered_ranking
def train_distmult(num_entities, triples, num_relations, seed, tie_directions, dim=32):
torch.manual_seed(seed)
model = DistMultModel(num_entities, num_relations, embedding_dim=dim)
opt = torch.optim.Adam(model.parameters(), lr=0.05, weight_decay=1e-4)
h, r, t = triples.T
for _ in range(300):
E, R = model.entity_emb.weight, model.relation_emb.weight
loss = F.cross_entropy((E[h] * R[r]) @ E.T, t) # tail queries
if tie_directions: # head queries, same r
loss = (loss + F.cross_entropy((R[r] * E[t]) @ E.T, h)) / 2
opt.zero_grad()
loss.backward()
opt.step()
return model
def compare(num_entities, edges, seeds=range(5)):
kg = KnowledgeGraph(torch.tensor(edges), num_entities=num_entities, num_relations=1)
both = kg.add_inverse_relations() # (h, 0, t) plus (t, 1, h)
n = len(edges)
results = {"plain": [], "reciprocal": []}
for seed in seeds:
plain = train_distmult(num_entities, kg.triples, 1, seed, tie_directions=True)
res = evaluate_filtered_ranking(plain, kg.triples, kg.positive_triple_set(), num_entities)
results["plain"].append((res.filt_mrr_tail, res.filt_mrr_head))
recip = train_distmult(num_entities, both.triples, 2, seed, tie_directions=False)
known = both.positive_triple_set()
tail = evaluate_filtered_ranking(recip, both.triples[:n], known, num_entities)
head = evaluate_filtered_ranking(recip, both.triples[n:], known, num_entities)
results["reciprocal"].append((tail.filt_mrr_tail, head.filt_mrr_tail))
for name, values in results.items():
mean = torch.tensor(values).mean(0)
print(f" {name:10s} tail-query MRR {mean[0]:.3f} head-query MRR {mean[1]:.3f}")
print("binary tree")
compare(31, [((c - 1) // 2, 0, c) for c in range(1, 31)])
print("ten 3-cycles")
compare(30, [(3 * k + i, 0, 3 * k + (i + 1) % 3) for k in range(10) for i in range(3)])
binary tree
plain tail-query MRR 0.703 head-query MRR 0.877
reciprocal tail-query MRR 1.000 head-query MRR 1.000
ten 3-cycles
plain tail-query MRR 0.753 head-query MRR 0.744
reciprocal tail-query MRR 0.747 head-query MRR 0.740
These are training-set (memorisation) ranks averaged over five seeds on toy graphs, not an accuracy claim. What they show is structural.
On the tree, the plain model has a direct conflict: for a middle node x, the tail query (x, r, ?) wants the children on top and the head query (?, r, x) wants the parent on top, from the same score vector. Reciprocal relations give the two queries different vectors, and the ranks become perfect.
On the cycles, reciprocal relations change nothing. Look at the tail queries alone, which use only r. In the cycle a → b → c → a, the query (b, r, ?) should rank the true tail c above a. But f(b, r, a) = f(a, r, b), the score of a true edge. So a perfect ranking needs
f(b,c) > f(a,b) from the query (b, r, ?)
f(c,a) > f(b,c) from the query (c, r, ?)
f(a,b) > f(c,a) from the query (a, r, ?)
which is a contradiction. At least one of the three queries cannot be ranked first, however large d is and however the model is trained. A tree escapes because scores may increase with depth, and a chain of "greater than" along an acyclic graph is satisfiable. The same argument applies to any directed cycle of length three or more, as long as the reverse edges are false.
So the reciprocal setting fixes the conflict between the two query directions. It does not fix the constraint within one relation vector.
Do not average the two directions
A natural idea is to score a triple as ½ (f(h, r, t) + f(t, r', h)). With one embedding per entity this equals DistMult with the relation vector (r + r') / 2, so it is symmetric again:
torch.manual_seed(0)
rec = DistMultModel(num_entities=5, num_relations=2, embedding_dim=8)
def combined(h, t):
return 0.5 * (rec.score_triples(torch.tensor([[h, 0, t]]))
+ rec.score_triples(torch.tensor([[t, 1, h]])))
print("f(0, r, 1) == f(1, r, 0):", torch.allclose(
rec.score_triples(torch.tensor([[0, 0, 1]])), rec.score_triples(torch.tensor([[1, 0, 0]]))))
print("averaged score symmetric:", torch.allclose(combined(0, 1), combined(1, 0)))
f(0, r, 1) == f(1, r, 0): True
averaged score symmetric: True
SimplE's average is not symmetric because each entity has a separate head vector and tail vector. If you need a directed score for a single triple, for example in triple classification, use a model with that property (SimplE, ComplEx, RotatE or a full bilinear form), not reciprocal DistMult.
Reciprocal relations with KGTrainer
KGTrainer needs no special mode. Give it the augmented training triples and a model with twice the relations. This short run only shows the wiring; it trains on a random synthetic graph, so its loss has no meaning.
from tgraphx.kg import (KGTrainer, KGTrainingConfig, UniformNegativeSampler,
generate_synthetic_kg)
kg = generate_synthetic_kg(num_entities=40, num_relations=3, num_triples=150, seed=0)
train_kg, valid_kg, test_kg = kg.train_valid_test_split(0.8, 0.1, 0.1, seed=0)
train_both = train_kg.add_inverse_relations() # split first, augment second
torch.manual_seed(0)
recip_model = DistMultModel(kg.num_entities, 2 * kg.num_relations, embedding_dim=16)
config = KGTrainingConfig(num_epochs=5, batch_size=64, lr=1e-2, loss_type="softplus", seed=0)
KGTrainer(recip_model, config, train_both.triples,
sampler=UniformNegativeSampler(kg.num_entities, num_negatives=4)).train()
test_both = test_kg.add_inverse_relations()
known = kg.add_inverse_relations().positive_triple_set() # all facts, both directions
res = evaluate_filtered_ranking(recip_model, test_both.triples, known, kg.num_entities)
print("train triples:", len(train_kg), "->", len(train_both))
print("ranked queries:", len(test_both), "(tail metrics only)")
train triples: 120 -> 240
ranked queries: 30 (tail metrics only)
res.filt_mrr_tail is the number to report under this protocol. The head fields of that result rank heads for both the original and the reversed triples, which is not part of the reciprocal protocol, so ignore them.
Check one property of the sampler as well: with a Uniform sampler, both the head and the tail are corrupted for the original and the reversed copy. The construction in Lacroix et al. instead only ever ranks the object position of the augmented data. Either is a legitimate recipe, but state which one you used.
Training choices that matter for DistMult
- Scores are unbounded. Doubling all embeddings multiplies every score by eight. With a logistic loss, a model can keep lowering the loss on separable training data by growing norms, so use weight decay or an explicit regulariser. Lacroix et al. study a nuclear 3-norm penalty for factorisation models of this family.
- The loss changes the gradient on negatives, independently of the score function. A margin loss ignores negatives that are already more than the margin below the positive, while a logistic loss never fully ignores them.
- A negative can be the mirror image of a true fact. Corrupting some other positive may produce
(t, r, h)while(h, r, t)is true. A symmetric model gives both one score, so it cannot push the negative down without pushing the true fact down. A sampler that rejects known training triples does not help, because the reversed triple is usually not one of them.
Tensor-valued entities
When entities carry images or feature maps, the common route is to encode each entity into a vector and keep the DistMult decoder. tgraphx.kg.MultimodalKGModel (Experimental) does this, so its scores are symmetric in head and tail too. Its built-in ImageEntityProjector averages over height and width before the linear layer, which means a mirrored image gets the same entity vector:
from tgraphx.kg import ImageEntityProjector
torch.manual_seed(0)
projector = ImageEntityProjector(in_channels=3, out_dim=8)
images = torch.randn(2, 3, 4, 4, generator=torch.Generator().manual_seed(1))
print("mirrored image, same vector:",
torch.allclose(projector(images), projector(images.flip(-1))))
mirrored image, same vector: True
You can also keep the tensor and apply the DistMult rule position by position: f = Σ_{c,h,w} H[c,h,w] · R[c,h,w] · T[c,h,w] for entity maps H, T and a relation tensor R of the same shape. Position now matters, because mirroring only one entity changes the score. Direction still does not, because the three factors still commute.
H, T = images[0], images[1]
R = torch.randn(3, 4, 4, generator=torch.Generator().manual_seed(2))
def tensor_distmult(a, rel, b):
return (a * rel * b).sum()
print("swap head and tail, same score:",
torch.isclose(tensor_distmult(H, R, T), tensor_distmult(T, R, H)).item())
print("mirror the tail only, same score:",
torch.isclose(tensor_distmult(H, R, T), tensor_distmult(H, R, T.flip(-1))).item())
swap head and tail, same score: True
mirror the tail only, same score: False
This elementwise form equals ordinary DistMult on flattened tensors; writing it with the shape kept only makes it easier to add a per-position or per-channel readout later. Knowledge graph embedding with tensor features shows a complete training loop with learned encoders.
Checklist for evaluating DistMult
- Report head and tail metrics separately. The combined number hides the case where one direction is much weaker. With symmetric test relations the two should be close.
- Say whether you used reciprocal relations, and evaluate head queries with
r'if you did. A default filtered evaluator will silently user. - Check for reversed test pairs in training. A symmetric model gives
(t, r, h)the score of(h, r, t), so a reversed training copy of a test triple raises its score with no inference at all. - State the tie rule. Zero or dead dimensions can make many candidates score equally.
- Mind
DistMultModel(entity_feature_dim=...). In 1.5.1 it creates a projector thatscore_triplesnever calls, so passing a feature size does not make the model read features. - Pass relation counts that include inverses. A reciprocal model needs
num_relations = 2·|R|.
References
- Yang, Yih, He, Gao and Deng, Embedding Entities and Relations for Learning and Inference in Knowledge Bases, ICLR 2015.
- Lacroix, Usunier and Obozinski, Canonical Tensor Decomposition for Knowledge Base Completion, ICML 2018.
- Kazemi and Poole, SimplE Embedding for Link Prediction in Knowledge Graphs, NeurIPS 2018.
- Trouillon, Welbl, Riedel, Gaussier and Bouchard, Complex Embeddings for Simple Link Prediction, ICML 2016.