Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

8.7 KB
Raw Blame
"""Parity between the GLiFormer adapter and the upstream ``gliformer`` package.

The goldens under ``goldens/gliformer`` hold the package's own float32 CPU
outputs for fixed texts, generated by
``packages/sie_server/scripts/generate_gliformer_goldens.py`` without any SIE
code. Each case pairs an SIE ``extract`` request with the GLiFormer call it must
translate to; this module sends the request through the catalog-configured
adapter on CPU and checks the mapped results against the package output.

The goldens record the stack that produced them (``generated_with``), here the
default bundle's transformers 4.57 and gliner 0.2.26. The package as its
authors run it (transformers 5.16, gliner 0.2.29) gives the same results on
these cases, with scores within 1.1e-6.
"""

from __future__ import annotations

import json
from collections.abc import Iterator
from pathlib import Path
from typing import Any

import numpy as np
import pytest
from sie_server.adapters.gliformer.adapter import GLiFormerAdapter
from sie_server.adapters.gliformer.output_schema import compile_output_schema, shape_structured_output
from sie_server.core.loader import load_adapter, load_model_configs
from sie_server.types.inputs import Item

pytestmark = pytest.mark.model

_GOLDENS = sorted((Path(__file__).parent / "goldens" / "gliformer").glob("*.json"))
_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
_CASES = [
    "entities",
    "classification",
    "classification_multi_label",
    "relations",
    "output_schema",
    "combined",
    "label_groups",
    "nested_objects",
    "metadata_entities",
]
# The goldens are float32 CPU outputs; only BLAS scheduling differs between hosts.
_SCORE_TOLERANCE = 1e-4
_EMBEDDING_TOLERANCE = 1e-4


@pytest.fixture(scope="module", params=_GOLDENS, ids=lambda path: path.stem)
def golden_adapter(request: pytest.FixtureRequest) -> Iterator[tuple[dict[str, Any], GLiFormerAdapter]]:
    golden = json.loads(request.param.read_text())
    config = load_model_configs(_MODELS_DIR)[golden["model"]]
    assert config.hf_revision == golden["revision"], "golden was generated for a different checkpoint revision"
    assert config.max_sequence_length == golden["generated_with"]["max_length"]
    adapter = load_adapter(config, _MODELS_DIR, device="cpu")
    adapter.load("cpu")
    yield golden, adapter
    adapter.unload()


def _expected(case: dict[str, Any], index: int, adapter: GLiFormerAdapter) -> dict[str, Any]:
    """Map the reference output for one text onto SIE's extract fields.

    Structured values go through GLiFormer's own typed formatter first, which
    is what ``GLiFormer.structure`` applies to raw ``inference`` output, and
    then through the adapter's JSON Schema shaping.
    """
    request, output = case["request"], case["reference_output"]
    options = request.get("options", {})
    metadata = request.get("item_metadata")
    plan = compile_output_schema(request["output_schema"]) if "output_schema" in request else None
    if "structuring" in output:
        assert adapter._build_formatter is not None
        formatter = adapter._build_formatter(case["reference_call"]["structures"])
        if formatter is not None:
            output = {**output, "structuring": formatter.format_batch(output["structuring"])}

    def for_text(task: str, default: Any) -> Any:
        return output[task][index] if task in output else default

    label_groups = options.get("label_groups") or {}
    group_names = (
        ([options["classification_task"]] if "classification_task" in options else [])
        + list(label_groups)
        + (list(plan.choice_groups) if plan is not None else [])
    )
    groups = {
        name: sorted(
            ((prediction["class_name"], prediction["score"]) for prediction in predictions), key=lambda p: -p[1]
        )
        for name, predictions in zip(group_names, for_text("classification", [[] for _ in group_names]), strict=True)
    }

    if metadata is not None:
        supplied = metadata[index]["entities"]
        entities = sorted((e["start"], e["end"], e["text"], e["label"], 1.0) for e in supplied)
    else:
        entities = sorted((e["start"], e["end"], e["text"], e["label"], e["score"]) for e in for_text("ner", []))
    expected: dict[str, Any] = {"entities": entities}
    if "relation_labels" in options or metadata is not None:
        allowed = {e["text"] for e in metadata[index]["entities"]} if metadata is not None else None
        expected["relations"] = sorted(
            (relation["relation"], relation["head"]["text"], relation["tail"]["text"], relation["score"])
            for relation in for_text("joint_relex", [])
            if allowed is None or (relation["head"]["text"] in allowed and relation["tail"]["text"] in allowed)
        )
    if "classification_task" in options:
        expected["classifications"] = groups[options["classification_task"]]
    if label_groups:
        expected["classifications"] = sorted(
            ((f"{name}.{label}", score) for name in label_groups for label, score in groups[name]),
            key=lambda pair: -pair[1],
        )
    if plan is not None:
        choices = {name: groups[name][0][0] for name in plan.choice_groups if groups[name]}
        structured = for_text("structuring", {}) if plan.structures is not None else None
        expected["data"], missing = shape_structured_output(plan, structured, choices)
        assert not missing, "golden cases declare no required root properties"
    return expected


