Skip to content

armgit / sie

Public Imported from GitHub
0

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

9.6 KB
Raw Blame
r"""Parity between the GLiNER2.5-Decide adapter and the ``gliner2`` 2.x package.

The goldens under ``goldens/gliner2_decide`` hold the package's own float32 CPU
probabilities for fixed texts, generated by
``packages/sie_server/scripts/generate_gliner2_decide_goldens.py`` without any
SIE code, on the transformers5 bundle's stack (``generated_with``). Each case
pairs an SIE ``extract`` request (Laya questions, label groups, multi-label
groups, plain labels, and a document longer than the window) with the
``gliner2.classification`` schema it must translate to.

* CPU float32: every label's probability within 1e-4 of the golden, and every
  encoder row byte-identical to the package's (hashes in the golden).
* CUDA, at the catalog precision (float16, the package's ``quantize=True``):
  every probability within 5e-3 of the package's own ``Classifier`` on the same
  weights, and within 1e-2 of the float32 golden, with the same top answers.
  The adapter pads a request's rows into one batch where the package scores one
  text at a time, so float16 rounding differs; on an L4 the largest difference
  was 2.3e-3 (the multilingual model), and 1.1e-3 or less for the other two.
* GLiNER2.5-Decide-1B: the loaded encoder runs RoPE base 160000 in every layer.

These tests need ``gliner2`` 2.x (the transformers5 bundle); run them with the
bundle's requirements:

    python -m sie_server.cli resolve-deps --bundle transformers5 > /tmp/t5.txt
    uv run --no-sync --with-requirements /tmp/t5.txt pytest -c pyproject.toml -m model \\
        packages/sie_server/tests/adapters/test_gliner2_decide_parity.py
"""

from __future__ import annotations

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

import numpy as np
import pytest
import torch
from sie_server.adapters.gliner2.decide import GLiNER2DecideAdapter, loaded_rope_thetas
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" / "gliner2_decide").glob("*.json"))
_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
# The goldens are float32 CPU outputs; only BLAS scheduling differs between hosts.
_CPU_TOLERANCE = 1e-4
# float16 on CUDA: against the package on the same weights (batched rows vs one
# text at a time), and against float32.
_GPU_PACKAGE_TOLERANCE = 5e-3
_GPU_FLOAT32_TOLERANCE = 1e-2


