Skill Tracer
Skills › Scientific Agent Skills › torchdrug › knowledge_graphs.md

knowledge_graphs.md

232 lines · skills/torchdrug/references/knowledge_graphs.md at 5f2bc03

Open on GitHub
1# Knowledge Graph Reasoning
2
3The official
4[TorchDrug 0.2.1 reasoning tutorial](https://torchdrug.ai/docs/tutorials/reasoning.html)
5covers two workflows:
6
7- knowledge graph embeddings with RotatE,
8- neural inductive logic programming with NeuralLP.
9
10Both use `tasks.KnowledgeGraphCompletion`.
11Full benchmark runs are illustrative; a tiny local graph can verify batching
12and loss/ranking semantics without downloading these datasets.

Knowledge Graph Reasoning

The official TorchDrug 0.2.1 reasoning tutorial covers two workflows:

  • knowledge graph embeddings with RotatE,
  • neural inductive logic programming with NeuralLP.

Both use tasks.KnowledgeGraphCompletion. Full benchmark runs are illustrative; a tiny local graph can verify batching and loss/ranking semantics without downloading these datasets.

Raw lines 1 to 13
14## Datasets
16Documented knowledge graph datasets:
18- `FB15k`: 14,951 entities, 1,345 relations, 592,213 triplets
19- `FB15k237`: 14,541 entities, 237 relations, 310,116 triplets
20- `WN18`: 40,943 entities, 18 relations, 151,442 triplets
21- `WN18RR`: 40,943 entities, 11 relations, 93,003 triplets
22- `Hetionet`: 45,158 entities, 24 relations, 2,025,177 triplets
24Use predefined splits:
26```python
27from torchdrug import datasets
29dataset = datasets.FB15k237("~/kg-datasets/")
30train_set, valid_set, test_set = dataset.split()
31```

Datasets

Documented knowledge graph datasets:

  • FB15k: 14,951 entities, 1,345 relations, 592,213 triplets
  • FB15k237: 14,541 entities, 237 relations, 310,116 triplets
  • WN18: 40,943 entities, 18 relations, 151,442 triplets
  • WN18RR: 40,943 entities, 11 relations, 93,003 triplets
  • Hetionet: 45,158 entities, 24 relations, 2,025,177 triplets

Use predefined splits:

from torchdrug import datasets

dataset = datasets.FB15k237("~/kg-datasets/")
train_set, valid_set, test_set = dataset.split()
Raw lines 14 to 32
33## RotatE embedding workflow

RotatE embedding workflow

Raw lines 33 to 34
35### Model
37```python
38import torch
39from torchdrug import core, models, tasks
41model = models.RotatE(
42 num_entity=dataset.num_entity,
43 num_relation=dataset.num_relation,
44 embedding_dim=2048,
45 max_score=9,
47```
49`embedding_dim=2048` follows the tutorial and may be reduced for memory or speed.

Model

import torch
from torchdrug import core, models, tasks

model = models.RotatE(
    num_entity=dataset.num_entity,
    num_relation=dataset.num_relation,
    embedding_dim=2048,
    max_score=9,
)

embedding_dim=2048 follows the tutorial and may be reduced for memory or speed.

Raw lines 35 to 50
51### Task
53```python
54task = tasks.KnowledgeGraphCompletion(
55 model,
56 num_negative=256,
57 adversarial_temperature=1,
59```
61- `num_negative` controls negative samples per positive.
62- `adversarial_temperature` enables score-weighted negative sampling.

Task

task = tasks.KnowledgeGraphCompletion(
    model,
    num_negative=256,
    adversarial_temperature=1,
)
  • num_negative controls negative samples per positive.
  • adversarial_temperature enables score-weighted negative sampling.
Raw lines 51 to 63
64### Train and evaluate
66```python
67optimizer = torch.optim.Adam(task.parameters(), lr=2e-5)
68solver = core.Engine(
69 task,
70 train_set,
71 valid_set,
72 test_set,
73 optimizer,
74 batch_size=1024,
76solver.train(num_epoch=200)
77solver.evaluate("valid")
78```
80Add `gpus=[0]` for a supported CUDA device. Reduce the epoch count for smoke
81tests.

Train and evaluate

optimizer = torch.optim.Adam(task.parameters(), lr=2e-5)
solver = core.Engine(
    task,
    train_set,
    valid_set,
    test_set,
    optimizer,
    batch_size=1024,
)
solver.train(num_epoch=200)
solver.evaluate("valid")

Add gpus=[0] for a supported CUDA device. Reduce the epoch count for smoke tests.

Raw lines 64 to 82
83## NeuralLP workflow
85NeuralLP learns weighted chain-like rules up to a configured maximum length.
87```python
88model = models.NeuralLP(
89 num_relation=dataset.num_relation,
90 hidden_dim=128,
91 num_step=3,
92 num_lstm_layer=2,
95task = tasks.KnowledgeGraphCompletion(
96 model,
97 fact_ratio=0.75,
98 num_negative=256,
99 sample_weight=False,
101```
103`fact_ratio=0.75` reserves 75% of training facts for the background graph used
104for reasoning and uses the remaining training triples as supervised labels.
105`Engine` adopts that reduced training subset returned by `preprocess()`.
107```python
108optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
109solver = core.Engine(
110 task,
111 train_set,
112 valid_set,
113 test_set,
114 optimizer,
115 batch_size=64,
117solver.train(num_epoch=10)
118solver.evaluate("valid")
119```

NeuralLP workflow

NeuralLP learns weighted chain-like rules up to a configured maximum length.

model = models.NeuralLP(
    num_relation=dataset.num_relation,
    hidden_dim=128,
    num_step=3,
    num_lstm_layer=2,
)

task = tasks.KnowledgeGraphCompletion(
    model,
    fact_ratio=0.75,
    num_negative=256,
    sample_weight=False,
)

fact_ratio=0.75 reserves 75% of training facts for the background graph used for reasoning and uses the remaining training triples as supervised labels. Engine adopts that reduced training subset returned by preprocess().

optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
solver = core.Engine(
    task,
    train_set,
    valid_set,
    test_set,
    optimizer,
    batch_size=64,
)
solver.train(num_epoch=10)
solver.evaluate("valid")
Raw lines 83 to 120
121## Other documented models
123Embedding models:
125- `models.TransE`
126- `models.DistMult`
127- `models.ComplEx`
128- `models.SimplE`
129- `models.RotatE`
131Graph-attention model:
133- `models.KBGAT`
135Verify each constructor in the
136[model API](https://torchdrug.ai/docs/api/models.html#knowledge-graph-reasoning-models).
137Do not transfer argument names from PyKEEN, DGL-KE, or PyTorch Geometric.

Other documented models

Embedding models:

  • models.TransE
  • models.DistMult
  • models.ComplEx
  • models.SimplE
  • models.RotatE

Graph-attention model:

  • models.KBGAT

Verify each constructor in the model API. Do not transfer argument names from PyKEEN, DGL-KE, or PyTorch Geometric.

Raw lines 121 to 138
139## Task behavior
141`KnowledgeGraphCompletion` owns:
143- negative sampling,
144- fact-graph construction,
145- loss computation,
146- head and tail prediction,
147- filtered ranking evaluation.
149Important constructor options include:
151- `criterion`
152- `metric`
153- `num_negative`
154- `margin`
155- `adversarial_temperature`
156- `strict_negative`
157- `fact_ratio`
158- `sample_weight`
159- `filtered_ranking` (default `True`)
160- `full_batch_eval`
162TorchDrug 0.2.1 added full-batch evaluation support. Choose it according to graph
163size and available memory.

Task behavior

KnowledgeGraphCompletion owns:

  • negative sampling,
  • fact-graph construction,
  • loss computation,
  • head and tail prediction,
  • filtered ranking evaluation.

Important constructor options include:

  • criterion
  • metric
  • num_negative
  • margin
  • adversarial_temperature
  • strict_negative
  • fact_ratio
  • sample_weight
  • filtered_ranking (default True)
  • full_batch_eval

TorchDrug 0.2.1 added full-batch evaluation support. Choose it according to graph size and available memory.

Raw lines 139 to 164
165## Evaluation
167Use filtered ranking metrics:
169- mean rank (MR)
170- mean reciprocal rank (MRR)
171- Hits@1
172- Hits@3
173- Hits@10
175Filtered evaluation removes other known true triples before ranking. Preserve
176training, validation, and test facts exactly as the task expects to avoid leakage
177or incorrect filtering.
179Also report:
181- results by relation,
182- head vs tail prediction,
183- variance across seeds,
184- memory/runtime settings,
185- whether reciprocal relations were added.

Evaluation

Use filtered ranking metrics:

  • mean rank (MR)
  • mean reciprocal rank (MRR)
  • Hits@1
  • Hits@3
  • Hits@10

Filtered evaluation removes other known true triples before ranking. Preserve training, validation, and test facts exactly as the task expects to avoid leakage or incorrect filtering.

Also report:

  • results by relation,
  • head vs tail prediction,
  • variance across seeds,
  • memory/runtime settings,
  • whether reciprocal relations were added.
Raw lines 165 to 186
187## Biomedical use
189Hetionet supports biomedical link-prediction experiments, but a high model score
190does not establish a new treatment, causal mechanism, or validated association.
192For drug-repurposing analysis:
1941. define the exact relation being predicted,
1952. preserve entity and relation type constraints,
1963. exclude known positives correctly,
1974. check for train/test leakage through inverse or duplicate relations,
1985. calibrate or rank model scores,
1996. validate candidates against independent evidence and domain experts.
201TorchDrug's generic `KnowledgeGraphCompletion` API does not automatically apply
202biomedical type constraints or causal interpretation.

Biomedical use

Hetionet supports biomedical link-prediction experiments, but a high model score does not establish a new treatment, causal mechanism, or validated association.

For drug-repurposing analysis:

  1. define the exact relation being predicted,
  2. preserve entity and relation type constraints,
  3. exclude known positives correctly,
  4. check for train/test leakage through inverse or duplicate relations,
  5. calibrate or rank model scores,
  6. validate candidates against independent evidence and domain experts.

TorchDrug's generic KnowledgeGraphCompletion API does not automatically apply biomedical type constraints or causal interpretation.

Raw lines 187 to 203
204## Common failures

Common failures

Raw lines 204 to 205
206### Entity/relation mismatch
208Build model sizes from `dataset.num_entity` and `dataset.num_relation`.

Entity/relation mismatch

Build model sizes from dataset.num_entity and dataset.num_relation.

Raw lines 206 to 209
210### Evaluation out of memory
212Lower batch size or disable full-batch evaluation. With `full_batch_eval=False`,
213`num_negative` also sets the chunk size for scoring candidate entities during
214evaluation. All entities are still ranked, and score/mask tensors scale with
215batch size times the entity count; chunking does not make this sampled evaluation.

Evaluation out of memory

Lower batch size or disable full-batch evaluation. With full_batch_eval=False, num_negative also sets the chunk size for scoring candidate entities during evaluation. All entities are still ranked, and score/mask tensors scale with batch size times the entity count; chunking does not make this sampled evaluation.

Raw lines 210 to 216
217### NeuralLP produces invalid shapes
219Use `num_relation=dataset.num_relation` and let
220`KnowledgeGraphCompletion.preprocess()` construct the fact graph.

NeuralLP produces invalid shapes

Use num_relation=dataset.num_relation and let KnowledgeGraphCompletion.preprocess() construct the fact graph.

Raw lines 217 to 221
222### Inflated metrics
224Check for inverse-relation leakage, duplicate triples, accidental use of test
225facts, and raw rather than filtered ranking.

Inflated metrics

Check for inverse-relation leakage, duplicate triples, accidental use of test facts, and raw rather than filtered ranking.

Raw lines 222 to 226
227## Source links
229- [Reasoning tutorial](https://torchdrug.ai/docs/tutorials/reasoning.html)
230- [Knowledge graph datasets](https://torchdrug.ai/docs/api/datasets.html#knowledge-graph-datasets)
231- [Knowledge graph models](https://torchdrug.ai/docs/api/models.html#knowledge-graph-reasoning-models)
232- [KnowledgeGraphCompletion task](https://torchdrug.ai/docs/api/tasks.html#knowledge-graph-completion)