Builds PaperTrail from the base skeleton into a full evidence-verification platform for the "Built with Claude: Life Sciences" hackathon (Builder Track). New named-user features (Build Beyond the Bench): - Lab Notebook Companion — rough bench notes -> structured, searchable, grounded experiment records (lib/labNotebook, /console/lab-notebook, migration 0059) - Clinical Trial Matcher — de-identified patient notes -> ranked eligible ClinicalTrials.gov trials with per-criterion inclusion/exclusion reasoning (lib/trialMatcher, /console/trial-matcher, migrations 0060) Platform: - Deterministic verification moat (biostats recompute, exact-span grounding) - 11 biomedical evidence engines (FAERS, GWAS, Open Targets, ChEMBL, ClinVar, PharmGKB, PubTator, DDI, repurposing, biomarker, unified verifier) - Evidence Intelligence (KG, dossier, provenance/export, RWE) + enterprise governance (RBAC, /api/v1 gateway, metering, audit chain, retention) - 17 OSS projects assimilated into native TypeScript on our stack (backend/engines retained + credited in NOTICE) - Multi-format upload (PDF/DOCX/XLSX/CSV/MD/TXT), logo, marketing site - Next.js 16 upgrade, benchmark harness (honest smoke-test caveat) Licensing: Apache-2.0 (LICENSE + NOTICE).
801 lines
25 KiB
Python
801 lines
25 KiB
Python
"""Test that models can be executed."""
|
|
|
|
import contextlib
|
|
import importlib
|
|
import pathlib
|
|
import unittest
|
|
from collections.abc import Iterable, MutableMapping
|
|
from typing import Any
|
|
|
|
import pytest
|
|
import torch
|
|
import unittest_templates
|
|
|
|
import pykeen.experiments
|
|
import pykeen.models
|
|
from pykeen.models import (
|
|
ERModel,
|
|
EvaluationOnlyModel,
|
|
FixedModel,
|
|
InductiveERModel,
|
|
Model,
|
|
_NewAbstractModel,
|
|
model_resolver,
|
|
)
|
|
from pykeen.models.multimodal.base import LiteralModel
|
|
from pykeen.nn import Embedding, NodePieceRepresentation
|
|
from pykeen.nn.combination import ConcatAggregationCombination
|
|
from pykeen.nn.perceptron import ConcatMLP
|
|
from pykeen.triples.triples_factory import CoreTriplesFactory
|
|
from pykeen.utils import all_in_bounds, extend_batch
|
|
from tests import cases
|
|
from tests.constants import EPSILON
|
|
from tests.test_batch_size_reduction import MockModel
|
|
|
|
SKIP_MODULES = {
|
|
Model,
|
|
_NewAbstractModel,
|
|
# DummyModel,
|
|
LiteralModel,
|
|
ERModel,
|
|
InductiveERModel,
|
|
FixedModel,
|
|
EvaluationOnlyModel,
|
|
MockModel,
|
|
}
|
|
SKIP_MODULES.update(LiteralModel.__subclasses__())
|
|
SKIP_MODULES.update(EvaluationOnlyModel.__subclasses__())
|
|
|
|
|
|
class TestCompGCN(cases.ModelTestCase):
|
|
"""Test the CompGCN model."""
|
|
|
|
cls = pykeen.models.CompGCN
|
|
create_inverse_triples = True
|
|
num_constant_init = 3 # BN(2) + Bias
|
|
cli_extras = ["--create-inverse-triples"]
|
|
|
|
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
|
|
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
|
|
dim = kwargs.pop("embedding_dim")
|
|
kwargs["encoder_kwargs"] = {
|
|
"entity_representations_kwargs": {
|
|
"shape": (dim,),
|
|
},
|
|
"relation_representations_kwargs": {
|
|
"shape": (dim,),
|
|
},
|
|
}
|
|
return kwargs
|
|
|
|
|
|
class TestComplex(cases.ModelTestCase):
|
|
"""Test the ComplEx model."""
|
|
|
|
cls = pykeen.models.ComplEx
|
|
|
|
|
|
class TestConvE(cases.ModelTestCase):
|
|
"""Test the ConvE model."""
|
|
|
|
cls = pykeen.models.ConvE
|
|
embedding_dim = 12
|
|
create_inverse_triples = True
|
|
kwargs = {
|
|
"output_channels": 2,
|
|
"embedding_height": 3,
|
|
"embedding_width": 4,
|
|
}
|
|
# 3x batch norm: bias + scale --> 6
|
|
# entity specific bias --> 1
|
|
# ==================================
|
|
# 7
|
|
num_constant_init = 7
|
|
|
|
|
|
class TestConvKB(cases.ModelTestCase):
|
|
"""Test the ConvKB model."""
|
|
|
|
cls = pykeen.models.ConvKB
|
|
kwargs = {
|
|
"num_filters": 2,
|
|
}
|
|
# two bias terms, one conv-filter
|
|
num_constant_init = 3
|
|
|
|
|
|
class TestDistMult(cases.ModelTestCase):
|
|
"""Test the DistMult model."""
|
|
|
|
cls = pykeen.models.DistMult
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity embeddings have to have unit L2 norm.
|
|
"""
|
|
entity_norms = self.instance.entity_representations[0](indices=None).norm(p=2, dim=-1)
|
|
assert torch.allclose(entity_norms, torch.ones_like(entity_norms))
|
|
|
|
|
|
class TestDistMA(cases.ModelTestCase):
|
|
"""Test the DistMA model."""
|
|
|
|
cls = pykeen.models.DistMA
|
|
|
|
|
|
class TestERMLP(cases.ModelTestCase):
|
|
"""Test the ERMLP model."""
|
|
|
|
cls = pykeen.models.ERMLP
|
|
kwargs = {
|
|
"hidden_dim": 4,
|
|
}
|
|
# Two linear layer biases
|
|
num_constant_init = 2
|
|
|
|
|
|
class TestERMLPE(cases.ModelTestCase):
|
|
"""Test the extended ERMLP model."""
|
|
|
|
cls = pykeen.models.ERMLPE
|
|
kwargs = {
|
|
"hidden_dim": 4,
|
|
}
|
|
# Two BN layers, bias & scale
|
|
num_constant_init = 4
|
|
|
|
|
|
class TestHolE(cases.ModelTestCase):
|
|
"""Test the HolE model."""
|
|
|
|
cls = pykeen.models.HolE
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity embeddings have to have at most unit L2 norm.
|
|
"""
|
|
assert all_in_bounds(
|
|
self.instance.entity_representations[0](indices=None).norm(p=2, dim=-1), high=1.0, a_tol=EPSILON
|
|
)
|
|
|
|
|
|
class TestKG2EWithKL(cases.BaseKG2ETest):
|
|
"""Test the KG2E model with KL similarity."""
|
|
|
|
kwargs = {
|
|
"dist_similarity": "negativekullbackleiblerdivergence",
|
|
}
|
|
|
|
|
|
class TestMuRE(cases.ModelTestCase):
|
|
"""Test the MuRE model."""
|
|
|
|
cls = pykeen.models.MuRE
|
|
num_constant_init = 2 # biases
|
|
|
|
|
|
class TestKG2EWithEL(cases.BaseKG2ETest):
|
|
"""Test the KG2E model with EL similarity."""
|
|
|
|
kwargs = {
|
|
"dist_similarity": "expectedlikelihood",
|
|
}
|
|
|
|
|
|
class TestNodePiece(cases.BaseNodePieceTest):
|
|
"""Test the NodePiece model."""
|
|
|
|
def test_disconnected(self):
|
|
"""Test handling of disconnected entities."""
|
|
edges = torch.tensor(
|
|
[[0, 0, 1], [1, 1, 0], [3, 1, 0], [3, 2, 1]], dtype=torch.long
|
|
) # node ID 2 is missing as a disconnected node
|
|
factory = CoreTriplesFactory.create(
|
|
mapped_triples=edges, num_entities=4, num_relations=3, create_inverse_triples=True
|
|
)
|
|
pykeen.models.NodePiece(triples_factory=factory, num_tokens=2)
|
|
|
|
|
|
class TestNodePieceMLP(cases.BaseNodePieceTest):
|
|
"""Test the NodePiece model with MLP aggregation."""
|
|
|
|
kwargs = {"aggregation": "mlp"}
|
|
|
|
def test_aggregation(self):
|
|
"""Test that the MLP gets registered properly and is trainable."""
|
|
assert isinstance(self.instance, pykeen.models.NodePiece)
|
|
r = self.instance.entity_representations[0]
|
|
assert isinstance(r, NodePieceRepresentation)
|
|
assert isinstance(r.combination, ConcatAggregationCombination)
|
|
assert isinstance(r.combination.aggregation, ConcatMLP)
|
|
|
|
# Test that the weight in the MLP is trainable (i.e. requires grad)
|
|
for key in [
|
|
f"entity_representations.0.combination.aggregation.{key}"
|
|
for key in ("0.weight", "0.bias", "3.weight", "3.bias")
|
|
]:
|
|
params = dict(self.instance.named_parameters())
|
|
assert key in set(params)
|
|
tensor = params[key]
|
|
assert isinstance(tensor, torch.Tensor)
|
|
assert tensor.requires_grad
|
|
|
|
|
|
class TestNodePieceAnchors(cases.BaseNodePieceTest):
|
|
"""Test the NodePiece model with anchors."""
|
|
|
|
kwargs = {
|
|
"tokenizers": "anchor",
|
|
}
|
|
|
|
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
|
|
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
|
|
kwargs["tokenizers_kwargs"] = {"selection_kwargs": {"num_anchors": self.factory.num_entities // 3}}
|
|
return kwargs
|
|
|
|
|
|
class TestNodePieceJoint(cases.BaseNodePieceTest):
|
|
"""Test the NodePiece model with joint anchor and relation tokenization."""
|
|
|
|
num_anchors = 5
|
|
num_tokens = [3, 2]
|
|
kwargs = {
|
|
"tokenizers": ["anchor", "relation"],
|
|
"tokenizers_kwargs": [
|
|
{
|
|
"selection": "degree",
|
|
"searcher": "scipy-sparse",
|
|
},
|
|
{},
|
|
],
|
|
}
|
|
|
|
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
|
|
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
|
|
kwargs["num_tokens"] = self.num_tokens
|
|
kwargs["tokenizers_kwargs"][0]["selection_kwargs"] = {"num_anchors": self.num_anchors}
|
|
return kwargs
|
|
|
|
def test_vocabulary_size(self):
|
|
"""Test the expected vocabulary size of the individual tokenizations."""
|
|
node_piece = self.instance.entity_representations[0]
|
|
assert isinstance(node_piece, NodePieceRepresentation)
|
|
assert isinstance(node_piece.base, torch.nn.ModuleList)
|
|
assert len(node_piece.base) == 2
|
|
anchor, relation = node_piece.base
|
|
assert anchor.vocabulary.max_id == self.num_anchors + 1
|
|
assert relation.vocabulary.max_id == 2 * self.factory.real_num_relations + 1
|
|
|
|
|
|
class TestInductiveNodePiece(cases.InductiveModelTestCase):
|
|
"""Test the InductiveNodePiece model."""
|
|
|
|
cls = pykeen.models.InductiveNodePiece
|
|
create_inverse_triples = True
|
|
|
|
def test_create_entity_representation_for_new_triples(self):
|
|
"""Test create_entity_representation_for_new_triples."""
|
|
assert isinstance(self.instance, pykeen.models.InductiveNodePiece)
|
|
# simulate creating a new triples factory with shared set of relations by shuffling
|
|
mapped_triples = self.factory.mapped_triples
|
|
mapped_triples = torch.stack(
|
|
[
|
|
mapped_triples[:, 0][torch.randperm(len(mapped_triples))],
|
|
mapped_triples[:, 1],
|
|
mapped_triples[:, 2][torch.randperm(len(mapped_triples))],
|
|
],
|
|
dim=1,
|
|
)
|
|
factory = CoreTriplesFactory(
|
|
mapped_triples=mapped_triples,
|
|
num_entities=self.factory.num_entities,
|
|
num_relations=self.factory.real_num_relations,
|
|
create_inverse_triples=True,
|
|
)
|
|
new_instance = self.instance.create_entity_representation_for_new_triples(factory)
|
|
assert isinstance(new_instance, pykeen.nn.NodePieceRepresentation)
|
|
|
|
|
|
class TestInductiveNodePieceGNN(cases.InductiveModelTestCase):
|
|
"""Test the InductiveNodePieceGNN model."""
|
|
|
|
cls = pykeen.models.InductiveNodePieceGNN
|
|
num_constant_init = 6
|
|
create_inverse_triples = True
|
|
train_batch_size = 8
|
|
|
|
|
|
class TestNTN(cases.ModelTestCase):
|
|
"""Test the NTN model."""
|
|
|
|
cls = pykeen.models.NTN
|
|
|
|
kwargs = {
|
|
"num_slices": 2,
|
|
}
|
|
|
|
|
|
class TestPairRE(cases.ModelTestCase):
|
|
"""Test the PairRE model."""
|
|
|
|
cls = pykeen.models.PairRE
|
|
|
|
|
|
class TestProjE(cases.ModelTestCase):
|
|
"""Test the ProjE model."""
|
|
|
|
cls = pykeen.models.ProjE
|
|
|
|
|
|
class TestQuatE(cases.ModelTestCase):
|
|
"""Test the QuatE model."""
|
|
|
|
cls = pykeen.models.QuatE
|
|
# quaternion have four components
|
|
embedding_dim = 4 * cases.ModelTestCase.embedding_dim
|
|
|
|
|
|
class TestRESCAL(cases.ModelTestCase):
|
|
"""Test the RESCAL model."""
|
|
|
|
cls = pykeen.models.RESCAL
|
|
|
|
|
|
class TestRGCNBasis(cases.BaseRGCNTest):
|
|
"""Test the R-GCN model."""
|
|
|
|
kwargs = {
|
|
"interaction": "transe",
|
|
"interaction_kwargs": {"p": 1},
|
|
"decomposition": "bases",
|
|
"decomposition_kwargs": {
|
|
"num_bases": 3,
|
|
},
|
|
}
|
|
|
|
|
|
class TestRGCNBlock(cases.BaseRGCNTest):
|
|
"""Test the R-GCN model with block decomposition."""
|
|
|
|
embedding_dim = 6
|
|
kwargs = {
|
|
"interaction": "distmult",
|
|
"decomposition": "block",
|
|
"decomposition_kwargs": {
|
|
"num_blocks": 3,
|
|
},
|
|
"edge_weighting": "symmetric",
|
|
}
|
|
|
|
|
|
class TestRotatE(cases.ModelTestCase):
|
|
"""Test the RotatE model."""
|
|
|
|
cls = pykeen.models.RotatE
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Relation embeddings' entries have to have absolute value 1 (i.e. represent a rotation in complex plane)
|
|
"""
|
|
relation_abs = self.instance.relation_representations[0](indices=None).abs()
|
|
assert torch.allclose(relation_abs, torch.ones_like(relation_abs))
|
|
|
|
|
|
class TestSimplE(cases.ModelTestCase):
|
|
"""Test the SimplE model."""
|
|
|
|
cls = pykeen.models.SimplE
|
|
|
|
|
|
class TestSE(cases.ModelTestCase):
|
|
"""Test the Structured Embedding model."""
|
|
|
|
cls = pykeen.models.SE
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity embeddings have to have unit L2 norm.
|
|
"""
|
|
norms = self.instance.entity_representations[0](indices=None).norm(p=2, dim=-1)
|
|
assert torch.allclose(norms, torch.ones_like(norms))
|
|
|
|
|
|
class TestTorusE(cases.DistanceModelTestCase):
|
|
"""Test the TorusE model."""
|
|
|
|
cls = pykeen.models.TorusE
|
|
|
|
|
|
class TestTransD(cases.DistanceModelTestCase):
|
|
"""Test the TransD model."""
|
|
|
|
cls = pykeen.models.TransD
|
|
kwargs = {
|
|
"relation_dim": 4,
|
|
}
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity and relation embeddings have to have at most unit L2 norm.
|
|
"""
|
|
self.instance: ERModel
|
|
for emb in (self.instance.entity_representations[0], self.instance.relation_representations[0]):
|
|
assert all_in_bounds(emb(indices=None).norm(p=2, dim=-1), high=1.0, a_tol=EPSILON)
|
|
|
|
def test_score_hrt_manual(self):
|
|
"""Manually test interaction function of TransD."""
|
|
# entity embeddings
|
|
weights = torch.as_tensor(data=[[2.0, 2.0], [4.0, 4.0]], dtype=torch.float)
|
|
entity_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=2,
|
|
)
|
|
entity_embeddings._embeddings.weight.data.copy_(weights)
|
|
|
|
projection_weights = torch.as_tensor(data=[[3.0, 3.0], [2.0, 2.0]], dtype=torch.float)
|
|
entity_projection_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=2,
|
|
)
|
|
entity_projection_embeddings._embeddings.weight.data.copy_(projection_weights)
|
|
self.instance.entity_representations = torch.nn.ModuleList([entity_embeddings, entity_projection_embeddings])
|
|
|
|
# relation embeddings
|
|
relation_weights = torch.as_tensor(data=[[4.0], [4.0]], dtype=torch.float)
|
|
relation_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=1,
|
|
)
|
|
relation_embeddings._embeddings.weight.data.copy_(relation_weights)
|
|
|
|
relation_projection_weights = torch.as_tensor(data=[[5.0], [3.0]], dtype=torch.float)
|
|
relation_projection_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=1,
|
|
)
|
|
relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)
|
|
self.instance.relation_representations = torch.nn.ModuleList(
|
|
[relation_embeddings, relation_projection_embeddings]
|
|
)
|
|
|
|
# Compute Scores
|
|
batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 1]], dtype=torch.long)
|
|
scores = self.instance.score_hrt(hrt_batch=batch)
|
|
assert scores.shape[0] == 2
|
|
assert scores.shape[1] == 1
|
|
first_score = scores[0].item()
|
|
assert first_score == pytest.approx(-16, abs=0.01)
|
|
|
|
# Use different dimension for relation embedding: relation_dim > entity_dim
|
|
# relation embeddings
|
|
relation_weights = torch.as_tensor(data=[[3.0, 3.0, 3.0], [3.0, 3.0, 3.0]], dtype=torch.float)
|
|
relation_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=3,
|
|
)
|
|
relation_embeddings._embeddings.weight.data.copy_(relation_weights)
|
|
|
|
relation_projection_weights = torch.as_tensor(data=[[4.0, 4.0, 4.0], [4.0, 4.0, 4.0]], dtype=torch.float)
|
|
relation_projection_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=3,
|
|
)
|
|
relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)
|
|
self.instance.relation_representations = torch.nn.ModuleList(
|
|
[relation_embeddings, relation_projection_embeddings]
|
|
)
|
|
|
|
# Compute Scores
|
|
batch = torch.as_tensor(data=[[0, 0, 0]], dtype=torch.long)
|
|
scores = self.instance.score_hrt(hrt_batch=batch)
|
|
assert scores.item() == pytest.approx(-27, abs=0.01)
|
|
|
|
batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 0]], dtype=torch.long)
|
|
scores = self.instance.score_hrt(hrt_batch=batch)
|
|
assert scores.shape[0] == 2
|
|
assert scores.shape[1] == 1
|
|
first_score = scores[0].item()
|
|
second_score = scores[1].item()
|
|
assert first_score == pytest.approx(-27, abs=0.01)
|
|
assert second_score == pytest.approx(-27, abs=0.01)
|
|
|
|
# Use different dimension for relation embedding: relation_dim < entity_dim
|
|
# entity embeddings
|
|
weights = torch.as_tensor(data=[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=torch.float)
|
|
entity_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=3,
|
|
)
|
|
entity_embeddings._embeddings.weight.data.copy_(weights)
|
|
|
|
projection_weights = torch.as_tensor(data=[[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]], dtype=torch.float)
|
|
entity_projection_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=3,
|
|
)
|
|
entity_projection_embeddings._embeddings.weight.data.copy_(projection_weights)
|
|
self.instance.entity_representations = torch.nn.ModuleList([entity_embeddings, entity_projection_embeddings])
|
|
|
|
# relation embeddings
|
|
relation_weights = torch.as_tensor(data=[[3.0, 3.0], [3.0, 3.0]], dtype=torch.float)
|
|
relation_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=2,
|
|
)
|
|
relation_embeddings._embeddings.weight.data.copy_(relation_weights)
|
|
|
|
relation_projection_weights = torch.as_tensor(data=[[4.0, 4.0], [4.0, 4.0]], dtype=torch.float)
|
|
relation_projection_embeddings = Embedding(
|
|
num_embeddings=2,
|
|
embedding_dim=2,
|
|
)
|
|
relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)
|
|
self.instance.relation_representations = torch.nn.ModuleList(
|
|
[relation_embeddings, relation_projection_embeddings]
|
|
)
|
|
|
|
# Compute Scores
|
|
batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 0]], dtype=torch.long)
|
|
scores = self.instance.score_hrt(hrt_batch=batch)
|
|
assert scores.shape[0] == 2
|
|
assert scores.shape[1] == 1
|
|
first_score = scores[0].item()
|
|
second_score = scores[1].item()
|
|
assert first_score == pytest.approx(-18, abs=0.01)
|
|
assert second_score == pytest.approx(-18, abs=0.01)
|
|
|
|
|
|
class TestTransE(cases.DistanceModelTestCase):
|
|
"""Test the TransE model."""
|
|
|
|
cls = pykeen.models.TransE
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity embeddings have to have unit L2 norm.
|
|
"""
|
|
entity_norms = self.instance.entity_representations[0](indices=None).norm(p=2, dim=-1)
|
|
assert torch.allclose(entity_norms, torch.ones_like(entity_norms))
|
|
|
|
|
|
class TestTransF(cases.ModelTestCase):
|
|
"""Test the TransF model."""
|
|
|
|
cls = pykeen.models.TransF
|
|
|
|
|
|
class TestTransH(cases.DistanceModelTestCase):
|
|
"""Test the TransH model."""
|
|
|
|
cls = pykeen.models.TransH
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Normal vectors of relation-specific hyperplanes have unit length.
|
|
"""
|
|
norm = self.instance.relation_representations[1](indices=None).norm(p=2, dim=-1)
|
|
assert torch.allclose(norm, torch.ones_like(norm))
|
|
|
|
|
|
class TestTransR(cases.DistanceModelTestCase):
|
|
"""Test the TransR model."""
|
|
|
|
cls = pykeen.models.TransR
|
|
kwargs = {
|
|
"relation_dim": 4,
|
|
}
|
|
|
|
def _check_constraints(self):
|
|
"""Check model constraints.
|
|
|
|
Entity and relation embeddings have to have at most unit L2 norm.
|
|
"""
|
|
for emb in (self.instance.entity_representations[0], self.instance.relation_representations[0]):
|
|
assert all_in_bounds(emb(indices=None).norm(p=2, dim=-1), high=1.0, a_tol=1.0e-06)
|
|
|
|
|
|
class TestTuckEr(cases.ModelTestCase):
|
|
"""Test the TuckEr model."""
|
|
|
|
cls = pykeen.models.TuckER
|
|
kwargs = {
|
|
"relation_dim": 4,
|
|
}
|
|
#: 2xBN (bias & scale)
|
|
num_constant_init = 4
|
|
|
|
|
|
class TestUM(cases.DistanceModelTestCase):
|
|
"""Test the Unstructured Model."""
|
|
|
|
cls = pykeen.models.UM
|
|
|
|
|
|
class TestCrossE(cases.ModelTestCase):
|
|
"""Test the CrossE model."""
|
|
|
|
cls = pykeen.models.CrossE
|
|
|
|
# the combination bias
|
|
num_constant_init = 1
|
|
|
|
|
|
class TestBoxE(cases.ModelTestCase):
|
|
"""Test the BoxE model."""
|
|
|
|
cls = pykeen.models.BoxE
|
|
|
|
|
|
class TestCP(cases.ModelTestCase):
|
|
"""Test the CP model."""
|
|
|
|
cls = pykeen.models.CP
|
|
|
|
|
|
class TestAutoSF(cases.ModelTestCase):
|
|
"""Test the AutoSF model."""
|
|
|
|
cls = pykeen.models.AutoSF
|
|
|
|
|
|
class TestTesting(unittest_templates.MetaTestCase[Model]):
|
|
"""Yo dawg, I heard you like testing, so I wrote a test to test the tests so you can test while you're testing."""
|
|
|
|
base_test = cases.ModelTestCase
|
|
base_cls = Model
|
|
skip_cls = SKIP_MODULES
|
|
|
|
def test_documentation(self):
|
|
"""Test all models have appropriate structured documentation."""
|
|
for name, cls in sorted(model_resolver.lookup_dict.items()):
|
|
with self.subTest(name=name):
|
|
try:
|
|
docdata = cls.__docdata__
|
|
except AttributeError:
|
|
self.fail("missing __docdata__")
|
|
assert "citation" in docdata
|
|
assert "author" in docdata["citation"]
|
|
assert "link" in docdata["citation"]
|
|
assert "year" in docdata["citation"]
|
|
|
|
def test_importing(self):
|
|
"""Test that all models are available from :mod:`pykeen.models`."""
|
|
models_path = pathlib.Path(pykeen.models.__file__).parent.absolute()
|
|
|
|
# Find models
|
|
model_names: set[str] = set()
|
|
for path in models_path.rglob("*.py"):
|
|
# skip private / __init__
|
|
if path.stem.startswith("_"):
|
|
continue
|
|
|
|
# build import path
|
|
rel_path = path.relative_to(models_path).with_suffix("")
|
|
import_path = ".".join(("pykeen", "models", *rel_path.parts))
|
|
module = importlib.import_module(import_path)
|
|
|
|
# Search for sub-classes of Model
|
|
for name in dir(module):
|
|
value = getattr(module, name)
|
|
with contextlib.suppress(TypeError):
|
|
if isinstance(value, type) and issubclass(value, Model):
|
|
model_names.add(value.__name__)
|
|
|
|
# remove skip modules
|
|
model_names.difference_update(m.__name__ for m in SKIP_MODULES)
|
|
assert model_names.issubset(pykeen.models.__all__), "Forgot to add some imports"
|
|
|
|
@unittest.skip("no longer necessary?")
|
|
def test_models_have_experiments(self):
|
|
"""Test that each model has an experiment folder in :mod:`pykeen.experiments`."""
|
|
experiments_path = pathlib.Path(pykeen.experiments.__file__).parent.absolute()
|
|
experiment_blacklist = {
|
|
"DistMultLiteral", # FIXME
|
|
"ComplExLiteral", # FIXME
|
|
"UnstructuredModel",
|
|
"StructuredEmbedding",
|
|
"RESCAL",
|
|
"NTN",
|
|
"ERMLP",
|
|
"ProjE", # FIXME
|
|
"ERMLPE", # FIXME
|
|
"PairRE",
|
|
"QuatE",
|
|
}
|
|
model_names = _remove_non_models(set(pykeen.models.__all__) - SKIP_MODULES - experiment_blacklist)
|
|
for model in _remove_non_models(model_names):
|
|
model_name = model_resolver.normalize_cls(model)
|
|
with self.subTest(model=model):
|
|
assert experiments_path.joinpath(model_name.lower()).exists(), (
|
|
f"Missing experimental configuration for {model}"
|
|
)
|
|
|
|
|
|
def _remove_non_models(elements: Iterable[str | type[Model]]) -> set[type[Model]]:
|
|
rv = set()
|
|
for element in elements:
|
|
try:
|
|
model_cls = model_resolver.lookup(element)
|
|
except KeyError: # invalid model name - aka not actually a model # noqa: PERF203
|
|
continue
|
|
else:
|
|
rv.add(model_cls)
|
|
return rv
|
|
|
|
|
|
class TestModelUtilities(unittest.TestCase):
|
|
"""Extra tests for utility functions."""
|
|
|
|
def test_extend_batch(self):
|
|
"""Test `_extend_batch()`."""
|
|
batch = torch.tensor([[a, b] for a in range(3) for b in range(4)]).view(-1, 2)
|
|
max_id = 5
|
|
|
|
batch_size = batch.shape[0]
|
|
num_choices = max_id
|
|
|
|
for dim in range(3):
|
|
h_ext_batch = extend_batch(batch=batch, max_id=max_id, dim=dim)
|
|
|
|
# check shape
|
|
assert h_ext_batch.shape == (batch_size * num_choices, 3)
|
|
|
|
# check content
|
|
actual_content = {tuple(map(int, hrt)) for hrt in h_ext_batch}
|
|
exp_content = set()
|
|
for i in range(max_id):
|
|
for b in batch:
|
|
c = list(map(int, b))
|
|
c.insert(dim, i)
|
|
exp_content.add(tuple(c))
|
|
|
|
assert actual_content == exp_content
|
|
|
|
|
|
class ERModelTests(cases.ModelTestCase):
|
|
"""Tests for the general ER-Model."""
|
|
|
|
cls = pykeen.models.ERModel
|
|
kwargs = {
|
|
"interaction": "distmult", # use name to test interaction resolution
|
|
}
|
|
|
|
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
|
|
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
|
|
shape = (kwargs.pop("embedding_dim"),)
|
|
kwargs["entity_representations_kwargs"] = {"shape": shape}
|
|
kwargs["relation_representations_kwargs"] = {"shape": shape}
|
|
return kwargs
|
|
|
|
def test_has_hpo_defaults(self): # noqa: D102
|
|
raise unittest.SkipTest(f"Base class {self.cls} does not provide HPO defaults.")
|
|
|
|
def test_multi_t_and_slicing(self):
|
|
"""Test whether we can use multi-tail scoring with slicing."""
|
|
hr_batch = torch.stack(
|
|
[
|
|
torch.randint(self.instance.num_entities, size=(self.batch_size,), generator=self.generator),
|
|
torch.randint(self.instance.num_relations, size=(self.batch_size,), generator=self.generator),
|
|
],
|
|
dim=-1,
|
|
)
|
|
tails = torch.randint(
|
|
self.instance.num_entities, size=(self.instance.num_entities // 2,), generator=self.generator
|
|
)
|
|
sliced_ts = self.instance.score_t(hr_batch=hr_batch, slice_size=2, tails=tails)
|
|
ts = self.instance.score_t(hr_batch=hr_batch, tails=tails)
|
|
torch.allclose(sliced_ts, ts)
|
|
|
|
|
|
class CooccurrenceFilteredModelTests(cases.ModelTestCase):
|
|
"""Tests for the filtered meta model."""
|
|
|
|
cls = pykeen.models.meta.filtered.CooccurrenceFilteredModel
|