def _golden(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def _adapter(golden: dict[str, Any], device: str) -> GLiNER2DecideAdapter:
    pytest.importorskip("gliner2.classification", reason="needs gliner2 2.x (the transformers5 bundle)")
    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"]["window"]
    adapter = load_adapter(config, _MODELS_DIR, device=device)
    adapter.load(device)
    assert isinstance(adapter, GLiNER2DecideAdapter)
    return adapter


def _documents(golden: dict[str, Any], case: dict[str, Any]) -> list[str]:
    return golden["texts"] if case["documents"] == "texts" else [golden["long_text"]]


def _request(case: dict[str, Any]) -> dict[str, Any]:
    request = case["request"]
    return {
        "labels": request.get("labels"),
        "output_schema": request.get("output_schema"),
        "instruction": request.get("instruction"),
        "options": request.get("options"),
    }


def _answers(case: dict[str, Any], output: Any, index: int) -> dict[str, dict[str, float]]:
    """The adapter's probabilities for one item, keyed like the golden's (task -> label -> p)."""
    tasks = case["reference_call"]["tasks"]
    if "labels" in case["request"]:
        return {tasks[0]["name"]: {c["label"]: c["score"] for c in output.classifications[index]}}
    data = output.data[index]
    answers: dict[str, dict[str, float]] = {}
    for key, answer in data.items():
        if answer.get("type") == "noul":
            answers[key] = {"yes": answer["noul"], "no": 1.0 - answer["noul"]}
        else:
            answers[key] = answer["probabilities"]
    return answers


def _run(adapter: GLiNER2DecideAdapter, case: dict[str, Any], texts: list[str]) -> tuple[Any, list[list[int]]]:
    rows: list[list[int]] = []
    score = adapter._score

    def spy(batch: list[list[int]], positions: list[int]) -> np.ndarray:
        rows.extend(batch)
        return score(batch, positions)

    adapter._score = spy  # ty:ignore[invalid-assignment]
    try:
        output = adapter.extract([Item(text=text) for text in texts], **_request(case))
    finally:
        del adapter._score
    return output, rows


def _max_difference(actual: dict[str, dict[str, float]], expected: dict[str, dict[str, float]]) -> float:
    assert list(actual) == list(expected)
    worst = 0.0
    for task, probabilities in expected.items():
        assert set(actual[task]) == set(probabilities), task
        worst = max(worst, *(abs(actual[task][label] - p) for label, p in probabilities.items()))
    return worst


def _same_top_answers(actual: dict[str, dict[str, float]], expected: dict[str, dict[str, float]]) -> bool:
    """Same highest-probability label per task, wherever the expected top label leads by more than 0.01."""
    for task, probabilities in expected.items():
        ranked = sorted(probabilities.values(), reverse=True)
        top = max(probabilities, key=probabilities.__getitem__)
        if len(ranked) > 1 and ranked[0] - ranked[1] <= 0.01:
            continue
        if max(actual[task], key=actual[task].__getitem__) != top:
            return False
    return True


@pytest.fixture(scope="module", params=_GOLDENS, ids=lambda path: path.stem)
def cpu_adapter(request: pytest.FixtureRequest) -> Iterator[tuple[dict[str, Any], GLiNER2DecideAdapter]]:
    golden = _golden(request.param)
    adapter = _adapter(golden, "cpu")
    yield golden, adapter
    adapter.unload()


def test_cpu_float32_matches_the_package(cpu_adapter: tuple[dict[str, Any], GLiNER2DecideAdapter]) -> None:
    golden, adapter = cpu_adapter
    for case in golden["cases"]:
        texts = _documents(golden, case)
        output, rows = _run(adapter, case, texts)
        assert output.errors is None, case["name"]
        for index, (row, expected) in enumerate(zip(rows, case["results"], strict=True)):
            assert len(row) == expected["row_length"], (case["name"], index)
            assert hashlib.sha256(json.dumps(row).encode()).hexdigest() == expected["row_sha256"], (case["name"], index)
            worst = _max_difference(_answers(case, output, index), expected["probabilities"])
            assert worst <= _CPU_TOLERANCE, (case["name"], index, worst)


def test_long_documents_are_read_to_the_window(cpu_adapter: tuple[dict[str, Any], GLiNER2DecideAdapter]) -> None:
    golden, adapter = cpu_adapter
    case = next(case for case in golden["cases"] if case["name"] == "long_document")
    assert case["results"][0]["max_len"] is not None, "the long document must not fit the window"
    output, rows = _run(adapter, case, [golden["long_text"]])
    assert len(rows[0]) <= golden["generated_with"]["window"]
    assert output.input_token_counts is not None
    assert 0 < output.input_token_counts[0] <= golden["generated_with"]["window"]


def test_decide_1b_runs_its_declared_rope_base(cpu_adapter: tuple[dict[str, Any], GLiNER2DecideAdapter]) -> None:
    golden, adapter = cpu_adapter
    if not golden["model"].endswith("Decide-1B"):
        pytest.skip("only the Ettin (ModernBERT) encoder has rotary tables")
    thetas = loaded_rope_thetas(adapter._model.encoder, 3)
    assert set(thetas) == {"full_attention", "sliding_attention"}
    for values in thetas.values():
        assert values == pytest.approx([160000.0] * len(values), rel=1e-3)


@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
@pytest.mark.parametrize("path", _GOLDENS, ids=lambda path: path.stem)
def test_cuda_matches_the_package_on_the_same_weights(path: Path) -> None:
    from gliner2.classification import (  # ty:ignore[unresolved-import]
        ClassificationConfig,
        ClassificationSchema,
        Classifier,
    )

    golden = _golden(path)
    adapter = _adapter(golden, "cuda:0")
    try:
        classifier = Classifier(adapter._model)
        for case in golden["cases"]:
            texts = _documents(golden, case)
            output, _ = _run(adapter, case, texts)
            assert output.errors is None, case["name"]
            schema = ClassificationSchema()
            for task in case["reference_call"]["tasks"]:
                add = schema.single if task["kind"] == "single" else schema.multi
                add(task["name"], task["labels"], instruction=task["instruction"])
            for index, (text, expected) in enumerate(zip(texts, case["results"], strict=True)):
                actual = _answers(case, output, index)
                scores = classifier.score(text, schema, config=ClassificationConfig(max_len=expected["max_len"]))
                package = {
                    task: {label: scores.probability(task, label) for label in labels}
                    for task, labels in expected["probabilities"].items()
                }
                assert _max_difference(actual, package) <= _GPU_PACKAGE_TOLERANCE, (case["name"], index)
                assert _max_difference(actual, expected["probabilities"]) <= _GPU_FLOAT32_TOLERANCE, (
                    case["name"],
                    index,
                )
                assert _same_top_answers(actual, package), (case["name"], index)
    finally:
        adapter.unload()