Module contents
Lesson 18 of 30Core 115 min

Knowledge graphs: relational embeddings, R-GCN and reasoning

Model directed knowledge-graph relations with translational, bilinear and rotational embeddings, evaluate filtered rankings and examine relational message passing and inductive reasoning.

After this lesson you can

  • Define knowledge graph triples and the open-world assumption.
  • Compare TransE, DistMult, ComplEx and RotatE on relational patterns.
  • Train and evaluate models with explicit negative sampling and filtered ranking.
  • Explain relation-specific message passing and basis decomposition.
  • Assess inductive transfer and memory requirements using controlled experiments.

Before you start

Entities and claims

A library can depend on another and a vulnerability can affect a version. Order matters: “A depends on B” does not imply B depends on A. A pair of entities can be connected by multiple relations.

In an open world, an absent triple may be true but unrecorded. Treating some absent ones as negatives helps training, but does not turn absence into refutation. The task extends link prediction with types and direction. A schema can restrict domains, but a high score is not a logical proof. Software-dependency queries also require source and version.

One name may refer to a package, a particular version or an organization. If the schema mixes these entities, an apparently coherent path can combine claims about different objects. Distinguish “package A declares a dependency” from “version A1 was installed with version B2”: the triples answer different questions. A graph extracted from text needs identity rules, dates and document references so a prediction can be reviewed.

Translate, multiply and rotate

Translational embeddings assign vectors to entities and relations. TransE favors eh+r≈et\vb e_h+\vb r\approx\vb e_t, for example with score −∥eh+r−et∥-\norm{\vb e_h+\vb r-\vb e_t}. A higher score is better, but is not a calibrated probability.

If both directions of a symmetric relation are fitted exactly with the same vector, eh+r=et\vb e_h+\vb r=\vb e_t and et+r=eh\vb e_t+\vb r=\vb e_h. Adding gives 2r=02\vb r=\vb 0. If each residual has norm at most ε\varepsilon, the triangle inequality implies ∥r∥≤ε\norm{\vb r}\leq\varepsilon. This is a property of simultaneous fitting, not proof that no approximate threshold separation is possible.

In bilinear embeddings, RESCAL uses a matrix per relation and DistMult a diagonal:

sRESCAL(h,r,t)=eh⊤Rret,sDistMult(h,r,t)=∑jeh,j rj et,j.s_{\mathrm{RESCAL}}(h,r,t)=\vb e_h\T\mat R_r\vb e_t,\qquad s_{\mathrm{DistMult}}(h,r,t)=\sum_j e_{h,j}\,r_j\,e_{t,j}.

A general matrix can score the two orders differently; DistMult’s diagonal cannot. Real multiplication commutes and s(h,r,t)=s(t,r,h)s(h,r,t)=s(t,r,h) always. This prevents strictly separating both directions with one threshold.

ComplEx permits complex vectors and conjugates the tail:

sComplEx(h,r,t)=Re⁡ ⁣(∑jeh,jrjet,j‾).s_{\mathrm{ComplEx}}(h,r,t)=\operatorname{Re}\!\left(\sum_j e_{h,j}r_j\overline{e_{t,j}}\right).

With one coordinate, eh=1e_h=1, et=ie_t=i and r=ir=i give s(h,r,t)=1s(h,r,t)=1 and s(t,r,h)=−1s(t,r,h)=-1. The imaginary part allows directionality; it does not force every learned relation to be antisymmetric. Relational patterns describe properties or rules among relations, not automatic training guarantees.

ComplEx notation is compact, but an implementation can maintain two real entity matrices and two relation matrices. Multiplication produces real terms and interactions between real and imaginary parts. Conjugating the tail changes the sign of some terms when endpoints are exchanged. The real expression for the product must retain that sign: without conjugation the program no longer computes the function defined above. A useful test compares vectorized scores of all candidates with the direct complex formula on small graphs.

RotatE takes rj=eiθjr_j=e^{i\theta_j} of unit modulus and favors eh⊙r≈et\vb e_h\odot\vb r\approx\vb e_t. The ideal inverse has phase −θj-\theta_j and an ideal composition adds phases modulo 2π2\pi. For an exact symmetric relation where eh,j≠0e_{h,j}\ne0, applying the rotation twice must return the entity: rj2=1r_j^2=1 and θj∈{0,π}\theta_j\in\{0,\pi\} modulo 2π2\pi. Zero coordinates do not impose that condition. These are exact equations; training learns approximations.

InteractiveThe geometry of relations
  • Head h
  • Tail t
  • Transformed T(h)
htT(h)

To exactly satisfy both directions with the same vector, translation must be zero. TransE and RotatE use negative Euclidean distance; DistMult uses the diagonal product.

Model
Pattern
90
0.6
0.6
0.2
0.2
0.6
Score h → t−0.447
Score t → h−1.077
Place two entities in the plane. TransE draws a translation, RotatE a complex rotation and DistMult a diagonal transformation used in a product. Scores are calculated with those vectors; they are not trained results.

In an exact composition two translations add and two rotations multiply. With RESCAL matrices order can matter; DistMult diagonals commute. No identity guarantees a model learns a domain rule: data, a loss and, when required, explicit constraints are needed.

Training and evaluation

In KG training and evaluation, one way to generate negatives corrupts the head or tail of a positive triple. If a corrupted triple matches a known fact it can be rejected; even so, it could be an unrecorded truth. In a temporal problem future knowledge must not decide which negatives were available in the past.

A margin loss compares a positive score with a negative. Another uses logistic loss. 1-N scoring calculates logits for all possible endpoints and applies multiclass loss. If there are several true answers, penalizing the others while treating one as the sole class may be inappropriate; a multilabel objective or modified protocol can be used. Lacroix et al. N3 regularization penalizes cubic powers of the factors involved; weighting and reduction are part of the implementation.

RotatE proposed self-adversarial negatives: higher-scoring ones receive more weight via softmax. A hard negative can be false. Architecture, dimension, loss, regularization, training and candidates change the result; attributing an improvement only to the model name obscures those choices.

For example, if s+s^+ is the positive logit and si−s_i^- the negative logits, one can take pi=exp⁡(αsi−)/∑jexp⁡(αsj−)p_i=\exp(\alpha s_i^-)/\sum_j\exp(\alpha s_j^-) and minimize

softplus⁡(−s+)+∑istopgrad⁡(pi) softplus⁡(si−).\operatorname{softplus}(-s^+)+\sum_i\operatorname{stopgrad}(p_i)\,\operatorname{softplus}(s_i^-).

