papertrail/backend/engines/pykeen/tests/test_nn/test_representation.py
caelum0x 174222bcaa feat: Builder-Track named-user tools, bio + evidence-intelligence platform, Apache-2.0
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).
2026-07-10 16:23:13 +03:00

573 lines
20 KiB
Python

"""Test embeddings."""
import pathlib
import tempfile
from collections import ChainMap
from collections.abc import MutableMapping
from typing import Any, ClassVar
from unittest.mock import MagicMock
import numpy
import pytest
import torch
import unittest_templates
from PIL import Image
import pykeen.nn.message_passing
import pykeen.nn.node_piece
import pykeen.nn.pyg
import pykeen.nn.representation
import pykeen.nn.utils
import pykeen.nn.vision
from pykeen.datasets import get_dataset
from tests import cases, constants, mocks
from ..utils import needs_packages
class EmbeddingTests(cases.RepresentationTestCase):
"""Tests for embeddings."""
cls = pykeen.nn.representation.Embedding
kwargs = {
"num_embeddings": 7,
"embedding_dim": 13,
}
def test_backwards_compatibility(self):
"""Test shape and num_embeddings."""
assert self.instance.max_id == self.instance_kwargs["num_embeddings"]
embedding_dim = int(numpy.prod(self.instance.shape))
assert self.instance.shape == (embedding_dim,)
class LowRankEmbeddingRepresentationTests(cases.RepresentationTestCase):
"""Tests for low-rank embedding representations."""
cls = pykeen.nn.representation.LowRankRepresentation
kwargs = {
"shape": (3, 7),
}
def test_approximate(self):
"""Test approximation of other representations."""
approx = self.cls.approximate(other=pykeen.nn.representation.Embedding(**self.instance_kwargs))
assert isinstance(approx, self.cls)
class TensorEmbeddingTests(cases.RepresentationTestCase):
"""Tests for Embedding with 2-dimensional shape."""
cls = pykeen.nn.representation.Embedding
kwargs = {
"shape": (3, 7),
}
class RGCNRepresentationTests(cases.TriplesFactoryRepresentationTestCase):
"""Test RGCN representations."""
cls = pykeen.nn.message_passing.RGCNRepresentation
num_bases: ClassVar[int] = 2
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
kwargs["entity_representations_kwargs"] = {"shape": self.num_entities}
return kwargs
class TestSingleCompGCNRepresentationTests(cases.TriplesFactoryRepresentationTestCase):
"""Test single CompGCN representations."""
cls = pykeen.nn.representation.SingleCompGCNRepresentation
dim: ClassVar[int] = 3
create_inverse_triples = True
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
kwargs["combined"] = pykeen.nn.representation.CombinedCompGCNRepresentations(
triples_factory=kwargs.pop("triples_factory"),
entity_representations_kwargs={"embedding_dim": self.dim},
relation_representations_kwargs={"embedding_dim": self.dim},
dims=self.dim,
)
# inferred from triples factory
kwargs.pop("max_id")
return kwargs
class NodePieceRelationTests(cases.NodePieceTestCase):
"""Tests for node piece representation."""
kwargs = {
"token_representations_kwargs": {
"shape": (3,),
}
}
class NodePieceAnchorTests(cases.NodePieceTestCase):
"""Tests for node piece representation with anchor nodes."""
kwargs = {
"token_representations_kwargs": {
"shape": (3,),
},
"tokenizers": "anchor",
"tokenizers_kwargs": {
"selection": "degree",
},
}
class NodePieceMixedTests(cases.NodePieceTestCase):
"""Tests for node piece representation with mixed tokenizers."""
kwargs = {
"token_representations_kwargs": (
{
"shape": (3,),
},
{
"shape": (3,),
},
),
"tokenizers": ("relation", "anchor"),
"num_tokens": (2, 3),
"tokenizers_kwargs": (
{},
{
"selection": "degree",
},
),
}
def test_token_representations(self):
"""Verify that the number of token representations is correct."""
assert len(self.instance.base) == 2
class TokenizationTests(cases.RepresentationTestCase):
"""Tests for tokenization representation."""
cls = pykeen.nn.node_piece.TokenizationRepresentation
vocabulary_size: int = 5
num_tokens: int = 3
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
kwargs["assignment"] = torch.randint(self.vocabulary_size, size=(self.max_id, self.num_tokens))
kwargs["token_representation_kwargs"] = {"shape": (self.vocabulary_size,)}
# inferred from assignment
kwargs.pop("max_id")
return kwargs
class SubsetRepresentationTests(cases.RepresentationTestCase):
"""Tests for subset representations."""
cls = pykeen.nn.representation.SubsetRepresentation
kwargs = {
"max_id": 7,
}
shape: tuple[int, ...] = (13,)
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
kwargs["base"] = pykeen.nn.representation.Embedding(
num_embeddings=2 * kwargs["max_id"],
shape=self.shape,
)
return kwargs
class TextRepresentationTests(cases.RepresentationTestCase):
"""Test the label based representations."""
cls = pykeen.nn.representation.TextRepresentation
kwargs = {"encoder": "character-embedding"}
key_labels: str = "labels"
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs=kwargs)
# the representation module infers the max_id from the provided labels
kwargs.pop("max_id")
dataset = get_dataset(dataset="nations")
kwargs[self.key_labels] = sorted(dataset.entity_to_id.keys())
self.max_id = dataset.num_entities
return kwargs
def test_from_dataset(self):
"""Test creating text-based representations from a dataset."""
dataset = get_dataset(dataset="nations")
kwargs = {key: value for key, value in self.instance_kwargs.items() if key != self.key_labels}
instance = self.cls.from_dataset(dataset=dataset, **kwargs)
assert instance.max_id == dataset.num_entities
class CachedTextRepresentationTests(TextRepresentationTests):
"""Tests for cached text representations."""
cls = pykeen.nn.representation.CachedTextRepresentation
kwargs = {"encoder": "character-embedding", "cache": pykeen.nn.text.IdentityCache()}
key_labels: str = "identifiers"
class SimpleMessagePassingRepresentationTests(cases.MessagePassingRepresentationTests):
"""Test for Pytorch Geometric representations using uni-relational message passing layers."""
cls = pykeen.nn.pyg.SimpleMessagePassingRepresentation
embedding_dim: int = 3
kwargs = {
"base_kwargs": {"shape": (embedding_dim,)},
"layers": ["gcn"] * 2,
"layers_kwargs": {"in_channels": embedding_dim, "out_channels": embedding_dim},
}
class TypedMessagePassingRepresentationTests(cases.MessagePassingRepresentationTests):
"""Test for Pytorch Geometric representations using categorical message passing layers."""
cls = pykeen.nn.pyg.TypedMessagePassingRepresentation
embedding_dim: int = 3
kwargs = {
"base_kwargs": {"shape": (embedding_dim,)},
"layers": ["rgcn"],
"layers_kwargs": {
"in_channels": embedding_dim,
"out_channels": embedding_dim,
"num_bases": 2,
"num_relations": cases.TriplesFactoryRepresentationTestCase.num_relations,
},
}
class FeaturizedMessagePassingRepresentationTests(cases.MessagePassingRepresentationTests):
"""Test for Pytorch Geometric representations using categorical message passing layers."""
cls = pykeen.nn.pyg.FeaturizedMessagePassingRepresentation
embedding_dim: int = 3
kwargs = {
"base_kwargs": {"shape": (embedding_dim,)},
"layers": ["gat"],
"layers_kwargs": {
"in_channels": embedding_dim,
"out_channels": embedding_dim,
"edge_dim": embedding_dim, # should match relation dim
},
"relation_representation_kwargs": {
"shape": embedding_dim,
},
}
@constants.skip_if_windows
@needs_packages("torchvision")
class VisualRepresentationTestCase(cases.RepresentationTestCase):
"""Tests for VisualRepresentation."""
cls = pykeen.nn.vision.VisualRepresentation
kwargs = {
"encoder": "resnet18",
"layer_name": "avgpool",
"transforms": [],
"trainable": False,
}
max_id = 7
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
kwargs = super()._pre_instantiation_hook(kwargs)
kwargs["images"] = list(torch.rand(self.max_id, 3, 28, 28))
return kwargs
@constants.skip_if_windows
@needs_packages("torchvision")
class WikidataVisualRepresentationTestCase(cases.RepresentationTestCase):
"""Tests for Wikidata visual representations."""
cls = pykeen.nn.vision.WikidataVisualRepresentation
kwargs = {
"encoder": "resnet18",
"layer_name": "avgpool",
"trainable": False,
"wikidata_ids": [
"Q1",
"Q42",
# the following entity does not have an image -> will have to use backfill
"Q676",
],
}
# docstr-coverage: inherited
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
kwargs.pop("max_id")
self.max_id = len(kwargs["wikidata_ids"])
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
fake_image_path = pathlib.Path(self._tmp.name) / "fake.jpg"
Image.new("RGB", (256, 256)).save(fake_image_path)
wikidata_ids = kwargs["wikidata_ids"]
mock_cache = MagicMock()
mock_cache.get_image_paths.return_value = [fake_image_path] * (len(wikidata_ids) - 1) + [None]
kwargs["cache"] = mock_cache
return kwargs
class CombinedRepresentationTestCase(cases.RepresentationTestCase):
"""Test for combined representations."""
cls = pykeen.nn.representation.CombinedRepresentation
kwargs = {
"base_kwargs": [
{"shape": (3,)},
{"shape": (4,)},
]
}
class WikidataTextRepresentationTests(cases.RepresentationTestCase):
"""Tests for Wikidata text representations."""
cls = pykeen.nn.representation.WikidataTextRepresentation
kwargs = {
"identifiers": ["Q100", "Q1000"],
"encoder": "character-embedding",
}
# docstr-coverage: inherited
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
# the representation module infers the max_id from the provided labels
kwargs.pop("max_id")
self.max_id = len(kwargs["identifiers"])
mock_cache = MagicMock()
mock_cache.get_texts.return_value = list(kwargs["identifiers"])
kwargs["cache"] = mock_cache
return kwargs
@needs_packages("pyobo")
class BiomedicalCURIERepresentationTests(cases.RepresentationTestCase):
"""Tests for biomedical CURIE representations."""
cls = pykeen.nn.representation.BiomedicalCURIERepresentation
kwargs = {
"identifiers": [
"hgnc:12929", # PCGF2
"hgnc:391", # AKT1
],
"encoder": "character-embedding",
}
# docstr-coverage: inherited
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
# the representation module infers the max_id from the provided labels
kwargs.pop("max_id")
self.max_id = len(kwargs["identifiers"])
mock_cache = MagicMock()
mock_cache.get_texts.return_value = list(kwargs["identifiers"])
kwargs["cache"] = mock_cache
return kwargs
class PartitionRepresentationTests(cases.RepresentationTestCase):
"""Tests for partition representation."""
cls = pykeen.nn.representation.PartitionRepresentation
max_ids: ClassVar[tuple[int, ...]] = (5, 7)
shape: tuple[int, ...] = (3,)
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
kwargs = super()._pre_instantiation_hook(kwargs)
# max_id is inferred from assignment
kwargs.pop("max_id")
self.max_id = sum(self.max_ids)
# create random assignment
assignment = []
for i, max_id in enumerate(self.max_ids):
assignment.append(torch.stack([torch.full(size=(max_id,), fill_value=i), torch.arange(max_id)], dim=-1))
assignment = torch.cat(assignment)
assignment = assignment[torch.randperm(assignment.shape[0])]
# update kwargs
kwargs.update(
{
"assignment": assignment,
"bases": [None] * len(self.max_ids),
"bases_kwargs": [{"max_id": max_id, "shape": self.shape} for max_id in self.max_ids],
}
)
return kwargs
def test_coherence(self):
"""Test coherence with base representations."""
xs = self.instance(indices=None)
for x, (repr_id, local_index) in zip(xs, self.instance.assignment, strict=False):
x_base = self.instance.bases[repr_id](indices=local_index)
assert (x_base == x).all()
def test_input_verification(self):
"""Verify that the input is correctly verified."""
# empty bases
with pytest.raises(ValueError, match="Must provide at least one base representation"):
self.cls(assignment=..., bases=[], bases_kwargs=[])
# inconsistent base shapes
shapes = range(2, len(self.max_ids) + 2)
bases_kwargs = [{"max_id": max_id, "shape": (dim,)} for max_id, dim in zip(self.max_ids, shapes, strict=False)]
with pytest.raises(ValueError, match="Inconsistent base shapes:"):
self.cls(**ChainMap({"bases_kwargs": bases_kwargs}, self.instance_kwargs))
# invalid base id
assignment = self.instance.assignment.clone()
assignment[torch.randint(assignment.shape[0], size=()), 0] = len(self.instance.bases)
with pytest.raises(ValueError, match="Invalid representation Ids in assignment"):
self.cls(**ChainMap({"assignment": assignment}, self.instance_kwargs))
# invalid local index
assignment = self.instance.assignment.clone()
assignment[torch.randint(assignment.shape[0], size=()), 1] = max(self.max_ids)
with pytest.raises(ValueError, match="cannot provide indices up to"):
self.cls(**ChainMap({"assignment": assignment}, self.instance_kwargs))
class MultiBackfillRepresentationTests(cases.RepresentationTestCase):
"""Tests for multi-backfill representation, based on the partition representation."""
cls = pykeen.nn.representation.MultiBackfillRepresentation
kwargs = {
"partitions": [
pykeen.nn.Partition(
ids=[i for i in range(cases.RepresentationTestCase.max_id) if i % 2],
base=None,
kwargs={"shape": (3,)},
)
],
}
def test_perfect_assignment(self) -> None:
"""Test that perfect assignment results in no backfill."""
x = pykeen.nn.representation.MultiBackfillRepresentation(
max_id=4,
partitions=[
pykeen.nn.Partition(ids=[0, 1], base=None, kwargs={"shape": (2,)}),
pykeen.nn.Partition(ids=[2, 3], base=None, kwargs={"shape": (2,)}),
],
)
assert len(x.bases) == 2
class BackfillRepresentationTests(cases.RepresentationTestCase):
"""Tests for backfill representation, based on the partition representation."""
cls = pykeen.nn.representation.BackfillRepresentation
kwargs = {
"base_kwargs": {"shape": (3,)},
"base_ids": [i for i in range(cases.RepresentationTestCase.max_id) if i % 2],
}
def test_max_id_verification_raises_value_error(self):
"""Test that an invalid max_id raises a ValueError."""
for base_ids, message_part in (
([0, 1, 1], "Duplicate"),
([0, 1, 2, 5], "exceed max_id"),
([-1, 1, 2, 5], "not non-negative"),
):
with self.subTest(message_part), pytest.raises(pykeen.nn.representation.InvalidBaseIdsError) as info:
pykeen.nn.representation.BackfillRepresentation(
base_ids=base_ids,
max_id=2,
base=pykeen.nn.representation.Embedding(max_id=4, shape=(4,)),
)
assert message_part in str(info.value)
with self.subTest(message_part), pytest.raises(pykeen.nn.representation.MaxIDMismatchError):
pykeen.nn.representation.BackfillRepresentation(
base_ids=[0, 1],
max_id=2,
base=pykeen.nn.representation.Embedding(max_id=4, shape=(4,)),
)
def test_max_id_verification(self):
"""Test that a valid max_id does not raise a ValueError."""
pykeen.nn.representation.BackfillRepresentation(
base_ids=[0, 1, 2],
max_id=12,
base=pykeen.nn.representation.Embedding(max_id=3, shape=(3,)),
)
class TransformedRepresentationTest(cases.RepresentationTestCase):
"""Tests for transformed representations."""
cls = pykeen.nn.representation.TransformedRepresentation
kwargs = {
"base_kwargs": {"shape": (5,)},
}
# docstr-coverage: inherited
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
kwargs["transformation"] = torch.nn.Linear(5, 7)
return kwargs
class TensorTrainRepresentationTest(cases.RepresentationTestCase):
"""Tests for tensor train representations."""
cls = pykeen.nn.representation.TensorTrainRepresentation
class EmbeddingBagRepresentation(cases.RepresentationTestCase):
"""Tests for embedding bag representations."""
cls = pykeen.nn.representation.EmbeddingBagRepresentation
kwargs = {"shape": (5,)}
# docstr-coverage: inherited
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
max_id = kwargs["max_id"]
mask = torch.rand(max_id, max_id) < 0.5
kwargs["assignment"] = mask.nonzero()
return kwargs
class MLPTransformedRepresentationTest(cases.RepresentationTestCase):
"""Tests for MLP transformed representations."""
cls = pykeen.nn.meta.MLPTransformedRepresentation
kwargs = {
"base_kwargs": {"shape": (5,)},
}
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
kwargs["base_kwargs"]["max_id"] = kwargs.pop("max_id")
return kwargs
class FeatureEnrichedEmbeddingTest(cases.RepresentationTestCase):
"""Tests for feature-enriched embeddings."""
cls = pykeen.nn.meta.FeatureEnrichedEmbedding
def _pre_instantiation_hook(self, kwargs: MutableMapping[str, Any]) -> MutableMapping[str, Any]: # noqa: D102
kwargs = super()._pre_instantiation_hook(kwargs)
kwargs["tensor"] = torch.rand(self.max_id, 9)
kwargs.pop("max_id")
return kwargs
class RepresentationModuleMetaTestCase(unittest_templates.MetaTestCase[pykeen.nn.representation.Representation]):
"""Test that there are tests for all representation modules."""
base_cls = pykeen.nn.representation.Representation
base_test = cases.RepresentationTestCase
skip_cls = {mocks.CustomRepresentation, pykeen.nn.pyg.MessagePassingRepresentation}