def _assert_scored(actual: list[tuple[Any, ...]], expected: list[tuple[Any, ...]], what: str) -> None:
    """Compare key fields exactly and the trailing/leading score within tolerance."""
    assert len(actual) == len(expected), f"{what}: {actual} != {expected}"
    for got, want in zip(actual, expected, strict=True):
        assert got[:-1] == want[:-1], f"{what}: {got} != {want}"
        assert abs(got[-1] - want[-1]) <= _SCORE_TOLERANCE, f"{what}: {got} != {want}"


@pytest.mark.parametrize("case_name", _CASES)
def test_extract_matches_reference_package(
    golden_adapter: tuple[dict[str, Any], GLiFormerAdapter],
    case_name: str,
) -> None:
    golden, adapter = golden_adapter
    case = next((case for case in golden["cases"] if case["name"] == case_name), None)
    if case is None:
        pytest.fail(f"golden has no {case_name!r} case; regenerate it with scripts/generate_gliformer_goldens.py")
    request = case["request"]
    metadata = request.get("item_metadata") or [None] * len(golden["texts"])

    output = adapter.extract(
        [
            Item(text=text, metadata=item_metadata)
            for text, item_metadata in zip(golden["texts"], metadata, strict=True)
        ],
        labels=request.get("labels"),
        output_schema=request.get("output_schema"),
        options=request.get("options"),
    )

    assert output.errors is None
    assert output.input_token_counts is not None
    assert all(count > 0 for count in output.input_token_counts)
    for index in range(len(golden["texts"])):
        expected = _expected(case, index, adapter)
        entities = [
            (entity["start"], entity["end"], entity["text"], entity["label"], entity["score"])
            for entity in output.entities[index]
        ]
        _assert_scored(sorted(entities), expected["entities"], f"{case_name} entities[{index}]")
        if "relations" in expected:
            assert output.relations is not None
            relations = [
                (relation["relation"], relation["head"], relation["tail"], relation["score"])
                for relation in output.relations[index]
            ]
            _assert_scored(sorted(relations), expected["relations"], f"{case_name} relations[{index}]")
        if "classifications" in expected:
            assert output.classifications is not None
            classifications = [(item["label"], item["score"]) for item in output.classifications[index]]
            _assert_scored(classifications, expected["classifications"], f"{case_name} classifications[{index}]")
        if "data" in expected:
            assert output.data is not None
            assert output.data[index] == expected["data"], f"{case_name} data[{index}]"
        else:
            assert output.data is None


def test_encode_matches_reference_package(golden_adapter: tuple[dict[str, Any], GLiFormerAdapter]) -> None:
    golden, adapter = golden_adapter
    reference = golden["embeddings"]

    output = adapter.encode([Item(text=text) for text in golden["texts"]], ["dense"])

    assert output.dense is not None
    assert output.dense.shape == (len(golden["texts"]), reference["dim"])
    head = np.asarray(reference["normalized_head"])
    np.testing.assert_allclose(output.dense[:, : head.shape[1]], head, atol=_EMBEDDING_TOLERANCE)
    np.testing.assert_allclose(
        output.dense @ output.dense.T, np.asarray(reference["cosine"]), atol=_EMBEDDING_TOLERANCE
    )