Stopping gradients through the weights means that during that step they weight losses without differentiating through the computation of pip_i. A larger α\alpha concentrates weight on higher-scoring negatives. In RotatE the logit includes a margin and distance; the preceding equation makes the weighting mechanism explicit, but does not replace every implementation decision in the paper.

To evaluate (h,r,t)(h,r,t), score head and tail candidates. In raw ranking another true answer may rank above tt. Filtered ranking removes other known true answers, retains the target and ranks the remainder. The filter set must be explicit: retrospective evaluation can use facts from all splits, but a system at a past date does not automatically have future facts.

For ties we use 1+#{si>st}+12#{i≠t:si=st}1+\#\{s_i>s_t\}+\tfrac12\#\{i\ne t:s_i=s_t\}. Rank can be fractional; MRR averages reciprocals and Hits@K counts queries with rank no greater than KK. Link evaluation requires specifying candidates, filtering and ties to compare figures.

Suppose the target ranks fourth raw and two known answers are above it. Removing them changes its filtered rank to two; no model score changes. If two remaining candidates tie with the target, average rank averages all their possible positions. Filtering does not remove unknown answers that are actually true: it has only the supplied fact collection. Nor does it by itself measure whether scores enable an operating threshold or whether probabilities are calibrated.

InteractiveRaw versus filtered ranking
Ada0.9
Beto (known)0.8
Carla (known)0.8
Diego (target)0.6
Eva0.3

Toy scores: a tie receives average rank. The filter always retains the evaluated answer.

Evaluated answer
Average rank4.0
Reciprocal rank0.250
Retained candidates5
Toy scores: Beto, Carla and Diego are known answers. The filter removes known answers other than the evaluated target. The tie between Beto and Carla gets average rank.

FB15k and WN18 contain inverse relation pairs that allow some test triples to be deduced from training triples. FB15k-237 and WN18RR were designed to reduce that shortcut; this does not show all bias or regularity disappears. A rule learned only from training must be evaluated with the same filter, entities and tie handling as the alternative.

InteractiveInverse-relation leakage
Inverse rule0.70541
Short TransE0.04633

Filtered MRR with average ties and both directions. The rule uses all training to choose inverses; TransE uses 20 000 positives per epoch for five epochs. The comparison shows leakage; it does not determine the best converged model.

Dataset
Rule coverage, sample71.9 %
Rule MRR on full test0.71568
Test triples59071
Results calculated on FB15k and FB15k-237 files from the RotatE repository. Each bar uses the same 512 test triples for that dataset, queries head and tail and filters known truths. The rule receives 1 if it finds the inverse fact and 0 otherwise. TransE was briefly trained; it is not a converged result.

For each relation the rule selects the one most often appearing inverted in training, including the relation itself if it is its best inverse. It does not learn the mapping from test. At evaluation a candidate scores one if its inverse appears in training and zero otherwise; ties are averaged and other known true answers from train, validation and test removed. Coverage is the fraction of queries whose test answer scores one. All entity candidates are used, not just sampled negatives.

The TransE control has dimension 32 and trained five epochs, each on 20 000 sampled positives and one random corruption per positive. Negatives are not filtered and can be true facts; hyperparameters were not selected on validation. The rule uses all training, so the methods have different training budgets and this comparison does not determine which would be better after convergence. Its purpose is to show a simple rule finds the inverse-relation shortcut in the original benchmark. Seed 19 selects 512 triples per dataset and head and tail are evaluated: 1024 queries with identical candidates, filters and ties for both bars. The rule’s figure on all test is shown separately.

The rule’s criterion is deliberately simple: count inverted matches per relation pair and choose the relation with the highest count, without tuning a precision threshold. A very frequent relation can dominate the choice, and a symmetric relation can select itself. Coverage says whether the answer appears among candidates scored one, not whether it is the only answer or whether the rule knows its meaning. Since candidates without evidence score zero, their average tie also counts toward MRR. Low coverage must not be replaced by an invented last-place rank.

Reproduce the inverse test

The local cell downloads files for four datasets from the RotatE authors’ repository pinned to commit 2e440e0f9c687314d5ff67ead68ce985dc446e3a, and records SHA-256 and size of each file. The rule is built from training facts; evaluation filters use train, validation and test. The full rule is checked and, for the figure, a fixed sample of 512 triples per dataset. TransE is trained on the same data sample described above and evaluated on the same candidates. The cell may take several minutes and requires a connection, NumPy and PyTorch; it uses CUDA if available. Scores are experimental and may vary slightly with hardware.

[ ]Inverse rules and TransE with identical candidatesLocal GPU
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import hashlib, json, urllib.request

commit = '2e440e0f9c687314d5ff67ead68ce985dc446e3a'
root = Path('dataset/kg-l18')
jobs = [(dataset, file) for dataset in ('FB15k','FB15k-237','wn18','wn18rr')
        for file in ('entities.dict','relations.dict','train.txt','valid.txt','test.txt')]
def fetch(job):
    dataset, file = job
    url = f'https://raw.githubusercontent.com/DeepGraphLearning/KnowledgeGraphEmbedding/{commit}/data/{dataset}/{file}'
    data = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent':'OryonLearn'}), timeout=90).read()
    path = root / dataset / file; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(data)
    return {'dataset':dataset, 'file':file, 'bytes':len(data), 'sha256':hashlib.sha256(data).hexdigest(), 'url':url}
with ThreadPoolExecutor(max_workers=6) as pool: results = list(pool.map(fetch, jobs))
(root / 'manifest.json').write_text(json.dumps(results, indent=2), encoding='utf8')
print('Descargados y registrados:', len(results), 'archivos')

import json
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np

def load(name):
    base = Path('dataset/kg-l18') / name
    entities = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'entities.dict').read_text(encoding='utf8').splitlines()}
    relations = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'relations.dict').read_text(encoding='utf8').splitlines()}
    def triples(part):
        rows = [line.split('\t') for line in (base/f'{part}.txt').read_text(encoding='utf8').splitlines()]
        return [(entities[h], relations[r], entities[t]) for h,r,t in rows]
    return entities, relations, triples('train'), triples('valid'), triples('test')

def study(name):
    entities, relations, train, valid, test = load(name)
    train = set(train)
    bypair = defaultdict(set)
    head = defaultdict(set); tail = defaultdict(set)
    for h,r,t in train:
        bypair[(h,t)].add(r); tail[(h,r)].add(t); head[(r,t)].add(h)
    counts = defaultdict(Counter)
    for h,r,t in train:
        for inverse in bypair[(t,h)]: counts[r][inverse] += 1
    # Decide la relación inversa únicamente a partir de entrenamiento.
    best = {r: sorted(counter.items(), key=lambda item: (-item[1], item[0]))[0][0] for r,counter in counts.items()}
    truth_head = defaultdict(set); truth_tail = defaultdict(set)
    for h,r,t in train.union(valid, test):
        truth_head[(r,t)].add(h); truth_tail[(h,r)].add(t)
    def query(h, r, t, predict_tail):
        inverse = best.get(r)
        candidates = (head.get((inverse,h), set()) if predict_tail else tail.get((t,inverse), set())) if inverse is not None else set()
        target = t if predict_tail else h
        known = truth_tail[(h,r)] if predict_tail else truth_head[(r,t)]
        retained_ones = candidates - (known - {target})
        eligible = len(entities) - (len(known) - 1)
        if target in retained_ones:
            rank = 1 + .5 * (len(retained_ones) - 1)
        else:
            rank = 1 + len(retained_ones) + .5 * (eligible - len(retained_ones) - 1)
        return 1/rank, target in retained_ones
    rng = np.random.default_rng(19)
    sample = set(rng.choice(len(test), min(512,len(test)), replace=False).tolist())
    result = {'all':[], 'sample':[]}; covered={'all':0, 'sample':0}
    for i, (h,r,t) in enumerate(test):
        for predict_tail in (False, True):
            rr, hit = query(h,r,t,predict_tail)
            result['all'].append(rr); covered['all'] += int(hit)
            if i in sample: result['sample'].append(rr); covered['sample'] += int(hit)
    return {'dataset':name, 'entities':len(entities), 'relations':len(relations), 'train':len(train), 'test':len(test),
            'mapped_relations':len(best), 'mrr_full':float(np.mean(result['all'])),
            'coverage_full':covered['all']/len(result['all']), 'mrr_sample':float(np.mean(result['sample'])),
            'coverage_sample':covered['sample']/len(result['sample']), 'sample_triples':len(sample)}

if __name__ == '__main__':
    results = [study(name) for name in ('FB15k','FB15k-237')]
    Path('dataset/kg-l18/inverse_results.json').write_text(json.dumps(results, indent=2), encoding='utf8')
    print(json.dumps(results, ensure_ascii=False, indent=2))

import json, time
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch

torch.set_num_threads(2)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
results=[]
for name in ('FB15k','FB15k-237'):
    entities, relations, train, valid, test = load(name)
    n, nr = len(entities), len(relations)
    torch.manual_seed(22); rng = np.random.default_rng(22)
    E = torch.nn.Embedding(n,32,device=device); R = torch.nn.Embedding(nr,32,device=device)
    torch.nn.init.uniform_(E.weight,-.1,.1); torch.nn.init.uniform_(R.weight,-.1,.1)
    optimizer = torch.optim.Adam(list(E.parameters()) + list(R.parameters()),lr=.003)
    train_arr = np.asarray(train,dtype=np.int64)
    start=time.perf_counter()
    for epoch in range(5):
        order = rng.choice(len(train_arr),size=min(20000,len(train_arr)),replace=False)
        for offset in range(0,len(order),1024):
            batch = torch.tensor(train_arr[order[offset:offset+1024]], device=device)
            h,r,t = batch.T
            corrupt_h = torch.rand(len(batch),device=device) < .5
            random_entity = torch.randint(n,(len(batch),),device=device)
            hn = torch.where(corrupt_h,random_entity,h); tn = torch.where(corrupt_h,t,random_entity)
            positive=(E(h)+R(r)-E(t)).norm(p=1,dim=1)
            negative=(E(hn)+R(r)-E(tn)).norm(p=1,dim=1)
            loss=torch.relu(1+positive-negative).mean()
            optimizer.zero_grad(); loss.backward(); optimizer.step()
            with torch.no_grad(): E.weight.renorm_(p=2,dim=0,maxnorm=1)
    known_head=defaultdict(set); known_tail=defaultdict(set)
    for h,r,t in train+valid+test:
        known_head[(r,t)].add(h); known_tail[(h,r)].add(t)
    sample = np.random.default_rng(19).choice(len(test),min(512,len(test)),replace=False)
    questions=[test[i] for i in sample]
    reciprocal=[]
    with torch.no_grad():
        for begin in range(0,len(questions),32):
            batch=questions[begin:begin+32]
            h=torch.tensor([x[0] for x in batch],device=device)
            r=torch.tensor([x[1] for x in batch],device=device)
            t=torch.tensor([x[2] for x in batch],device=device)
            for side in ('head','tail'):
                query=E(t)-R(r) if side=='head' else E(h)+R(r)
                scores=-torch.cdist(query,E.weight,p=1)
                target=h if side=='head' else t
                for i,(hi,ri,ti) in enumerate(batch):
                    other=(known_head[(ri,ti)]-{hi}) if side=='head' else (known_tail[(hi,ri)]-{ti})
                    if other: scores[i,torch.tensor(list(other),device=device)]=-torch.inf
                target_score=scores.gather(1,target[:,None])
                rank=1+(scores>target_score).sum(1)+.5*((scores==target_score).sum(1)-1)
                reciprocal.extend((1/rank).cpu().tolist())
    if device.type == 'cuda': torch.cuda.synchronize()
    results.append({'dataset':name,'sample_triples':len(sample),'queries':len(reciprocal),
                    'filtered_mrr':float(np.mean(reciprocal)), 'device':str(device),
                    'epochs':5,'train_sample_per_epoch':min(20000,len(train)),'seconds':round(time.perf_counter()-start,2)})
    print(json.dumps(results[-1]),flush=True)
Path('dataset/kg-l18/transe_sample.json').write_text(json.dumps(results,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

R-GCN: relation-specific messages

An R-GCN aggregates messages with an edge-type-dependent matrix. For incoming neighbors Nr(v)\mathcal N_r(v) and normalization cv,rc_{v,r},

hv′=σ ⁣(W0hv+∑r∈R∑u∈Nr(v)1cv,rWrhu).\vb h_v' = \sigma\!\left(\mat W_0\vb h_v+\sum_{r\in\mathcal R}\sum_{u\in\mathcal N_r(v)}\frac{1}{c_{v,r}}\mat W_r\vb h_u\right).

The self term differs from adding an edge for every relation. Normalization may use neighbor count per relation or another stated rule. To send messages both ways, explicit inverse relations can be included, but not inverses of facts reserved for test.

A full matrix per relation costs Rd2R d^2 parameters for equal dimensions. With bases, Wr=∑b=1BarbVb\mat W_r=\sum_{b=1}^{B}a_{rb}\mat V_b, cost is Bd2+RBB d^2+RB, excluding biases and W0\mat W_0. With BB equal diagonal blocks, each relation has d2/Bd^2/B parameters when BB divides dd. Bases share components; blocks restrict which coordinates interact. An R-GCN encoder can produce embeddings for a DistMult decoder, as in the original paper.

For example, with d=128d=128, R=1000R=1000 and eight bases, matrices and coefficients occupy 8⋅1282+1000⋅8=1390728\cdot128^2+1000\cdot8=139072 parameters, versus 1000⋅1282=163840001000\cdot128^2=16384000 in full matrices. The saving has an expressivity cost: all relation matrices must belong to the space spanned by the same eight bases. With blocks, each output receives information only from coordinates of the corresponding block in that transformation; additional layers and other operations can mix information, but one block matrix is not an arbitrary matrix.

Induction and retrieval

Inductive KG models must specify what changes between training and test. A free table per entity does not automatically provide a trained vector for a new entity. NBFNet propagates query-conditioned states and can handle new entities if it has structure and relations it can represent. Generalizing to unseen relations also requires a representation not dependent exclusively on a fixed table.

ULTRA constructs relation representations from their structural interactions and uses conditioned propagation; a pretrained checkpoint can transfer between graphs with different vocabularies. Transfer does not mean automatically knowing a new name’s semantics or verifying a fact. Results depend on the observable graph and protocol.

Serving millions of entities is another constraint independent of expressivity. Five million vectors of dimension 256 in float32 occupy 5.12 decimal GB for parameters alone. An optimizer like Adam maintains two additional states of the same size, and training also needs gradients, relations, activations and batch memory. Complex embeddings with 256 complex coordinates require two real components per coordinate. With 8 GB VRAM, partitioning or keeping parameters off GPU may be needed; before promising a model, measure both memory and retrieval latency.

A language model can extract candidate triples from documents, save their sources and query paths like “package → version → vulnerability.” Vector search retrieves texts by similarity; a graph permits traversing relations and constraining types over multiple hops. They complement one another: a path is a traceable clue, not sufficient evidence if edges were extracted incorrectly or outdated. GraphRAG is studied in the RAG module.

Multi-hop dependency query

This example is fictional: neither packages nor vulnerability are presented as real facts. The query follows two dependency relations and then an affects relation. In an application each edge should retain a source, affected version and effective date; the result would still need checking against that source.

[ ]A dependency pathBrowser
facts = [
    ("app-demo", "depende_de", "parser-demo", "ejemplo sintético"),
    ("parser-demo", "depende_de", "codec-demo", "ejemplo sintético"),
    ("codec-demo", "afectado_por", "VULN-DEMO-1", "ejemplo sintético"),
    ("app-demo", "depende_de", "utils-demo", "ejemplo sintético"),
]
def paths(start, relations):
    found = [(start, [])]
    for relation in relations:
        found = [(t, trail + [(h, r, t, source)])
                 for node, trail in found
                 for h, r, t, source in facts if h == node and r == relation]
    return [trail for _, trail in found]
for path in paths("app-demo", ["depende_de", "depende_de", "afectado_por"]):
    for h, r, t, source in path:
        print(f"{h} --{r}--> {t} ({source})")

Lab from scratch

The following dependency graph is synthetic, with six entities and two inverse relations. Training, validation and test are separate; negative filtering consults all known triples to avoid incorrectly labeling them, a retrospective convention that does not represent temporal deployment. The single test triple produces two queries, so its MRR has enormous uncertainty. This is not a benchmark comparison.

The four scoring functions train with logistic loss and central differences on each parameter. This numerical gradient is transparent in a small example but too expensive for a real KG; local models use autograd. The R-GCN layer uses scatter_sum from the message-passing framework, two bases and a classifier trained with explicit gradients. Here messages are summed without normalization and the self term is identity; its labels and node split are also synthetic. A second block-matrix implementation without a self term is checked against multiplication by its equivalent full matrices. Preparation includes an independent module copy, SHA-256 722eb1df61bde98ee9a7770777bd4ab4646c8094144f4165d9e979f468252587.

[ ]Relational scorers and basis R-GCNBrowser
import numpy as np

# Grafo sintético de dependencias y su relación inversa, no datos de producción.
names = ['app','parser','io','codec','utils','core']
facts = [(i,0,i+1) for i in range(5)] + [(i+1,1,i) for i in range(5)]
train, valid, test = facts[:4]+facts[5:9], [facts[4]], [facts[9]]
known = set(train+valid+test)
n, nr, d = len(names), 2, 2

def score(kind,E,R,triples):
    p=np.asarray(triples,dtype=int); h,r,t=p.T
    if kind=='TransE': return -np.sqrt(((E[h]+R[r]-E[t])**2).sum(axis=1)+1e-8)
    if kind=='DistMult': return (E[h]*R[r]*E[t]).sum(axis=1)
    if kind=='ComplEx':
        z=E[...,0]+1j*E[...,1]; w=R[...,0]+1j*R[...,1]
        return np.real((z[h]*w[r]*np.conjugate(z[t])).sum(axis=1))
    if kind=='RotatE':
        z=E[...,0]+1j*E[...,1]; phase=np.exp(1j*R[r])
        return -np.sqrt((np.abs(z[h]*phase-z[t])**2).sum(axis=1)+1e-8)
    raise ValueError(kind)

def negatives(rng):
    out=[]
    for h,r,t in train:
        while True:
            if rng.random()<.5: h2,t2=int(rng.integers(n)),t
            else: h2,t2=h,int(rng.integers(n))
            if (h2,r,t2) not in known:
                out.append((h2,r,t2)); break
    return out

def filtered_mrr(kind,E,R):
    ranks=[]
    for h,r,t in test:
        for tail in (False,True):
            candidates=[(h,r,x) if tail else (x,r,t) for x in range(n)]
            candidates=[p for p in candidates if p==(h,r,t) or p not in known]
            s=score(kind,E,R,candidates); target=candidates.index((h,r,t)); v=s[target]
            rank=1+np.sum(s>v)+.5*(np.sum(s==v)-1)
            ranks.append(1/rank)
    return float(np.mean(ranks))

def train_kge(kind):
    rng=np.random.default_rng(11)
    complex_entities = kind in ('ComplEx','RotatE')
    E=rng.normal(0,.2,(n,d,2) if complex_entities else (n,d))
    R=rng.normal(0,.2,(nr,d,2) if kind=='ComplEx' else (nr,d))
    neg=negatives(rng)  # usa el grafo completo conocido, no simula disponibilidad futura
    def loss():
        pos=score(kind,E,R,train); bad=score(kind,E,R,neg)
        return float(np.mean(np.logaddexp(0,-pos)+np.logaddexp(0,bad)))
    initial=loss(); step=1e-5
    # Diferencias centrales: didácticas y costosas, no una alternativa para producción.
    for _ in range(60):
        gradients=[]
        for parameter in (E,R):
            grad=np.zeros_like(parameter)
            for ix in np.ndindex(parameter.shape):
                old=parameter[ix]; parameter[ix]=old+step; up=loss()
                parameter[ix]=old-step; down=loss(); parameter[ix]=old
                grad[ix]=(up-down)/(2*step)
            gradients.append(grad)
        E-=.12*gradients[0]; R-=.12*gradients[1]
    return initial,loss(),filtered_mrr(kind,E,R)

for kind in ('TransE','DistMult','ComplEx','RotatE'):
    before,after,mrr=train_kge(kind)
    print(kind,'pérdida',round(before,4),'→',round(after,4),'MRR filtrado',round(mrr,4))

# R-GCN en bases con suma de mini_mp, entrenada para etiquetas sintéticas.
rng=np.random.default_rng(3)
edges=np.array([[h,t] for h,r,t in train],dtype=int).T
types=np.array([r for h,r,t in train],dtype=int)
degree=np.bincount(edges[1],minlength=n)
x=np.column_stack([np.ones(n),degree/4,rng.normal(0,.2,n)])
bases=rng.normal(0,.15,(2,3,3)); coeff=rng.normal(0,.15,(nr,2))
w=rng.normal(0,.1,(3,2)); y=np.array([0,0,0,1,1,1]); train_nodes=np.array([0,1,3,4]); test_nodes=np.array([2,5])
for epoch in range(180):
    W=np.einsum('eb,bij->eij',coeff[types],bases)
    messages=np.einsum('ei,eij->ej',x[edges[0]],W)
    pre=x+scatter_sum(messages,edges[1],n); h=np.maximum(pre,0)
    logits=h@w; logits-=logits.max(axis=1,keepdims=True)
    prob=np.exp(logits); prob/=prob.sum(axis=1,keepdims=True)
    delta=np.zeros_like(prob); delta[train_nodes]=prob[train_nodes]
    delta[train_nodes,y[train_nodes]]-=1; delta/=len(train_nodes)
    grad_w=h.T@delta; grad_h=(delta@w.T)*(pre>0)
    grad_W=np.einsum('ei,ej->eij',x[edges[0]],grad_h[edges[1]])
    grad_bases=np.einsum('eb,eij->bij',coeff[types],grad_W)
    grad_coeff=np.zeros_like(coeff); np.add.at(grad_coeff,types,np.einsum('eij,bij->eb',grad_W,bases))
    bases-=.05*grad_bases; coeff-=.05*grad_coeff; w-=.05*grad_w
W=np.einsum('eb,bij->eij',coeff[types],bases)
messages=np.einsum('ei,eij->ej',x[edges[0]],W)
h=np.maximum(x+scatter_sum(messages,edges[1],n),0)
print('R-GCN, exactitud en dos nodos sintéticos de test:',float(np.mean(np.argmax(h[test_nodes]@w,axis=1)==y[test_nodes])))
print('Parámetros relacionales en bases:', bases.size+coeff.size)

def rgcn_blocks(x, edge_index, edge_type, blocks):
    # blocks: (relaciones, bloques, ancho_bloque, ancho_bloque)
    src,dst=edge_index; B,width=blocks.shape[1:3]
    x_blocks=x[src].reshape(len(src),B,width)
    messages=np.einsum('ebi,ebij->ebj',x_blocks,blocks[edge_type]).reshape(len(src),B*width)
    return scatter_sum(messages,dst,len(x))

block_x=rng.normal(size=(n,4)); blocks=rng.normal(size=(nr,2,2,2))
block_result=rgcn_blocks(block_x,edges,types,blocks)
matrices=np.zeros((nr,4,4))
for r in range(nr):
    for b in range(2): matrices[r,2*b:2*b+2,2*b:2*b+2]=blocks[r,b]
reference=scatter_sum(np.einsum('ei,eij->ej',block_x[edges[0]],matrices[types]),edges[1],n)
assert np.allclose(block_result,reference)
print('R-GCN bloques coincide con matrices completas:',np.allclose(block_result,reference),'; parámetros:',blocks.size)

Local experiment with FB15k-237 and WN18RR

The cell downloads data pinned to the RotatE repository commit and trains three models with CUDA if available. ComplEx uses 1-N softmax over tails and N3 penalty on involved factors; the single-class objective treats other potentially true tails as negative alternatives. RotatE uses torch_geometric.nn.kge.RotatE and its logistic loss with random corruption. For R-GCN plus DistMult, 1024 positive training triples are separated from the message graph along with their generated inverses; evaluation uses the full training graph. Corruptions of the latter two models are not filtered and may contain false negatives. No model selects hyperparameters on validation.

The initial configuration is a short test: two epochs, up to 2048 positives per epoch for the first two methods and 32 test triples per dataset, each evaluated for head and tail against all entities with retrospective filtering of known facts. R-GCN uses 1024 supervision positives per epoch. Sample count and architecture differ among methods. In a CUDA run, ComplEx, RotatE and R-GCN obtained filtered MRR 0.00207, 0.00025 and 0.00048 on 32 FB15k-237 triples; on WN18RR they were 0.000092, 0.000096 and 0.000178. These are test measurements, not converged or official results. The program also reports MRR of the first eight triples to facilitate comparison with the inductive checkpoint, if run with the same sample.

For a broader evaluation, set KG_EPOCHS, KG_TRAIN_SAMPLES and KG_EVAL_TRIPLES; zero in the last evaluates all test and can take a long time. More epochs or a larger selection change the experiment and do not guarantee convergence. You need NumPy, PyTorch and PyG, data storage and a connection on first run. The download records provenance and hashes.

[ ]ComplEx, RotatE and R-GCN on two KGsLocal GPU
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import hashlib, json, urllib.request

commit = '2e440e0f9c687314d5ff67ead68ce985dc446e3a'
root = Path('dataset/kg-l18')
jobs = [(dataset, file) for dataset in ('FB15k','FB15k-237','wn18','wn18rr')
        for file in ('entities.dict','relations.dict','train.txt','valid.txt','test.txt')]
def fetch(job):
    dataset, file = job
    url = f'https://raw.githubusercontent.com/DeepGraphLearning/KnowledgeGraphEmbedding/{commit}/data/{dataset}/{file}'
    data = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent':'OryonLearn'}), timeout=90).read()
    path = root / dataset / file; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(data)
    return {'dataset':dataset, 'file':file, 'bytes':len(data), 'sha256':hashlib.sha256(data).hexdigest(), 'url':url}
with ThreadPoolExecutor(max_workers=6) as pool: results = list(pool.map(fetch, jobs))
(root / 'manifest.json').write_text(json.dumps(results, indent=2), encoding='utf8')
print('Descargados y registrados:', len(results), 'archivos')

import json
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np

def load(name):
    base = Path('dataset/kg-l18') / name
    entities = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'entities.dict').read_text(encoding='utf8').splitlines()}
    relations = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'relations.dict').read_text(encoding='utf8').splitlines()}
    def triples(part):
        rows = [line.split('\t') for line in (base/f'{part}.txt').read_text(encoding='utf8').splitlines()]
        return [(entities[h], relations[r], entities[t]) for h,r,t in rows]
    return entities, relations, triples('train'), triples('valid'), triples('test')


import json, os, time
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.nn import RGCNConv
from torch_geometric.nn.kge import RotatE

torch.set_num_threads(2)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
epochs=int(os.environ.get('KG_EPOCHS','2'))
budget=int(os.environ.get('KG_TRAIN_SAMPLES','2048'))
eval_count=int(os.environ.get('KG_EVAL_TRIPLES','32'))  # 0: test completo
all_results=[]
for dataset in ('FB15k-237','wn18rr'):
    entities,relations,train,valid,test=load(dataset); n,nr=len(entities),len(relations)
    rng=np.random.default_rng(19); torch.manual_seed(23)
    order=rng.choice(len(test),len(test),replace=False)
    questions=[test[i] for i in (order if eval_count==0 else order[:eval_count])]
    heads=defaultdict(set); tails=defaultdict(set)
    for h,r,t in train+valid+test:
        heads[(r,t)].add(h); tails[(h,r)].add(t)
    train_array=np.asarray(train,dtype=np.int64)
    def evaluate(predict):
        rrs=[]
        for h,r,t in questions:
            for side in ('head','tail'):
                scores=predict(h,r,t,side).clone()
                other=(heads[(r,t)]-{h}) if side=='head' else (tails[(h,r)]-{t})
                if other: scores[torch.tensor(list(other),device=device)]=-torch.inf
                target=h if side=='head' else t; value=scores[target]
                rank=1+(scores>value).sum()+.5*((scores==value).sum()-1)
                rrs.append(float((1/rank).cpu()))
        return {'mrr':float(np.mean(rrs)), 'mrr_8_triples':float(np.mean(rrs[:16])), 'queries':len(rrs)}
    def record(name,metrics,start):
        if device.type=='cuda': torch.cuda.synchronize()
        row={'dataset':dataset,'method':name,**metrics,'seconds':round(time.perf_counter()-start,2),'device':str(device)}
        all_results.append(row); print(json.dumps(row),flush=True)

    # ComplEx: softmax 1-N sobre colas y N3 de factores involucrados.
    class ComplexModel(nn.Module):
        def __init__(self):
            super().__init__(); self.entity=nn.Embedding(n,32); self.relation=nn.Embedding(nr,32)
            nn.init.normal_(self.entity.weight,std=.05); nn.init.normal_(self.relation.weight,std=.05)
        def all(self,h,r,t,side):
            a,b=self.entity(h).chunk(2,-1); u,v=self.relation(r).chunk(2,-1)
            c,d=self.entity(t).chunk(2,-1); er,ei=self.entity.weight.chunk(2,-1)
            if side=='tail': real=a*u-b*v; imag=a*v+b*u
            else: real=u*c+v*d; imag=u*d-v*c
            return real@er.T+imag@ei.T
        def reg(self,h,r,t):
            value=0
            for emb in (self.entity(h),self.relation(r),self.entity(t)):
                re,im=emb.chunk(2,-1); value+=(re.square()+im.square()+1e-12).sqrt().pow(3).sum(-1).mean()
            return value
    start=time.perf_counter(); model=ComplexModel().to(device); opt=torch.optim.Adam(model.parameters(),lr=.003)
    rng=np.random.default_rng(23)
    for _ in range(epochs):
        indices=rng.choice(len(train_array),size=min(budget,len(train_array)),replace=False)
        for offset in range(0,len(indices),128):
            batch=torch.tensor(train_array[indices[offset:offset+128]],device=device); h,r,t=batch.T
            logits=model.all(h,r,t,'tail')
            loss=F.cross_entropy(logits,t)+.01*model.reg(h,r,t)
            opt.zero_grad(); loss.backward(); opt.step()
    model.eval()
    def predict_complex(h,r,t,side):
        with torch.no_grad(): return model.all(torch.tensor([h],device=device),torch.tensor([r],device=device),torch.tensor([t],device=device),side).flatten()
    record('ComplEx 1-N N3',evaluate(predict_complex),start)
    del model,opt

    # La implementación PyG usa pérdida logística y una corrupción aleatoria.
    start=time.perf_counter(); model=RotatE(n,nr,hidden_channels=16,margin=1).to(device); opt=torch.optim.Adam(model.parameters(),lr=.003)
    rng=np.random.default_rng(24)
    for _ in range(epochs):
        indices=rng.choice(len(train_array),size=min(budget,len(train_array)),replace=False)
        for offset in range(0,len(indices),512):
            batch=torch.tensor(train_array[indices[offset:offset+512]],device=device); h,r,t=batch.T
            loss=model.loss(h,r,t); opt.zero_grad(); loss.backward(); opt.step()
    model.eval(); candidates=torch.arange(n,device=device)
    def predict_rotate(h,r,t,side):
        with torch.no_grad():
            hh=candidates if side=='head' else torch.full_like(candidates,h)
            tt=candidates if side=='tail' else torch.full_like(candidates,t)
            return model(hh,torch.full_like(candidates,r),tt)
    record('RotatE PyG',evaluate(predict_rotate),start)
    del model,opt,candidates

    # Objetivos de entrenamiento disjuntos de las aristas de mensaje, incluso inversas.
    rng=np.random.default_rng(25); supervised=rng.choice(len(train_array),size=min(1024,len(train_array)//4),replace=False)
    selected={tuple(v) for v in train_array[supervised].tolist()}
    messages=np.array([v for v in train if tuple(v) not in selected],dtype=np.int64)
    def graph_edges(triples):
        edge=torch.tensor(np.concatenate([triples[:,[0,2]],triples[:,[2,0]]]),dtype=torch.long,device=device).T.contiguous()
        typ=torch.tensor(np.r_[triples[:,1],triples[:,1]+nr],dtype=torch.long,device=device)
        return edge,typ
    train_edge,train_type=graph_edges(messages); test_edge,test_type=graph_edges(train_array)
    class Encoder(nn.Module):
        def __init__(self):
            super().__init__(); self.entity=nn.Embedding(n,16); self.rel=nn.Embedding(nr,16)
            self.conv=RGCNConv(16,16,num_relations=2*nr,num_bases=4,aggr='mean')
        def encode(self,edge,typ): return F.relu(self.conv(self.entity.weight,edge,typ))
        def score(self,z,p): return (z[p[:,0]]*self.rel(p[:,1])*z[p[:,2]]).sum(-1)
    start=time.perf_counter(); model=Encoder().to(device); opt=torch.optim.Adam(model.parameters(),lr=.003)
    positives=torch.tensor(train_array[supervised],dtype=torch.long,device=device)
    for _ in range(epochs):
        negative=positives.clone(); selector=torch.rand(len(negative),device=device)<.5
        replacement=torch.randint(n,(len(negative),),device=device)
        negative[:,0]=torch.where(selector,replacement,negative[:,0])
        negative[:,2]=torch.where(selector,negative[:,2],replacement)
        z=model.encode(train_edge,train_type)
        loss=F.softplus(-model.score(z,positives)).mean()+F.softplus(model.score(z,negative)).mean()
        opt.zero_grad(); loss.backward(); opt.step()
    model.eval()
    with torch.no_grad(): z=model.encode(test_edge,test_type)
    def predict_rgcn(h,r,t,side):
        with torch.no_grad():
            query=(z[t] if side=='head' else z[h])*model.rel.weight[r]
            return z@query
    record('R-GCN + DistMult',evaluate(predict_rgcn),start)
    del model,opt,z,train_edge,train_type,test_edge,test_type
    if device.type=='cuda': torch.cuda.empty_cache()

Path('dataset/kg-l18/kg_results.json').write_text(json.dumps(all_results,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Bounded comparison with pretrained ULTRA

The official ULTRA repository offers ultra_3g, pretrained on training graphs of FB15k-237, WN18RR and CoDExMedium. Thus running that checkpoint on the first two without further tuning is not a test of transfer to completely unseen graphs. To observe structural capacity on a graph with another vocabulary, the cell first checks finite scores on the small synthetic dependency graph; this also does not measure general quality.

Then the same first eight triples of each preceding sample are evaluated in both directions with the same entity filter. In a CUDA run, MRR for ComplEx, RotatE, R-GCN and ULTRA was respectively 0.000788, 0.000264, 0.000320 and 0.198769 on FB15k-237; on WN18RR it was 0.000112, 0.000065, 0.000179 and 0.110915. There are only 16 queries per dataset. ULTRA is pretrained much longer and the other three models receive two short epochs: these figures are not a fair architectural comparison and do not show those differences persist on full test. Full evaluation has not been run here.

The following program pins official commit 427966ad8ed60420eef034063d44f3153addff90, verifies SHA-256 of the file and checkpoint and loads weights with weights_only=True. For this machine, which lacks nvcc and torch-scatter, this process uses PyG scatter operations and forces the official code’s separate message and aggregation path rather than the fused kernel. This path was checked to run the checkpoint and return finite scores; it has not been numerically compared with the compiled kernel. It may consume more memory and take much longer. It requires PyTorch, PyG and a connection for data and code; ULTRA_DATASETS=0 runs only the synthetic test.

[ ]Pretrained ULTRA with separate propagationLocal GPU
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import hashlib, json, urllib.request

commit = '2e440e0f9c687314d5ff67ead68ce985dc446e3a'
root = Path('dataset/kg-l18')
jobs = [(dataset, file) for dataset in ('FB15k','FB15k-237','wn18','wn18rr')
        for file in ('entities.dict','relations.dict','train.txt','valid.txt','test.txt')]
def fetch(job):
    dataset, file = job
    url = f'https://raw.githubusercontent.com/DeepGraphLearning/KnowledgeGraphEmbedding/{commit}/data/{dataset}/{file}'
    data = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent':'OryonLearn'}), timeout=90).read()
    path = root / dataset / file; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(data)
    return {'dataset':dataset, 'file':file, 'bytes':len(data), 'sha256':hashlib.sha256(data).hexdigest(), 'url':url}
with ThreadPoolExecutor(max_workers=6) as pool: results = list(pool.map(fetch, jobs))
(root / 'manifest.json').write_text(json.dumps(results, indent=2), encoding='utf8')
print('Descargados y registrados:', len(results), 'archivos')

import json
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np

def load(name):
    base = Path('dataset/kg-l18') / name
    entities = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'entities.dict').read_text(encoding='utf8').splitlines()}
    relations = {line.split('\t')[1].strip(): int(line.split('\t')[0]) for line in (base/'relations.dict').read_text(encoding='utf8').splitlines()}
    def triples(part):
        rows = [line.split('\t') for line in (base/f'{part}.txt').read_text(encoding='utf8').splitlines()]
        return [(entities[h], relations[r], entities[t]) for h,r,t in rows]
    return entities, relations, triples('train'), triples('valid'), triples('test')


from pathlib import Path
import hashlib, io, urllib.request, zipfile
commit='427966ad8ed60420eef034063d44f3153addff90'
url=f'https://codeload.github.com/DeepGraphLearning/ULTRA/zip/{commit}'
content=urllib.request.urlopen(urllib.request.Request(url,headers={'User-Agent':'OryonLearn'}),timeout=90).read()
assert hashlib.sha256(content).hexdigest() == '70de0a98d53c8600e069b82bfedfaebd43db1bd9107e888e02a10c7560a45e6e'
root=Path('dataset/kg-l18/ultra_source').resolve(); root.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(io.BytesIO(content)) as z:
    for member in z.infolist():
        target=(root/member.filename).resolve(); target.relative_to(root)
    z.extractall(root)
print('ULTRA commit',commit,'archivo sha256',hashlib.sha256(content).hexdigest())

import hashlib, json, os, sys, time, types
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch
import torch_geometric
from torch_geometric.data import Data
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import scatter as pyg_scatter

# Solo en este proceso: sustitución compatible de scatter; no modifica paquetes instalados.
shim=types.ModuleType('torch_scatter')
def scatter(src,index,dim=-1,out=None,dim_size=None,reduce='sum'):
    if out is not None: raise NotImplementedError('out no se usa en esta prueba')
    return pyg_scatter(src,index,dim=dim,dim_size=dim_size,reduce=reduce)
def scatter_add(src,index,dim=-1,out=None,dim_size=None):
    return scatter(src,index,dim,out,dim_size,'sum')
shim.scatter=scatter; shim.scatter_add=scatter_add
sys.modules['torch_scatter']=shim
root=Path('dataset/kg-l18/ultra_source/ULTRA-427966ad8ed60420eef034063d44f3153addff90')
sys.path.insert(0,str(root.resolve()))
from ultra import models,tasks,layers

# La implementación oficial permite ruta separada mensaje/agregación; se fuerza
# para evitar compilar el kernel rspmm en una máquina sin nvcc.
def unfused(self,edge_index,size=None,**kwargs):
    return MessagePassing.propagate(self,edge_index,size=size,**kwargs)
layers.GeneralizedRelationalConv.propagate=unfused
cfg={'input_dim':64,'hidden_dims':[64]*6,'message_func':'distmult','aggregate_func':'sum','short_cut':True,'layer_norm':True}
model=models.Ultra({'class':'RelNBFNet',**cfg},{'class':'EntityNBFNet',**cfg})
checkpoint=root/'ckpts/ultra_3g.pth'
assert hashlib.sha256(checkpoint.read_bytes()).hexdigest()=='fdedc01b0045fc089d2ad5da08569466b7b221691fe978a18e91082bbb133c18'
weights=torch.load(checkpoint,map_location='cpu',weights_only=True)
model.load_state_dict(weights['model']); model.eval()
triples=torch.tensor([[0,1,0],[1,2,0],[2,3,0],[1,0,1],[2,1,1],[3,2,1]],dtype=torch.long)
edges=triples[:,:2].T
data=Data(edge_index=torch.cat([edges,edges.flip(0)],1),edge_type=torch.cat([triples[:,2],triples[:,2]+2]),num_nodes=6,num_relations=4)
data=tasks.build_relation_graph(data)
batch=torch.stack([torch.zeros(6,dtype=torch.long),torch.arange(6),torch.zeros(6,dtype=torch.long)],dim=-1)[None,:,:]
with torch.no_grad(): scores=model(data,batch)
assert scores.shape==(1,6) and torch.isfinite(scores).all()
print('ULTRA pretrained, puntuaciones finitas:',scores.tolist())

if os.environ.get('ULTRA_DATASETS', '1') == '1':
    device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model=model.to(device); results=[]
    for dataset in ('FB15k-237','wn18rr'):
        entities,relations,train,valid,test=load(dataset); n=len(entities); nr=len(relations)
        tr=torch.tensor(train,dtype=torch.long)
        edge=tr[:,[0,2]].T.contiguous()
        graph=Data(edge_index=torch.cat([edge,edge.flip(0)],dim=1),edge_type=torch.cat([tr[:,1],tr[:,1]+nr]),num_nodes=n,num_relations=2*nr)
        graph=tasks.build_relation_graph(graph).to(device)
        known_h=defaultdict(set); known_t=defaultdict(set)
        for h,r,t in train+valid+test:
            known_h[(r,t)].add(h); known_t[(h,r)].add(t)
        sample=np.random.default_rng(19).choice(len(test),len(test),replace=False)[:8]
        reciprocal=[]; start=time.perf_counter(); candidates=torch.arange(n,device=device)
        with torch.no_grad():
            for index in sample:
                h,r,t=test[index]
                for side in ('head','tail'):
                    hh=candidates if side=='head' else torch.full_like(candidates,h)
                    tt=candidates if side=='tail' else torch.full_like(candidates,t)
                    batch=torch.stack([hh,tt,torch.full_like(candidates,r)],dim=-1)[None,:,:]
                    scores=model(graph,batch).flatten()
                    other=(known_h[(r,t)]-{h}) if side=='head' else (known_t[(h,r)]-{t})
                    if other: scores[torch.tensor(list(other),device=device)]=-torch.inf
                    target=h if side=='head' else t; value=scores[target]
                    rank=1+(scores>value).sum()+.5*((scores==value).sum()-1)
                    reciprocal.append(float((1/rank).cpu()))
        if device.type=='cuda': torch.cuda.synchronize()
        result={'dataset':dataset,'triples':len(sample),'queries':len(reciprocal),
                'filtered_mrr':float(np.mean(reciprocal)),'seconds':round(time.perf_counter()-start,2),'device':str(device)}
        results.append(result); print(json.dumps(result),flush=True)
        del graph
        if device.type=='cuda': torch.cuda.empty_cache()
    Path('dataset/kg-l18/ultra_results.json').write_text(json.dumps(results,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: DistMult assigns equal scores to (h,r,t) and (t,r,h), while ComplEx can distinguish them.
0
Use the real diagonal formula and then one complex coordinate.

Step 1 of 2. Why does DistMult agree when endpoints are reversed?

Proof
Prove: When both directions fit exactly, TransE requires r=0; RotatE requires rⱼ²=1 in every nonzero coordinate.
0
Suppose h+r=t and t+r=h in TransE; in RotatE, t=h⊙r and h=t⊙r with |rⱼ|=1.

Step 1 of 2. What follows by adding the translational equations?

Numeric
In five queries, the star marks the target and each list's 1.0 score belongs to another known answer to filter: [1.0, 0.9, 0.8, 0.2], [1.0, 0.9, 0.7, 0.1], [1.0, 0.9, 0.6, 0.6, 0.1], [1.0, 0.9, 0.8, 0.7, 0.2, 0.1] and [1.0, 0.9, 0.8, 0.7, 0.6, 0.1*]. Use average rank for ties and calculate filtered MRR.
Numeric
A layer has two 2×2 bases and coefficients for three relations. Excluding bias and self-loop, how many relational parameters does it learn?
Quiz
There are five million entities, 8 GB GPU memory and several compositional relations. What is the most defensible decision before choosing a model?
Code
Implement rgcn_basis_layer(x, edge_index, edge_type, bases, coeffs), without bias, self-loop or normalization. edge_index[0] is source and [1] destination; W_r = sum_b coeffs[r,b] bases[b]. Sum x[u] @ W_r at the destination. Return an (N,d) matrix. For B square d×d bases and R relations, count B·d² + R·B parameters.
import numpy as np
def rgcn_basis_layer(x, edge_index, edge_type, bases, coeffs):
  pass
Shift+Enter to run
Key idea
A relational embedding scores triples; its geometry limits which patterns it can distinguish. Visible information, negative distribution and filtering determine what the result means.