Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(server): add GLiFormer multi-task extraction models (#358)
svonava28a07f500490
diff --git a/README.md b/README.mdindex 974645d21..017dbe7bc 100644--- a/README.md+++ b/README.md@@ -45,7 +45,7 @@ One SIE cluster runs the inference behind a whole agent. Each task is a handful|---|---|---|| **Search** | Embed, match, and rerank to retrieve the right context. | [`bge-m3`](packages/sie_server/models/BAAI__bge-m3.yaml), [`splade-v3`](packages/sie_server/models/naver__splade-v3.yaml), [`colbertv2`](packages/sie_server/models/colbert-ir__colbertv2.0.yaml), [`qwen3-reranker`](packages/sie_server/models/Qwen__Qwen3-Reranker-4B.yaml) || **Document to markdown** | PDFs, Office files, and scans become clean markdown. | [`lightonocr`](packages/sie_server/models/lightonai__LightOnOCR-2-1B.yaml), [`glm-ocr`](packages/sie_server/models/zai-org__GLM-OCR.yaml), [`mineru`](packages/sie_server/models/opendatalab__MinerU2.5-Pro-2604-1.2B.yaml), [`paddleocr-vl`](packages/sie_server/models/PaddlePaddle__PaddleOCR-VL-1.5.yaml), [`docling`](packages/sie_server/models/docling.yaml) |-| **Structured output** | Schema-valid JSON, extracted or generated. | [`gliner2`](packages/sie_server/models/fastino__gliner2-large-v1.yaml), [`gliner-relex`](packages/sie_server/models/knowledgator__gliner-relex-large-v1.0.yaml), [`nuner-zero`](packages/sie_server/models/numind__NuNER_Zero.yaml), [`qwen3.8-27b`](packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml), [`qwen3.6-27b`](packages/sie_server/models/Qwen__Qwen3.6-27B.yaml) |+| **Structured output** | Schema-valid JSON, extracted or generated. | [`gliner2`](packages/sie_server/models/fastino__gliner2-large-v1.yaml), [`gliner-relex`](packages/sie_server/models/knowledgator__gliner-relex-large-v1.0.yaml), [`gliformer`](packages/sie_server/models/knowledgator__gliformer-large-v1.yaml), [`nuner-zero`](packages/sie_server/models/numind__NuNER_Zero.yaml), [`qwen3.8-27b`](packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml), [`qwen3.6-27b`](packages/sie_server/models/Qwen__Qwen3.6-27B.yaml) || **Decide** | Choice, yes/no, and score answers with probabilities to typed questions about a text or JSON state. | [`laya`](packages/sie_server/models/convaiinnovations__laya.yaml), [`laya-multilingual`](packages/sie_server/models/convaiinnovations__laya-multilingual.yaml), [`laya-typed-decisions`](packages/sie_server/models/convaiinnovations__laya-typed-decisions.yaml) || **Classify** | Zero-shot labels, with several label groups answered in one call. The instruct models also follow a task instruction and few-shot examples. | [`gliclass-large-v3`](packages/sie_server/models/knowledgator__gliclass-large-v3.0.yaml), [`gliclass-instruct-large`](packages/sie_server/models/knowledgator__gliclass-instruct-large-v1.0.yaml), [`gliclass-multilang-mini`](packages/sie_server/models/knowledgator__gliclass-multilang-mini.yaml) || **Guard content** | A safety verdict: Yes/No with the threshold set in the model config, or safe/unsafe and policy-label scores with the threshold chosen per request. | [`granite-guardian-2b`](packages/sie_server/models/ibm-granite__granite-guardian-3.0-2b.yaml), [`opir-multitask-large`](packages/sie_server/models/knowledgator__opir-multitask-large-v1.0.yaml), [`opir-edge`](packages/sie_server/models/knowledgator__opir-edge-v1.0.yaml) |@@ -141,6 +141,23 @@ result = client.extract()print(result["entities"][0])# {'text': 'Tim Cook', 'label': 'person', 'score': 0.992, 'start': 0, 'end': 8, ...}++# Entities and a schema-valid record from one forward pass+result = client.extract(+ "knowledgator/gliformer-base-v1",+ Item(text="Refund request from Maria Lopez for order 4471 was denied: the item was returned after 45 days."),+ labels=["person"],+ output_schema={+ "type": "object",+ "properties": {+ "order number": {"type": "string"},+ "reason": {"type": "string"},+ "decision": {"type": "string", "enum": ["approved", "denied", "escalated"]},+ },+ },+)+print(result["data"])+# e.g. {'order number': '4471', 'reason': 'the item was returned after 45 days', 'decision': 'denied'}```Typed decisions ask one or more typed questions about each item (a text, or a JSON object or conversation passed asdiff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yamlindex 3613dc5c5..3be358ec3 100644--- a/packages/sie_server/bundles/default.yaml+++ b/packages/sie_server/bundles/default.yaml@@ -42,6 +42,7 @@ adapters:- sie_server.adapters.glirel- sie_server.adapters.gliclass- sie_server.adapters.laya.adapter+- sie_server.adapters.gliformer.adapter- sie_server.adapters.donut- sie_server.adapters.florence2- sie_server.adapters.docling.adapter@@ -82,6 +83,8 @@ deps:# gliclass (0.1.17: cross-attention scorer for the multilingual checkpoints;# 0.1.18+ needs transformers 5)gliclass: '>=0.1.17,<1'+ # gliformer: exact, the adapter uses package internals (see pyproject.toml)+ gliformer: '==0.1.2'# gliner/glirel/gliclass shared deploguru: '>=0.7,<1'# donut, florence2diff --git a/packages/sie_server/models/knowledgator__gliformer-base-v1.yaml b/packages/sie_server/models/knowledgator__gliformer-base-v1.yamlnew file mode 100644index 000000000..ea5d7fa09--- /dev/null+++ b/packages/sie_server/models/knowledgator__gliformer-base-v1.yaml@@ -0,0 +1,23 @@+sie_id: knowledgator/gliformer-base-v1+hf_id: knowledgator/gliformer-base-v1+hf_revision: 590f9d3f577ea2f6d685aaec84b2d66b6db86b15+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ score: null+ extract: {}+max_sequence_length: 2048+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.gliformer.adapter:GLiFormerAdapter+ adapter_options:+ loadtime: {}+ runtime: {}diff --git a/packages/sie_server/models/knowledgator__gliformer-large-v1.yaml b/packages/sie_server/models/knowledgator__gliformer-large-v1.yamlnew file mode 100644index 000000000..1763362c9--- /dev/null+++ b/packages/sie_server/models/knowledgator__gliformer-large-v1.yaml@@ -0,0 +1,23 @@+sie_id: knowledgator/gliformer-large-v1+hf_id: knowledgator/gliformer-large-v1+hf_revision: d0a4e53d09cebe6bc963dd9be319d4279084bb2d+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 1024+ score: null+ extract: {}+max_sequence_length: 2048+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.gliformer.adapter:GLiFormerAdapter+ adapter_options:+ loadtime: {}+ runtime: {}diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex d6d70f80a..2a54f634a 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -51,6 +51,10 @@ dependencies = [# 0.1.17 adds the cross-attention scorer and pass-through pooling used by# the multilingual GLiClass checkpoints; 0.1.18+ requires transformers 5."gliclass>=0.1.17,<1",+ # GLiFormer multi-task extraction adapter. Pinned exactly: the adapter+ # drives the package's processor and schema internals, which change between+ # 0.x releases, and the bundle overlay resolves this pin live from PyPI.+ "gliformer==0.1.2",# Docling, composite-document parser (PDF/DOCX/HTML) for extract().# PINNED TO THE ARTIFACT REVISION, NOT FLOATED (#2872). Docling resolves# its RapidOCR det/cls/rec files by a version-specific path table, so thediff --git a/packages/sie_server/scripts/generate_gliformer_goldens.py b/packages/sie_server/scripts/generate_gliformer_goldens.pynew file mode 100644index 000000000..01009cb6b--- /dev/null+++ b/packages/sie_server/scripts/generate_gliformer_goldens.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+"""Generate reference outputs for the GLiFormer adapter parity tests.++Companion to ``packages/sie_server/tests/adapters/test_gliformer_parity.py``.++The script runs the upstream ``gliformer`` package directly, with no SIE code+involved, over a fixed set of texts. Each case records the SIE ``extract``+request under test next to the GLiFormer call that request must translate to,+and stores the package's raw output for that call. The parity test sends the+recorded requests through the adapter and checks the results against these+outputs, with structured values passed through GLiFormer's own output+formatter as ``GLiFormer.structure`` does.++It downloads the pinned checkpoint and runs it in float32 on the CPU, in any+environment with the package installed (inside an activated virtual+environment, the command below runs on that environment's packages). The+output records the stack it ran on under ``generated_with``:++ uv run --no-project --python 3.12 --with gliformer==0.1.2 python \\+ packages/sie_server/scripts/generate_gliformer_goldens.py \\+ --model knowledgator/gliformer-base-v1 \\+ --revision 590f9d3f577ea2f6d685aaec84b2d66b6db86b15 \\+ --out packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-base-v1.json+"""++from __future__ import annotations++import argparse+import json+from importlib.metadata import version+from pathlib import Path+from typing import Any++import torch+from gliformer import GLiFormer+from huggingface_hub import snapshot_download++MAX_LENGTH = 2048+EMBEDDING_HEAD_DIMS = 32++TEXTS = [+ "Alice Johnson works at Acme Corp in London. She joined in March 2021 as a senior software engineer.",+ "Apple announced the iPhone 17 in Cupertino on Tuesday; Tim Cook called it the best phone ever made.",+ "The refund request from Maria Lopez for order 4471 was denied because the item was returned after 45 days.",+ "Dr. Maria Rossi prescribed 20 mg of atorvastatin to the patient at St. Mary's Hospital in Boston.",+]+ENTITY_TYPES = ["person", "organization", "location", "date", "product"]+RELATION_TYPES = ["works at", "located in", "chief executive of"]+DECISIONS = ["approved", "denied", "escalated"]+OUTPUT_SCHEMA = {+ "type": "object",+ "properties": {+ "customer": {"type": "string"},+ "order number": {"type": "string"},+ "decision": {"type": "string", "enum": DECISIONS},+ "reasons": {"type": "array", "items": {"type": "string"}},+ "people": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {"name": {"type": "string"}, "role": {"type": "string"}},+ },+ },+ },+}+# The structuring template and classification group ``OUTPUT_SCHEMA`` maps to.+SCHEMA_STRUCTURES = {+ "$root": {"customer": "str", "order number": "str", "reasons": ["str"], "people": [{"name": "str", "role": "str"}]}+}+SCHEMA_CLASSES = {"decision": DECISIONS}+JOINT_RELATIONS = {None: {"entities": ENTITY_TYPES, "relations": RELATION_TYPES}}+LABEL_GROUPS = {+ "sentiment": ["positive", "negative", "neutral"],+ "topic": ["business", "technology", "health", "customer support"],+}+NESTED_SCHEMA = {+ "type": "object",+ "properties": {+ "patient": {"type": "object", "properties": {"name": {"type": "string"}, "hospital": {"type": "string"}}},+ "medications": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {"drug": {"type": "string"}, "dose": {"type": "string"}},+ "required": ["drug"],+ },+ },+ "employer": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "location": {"type": "object", "properties": {"city": {"type": "string"}}},+ },+ },+ },+}+NESTED_STRUCTURES = {+ "$root": {+ "patient": {"name": "str", "hospital": "str"},+ "medications": [{"drug": "str", "dose": "str"}],+ "employer": {"name": "str", "location": {"city": "str"}},+ }+}+# Entity spans supplied through item metadata for relation extraction.+METADATA_SPANS = [+ [("Alice Johnson", "person"), ("Acme Corp", "organization"), ("London", "location")],+ [("Apple", "organization"), ("Cupertino", "location"), ("Tim Cook", "person")],+ [("Maria Lopez", "person")],+ [("Dr. Maria Rossi", "person"), ("St. Mary's Hospital", "organization"), ("Boston", "location")],+]+ITEM_METADATA = [+ {+ "entities": [+ {"text": span, "label": label, "start": text.index(span), "end": text.index(span) + len(span)}+ for span, label in spans+ ]+ }+ for text, spans in zip(TEXTS, METADATA_SPANS, strict=True)+]++# (name, SIE extract request, GLiFormer.inference keyword arguments)+CASES: list[tuple[str, dict[str, Any], dict[str, Any]]] = [+ ("entities", {"labels": ENTITY_TYPES}, {"entities": ENTITY_TYPES}),+ (+ "classification",+ {"labels": ["positive", "negative", "neutral"], "options": {"classification_task": "sentiment"}},+ {"classes": {"sentiment": ["positive", "negative", "neutral"]}},+ ),+ (+ "classification_multi_label",+ {+ "labels": ["business", "technology", "health", "customer support"],+ "options": {"classification_task": "topic", "multi_label": True, "threshold": 0.3},+ },+ {+ "classes": {"topic": ["business", "technology", "health", "customer support"]},+ "multi_label": True,+ "threshold": 0.3,+ },+ ),+ (+ "relations",+ {"labels": ENTITY_TYPES, "options": {"relation_labels": RELATION_TYPES}},+ {"joint_relations": JOINT_RELATIONS},+ ),+ ("output_schema", {"output_schema": OUTPUT_SCHEMA}, {"classes": SCHEMA_CLASSES, "structures": SCHEMA_STRUCTURES}),+ (+ "combined",+ {"labels": ENTITY_TYPES, "output_schema": OUTPUT_SCHEMA, "options": {"relation_labels": RELATION_TYPES}},+ {"classes": SCHEMA_CLASSES, "joint_relations": JOINT_RELATIONS, "structures": SCHEMA_STRUCTURES},+ ),+ (+ "label_groups",+ {"labels": ENTITY_TYPES, "options": {"label_groups": LABEL_GROUPS}},+ {"entities": ENTITY_TYPES, "classes": LABEL_GROUPS},+ ),+ ("nested_objects", {"output_schema": NESTED_SCHEMA}, {"structures": NESTED_STRUCTURES}),+ # Relations between supplied entities: one call per distinct entity-type+ # set, in sorted order, as the adapter batches them.+ ("metadata_entities", {"labels": RELATION_TYPES, "item_metadata": ITEM_METADATA}, {}),+]+++def _json_safe(kwargs: dict[str, Any]) -> dict[str, Any]:+ joint = kwargs.get("joint_relations")+ if joint is None:+ return kwargs+ return {**kwargs, "joint_relations": [{"name": name, **group} for name, group in joint.items()]}+++def _metadata_reference(model: Any, request: dict[str, Any]) -> tuple[list[dict[str, Any]], dict[str, list[Any]]]:+ """Joint relation calls grouped by each item's entity types."""+ groups: dict[tuple[str, ...], list[int]] = {}+ for index, metadata in enumerate(request["item_metadata"]):+ types = tuple(sorted({entity["label"] for entity in metadata["entities"]}))+ groups.setdefault(types, []).append(index)+ outputs: dict[str, list[Any]] = {"ner": [[] for _ in TEXTS], "joint_relex": [[] for _ in TEXTS]}+ calls = []+ for types, indices in groups.items():+ joint = {None: {"entities": list(types), "relations": request["labels"]}}+ result = model.inference(+ [TEXTS[index] for index in indices], joint_relations=joint, threshold=0.5, batch_size=len(indices)+ )+ for task, per_text in outputs.items():+ for index, value in zip(indices, result.get(task, [[] for _ in indices]), strict=True):+ per_text[index] = value+ calls.append({"texts": indices, **_json_safe({"joint_relations": joint, "threshold": 0.5})})+ return calls, outputs+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--model", required=True)+ parser.add_argument("--revision", required=True)+ parser.add_argument("--out", required=True, type=Path)+ args = parser.parse_args()++ torch.manual_seed(0)+ model_dir = snapshot_download(args.model, revision=args.revision, ignore_patterns=["*.gif"])+ model = GLiFormer.from_pretrained(model_dir, load_tokenizer=True, map_location="cpu", max_length=MAX_LENGTH)+ model = model.to(dtype=torch.float32).eval()++ cases = []+ with torch.inference_mode():+ for name, request, reference_kwargs in CASES:+ if "item_metadata" in request:+ calls, outputs = _metadata_reference(model, request)+ cases.append({"name": name, "request": request, "reference_calls": calls, "reference_output": outputs})+ continue+ call = {"threshold": 0.5, **reference_kwargs}+ outputs = model.inference(TEXTS, batch_size=len(TEXTS), **call)+ cases.append(+ {"name": name, "request": request, "reference_call": _json_safe(call), "reference_output": outputs}+ )+ embeddings = model.embed_text(TEXTS, batch_size=len(TEXTS)).float()+ unit = torch.nn.functional.normalize(embeddings, dim=-1)++ golden = {+ "model": args.model,+ "revision": args.revision,+ "generated_with": {+ "gliformer": version("gliformer"),+ "gliner": version("gliner"),+ "transformers": version("transformers"),+ "torch": version("torch"),+ "device": "cpu",+ "dtype": "float32",+ "max_length": MAX_LENGTH,+ },+ "texts": TEXTS,+ "cases": cases,+ "embeddings": {+ "dim": int(unit.shape[1]),+ "normalized_head": [[round(value, 6) for value in row[:EMBEDDING_HEAD_DIMS]] for row in unit.tolist()],+ "cosine": [[round(value, 6) for value in row] for row in (unit @ unit.T).tolist()],+ },+ }+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(json.dumps(golden, indent=1, ensure_ascii=False) + "\n")+ print(f"wrote {args.out}")+++if __name__ == "__main__":+ main()diff --git a/packages/sie_server/src/sie_server/adapters/gliformer/__init__.py b/packages/sie_server/src/sie_server/adapters/gliformer/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py b/packages/sie_server/src/sie_server/adapters/gliformer/adapter.pynew file mode 100644index 000000000..4af448f82--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py@@ -0,0 +1,1141 @@+"""Adapter for GLiFormer multi-task extraction and embedding models."""++from __future__ import annotations++import copy+import logging+import math+import threading+import warnings+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from numbers import Real+from pathlib import Path+from types import ModuleType+from typing import Any, ClassVar++import torch+import transformers+from huggingface_hub import snapshot_download+from transformers import Qwen3Config, Qwen3Model+from transformers.models.auto import modeling_auto++from sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters.gliformer.output_schema import (+ MAX_LABEL_CHARS,+ SchemaField,+ StructuredPlan,+ clip,+ compile_output_schema,+ shape_structured_output,+)+from sie_server.core.extract_cost import MAX_EXTRACT_LABELS+from sie_server.core.inference_output import EncodeOutput, ExtractItemError, ExtractOutput+from sie_server.types.inputs import InvalidInputError, Item+from sie_server.types.responses import Classification, Entity, ErrorCode, Relation++logger = logging.getLogger(__name__)++_ERR_REQUIRES_TASK = "GLiFormer requires labels, label_groups, or output_schema for extraction"+_ERR_BLANK_TEXT = "GLiFormer requires non-blank text"+_ERR_PROMPT_EXHAUSTS_DOCUMENT = "GLiFormer task prompt leaves no document tokens within max_sequence_length"+_ERR_MALFORMED = "GLiFormer returned malformed {output}"+_ERR_ITEM_OUTPUT = "GLiFormer returned malformed or non-finite output for this item"+_ERR_RELATIONS_OPTION = "GLiFormer takes relation types as options.relation_labels, not options.relations"++# The model repositories ship a multi-megabyte demo animation next to the weights.+_SNAPSHOT_IGNORE_PATTERNS = ["*.gif"]++# Lowest threshold for requests that decode spans (entities, relations,+# output_schema fields). GLiFormer's span decoder pairs every start above the+# threshold with every end above it in Python, so a near-zero threshold turns+# decoding quadratic in words x labels (seconds at a few hundred words); the+# relation head decodes its entities the same way. Classification decoding is+# a sigmoid and a filter per label, so classification-only requests accept any+# threshold.+_MIN_SPAN_THRESHOLD = 0.1+# GLiFormer's classification decoder reads a threshold of 0 as "unset" and+# falls back to 0.5, so 0 is passed on as the smallest positive threshold.+_MIN_DECODER_THRESHOLD = 1e-6++# Padded prompt + document tokens per forward pass. Eager DeBERTa attention is+# quadratic in the sequence length, so a request is split into chunks whose+# padded size stays within this budget.+_DEFAULT_INFERENCE_BATCH_TOKENS = 16384++# Model outputs that the decoders turn into scores. Masked positions hold -inf.+_SCORE_OUTPUT_SUFFIXES = ("_logits", "_scores")++# Tokens the task prompt (labels, relation types, class labels, schema fields)+# may take. The prompt is not billed, so this bounds how much unbilled work a+# request can attach to each document: at most (512 + d) / d times the billed+# d document tokens, about 172x for a one-word document (d = 3 with the two+# special tokens).+_DEFAULT_MAX_PROMPT_TOKENS = 512++# Joint relation extraction scores every ordered pair of the entities it keeps,+# through a projection four times the hidden width. Keep the most confident 100+# entities per document (as the GLiNER relation adapter does) and at most+# 131072 candidate pairs per forward pass, about 2.4 GB of pair activations for+# the large model in float16.+_MAX_RELATION_ENTITIES = 100+_RELATION_PAIR_BUDGET = 131072+# The package decodes relations cell by cell over pairs x relation types.+_MAX_RELATION_TYPES = 20++# Entity spans a caller may supply per item for relation extraction.+_MAX_SUPPLIED_ENTITIES = MAX_EXTRACT_LABELS+# Distinct entity-type sets across a request's supplied entities. Each one is+# its own task prompt and its own forward passes.+_MAX_TYPE_GROUPS = 64++# Marks an item whose model output could not be used.+_ITEM_ERROR = "__gliformer_item_error__"++_IMPORT_LOCK = threading.Lock()+++def _import_gliformer() -> ModuleType:+ """Import the ``gliformer`` package without its Auto-class side effects.++ Importing ``gliformer`` registers its bidirectional Qwen3 backbones as the+ ``AutoModel`` implementation for transformers' own Qwen3 configs. That+ registration is process-wide, so any other model loaded through+ ``AutoModel`` in the same worker would silently get the wrong architecture.+ GLiFormer resolves its backbones through its own registry, so only the+ registrations for configs that are new to transformers are kept.+ """+ with _IMPORT_LOCK:+ import gliformer # ty:ignore[unresolved-import]++ _drop_builtin_auto_model_overrides()+ return gliformer+++def _drop_builtin_auto_model_overrides() -> None:+ """Remove gliformer's ``AutoModel`` overrides of built-in configs, or fail.++ Raises:+ RuntimeError: The registrations cannot be inspected on this+ transformers version, or a built-in config still resolves to a+ gliformer class afterwards.+ """+ mapping = modeling_auto.MODEL_MAPPING+ registered = getattr(mapping, "_extra_content", None)+ reverse_config = getattr(mapping, "_reverse_config_mapping", None)+ builtin_models = getattr(mapping, "_model_mapping", None)+ if not isinstance(registered, dict) or not isinstance(reverse_config, Mapping) or builtin_models is None:+ raise RuntimeError("Cannot inspect the AutoModel registrations made by gliformer on this transformers version")+ overridden = [+ config_class+ for config_class, model_class in registered.items()+ if getattr(model_class, "__module__", "").startswith("gliformer.")+ and reverse_config.get(getattr(config_class, "__name__", "")) in builtin_models+ ]+ for config_class in overridden:+ del registered[config_class]++ expected = [(Qwen3Config, Qwen3Model)]+ qwen3_5_config = getattr(transformers, "Qwen3_5Config", None)+ qwen3_5_model = getattr(transformers, "Qwen3_5Model", None)+ if qwen3_5_config is not None and qwen3_5_model is not None:+ expected.append((qwen3_5_config, qwen3_5_model))+ for config_class, model_class in expected:+ if mapping[config_class] is not model_class:+ raise RuntimeError(f"AutoModel for {config_class.__name__} no longer resolves to {model_class.__name__}")+ for config_class in overridden:+ if getattr(mapping[config_class], "__module__", "").startswith("gliformer."):+ raise RuntimeError(f"AutoModel for {config_class.__name__} still resolves to a gliformer class")+++class _NonFiniteScoresError(RuntimeError):+ """The model produced NaN or +inf scores for at least one document in a pass."""+++def _upcast_score_outputs(_module: torch.nn.Module, _args: Any, output: Any) -> Any:+ """Forward hook: decode scores in float32 from host memory; reject NaN or +inf.++ The decoders apply a sigmoid to these logits. In float16 every logit+ above about 8.3 rounds to 1.0, which turns single-label classification+ into "first label wins". Upcasting before decoding keeps the ranking.+ A NaN would otherwise fail every threshold comparison and silently drop+ predictions. The decoders read span and relation scores one element at a+ time, so outputs are copied to host memory once, as on CPU inference,+ instead of synchronizing with the device for every element.+ """+ if not isinstance(output, Mapping):+ return output+ flags = []+ for key in list(output.keys()):+ value = output[key]+ if not (isinstance(key, str) and key.endswith(_SCORE_OUTPUT_SUFFIXES)):+ continue+ if not isinstance(value, torch.Tensor) or not value.is_floating_point():+ continue+ if value.dtype != torch.float32:+ value = value.float()+ output[key] = value+ flags.append(torch.isnan(value).any() | torch.isposinf(value).any())+ if flags and bool(torch.stack(flags).any()):+ raise _NonFiniteScoresError("GLiFormer produced non-finite scores")+ for key in list(output.keys()):+ value = output[key]+ if isinstance(value, torch.Tensor):+ output[key] = value.cpu()+ return output+++class GLiFormerAdapter(BaseAdapter):+ """Adapter for GLiFormer checkpoints (``gliformer`` pip package).++ One GLiFormer prompt carries every task in a request, so a single+ ``extract`` call can combine:++ - named entity recognition over ``labels``;+ - joint relation extraction with ``options["relation_labels"]`` (relation+ types, with ``labels`` as the entity types, as in the GLiNER adapter);+ - classification of ``labels`` under ``options["classification_task"]``;+ - several named classification questions with ``options["label_groups"]``,+ reported as ``"group.label"`` classifications like the GLiClass adapter+ (GLiFormer scores only the labels that pass the threshold, so no+ per-group distribution is returned in ``data``);+ - structured extraction into ``output_schema``: span-valued properties+ are filled by the structuring head (nested objects and record arrays+ included) and root string ``enum`` properties by classification groups.++ For compatibility with the other relation extractors, items whose+ ``metadata["entities"]`` carry entity spans switch ``labels`` to relation+ types, and relations are reported only between the supplied entities.++ ``options["threshold"]`` (default 0.5) applies to every task in the+ request. Requests that extract entities, relations, or span-valued+ ``output_schema`` fields need at least 0.1: below that, GLiFormer's span+ decoding grows quadratically with the document and label count.+ Classification-only requests (``classification_task``, ``label_groups``,+ or an ``output_schema`` of root enums only) accept any threshold from 0,+ where every question gets its best answer.++ ``options["relation_threshold"]`` raises the minimum score for relations+ only. GLiFormer decodes entities and relations with one threshold, so it+ cannot be lower than ``threshold``.++ Relations are scored among the 100 most confident entities of each+ document; pairs involving other entities are not reported. A request may+ ask for at most 20 relation types. Supplied ``metadata.entities`` may use+ at most 64 distinct sets of entity labels per request.++ Structured output follows GLiFormer's own formatting: a string property+ keeps the best of several extracted values, and array-of-string values+ are split on commas. A root ``required`` property that the model did not+ extract becomes a per-item error (GLiNER2 rejects the whole request),+ so the rest of the batch still completes. Malformed or non-finite model+ output for one document is also a per-item error. An errored item+ returns no entities, relations, classifications, or data.++ Billed input tokens are the document subwords that survive truncation;+ errored items bill nothing. The task prompt (labels, relation types,+ schema fields) is not billed, matching the GLiNER family, so it is+ bounded instead: labels, field names, and choices have at most 128+ characters, a request carries at most 1000 of them, and the prompt takes+ at most ``max_prompt_tokens`` (default 512) tokens.++ ``encode`` returns the checkpoint's text embedding head output.++ Reference models:+ - knowledgator/gliformer-base-v1+ - knowledgator/gliformer-large-v1+ """++ spec: ClassVar[AdapterSpec] = AdapterSpec(+ inputs=("text",),+ outputs=("json", "dense"),+ unload_fields=("_model", "_tokenizer", "_normalize_structures", "_build_formatter"),+ )++ def __init__(+ self,+ model_name_or_path: str | Path,+ *,+ threshold: float = 0.5,+ flat_ner: bool = True,+ multi_label: bool = False,+ normalize: bool = True,+ max_seq_length: int | None = None,+ inference_batch_tokens: int = _DEFAULT_INFERENCE_BATCH_TOKENS,+ max_prompt_tokens: int = _DEFAULT_MAX_PROMPT_TOKENS,+ compute_precision: ComputePrecision = "float16",+ revision: str | None = None,+ dense_dim: int | None = None,+ **kwargs: Any,+ ) -> None:+ """Initialize the adapter.++ Args:+ model_name_or_path: HuggingFace model ID or local path.+ threshold: Minimum confidence for every task, from 0 to 1 (at least+ 0.1 for requests that extract entities, relations, or+ output_schema fields).+ flat_ner: Keep entity spans non-overlapping.+ multi_label: Allow several labels per span and per classification.+ normalize: L2-normalize ``encode`` embeddings.+ max_seq_length: Token budget shared by the task prompt and the+ document; longer documents are truncated.+ inference_batch_tokens: Padded tokens per forward pass (prompt ++ document for ``extract``); larger requests are split into+ chunks, for ``encode`` too.+ max_prompt_tokens: Most tokens the unbilled task prompt may take.+ compute_precision: Accelerator weight precision. Scores are always+ decoded in float32. CPU runs float32.+ revision: HuggingFace revision to pin when downloading artifacts.+ dense_dim: Catalog-declared embedding dimension, checked at load.+ **kwargs: Additional arguments (ignored, for compatibility).+ """+ _ = kwargs+ for name, value in (+ ("inference_batch_tokens", inference_batch_tokens),+ ("max_prompt_tokens", max_prompt_tokens),+ ):+ if not _is_int(value) or value <= 0:+ raise ValueError(f"GLiFormer {name} must be a positive integer")+ self._model_name_or_path = str(model_name_or_path)+ self._threshold = _validate_threshold(threshold)+ self._flat_ner = _validate_flag(flat_ner, "flat_ner")+ self._multi_label = _validate_flag(multi_label, "multi_label")+ self._normalize = _validate_flag(normalize, "normalize")+ self._max_seq_length = max_seq_length+ self._inference_batch_tokens = inference_batch_tokens+ self._max_prompt_tokens = max_prompt_tokens+ self._compute_precision = compute_precision+ self._revision = revision+ self._dense_dim = dense_dim++ self._model: Any = None+ self._tokenizer: Any = None+ self._normalize_structures: Callable[[Any], Any] | None = None+ self._build_formatter: Callable[[Any], Any] | None = None+ self._device: str | None = None++ def load(self, device: str) -> None:+ """Load the checkpoint onto ``device``."""+ gliformer = _import_gliformer()++ model_path = self._model_name_or_path+ if not Path(model_path).is_dir():+ model_path = snapshot_download(+ repo_id=model_path,+ revision=self._revision,+ ignore_patterns=_SNAPSHOT_IGNORE_PATTERNS,+ )++ with warnings.catch_warnings():+ # The checkpoints request the optional flashdeberta kernels. Without+ # them GLiFormer uses its eager attention, which is what SIE serves.+ warnings.filterwarnings("ignore", message=".*flashdeberta.*")+ model = gliformer.GLiFormer.from_pretrained(+ str(model_path),+ load_tokenizer=True,+ map_location="cpu",+ max_length=self._max_seq_length,+ )++ # Reduced precision only pays off on accelerators; CPU keeps the+ # reference float32 numerics.+ dtype = torch.float32 if device == "cpu" else self._resolve_dtype()+ model.to(device=device, dtype=dtype)+ model.eval()+ model.model.register_forward_hook(_upcast_score_outputs)+ _limit_relation_entities(model.model)++ embedding_config = getattr(model.config, "embedding_config", None)+ embedding_dim = getattr(embedding_config, "projection_dim", None)+ if self._dense_dim is not None and embedding_dim != self._dense_dim:+ raise ValueError(+ f"GLiFormer embedding dimension mismatch: configured dense_dim={self._dense_dim}, "+ f"checkpoint projection_dim={embedding_dim}"+ )++ tokenizer = model.data_processor.transformer_tokenizer+ # ``embed_text`` truncates at the tokenizer limit, which the saved+ # tokenizer leaves unbounded; share the extraction budget instead.+ tokenizer.model_max_length = int(model.config.max_len)++ self._model = model+ self._tokenizer = tokenizer+ self._normalize_structures = gliformer.processing.schema.normalize_structuring_schemas+ self._build_formatter = gliformer.processing.schema.build_structuring_output_formatter+ self._device = device++ def extract(+ self,+ items: list[Item],+ *,+ labels: list[str] | None = None,+ output_schema: dict[str, Any] | None = None,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ prepared_items: list[Any] | None = None,+ ) -> ExtractOutput:+ """Run every requested GLiFormer task over ``items`` in one prompt."""+ _ = instruction, prepared_items+ self._check_loaded()+ texts = [self._extract_text(item) for item in items]+ opts = options or {}+ if "relations" in opts:+ raise InvalidInputError(_ERR_RELATIONS_OPTION)+ threshold = _validate_threshold(opts.get("threshold", self._threshold))+ relation_threshold = opts.get("relation_threshold")+ if relation_threshold is not None:+ relation_threshold = _validate_threshold(relation_threshold, "relation_threshold")+ relation_labels = opts.get("relation_labels")+ flat_ner = _validate_flag(opts.get("flat_ner", self._flat_ner), "flat_ner")+ multi_label = _resolve_multi_label(opts, default=self._multi_label)+ request = _plan_request(+ labels=_validate_labels(labels, "labels") if labels else None,+ plan=compile_output_schema(output_schema) if output_schema is not None else None,+ classification_task=_validate_task(opts.get("classification_task")),+ label_groups=_validate_label_groups(opts.get("label_groups")),+ # An empty list asks for no relations, as in the GLiNER adapter.+ relation_types=(+ None if relation_labels in (None, []) else _validate_labels(relation_labels, "relation_labels")+ ),+ supplied_entities=self._supplied_relation_entities(items),+ relation_threshold=relation_threshold,+ )+ if request.decodes_spans and threshold < _MIN_SPAN_THRESHOLD:+ raise InvalidInputError(+ f"GLiFormer threshold must be at least {_MIN_SPAN_THRESHOLD} when extracting entities, relations, "+ "or output_schema fields; classification-only requests accept any threshold"+ )+ threshold = max(threshold, _MIN_DECODER_THRESHOLD)+ max_items = None+ if request.relations_requested:+ if len(request.relation_types or []) > _MAX_RELATION_TYPES:+ raise InvalidInputError(+ f"GLiFormer relation extraction accepts at most {_MAX_RELATION_TYPES} relation types"+ )+ if relation_threshold is not None and relation_threshold < threshold:+ raise InvalidInputError(+ "GLiFormer relation_threshold must be at least threshold: entities and relations are "+ "decoded with one threshold, so relation_threshold can only raise it for relations"+ )+ max_items = max(1, _RELATION_PAIR_BUDGET // (_MAX_RELATION_ENTITIES * (_MAX_RELATION_ENTITIES - 1)))++ # Items are grouped by their entity types: relation extraction over+ # supplied entities prompts each item with the types it carries, in a+ # canonical order so that label order alone never adds a group.+ batches: dict[tuple[str, ...], list[int]] = {}+ for index in range(len(items)):+ types = (+ tuple(sorted({entity["label"] for entity in request.supplied_entities[index]}))+ if request.supplied_entities is not None+ else tuple(request.entity_types or ())+ )+ batches.setdefault(types, []).append(index)+ if len(batches) > _MAX_TYPE_GROUPS:+ raise InvalidInputError(+ f"GLiFormer item metadata may use at most {_MAX_TYPE_GROUPS} distinct sets of entity labels "+ "per request"+ )+ task_kwargs = {types: request.task_kwargs(list(types) if types else None) for types in batches}++ with self._tokenizer_guard():+ # Every group's prompt is built and measured before any per-item+ # work, so an over-budget request is rejected cheaply and before+ # any inference has run.+ prompt_tokens = {types: self._prompt_tokens(kwargs) for types, kwargs in task_kwargs.items()}+ document_tokens = self._document_tokens(texts)+ specials = int(self._tokenizer.num_special_tokens_to_add(pair=False))+ window = int(self._model.config.max_len)+ counts = [0] * len(items)+ lengths = [0] * len(items)+ for types, indices in batches.items():+ room = window - specials - prompt_tokens[types]+ for index in indices:+ counts[index] = min(document_tokens[index], room) + specials+ lengths[index] = prompt_tokens[types] + counts[index]++ raw_results: list[dict[str, Any]] = [{} for _ in items]+ structures = request.plan.structures if request.plan is not None else None+ for types, indices in batches.items():+ rows = self._run(+ [texts[index] for index in indices],+ task_kwargs[types],+ [lengths[index] for index in indices],+ structures=structures,+ threshold=threshold,+ flat_ner=flat_ner,+ multi_label=multi_label,+ max_items=max_items,+ )+ for index, row in zip(indices, rows, strict=True):+ raw_results[index] = row++ return _assemble_output(texts, raw_results, request, input_token_counts=counts)++ def encode(+ self,+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ prepared_items: list[Any] | None = None,+ options: dict[str, Any] | None = None,+ ) -> EncodeOutput:+ """Embed ``items`` with the checkpoint's embedding head."""+ _ = instruction, prepared_items+ self._check_loaded()+ unsupported = sorted(set(output_types) - {"dense"})+ if unsupported or "dense" not in output_types:+ raise InvalidInputError(+ f"GLiFormer encode supports only dense output, got {clip(str(sorted(output_types)))}"+ )+ texts = [self._extract_text(item) for item in items]+ normalize = _validate_flag((options or {}).get("normalize", self._normalize), "normalize")++ with self._tokenizer_guard():+ counts = [len(ids) for ids in self._tokenizer(texts, truncation=True)["input_ids"]]+ parts = []+ for chunk in _token_budget_chunks(counts, self._inference_batch_tokens):+ with torch.inference_mode():+ parts.append(self._model.embed_text([texts[i] for i in chunk], batch_size=len(chunk)).float())+ embeddings = torch.cat(parts)+ if not bool(torch.isfinite(embeddings).all()):+ raise RuntimeError("GLiFormer produced non-finite embeddings")+ if normalize:+ embeddings = torch.nn.functional.normalize(embeddings, dim=-1)+ dense = embeddings.numpy()+ output = EncodeOutput(dense=dense, batch_size=len(items), is_query=is_query, dense_dim=dense.shape[1])+ output.extra["input_token_counts"] = counts+ return output++ def _run(+ self,+ texts: list[str],+ task_kwargs: dict[str, Any],+ lengths: list[int],+ *,+ structures: dict[str, Any] | None,+ threshold: float,+ flat_ner: bool,+ multi_label: bool,+ max_items: int | None,+ ) -> list[dict[str, Any]]:+ """Run ``GLiFormer.inference`` in bounded chunks; one raw result per text."""+ formatter = self._build_formatter(structures) if structures and self._build_formatter else None+ rows: list[dict[str, Any]] = [{} for _ in texts]+ with self._tokenizer_guard():+ for chunk in _token_budget_chunks(lengths, self._inference_batch_tokens, max_items=max_items):+ chunk_rows = self._infer(+ texts,+ chunk,+ task_kwargs,+ threshold=threshold,+ flat_ner=flat_ner,+ multi_label=multi_label,+ )+ for index, row in zip(chunk, chunk_rows, strict=True):+ rows[index] = _format_row(row, formatter)+ return rows++ def _infer(+ self,+ texts: list[str],+ chunk: list[int],+ task_kwargs: dict[str, Any],+ **inference_kwargs: Any,+ ) -> list[dict[str, Any]]:+ """Run ``chunk``, isolating documents whose scores are non-finite.++ A non-finite score fails the whole pass. The chunk is then split in+ halves, following only the failing half, until the failing document+ runs alone: about 2 log2(n) extra passes for one bad document in n.+ When both halves fail, the failures are spread out, so each document+ is tried alone instead: at most n + 3 passes in all.+ """++ def attempt(part: list[int]) -> list[dict[str, Any]] | None:+ return self._forward(texts, part, task_kwargs, **inference_kwargs)++ def isolate(part: list[int]) -> list[dict[str, Any]]:+ if len(part) == 1:+ return [{_ITEM_ERROR: True}]+ middle = len(part) // 2+ left, right = part[:middle], part[middle:]+ left_rows, right_rows = attempt(left), attempt(right)+ if left_rows is None and right_rows is None:+ return [row for index in part for row in attempt([index]) or [{_ITEM_ERROR: True}]]+ return [*(left_rows or isolate(left)), *(right_rows or isolate(right))]++ rows = attempt(chunk)+ return rows if rows is not None else isolate(chunk)++ def _forward(+ self,+ texts: list[str],+ chunk: list[int],+ task_kwargs: dict[str, Any],+ **inference_kwargs: Any,+ ) -> list[dict[str, Any]] | None:+ """One forward pass; ``None`` when it produced non-finite scores."""+ try:+ with torch.inference_mode():+ results = self._model.inference(+ [texts[index] for index in chunk],+ **task_kwargs,+ **inference_kwargs,+ batch_size=len(chunk),+ )+ except _NonFiniteScoresError:+ return None+ rows: list[dict[str, Any]] = [{} for _ in chunk]+ for task_name in ("ner", "classification", "joint_relex", "structuring"):+ task_results = results.get(task_name)+ if task_results is None:+ continue+ if not isinstance(task_results, list) or len(task_results) != len(chunk):+ raise RuntimeError(_ERR_MALFORMED.format(output=task_name))+ for row, value in zip(rows, task_results, strict=True):+ row[task_name] = value+ return rows++ def _prompt_tokens(self, task_kwargs: dict[str, Any]) -> int:+ """Build one task prompt with the package's processor and count its tokens.++ GLiFormer prepends the same prompt to every document of a task group+ and truncates the combined sequence to ``max_len``, so the prompt is+ measured once per group, not per document.++ Raises:+ InvalidInputError: The prompt exceeds ``max_prompt_tokens`` or+ leaves no room for a document.+ RuntimeError: The package's processor could not build the prompt.+ """+ model = self._model+ processor = model.data_processor+ try:+ kwargs = copy.deepcopy(task_kwargs)+ if kwargs.get("structures") is not None:+ # ``inference`` compiles templates into the processor's wire form first.+ if self._normalize_structures is None:+ raise RuntimeError("structuring templates cannot be normalized")+ kwargs["structures"] = self._normalize_structures(kwargs["structures"])+ raw_batch = processor.collate_raw_batch(model._build_inference_input([["x"]], **kwargs))+ sequences, prompt_lengths = processor.prepare_inputs(raw_batch["tokens"], raw_batch["classes_mapping"])+ prompt_words = list(sequences[0][: prompt_lengths[0]])+ encoded = processor.transformer_tokenizer(+ [prompt_words], is_split_into_words=True, add_special_tokens=False+ )+ count = len(encoded["input_ids"][0])+ except Exception as exc:+ raise RuntimeError("GLiFormer could not build the task prompt") from exc+ if count > self._max_prompt_tokens:+ raise InvalidInputError(+ f"GLiFormer task prompt needs {count} tokens; labels, relation types, class labels, and "+ f"schema fields may take at most {self._max_prompt_tokens}"+ )+ specials = int(processor.transformer_tokenizer.num_special_tokens_to_add(pair=False))+ if count + specials >= int(model.config.max_len):+ raise InvalidInputError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)+ return count++ def _document_tokens(self, texts: list[str]) -> list[int]:+ """Document subwords per text before the prompt's share of the window.++ Words are tokenized independently of each other, so the document's+ tokens are the same with or without the prompt in front of it.+ """+ model = self._model+ max_words = int(model.config.max_len)+ words, _, _ = model.prepare_inputs(texts)+ encoded = model.data_processor.transformer_tokenizer(+ [list(text_words[:max_words]) for text_words in words],+ is_split_into_words=True,+ add_special_tokens=False,+ )+ return [len(ids) for ids in encoded["input_ids"]]++ def _extract_text(self, item: Item) -> str:+ if item.text is None:+ raise InvalidInputError(ERR_REQUIRES_TEXT.format(adapter_name="GLiFormer adapter"))+ if not item.text.strip():+ raise InvalidInputError(_ERR_BLANK_TEXT)+ return item.text++ @staticmethod+ def _supplied_relation_entities(items: list[Item]) -> list[list[Entity]] | None:+ """Return per-item entities from ``metadata["entities"]``, if supplied."""+ supplied = [item.metadata.get("entities") if item.metadata else None for item in items]+ if all(entities is None for entities in supplied):+ return None+ if not all(isinstance(entities, list) and entities for entities in supplied):+ raise InvalidInputError("GLiFormer relation extraction requires non-empty entities in every item metadata")+ if any(len(entities or []) > _MAX_SUPPLIED_ENTITIES for entities in supplied):+ raise InvalidInputError(f"GLiFormer item metadata may carry at most {_MAX_SUPPLIED_ENTITIES} entities")+ return [+ [_normalize_input_entity(item.text or "", entity) for entity in entities or []]+ for item, entities in zip(items, supplied, strict=True)+ ]+++def _limit_relation_entities(model: Any) -> None:+ """Keep only the most confident entities as relation candidates.++ The package ranks the decoded entities and slices the kept ones into+ compact tensors before it builds entity pairs, so the pair tensors never+ grow past this many entities per document.+ """+ heads = getattr(model, "heads", None)+ if heads is None or "joint_relex" not in heads:+ raise RuntimeError("GLiFormer checkpoint has no joint relation head to bound")+ head = heads["joint_relex"]+ current = getattr(head, "max_relation_entities", None)+ head.max_relation_entities = _MAX_RELATION_ENTITIES if current is None else min(current, _MAX_RELATION_ENTITIES)+++def _format_row(row: dict[str, Any], formatter: Any) -> dict[str, Any]:+ """Apply GLiFormer's typed output formatting, as ``GLiFormer.structure`` does.++ ``inference`` returns raw decoder values: a scalar field for which+ several spans were found holds all of them, best first. The formatter+ keeps the best value for scalar fields and normalizes list fields.+ """+ if formatter is None or "structuring" not in row or _ITEM_ERROR in row:+ return row+ try:+ return {**row, "structuring": formatter.format_batch([row["structuring"]])[0]}+ except Exception: # noqa: BLE001 -- one document's output must not fail the batch+ logger.warning("GLiFormer structured output could not be formatted", exc_info=True)+ return {_ITEM_ERROR: True}+++def _token_budget_chunks(lengths: list[int], budget: int, max_items: int | None = None) -> list[list[int]]:+ """Split positions into in-order chunks whose padded size fits ``budget``.++ A chunk is padded to its longest sequence, so its cost is+ ``len(chunk) * max(length)``. A single sequence longer than the budget+ runs alone. ``max_items`` additionally caps the documents per chunk.+ """+ chunks: list[list[int]] = []+ current: list[int] = []+ longest = 0+ for index, length in enumerate(lengths):+ full = max_items is not None and len(current) >= max_items+ if current and (full or (len(current) + 1) * max(longest, length) > budget):+ chunks.append(current)+ current, longest = [], 0+ current.append(index)+ longest = max(longest, length)+ if current:+ chunks.append(current)+ return chunks+++@dataclass(frozen=True)+class _RequestPlan:+ """How one extract request maps onto GLiFormer's task heads."""++ entity_types: list[str] | None+ relation_types: list[str] | None+ classes: dict[str, list[str]]+ classification_task: str | None+ label_groups: dict[str, list[str]] | None+ plan: StructuredPlan | None+ supplied_entities: list[list[Entity]] | None+ relation_threshold: float | None++ @property+ def relations_requested(self) -> bool:+ return self.relation_types is not None++ @property+ def decodes_spans(self) -> bool:+ """Whether any task decodes text spans (everything but classification)."""+ return (+ self.entity_types is not None+ or self.relations_requested+ or (self.plan is not None and self.plan.structures is not None)+ )++ def task_kwargs(self, entity_types: list[str] | None) -> dict[str, Any]:+ """``GLiFormer.inference`` task arguments for one entity-type group."""+ kwargs: dict[str, Any] = {+ "entities": None,+ "classes": self.classes or None,+ "joint_relations": None,+ "structures": self.plan.structures if self.plan is not None else None,+ }+ if self.relation_types is not None:+ # An unnamed group shares the plain NER prompt, so the joint head+ # returns the entity spans and the relations between them.+ kwargs["joint_relations"] = {None: {"entities": entity_types, "relations": self.relation_types}}+ else:+ kwargs["entities"] = entity_types+ return kwargs+++def _plan_request(+ *,+ labels: list[str] | None,+ plan: StructuredPlan | None,+ classification_task: str | None,+ label_groups: dict[str, list[str]] | None,+ relation_types: list[str] | None,+ supplied_entities: list[list[Entity]] | None,+ relation_threshold: float | None,+) -> _RequestPlan:+ """Resolve what ``labels`` mean and which classification groups to run.++ ``labels`` are entity types unless ``classification_task`` makes them+ class labels or supplied ``metadata.entities`` make them relation types.+ """+ classes: dict[str, list[str]] = {}+ if classification_task is not None:+ if labels is None:+ raise InvalidInputError("GLiFormer classification_task requires labels")+ if label_groups is not None:+ raise InvalidInputError("GLiFormer label_groups cannot be combined with classification_task")+ classes[classification_task] = labels+ if label_groups is not None:+ if plan is not None:+ raise InvalidInputError(+ "GLiFormer label_groups cannot be combined with output_schema; declare enum properties instead"+ )+ classes.update(label_groups)+ if plan is not None:+ for name, choices in plan.choice_groups.items():+ if name in classes:+ raise InvalidInputError(+ "GLiFormer classification_task must differ from output_schema enum property names"+ )+ classes[name] = choices++ entity_types: list[str] | None = None+ if supplied_entities is not None:+ if classification_task is not None or relation_types is not None:+ raise InvalidInputError(+ "GLiFormer item metadata.entities cannot be combined with classification_task or relation_labels"+ )+ if labels is None:+ raise InvalidInputError("GLiFormer relation extraction requires relation labels")+ relation_types = labels+ elif classification_task is None:+ entity_types = labels+ if relation_types is not None and entity_types is None:+ raise InvalidInputError("GLiFormer relation_labels require labels as entity types")+ elif relation_types is not None:+ raise InvalidInputError("GLiFormer relation_labels cannot be combined with classification_task")+ if entity_types is None and supplied_entities is None and not classes and plan is None:+ raise InvalidInputError(_ERR_REQUIRES_TASK)++ # Everything that becomes prompt text counts against one budget,+ # including the entity types carried by supplied entities.+ prompt_labels = (+ len(entity_types or [])+ + len(relation_types or [])+ + sum(len(group) + 1 for group in classes.values())+ + (_schema_field_count(plan.root) if plan is not None else 0)+ + len({entity["label"] for entities in supplied_entities or [] for entity in entities})+ )+ if prompt_labels > MAX_EXTRACT_LABELS:+ raise InvalidInputError(+ f"GLiFormer requests may carry at most {MAX_EXTRACT_LABELS} labels, relation types, class labels, "+ "and schema fields in total"+ )+ return _RequestPlan(+ entity_types=entity_types,+ relation_types=relation_types,+ classes=classes,+ classification_task=classification_task,+ label_groups=label_groups,+ plan=plan,+ supplied_entities=supplied_entities,+ relation_threshold=relation_threshold,+ )+++def _schema_field_count(node: SchemaField) -> int:+ return sum(1 + _schema_field_count(child) for _, child in node.properties if child.kind != "choice")+++def _assemble_output(+ texts: list[str],+ raw_results: list[dict[str, Any]],+ request: _RequestPlan,+ *,+ input_token_counts: list[int],+) -> ExtractOutput:+ """Map raw results to SIE fields. Errored items get empty results and bill 0."""+ plan = request.plan+ classified = request.classification_task is not None or request.label_groups is not None+ all_entities: list[list[Entity]] = []+ all_classifications: list[list[Classification]] = []+ all_relations: list[list[Relation]] = []+ all_data: list[dict[str, Any]] = []+ errors: list[ExtractItemError | None] = []+ counts = list(input_token_counts)++ for index, (text, raw) in enumerate(zip(texts, raw_results, strict=True)):+ try:+ if _ITEM_ERROR in raw:+ raise RuntimeError(_ERR_ITEM_OUTPUT)+ entities, relations, classifications, data, error = _assemble_item(text, raw, request, index)+ except RuntimeError as exc:+ logger.warning("GLiFormer output for one item could not be used: %s", exc)+ entities, relations, classifications, data = [], [], [], {}+ error = ExtractItemError(code=ErrorCode.INFERENCE_ERROR.value, message=_ERR_ITEM_OUTPUT)+ if error is not None:+ # An errored item returns nothing and bills nothing.+ entities, relations, classifications, data = [], [], [], {}+ counts[index] = 0+ all_entities.append(entities)+ all_relations.append(relations)+ if classified:+ all_classifications.append(classifications)+ if plan is not None:+ all_data.append(data)+ errors.append(error)++ return ExtractOutput(+ entities=all_entities,+ classifications=all_classifications if classified else None,+ relations=all_relations if request.relations_requested else None,+ data=all_data if plan is not None else None,+ errors=errors if any(error is not None for error in errors) else None,+ input_token_counts=counts,+ )+++def _assemble_item(+ text: str,+ raw: dict[str, Any],+ request: _RequestPlan,+ index: int,+) -> tuple[list[Entity], list[Relation], list[Classification], dict[str, Any], ExtractItemError | None]:+ """One document's SIE fields; raises RuntimeError on malformed model output."""+ if request.supplied_entities is not None:+ entities = request.supplied_entities[index]+ allowed_endpoints: set[str] | None = {entity["text"] for entity in entities}+ else:+ entities = _to_entities(text, raw.get("ner", []))+ allowed_endpoints = None+ relations = _to_relations(raw.get("joint_relex", []), allowed_endpoints, request.relation_threshold)++ groups = _classification_groups(raw.get("classification"), request.classes)+ classifications: list[Classification] = []+ if request.classification_task is not None:+ classifications = groups[request.classification_task]+ if request.label_groups is not None:+ # Same "group.label" naming as the GLiClass adapter's label groups.+ flattened = [+ Classification(label=f"{name}.{prediction['label']}", score=prediction["score"])+ for name in request.label_groups+ for prediction in groups[name]+ ]+ classifications = sorted(flattened, key=lambda item: item["score"], reverse=True)++ data: dict[str, Any] = {}+ error: ExtractItemError | None = None+ plan = request.plan+ if plan is not None:+ choices = {name: groups[name][0]["label"] for name in plan.choice_groups if groups[name]}+ data, missing = shape_structured_output(+ plan,+ raw.get("structuring", {}) if plan.structures is not None else None,+ choices,+ )+ if missing:+ data = {}+ error = ExtractItemError(+ code=ErrorCode.INFERENCE_ERROR.value,+ message=f"GLiFormer did not extract required output_schema properties: {clip(str(missing))}",+ )+ return entities, relations, classifications, data, error+++def _normalize_input_entity(text: str, entity: Any) -> Entity:+ if not isinstance(entity, dict):+ raise InvalidInputError("GLiFormer relation entities must be objects")+ start = entity.get("start")+ end = entity.get("end")+ entity_text = entity.get("text")+ label = entity.get("label", "ENTITY")+ if (+ not _is_int(start)+ or not _is_int(end)+ or not isinstance(entity_text, str)+ or not isinstance(label, str)+ or not label.strip()+ or not 0 <= start < end <= len(text)+ or text[start:end] != entity_text+ ):+ raise InvalidInputError("GLiFormer relation entities require valid character offsets")+ if len(label.strip()) > MAX_LABEL_CHARS:+ raise InvalidInputError(f"GLiFormer relation entity labels may have at most {MAX_LABEL_CHARS} characters")+ score = entity.get("score", 1.0)+ # The range check comes first: math.isfinite cannot convert a huge integer.+ if isinstance(score, bool) or not isinstance(score, Real) or not 0 <= score <= 1 or not math.isfinite(score):+ raise InvalidInputError("GLiFormer relation entity score must be a number between 0 and 1")+ return Entity(text=entity_text, label=label.strip(), score=float(score), start=start, end=end)+++def _to_entities(text: str, raw_entities: Any) -> list[Entity]:+ if not isinstance(raw_entities, list):+ raise RuntimeError(_ERR_MALFORMED.format(output="entities"))+ entities: list[Entity] = []+ for raw in raw_entities:+ if not isinstance(raw, dict):+ raise RuntimeError(_ERR_MALFORMED.format(output="entities"))+ start, end, span, label = raw.get("start"), raw.get("end"), raw.get("text"), raw.get("label")+ if (+ not _is_int(start)+ or not _is_int(end)+ or not 0 <= start < end <= len(text)+ or span != text[start:end]+ or not isinstance(label, str)+ ):+ raise RuntimeError(_ERR_MALFORMED.format(output="entity offsets"))+ score = _validate_score(raw.get("score"), "entity")+ entities.append(Entity(text=span, label=label, score=score, start=start, end=end))+ entities.sort(key=lambda entity: (entity.get("start") or 0, entity.get("end") or 0))+ return entities+++def _to_relations(+ raw_relations: Any, allowed_endpoints: set[str] | None, relation_threshold: float | None+) -> list[Relation]:+ if not isinstance(raw_relations, list):+ raise RuntimeError(_ERR_MALFORMED.format(output="relations"))+ relations: list[Relation] = []+ for raw in raw_relations:+ if not isinstance(raw, dict) or not isinstance(raw.get("head"), dict) or not isinstance(raw.get("tail"), dict):+ raise RuntimeError(_ERR_MALFORMED.format(output="relations"))+ head, tail, relation = raw["head"].get("text"), raw["tail"].get("text"), raw.get("relation")+ if not isinstance(head, str) or not isinstance(tail, str) or not isinstance(relation, str):+ raise RuntimeError(_ERR_MALFORMED.format(output="relations"))+ # The joint head finds endpoints in the text itself; with supplied+ # entities, anything outside that set is not a valid answer.+ if allowed_endpoints is not None and (head not in allowed_endpoints or tail not in allowed_endpoints):+ continue+ score = _validate_score(raw.get("score"), "relation")+ # Same comparison as the package's decoder applies to ``threshold``.+ if relation_threshold is not None and score <= relation_threshold:+ continue+ relations.append(Relation(head=head, tail=tail, relation=relation, score=score))+ relations.sort(key=lambda item: (-item["score"], item["relation"], item["head"], item["tail"]))+ return relations+++def _classification_groups(raw_groups: Any, classes: dict[str, list[str]]) -> dict[str, list[Classification]]:+ """Name GLiFormer's positional per-group predictions, best first."""+ if not classes:+ return {}+ groups = raw_groups if raw_groups is not None else [[] for _ in classes]+ if not isinstance(groups, list) or len(groups) != len(classes):+ raise RuntimeError(_ERR_MALFORMED.format(output="classifications"))+ mapped: dict[str, list[Classification]] = {}+ for name, predictions in zip(classes, groups, strict=True):+ if not isinstance(predictions, list):+ raise RuntimeError(_ERR_MALFORMED.format(output="classifications"))+ group: list[Classification] = []+ for prediction in predictions:+ label = prediction.get("class_name") if isinstance(prediction, dict) else None+ if not isinstance(label, str) or label not in classes[name]:+ raise RuntimeError(_ERR_MALFORMED.format(output="classifications"))+ group.append(Classification(label=label, score=_validate_score(prediction.get("score"), "classification")))+ group.sort(key=lambda classification: classification["score"], reverse=True)+ mapped[name] = group+ return mapped+++def _is_int(value: object) -> bool:+ return isinstance(value, int) and not isinstance(value, bool)+++def _validate_threshold(value: object, name: str = "threshold") -> float:+ message = f"GLiFormer {name} must be a number between 0 and 1"+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise InvalidInputError(message)+ try:+ threshold = float(value)+ except OverflowError as exc:+ raise InvalidInputError(message) from exc+ if not math.isfinite(threshold) or not 0.0 <= threshold <= 1.0:+ raise InvalidInputError(message)+ return threshold+++def _validate_flag(value: object, name: str) -> bool:+ if not isinstance(value, bool):+ raise InvalidInputError(f"GLiFormer {name} must be boolean")+ return value+++def _validate_task(value: Any) -> str | None:+ if value is None:+ return None+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > MAX_LABEL_CHARS:+ raise InvalidInputError(+ f"GLiFormer classification_task must be a non-empty string of at most {MAX_LABEL_CHARS} characters"+ )+ return value.strip()+++def _resolve_multi_label(options: dict[str, Any], *, default: bool) -> bool:+ """Read ``multi_label``, also accepting GLiClass's ``classification_type`` spelling."""+ value = options.get("multi_label")+ classification_type = options.get("classification_type")+ if classification_type is None:+ return _validate_flag(default if value is None else value, "multi_label")+ if classification_type not in ("single-label", "multi-label"):+ raise InvalidInputError("GLiFormer classification_type must be 'single-label' or 'multi-label'")+ multi_label = classification_type == "multi-label"+ if value is not None and _validate_flag(value, "multi_label") != multi_label:+ raise InvalidInputError("GLiFormer multi_label contradicts classification_type")+ return multi_label+++def _validate_label_groups(groups: Any) -> dict[str, list[str]] | None:+ if groups is None:+ return None+ if not isinstance(groups, dict) or not groups:+ raise InvalidInputError("GLiFormer label_groups must be a non-empty object of label lists")+ if sum(len(labels) if isinstance(labels, list) else 1 for labels in groups.values()) > MAX_EXTRACT_LABELS:+ raise InvalidInputError(f"GLiFormer label_groups must contain at most {MAX_EXTRACT_LABELS} labels")+ validated: dict[str, list[str]] = {}+ for name, labels in groups.items():+ if not isinstance(name, str) or not name.strip() or len(name.strip()) > MAX_LABEL_CHARS:+ raise InvalidInputError(+ f"GLiFormer label_groups names must be non-empty strings of at most {MAX_LABEL_CHARS} characters"+ )+ if name.strip() in validated:+ raise InvalidInputError("GLiFormer label_groups names must be unique")+ validated[name.strip()] = _validate_labels(labels, f"label_groups[{clip(repr(name.strip()))}]")+ return validated+++def _validate_labels(labels: Any, name: str) -> list[str]:+ if not isinstance(labels, list) or not labels:+ raise InvalidInputError(f"GLiFormer {name} must be a non-empty list")+ if len(labels) > MAX_EXTRACT_LABELS:+ raise InvalidInputError(f"GLiFormer {name} must contain at most {MAX_EXTRACT_LABELS} entries")+ if any(not isinstance(label, str) or not label.strip() for label in labels):+ raise InvalidInputError(f"GLiFormer {name} must be non-empty strings")+ normalized = [label.strip() for label in labels]+ if any(len(label) > MAX_LABEL_CHARS for label in normalized):+ raise InvalidInputError(f"GLiFormer {name} may have at most {MAX_LABEL_CHARS} characters each")+ if len(set(normalized)) != len(normalized):+ raise InvalidInputError(f"GLiFormer {name} must be unique")+ return normalized+++def _validate_score(value: object, output_name: str) -> float:+ """Validate a score the model produced."""+ if isinstance(value, bool) or not isinstance(value, Real):+ raise RuntimeError(f"GLiFormer returned an invalid {output_name} score")+ score = float(value)+ if not math.isfinite(score) or not 0.0 <= score <= 1.0:+ raise RuntimeError(f"GLiFormer returned an invalid {output_name} score")+ return scorediff --git a/packages/sie_server/src/sie_server/adapters/gliformer/output_schema.py b/packages/sie_server/src/sie_server/adapters/gliformer/output_schema.pynew file mode 100644index 000000000..a144349d8--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/gliformer/output_schema.py@@ -0,0 +1,420 @@+"""JSON Schema support for GLiFormer structured extraction.++GLiFormer answers an ``output_schema`` with two of its task heads in the same+forward pass:++* span-valued properties (strings, arrays of strings, nested objects, and+ arrays of objects) become a GLiFormer structuring template rooted at+ ``$root``, which the structuring head decodes into one object per document;+* root-level string ``enum`` properties become named classification groups,+ so each one is answered with exactly one of its choices.++This module compiles the supported JSON Schema subset into that request and+shapes the decoded values back into a schema-valid object. It has no runtime+dependency on the ``gliformer`` package so the contract is testable without+model weights.+"""++from __future__ import annotations++from collections.abc import Iterator, Mapping, Sequence+from contextlib import contextmanager+from dataclasses import dataclass, field+from typing import Any, Final, Literal++from sie_server.core.extract_cost import MAX_EXTRACT_LABELS, output_schema_shape_error+from sie_server.types.inputs import InvalidInputError++FieldKind = Literal["string", "string_array", "choice", "object", "object_array"]++_ANNOTATION_KEYWORDS: Final[frozenset[str]] = frozenset({"title", "description", "default", "examples"})+_OBJECT_KEYWORDS: Final[frozenset[str]] = _ANNOTATION_KEYWORDS | {+ "type",+ "properties",+ "required",+ "additionalProperties",+}+_ROOT_KEYWORDS: Final[frozenset[str]] = _OBJECT_KEYWORDS | {"$defs", "definitions", "$schema", "$id"}+_STRING_KEYWORDS: Final[frozenset[str]] = _ANNOTATION_KEYWORDS | {"type", "enum"}+_ARRAY_KEYWORDS: Final[frozenset[str]] = _ANNOTATION_KEYWORDS | {"type", "items"}+_REF_PREFIXES: Final[tuple[str, ...]] = ("#/$defs/", "#/definitions/")++# GLiFormer reads a template object whose keys all come from its legacy+# descriptor vocabulary as a descriptor rather than as field names.+_DESCRIPTOR_KEYS: Final[frozenset[str]] = frozenset({"description", "children", "fields", "required_fields"})+_DESCRIPTOR_MARKERS: Final[frozenset[str]] = frozenset({"children", "fields", "required_fields"})++# Bounds that keep compiling a caller's schema cheap. Shared ``$ref`` targets+# are expanded as a tree, so properties and expansions are counted while+# compiling, not afterwards.+MAX_SCHEMA_DEPTH: Final[int] = 32+MAX_REF_EXPANSIONS: Final[int] = MAX_EXTRACT_LABELS+# Longest label, field name, or choice. These become prompt text, which is not+# billed, so every one of them is bounded.+MAX_LABEL_CHARS: Final[int] = 128+# Longest caller-supplied text echoed back in an error message.+_ECHO_CHARS: Final[int] = 120++# Key under which a root object template is passed to GLiFormer. The package+# decodes it into a single object per document rather than a list of records.+ROOT_TEMPLATE_KEY: Final[str] = "$root"+_TEMPLATE_STRING: Final[str] = "str"+++@dataclass(frozen=True)+class SchemaField:+ """One compiled ``output_schema`` node."""++ kind: FieldKind+ properties: tuple[tuple[str, SchemaField], ...] = ()+ required: frozenset[str] = frozenset()+ choices: tuple[str, ...] = ()+++@dataclass(frozen=True)+class StructuredPlan:+ """GLiFormer inputs for one ``output_schema``.++ Attributes:+ root: The compiled root object.+ structures: ``{"$root": template}`` for the structuring head, or+ ``None`` when every property is answered by classification.+ choice_groups: Root ``enum`` properties as ``{name: choices}``+ classification groups, in schema order.+ """++ root: SchemaField+ structures: dict[str, Any] | None+ choice_groups: dict[str, list[str]] = field(default_factory=dict)+++def compile_output_schema(output_schema: Any) -> StructuredPlan:+ """Validate ``output_schema`` and build the GLiFormer request for it.++ Raises:+ InvalidInputError: The schema is outside the supported subset.+ """+ if not isinstance(output_schema, Mapping):+ raise InvalidInputError("GLiFormer output_schema must be a JSON object")+ if shape_error := output_schema_shape_error(output_schema):+ raise InvalidInputError(f"GLiFormer {shape_error}")+ root = _SchemaCompiler(output_schema).compile_root()++ template = _template(root)+ return StructuredPlan(+ root=root,+ structures={ROOT_TEMPLATE_KEY: template} if template else None,+ choice_groups={name: list(child.choices) for name, child in root.properties if child.kind == "choice"},+ )+++def shape_structured_output(+ plan: StructuredPlan,+ structured: Any,+ choices: Mapping[str, str],+) -> tuple[dict[str, Any], list[str]]:+ """Build the schema-valid ``data`` object for one document.++ A property is present only when the model extracted a value for it.+ Nested objects and array records that lack one of their ``required``+ properties are discarded, as GLiFormer itself does for record arrays.++ Args:+ plan: The compiled schema.+ structured: GLiFormer's decoded ``$root`` object (``{}`` when nothing+ was found, ``None`` when no structuring was requested).+ choices: The selected label for each answered root ``enum`` property.++ Returns:+ ``(data, missing_required)`` where ``missing_required`` lists the root+ ``required`` properties that were not extracted.++ Raises:+ RuntimeError: GLiFormer returned values of the wrong shape.+ """+ raw = {} if structured is None else structured+ if not isinstance(raw, Mapping):+ raise RuntimeError("GLiFormer returned malformed structured output")++ data: dict[str, Any] = {}+ for name, child in plan.root.properties:+ if child.kind == "choice":+ label = choices.get(name)+ if label is not None:+ data[name] = label+ continue+ value = _shape_value(child, raw.get(name))+ if value is not None:+ data[name] = value+ missing = [name for name, _ in plan.root.properties if name in plan.root.required and name not in data]+ return data, missing+++class _SchemaCompiler:+ def __init__(self, root: Mapping[str, Any]) -> None:+ self._root = root+ # ``$ref`` targets currently being compiled, to reject recursive schemas.+ self._active_refs: list[str] = []+ self.property_count = 0+ self.ref_expansions = 0++ def compile_root(self) -> SchemaField:+ refs: list[str] = []+ root = self._resolve(self._root, "output_schema", refs)+ if root.get("type") != "object":+ raise InvalidInputError("GLiFormer output_schema root type must be object")+ with self._tracking(refs):+ return self._compile_object(root, "output_schema", depth=1, allowed=_ROOT_KEYWORDS, root=True)++ @contextmanager+ def _tracking(self, refs: list[str]) -> Iterator[None]:+ self._active_refs.extend(refs)+ try:+ yield+ finally:+ del self._active_refs[len(self._active_refs) - len(refs) :]++ def _resolve(self, node: Any, path: str, refs: list[str]) -> Mapping[str, Any]:+ """Inline a local ``$ref`` (as emitted by Pydantic) and drop ``null`` unions.++ Every followed reference is appended to ``refs`` so the caller can+ keep it active while compiling the resolved subtree.+ """+ if not isinstance(node, Mapping):+ raise InvalidInputError(f"GLiFormer {clip(path)} must be an object")+ if "$ref" in node:+ ref = node["$ref"]+ unexpected = set(node) - {"$ref"} - _ANNOTATION_KEYWORDS+ if unexpected:+ raise InvalidInputError(f"GLiFormer {clip(path)} combines $ref with {clip(str(sorted(unexpected)))}")+ if ref in self._active_refs or ref in refs:+ raise InvalidInputError(f"GLiFormer {clip(path)} is recursive, which is not supported")+ self.ref_expansions += 1+ if self.ref_expansions > MAX_REF_EXPANSIONS:+ raise InvalidInputError(f"GLiFormer output_schema expands more than {MAX_REF_EXPANSIONS} $ref values")+ if len(refs) >= MAX_SCHEMA_DEPTH:+ raise InvalidInputError(f"GLiFormer output_schema chains more than {MAX_SCHEMA_DEPTH} $ref values")+ target = self._lookup_ref(ref, path)+ refs.append(ref)+ resolved = self._resolve(target, path, refs)+ return {**resolved, **{key: node[key] for key in _ANNOTATION_KEYWORDS if key in node}}+ if "anyOf" in node:+ options = node["anyOf"]+ if not isinstance(options, list):+ raise InvalidInputError(f"GLiFormer {clip(path)} anyOf must be a list")+ non_null = [option for option in options if option != {"type": "null"}]+ unexpected = set(node) - {"anyOf"} - _ANNOTATION_KEYWORDS+ if len(non_null) != 1 or len(options) != 2 or unexpected:+ raise InvalidInputError(f"GLiFormer {clip(path)} supports anyOf only as an optional (nullable) type")+ resolved = self._resolve(non_null[0], path, refs)+ return {**resolved, **{key: node[key] for key in _ANNOTATION_KEYWORDS if key in node}}+ node_type = node.get("type")+ if isinstance(node_type, list):+ non_null_types = [value for value in node_type if value != "null"]+ if len(non_null_types) != 1 or len(node_type) != 2:+ raise InvalidInputError(f"GLiFormer {clip(path)} supports type lists only as an optional type")+ return {**node, "type": non_null_types[0]}+ return node++ def _lookup_ref(self, ref: Any, path: str) -> Any:+ if not isinstance(ref, str):+ raise InvalidInputError(f"GLiFormer {clip(path)} $ref must be a string")+ for prefix in _REF_PREFIXES:+ if ref.startswith(prefix):+ container = self._root.get(prefix[2:-1])+ name = ref[len(prefix) :]+ if isinstance(container, Mapping) and name in container:+ return container[name]+ break+ raise InvalidInputError(f"GLiFormer {clip(path)} has an unresolvable $ref {clip(repr(ref))}")++ def _compile_object(+ self,+ node: Mapping[str, Any],+ path: str,+ *,+ depth: int,+ allowed: frozenset[str] = _OBJECT_KEYWORDS,+ root: bool = False,+ ) -> SchemaField:+ if depth > MAX_SCHEMA_DEPTH:+ raise InvalidInputError(f"GLiFormer output_schema nests objects more than {MAX_SCHEMA_DEPTH} levels deep")+ _reject_keywords(node, allowed, path)+ properties = node.get("properties")+ if not isinstance(properties, Mapping) or not properties:+ raise InvalidInputError(f"GLiFormer {clip(path)} requires non-empty properties")+ additional = node.get("additionalProperties", True)+ if not isinstance(additional, bool):+ raise InvalidInputError(f"GLiFormer {clip(path)} additionalProperties must be boolean")+ required: Any = node.get("required", [])+ if (+ not isinstance(required, list)+ or any(not isinstance(name, str) or name not in properties for name in required)+ or len(set(required)) != len(required)+ ):+ raise InvalidInputError(f"GLiFormer {clip(path)} required must list unique property names")+ required_names = frozenset(str(name) for name in required)++ names = set(properties)+ if names <= _DESCRIPTOR_KEYS and names & _DESCRIPTOR_MARKERS:+ raise InvalidInputError(+ f"GLiFormer {clip(path)} cannot consist only of properties named "+ f"{sorted(_DESCRIPTOR_KEYS)}; add another property or rename one"+ )++ compiled: list[tuple[str, SchemaField]] = []+ for name, child in properties.items():+ _validate_property_name(name, path)+ self.property_count += 1+ if self.property_count > MAX_EXTRACT_LABELS:+ raise InvalidInputError(f"GLiFormer output_schema declares more than {MAX_EXTRACT_LABELS} properties")+ child_path = f"{path}.{name}"+ refs: list[str] = []+ resolved = self._resolve(child, child_path, refs)+ with self._tracking(refs):+ compiled.append((name, self._compile_property(resolved, child_path, depth=depth, root=root)))+ return SchemaField(kind="object", properties=tuple(compiled), required=required_names)++ def _compile_property(self, node: Mapping[str, Any], path: str, *, depth: int, root: bool) -> SchemaField:+ node_type = node.get("type")+ if "enum" in node:+ _reject_keywords(node, _STRING_KEYWORDS, path)+ if node_type not in (None, "string"):+ raise InvalidInputError(f"GLiFormer {clip(path)} enum must hold strings")+ if not root:+ raise InvalidInputError(+ f"GLiFormer {clip(path)}: enum properties are supported only at the schema root, "+ "where they are answered by document-level classification"+ )+ return SchemaField(kind="choice", choices=_validate_choices(node["enum"], path))+ if node_type == "string":+ _reject_keywords(node, _STRING_KEYWORDS, path)+ return SchemaField(kind="string")+ if node_type == "object":+ return self._compile_object(node, path, depth=depth + 1)+ if node_type == "array":+ _reject_keywords(node, _ARRAY_KEYWORDS, path)+ refs: list[str] = []+ items = self._resolve(node.get("items"), f"{path}[]", refs)+ if "enum" in items:+ raise InvalidInputError(+ f"GLiFormer {clip(path)}: arrays of enum values are not supported; "+ "use a single-choice enum property"+ )+ if items.get("type") == "string":+ _reject_keywords(items, _STRING_KEYWORDS, f"{path}[]")+ return SchemaField(kind="string_array")+ if items.get("type") == "object":+ with self._tracking(refs):+ record = self._compile_object(items, f"{path}[]", depth=depth + 1)+ return SchemaField(kind="object_array", properties=record.properties, required=record.required)+ raise InvalidInputError(f"GLiFormer {clip(path)} arrays must hold strings or objects")+ raise InvalidInputError(+ f"GLiFormer {clip(path)} supports string, string enum, object, and array of string or object values only"+ )+++def clip(text: str, limit: int = _ECHO_CHARS) -> str:+ """Shorten caller-supplied text echoed back in an error message."""+ return text if len(text) <= limit else f"{text[:limit]}..."+++def _reject_keywords(node: Mapping[str, Any], allowed: frozenset[str], path: str) -> None:+ unsupported = set(node) - allowed+ if unsupported:+ raise InvalidInputError(f"GLiFormer {clip(path)} has unsupported keywords: {clip(str(sorted(unsupported)))}")+++def _validate_property_name(name: Any, path: str) -> None:+ # GLiFormer addresses nested fields with dotted paths, so a dot inside a+ # name would be ambiguous.+ if not isinstance(name, str) or not name.strip() or "." in name or len(name) > MAX_LABEL_CHARS:+ raise InvalidInputError(+ f"GLiFormer {clip(path)} property names must be non-empty, contain no '.', "+ f"and have at most {MAX_LABEL_CHARS} characters"+ )+++def _validate_choices(values: Any, path: str) -> tuple[str, ...]:+ if (+ not isinstance(values, list)+ or not values+ or any(not isinstance(value, str) or not value.strip() or len(value) > MAX_LABEL_CHARS for value in values)+ or len(set(values)) != len(values)+ ):+ raise InvalidInputError(+ f"GLiFormer {clip(path)} enum must list unique non-empty strings of at most {MAX_LABEL_CHARS} characters"+ )+ return tuple(values)+++def _template_key(name: str) -> str:+ # The template language marks required fields with a leading "!" and+ # reserves a leading "$"; doubling the marker keeps the literal name.+ return name[0] + name if name[0] in "!$" else name+++def _template(node: SchemaField) -> dict[str, Any]:+ template: dict[str, Any] = {}+ for name, child in node.properties:+ key = _template_key(name)+ if child.kind == "string":+ template[key] = _TEMPLATE_STRING+ elif child.kind == "string_array":+ template[key] = [_TEMPLATE_STRING]+ elif child.kind == "object":+ template[key] = _template(child)+ elif child.kind == "object_array":+ template[key] = [_template(child)]+ return template+++def _first_candidate(value: Any) -> Any:+ """Pick the best of several decoded candidates for a single-valued field.++ GLiFormer reports every span it found for a field, best first, and merges+ several predicted root objects into one by listing their values.+ """+ while isinstance(value, list):+ value = next((item for item in value if item is not None), None)+ return value+++def _shape_value(node: SchemaField, value: Any) -> Any:+ """Return the schema-valid value, or ``None`` when nothing was extracted."""+ if node.kind in ("string", "object"):+ value = _first_candidate(value)+ if value is None:+ return None+ if node.kind == "string":+ if not isinstance(value, str):+ raise RuntimeError("GLiFormer returned malformed structured output")+ return value if value.strip() else None+ if node.kind == "string_array":+ if not isinstance(value, list) or any(item is not None and not isinstance(item, str) for item in value):+ raise RuntimeError("GLiFormer returned malformed structured output")+ strings = [item for item in value if isinstance(item, str) and item.strip()]+ return strings or None+ if node.kind == "object":+ return _shape_object(node, value)+ if node.kind == "object_array":+ if not isinstance(value, Sequence) or isinstance(value, str):+ raise RuntimeError("GLiFormer returned malformed structured output")+ records = [record for record in (_shape_object(node, item) for item in value) if record is not None]+ return records or None+ raise RuntimeError("GLiFormer returned malformed structured output")+++def _shape_object(node: SchemaField, value: Any) -> dict[str, Any] | None:+ if value is None:+ return None+ if not isinstance(value, Mapping):+ raise RuntimeError("GLiFormer returned malformed structured output")+ shaped: dict[str, Any] = {}+ for name, child in node.properties:+ child_value = _shape_value(child, value.get(name))+ if child_value is not None:+ shaped[name] = child_value+ if not shaped or any(name not in shaped for name in node.required):+ return None+ return shapeddiff --git a/packages/sie_server/src/sie_server/core/extract_cost.py b/packages/sie_server/src/sie_server/core/extract_cost.pyindex c616b8d85..db002a874 100644--- a/packages/sie_server/src/sie_server/core/extract_cost.py+++ b/packages/sie_server/src/sie_server/core/extract_cost.py@@ -46,6 +46,40 @@ if TYPE_CHECKING:# rerank candidate cap (``MAX_SCORE_ITEMS``) in magnitude and named-400 shape.MAX_EXTRACT_LABELS: Final[int] = 1000+# Bounds on an extract ``output_schema``'s nesting and size, checked at request+# ingress. The worker builds its batching key and adapters compile the schema by+# walking it recursively, so a pathologically deep schema would otherwise fail+# with a RecursionError deep inside the worker (or strand the other requests+# batched with it) instead of a 400 for the request that sent it. Nesting counts+# JSON objects and arrays; a JSON Schema object property adds two levels.+MAX_OUTPUT_SCHEMA_DEPTH: Final[int] = 128+MAX_OUTPUT_SCHEMA_VALUES: Final[int] = 100_000+++def output_schema_shape_error(schema: Any) -> str | None:+ """Return why ``schema`` is too deeply nested or too large, or ``None``.++ Walks the value iteratively, so the check itself cannot hit Python's+ recursion limit.+ """+ stack: list[tuple[Any, int]] = [(schema, 1)]+ values = 0+ while stack:+ value, depth = stack.pop()+ values += 1+ if values > MAX_OUTPUT_SCHEMA_VALUES:+ return f"'output_schema' must contain at most {MAX_OUTPUT_SCHEMA_VALUES} values"+ if isinstance(value, dict):+ children = list(value.values())+ elif isinstance(value, list):+ children = value+ else:+ continue+ if depth > MAX_OUTPUT_SCHEMA_DEPTH:+ return f"'output_schema' must nest objects and arrays at most {MAX_OUTPUT_SCHEMA_DEPTH} levels deep"+ stack.extend((child, depth + 1) for child in children)+ return None+def extract_item_cost(item: Item,diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 65c13a06a..a26b74022 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -16,7 +16,11 @@ from sie_server.adapters.errors import InputTooLongErrorfrom sie_server.api.ws import compute_bundle_config_hash_cachedfrom sie_server.config.model import ModelConfigfrom sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_types-from sie_server.core.extract_cost import adapter_extract_item_costs, build_extract_prepared_items+from sie_server.core.extract_cost import (+ adapter_extract_item_costs,+ build_extract_prepared_items,+ output_schema_shape_error,+)from sie_server.core.oom import is_oom_errorfrom sie_server.core.prepared import AudioPayload, AudioPreparedItemfrom sie_server.core.registry import ModelRegistry@@ -1423,6 +1427,10 @@ class QueueExecutor:for bi in req.items:try:+ # Reject before the worker walks the schema to build its+ # batching key (same bound as the HTTP ExtractParams check).+ if bi.output_schema is not None and (schema_error := output_schema_shape_error(bi.output_schema)):+ raise InvalidInputError(schema_error)options = merge_runtime_options(config, bi.options)# Same precedence as the HTTP extract path: the request's own# instruction, else one from the options (profile defaultsdiff --git a/packages/sie_server/src/sie_server/types/requests.py b/packages/sie_server/src/sie_server/types/requests.pyindex 8c2c14a66..6fee8bd41 100644--- a/packages/sie_server/src/sie_server/types/requests.py+++ b/packages/sie_server/src/sie_server/types/requests.py@@ -2,7 +2,7 @@ from typing import Anyimport msgspec-from sie_server.core.extract_cost import MAX_EXTRACT_LABELS+from sie_server.core.extract_cost import MAX_EXTRACT_LABELS, output_schema_shape_errorfrom sie_server.core.score_cost import MAX_SCORE_ITEMSfrom sie_server.types.inputs import Item@@ -63,6 +63,8 @@ class ExtractParams(msgspec.Struct):msgspec.convert(self.options["instruction"], type=str | None, strict=True)except msgspec.ValidationError as exc:raise msgspec.ValidationError(f"{exc} - at `$.params.options.instruction`") from exc+ if self.output_schema is not None and (error := output_schema_shape_error(self.output_schema)):+ raise msgspec.ValidationError(f"Field {error}")class ExtractRequest(msgspec.Struct):diff --git a/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-base-v1.json b/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-base-v1.jsonnew file mode 100644index 000000000..685238019--- /dev/null+++ b/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-base-v1.json@@ -0,0 +1,2093 @@+{+ "model": "knowledgator/gliformer-base-v1",+ "revision": "590f9d3f577ea2f6d685aaec84b2d66b6db86b15",+ "generated_with": {+ "gliformer": "0.1.2",+ "gliner": "0.2.26",+ "transformers": "4.57.6",+ "torch": "2.9.1+cu129",+ "device": "cpu",+ "dtype": "float32",+ "max_length": 2048+ },+ "texts": [+ "Alice Johnson works at Acme Corp in London. She joined in March 2021 as a senior software engineer.",+ "Apple announced the iPhone 17 in Cupertino on Tuesday; Tim Cook called it the best phone ever made.",+ "The refund request from Maria Lopez for order 4471 was denied because the item was returned after 45 days.",+ "Dr. Maria Rossi prescribed 20 mg of atorvastatin to the patient at St. Mary's Hospital in Boston."+ ],+ "cases": [+ {+ "name": "entities",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ]+ },+ "reference_call": {+ "threshold": 0.5,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ]+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.998687207698822+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9987726807594299+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9904738068580627+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.98014235496521+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9994114637374878+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9953331351280212+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9993935823440552+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9983695149421692+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9993093013763428+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.994909942150116+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.6843111515045166+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.9503074288368225+ },+ {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "label": "product",+ "score": 0.8504046201705933+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.956914484500885+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9274460673332214+ }+ ]+ ]+ }+ },+ {+ "name": "classification",+ "request": {+ "labels": [+ "positive",+ "negative",+ "neutral"+ ],+ "options": {+ "classification_task": "sentiment"+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ]+ }+ },+ "reference_output": {+ "classification": [+ [+ [+ {+ "class_name": "neutral",+ "score": 0.9999700784683228+ }+ ]+ ],+ [+ [+ {+ "class_name": "positive",+ "score": 0.9999016523361206+ }+ ]+ ],+ [+ [+ {+ "class_name": "negative",+ "score": 0.9999743700027466+ }+ ]+ ],+ [+ [+ {+ "class_name": "neutral",+ "score": 0.9999922513961792+ }+ ]+ ]+ ]+ }+ },+ {+ "name": "classification_multi_label",+ "request": {+ "labels": [+ "business",+ "technology",+ "health",+ "customer support"+ ],+ "options": {+ "classification_task": "topic",+ "multi_label": true,+ "threshold": 0.3+ }+ },+ "reference_call": {+ "threshold": 0.3,+ "classes": {+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ },+ "multi_label": true+ },+ "reference_output": {+ "classification": [+ [+ [+ {+ "class_name": "business",+ "score": 0.9943450689315796+ },+ {+ "class_name": "technology",+ "score": 0.983393132686615+ }+ ]+ ],+ [+ [+ {+ "class_name": "technology",+ "score": 0.9674676060676575+ }+ ]+ ],+ [+ [+ {+ "class_name": "business",+ "score": 0.9786849021911621+ },+ {+ "class_name": "customer support",+ "score": 0.9734137654304504+ }+ ]+ ],+ [+ [+ {+ "class_name": "health",+ "score": 0.9973570704460144+ }+ ]+ ]+ ]+ }+ },+ {+ "name": "relations",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "options": {+ "relation_labels": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ]+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9992438554763794+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9997832179069519+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9992039799690247+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9951400756835938+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.999916672706604+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9990525841712952+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9998286962509155+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9989157319068909+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9997623562812805+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.9968036413192749+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.8277521133422852+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.9825044274330139+ },+ {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "label": "product",+ "score": 0.8257777690887451+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9964388608932495+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9968149065971375+ }+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9429084062576294+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.8052617311477661+ }+ ],+ [+ {+ "head": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6062094569206238+ },+ {+ "head": {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6795557737350464+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.7263557314872742+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.6439918279647827+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 2+ },+ "relation": "works at",+ "score": 0.885895311832428+ },+ {+ "head": {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 3+ },+ "relation": "located in",+ "score": 0.5062950253486633+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 2+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 3+ },+ "relation": "located in",+ "score": 0.8539669513702393+ }+ ]+ ]+ }+ },+ {+ "name": "output_schema",+ "request": {+ "output_schema": {+ "type": "object",+ "properties": {+ "customer": {+ "type": "string"+ },+ "order number": {+ "type": "string"+ },+ "decision": {+ "type": "string",+ "enum": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "reasons": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "people": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "role": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "decision": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "structures": {+ "$root": {+ "customer": "str",+ "order number": "str",+ "reasons": [+ "str"+ ],+ "people": [+ {+ "name": "str",+ "role": "str"+ }+ ]+ }+ }+ },+ "reference_output": {+ "classification": [+ [+ []+ ],+ [+ []+ ],+ [+ [+ {+ "class_name": "denied",+ "score": 0.9998706579208374+ }+ ]+ ],+ [+ []+ ]+ ],+ "structuring": [+ {+ "customer": null,+ "order number": null,+ "reasons": [],+ "people": [+ {+ "name": "Alice Johnson",+ "role": "senior software engineer"+ }+ ]+ },+ {+ "customer": null,+ "order number": null,+ "reasons": [],+ "people": [+ {+ "name": "Tim Cook",+ "role": null+ }+ ]+ },+ {+ "customer": "Maria Lopez",+ "order number": "4471",+ "reasons": [+ "the item was returned after 45 days"+ ],+ "people": []+ },+ {}+ ]+ }+ },+ {+ "name": "combined",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "output_schema": {+ "type": "object",+ "properties": {+ "customer": {+ "type": "string"+ },+ "order number": {+ "type": "string"+ },+ "decision": {+ "type": "string",+ "enum": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "reasons": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "people": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "role": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "options": {+ "relation_labels": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "decision": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "structures": {+ "$root": {+ "customer": "str",+ "order number": "str",+ "reasons": [+ "str"+ ],+ "people": [+ {+ "name": "str",+ "role": "str"+ }+ ]+ }+ }+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9790270328521729+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9995777010917664+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9974365830421448+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9894367456436157+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9997462630271912+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9951222538948059+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9991375207901001+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9976429343223572+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9976812601089478+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.6708275079727173+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.9292746782302856+ },+ {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "label": "product",+ "score": 0.8454955816268921+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9858440160751343+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9933439493179321+ }+ ]+ ],+ "classification": [+ [+ []+ ],+ [+ []+ ],+ [+ [+ {+ "class_name": "denied",+ "score": 0.9998306035995483+ }+ ]+ ],+ [+ []+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9450026750564575+ },+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "works at",+ "score": 0.5902034640312195+ },+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.5139472484588623+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.8067009449005127+ }+ ],+ [+ {+ "head": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6147376298904419+ },+ {+ "head": {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6687809824943542+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.7464385628700256+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.5472172498703003+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "works at",+ "score": 0.5529800057411194+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 2+ },+ "relation": "works at",+ "score": 0.8912127017974854+ },+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 3+ },+ "relation": "located in",+ "score": 0.505382239818573+ },+ {+ "head": {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 3+ },+ "relation": "located in",+ "score": 0.6236289739608765+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 2+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 3+ },+ "relation": "located in",+ "score": 0.8565820455551147+ }+ ]+ ],+ "structuring": [+ {+ "people": [+ {+ "name": "Alice Johnson",+ "role": "senior software engineer"+ }+ ]+ },+ {+ "people": [+ {+ "name": "Tim Cook",+ "role": null+ }+ ]+ },+ {+ "customer": "Maria Lopez",+ "order number": "4471",+ "reasons": [+ "the item was returned after 45 days"+ ],+ "people": []+ },+ {}+ ]+ }+ },+ {+ "name": "label_groups",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "options": {+ "label_groups": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ],+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "classes": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ],+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ }+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.99660325050354+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.99643874168396+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9908099174499512+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9783049821853638+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9964777827262878+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9844722151756287+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9893314838409424+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9891701340675354+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9964523315429688+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.9686092138290405+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.7610914707183838+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.8969882130622864+ },+ {+ "start": 36,+ "end": 48,+ "text": "atorvastatin",+ "label": "product",+ "score": 0.7445228695869446+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9035640954971313+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9169180393218994+ }+ ]+ ],+ "classification": [+ [+ [+ {+ "class_name": "neutral",+ "score": 0.998162567615509+ }+ ],+ []+ ],+ [+ [+ {+ "class_name": "positive",+ "score": 0.9932578802108765+ }+ ],+ []+ ],+ [+ [+ {+ "class_name": "negative",+ "score": 0.99916672706604+ }+ ],+ []+ ],+ [+ [+ {+ "class_name": "neutral",+ "score": 0.999794065952301+ }+ ],+ []+ ]+ ]+ }+ },+ {+ "name": "nested_objects",+ "request": {+ "output_schema": {+ "type": "object",+ "properties": {+ "patient": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "hospital": {+ "type": "string"+ }+ }+ },+ "medications": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "drug": {+ "type": "string"+ },+ "dose": {+ "type": "string"+ }+ },+ "required": [+ "drug"+ ]+ }+ },+ "employer": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "location": {+ "type": "object",+ "properties": {+ "city": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "structures": {+ "$root": {+ "patient": {+ "name": "str",+ "hospital": "str"+ },+ "medications": [+ {+ "drug": "str",+ "dose": "str"+ }+ ],+ "employer": {+ "name": "str",+ "location": {+ "city": "str"+ }+ }+ }+ }+ },+ "reference_output": {+ "structuring": [+ {+ "patient": {+ "name": null,+ "hospital": null+ },+ "employer": {+ "name": "Acme Corp",+ "location": {+ "city": "London"+ }+ },+ "medications": []+ },+ {},+ {},+ {+ "patient": {+ "name": "patient",+ "hospital": "St. Mary's Hospital"+ },+ "employer": {+ "name": null,+ "location": {+ "city": null+ }+ },+ "medications": [+ {+ "drug": "atorvastatin",+ "dose": "20 mg"+ }+ ]+ }+ ]+ }+ },+ {+ "name": "metadata_entities",+ "request": {+ "labels": [+ "works at",+ "located in",+ "chief executive of"+ ],+ "item_metadata": [+ {+ "entities": [+ {+ "text": "Alice Johnson",+ "label": "person",+ "start": 0,+ "end": 13+ },+ {+ "text": "Acme Corp",+ "label": "organization",+ "start": 23,+ "end": 32+ },+ {+ "text": "London",+ "label": "location",+ "start": 36,+ "end": 42+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Apple",+ "label": "organization",+ "start": 0,+ "end": 5+ },+ {+ "text": "Cupertino",+ "label": "location",+ "start": 33,+ "end": 42+ },+ {+ "text": "Tim Cook",+ "label": "person",+ "start": 55,+ "end": 63+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Maria Lopez",+ "label": "person",+ "start": 24,+ "end": 35+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Dr. Maria Rossi",+ "label": "person",+ "start": 0,+ "end": 15+ },+ {+ "text": "St. Mary's Hospital",+ "label": "organization",+ "start": 67,+ "end": 86+ },+ {+ "text": "Boston",+ "label": "location",+ "start": 90,+ "end": 96+ }+ ]+ }+ ]+ },+ "reference_calls": [+ {+ "texts": [+ 0,+ 1,+ 3+ ],+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "location",+ "organization",+ "person"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "threshold": 0.5+ },+ {+ "texts": [+ 2+ ],+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "threshold": 0.5+ }+ ],+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9989445805549622+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9999117851257324+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9998037219047546+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9998822212219238+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.999714195728302+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9997449517250061+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.997208297252655+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.9910715222358704+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9987630844116211+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9997548460960388+ }+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9344766139984131+ },+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.5706331729888916+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.8232421875+ }+ ],+ [+ {+ "head": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 1+ },+ "relation": "located in",+ "score": 0.6930734515190125+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 2+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.6978469491004944+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 2+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.6321127414703369+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.871353030204773+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.8645806908607483+ }+ ]+ ]+ }+ }+ ],+ "embeddings": {+ "dim": 768,+ "normalized_head": [+ [+ -0.018502,+ -0.018632,+ -0.008736,+ 0.016341,+ 0.052293,+ 0.022783,+ -0.003933,+ -0.056564,+ 0.045225,+ -0.001035,+ -0.027572,+ 0.032462,+ -0.013723,+ 0.001705,+ -0.027491,+ -0.052751,+ -0.035627,+ -0.007689,+ 0.020974,+ -0.025024,+ -0.074117,+ 0.009489,+ 0.057615,+ -0.001391,+ -0.000291,+ 0.052993,+ 0.032606,+ 0.002227,+ 0.0226,+ -0.06802,+ 0.000411,+ 0.024973+ ],+ [+ -0.015014,+ 0.011539,+ 0.00173,+ 0.007041,+ 0.029498,+ -0.020323,+ 0.038047,+ -0.06919,+ -0.00934,+ 0.008803,+ -0.01832,+ 0.012771,+ -0.043397,+ -0.03958,+ -0.009253,+ -0.022304,+ 0.012995,+ -0.018696,+ 0.067448,+ 0.016524,+ -0.079188,+ 0.03399,+ 0.025882,+ -0.027322,+ -0.010041,+ 0.027105,+ -0.018423,+ -0.01463,+ 0.031063,+ -0.024317,+ -0.004779,+ -0.002745+ ],+ [+ -0.016719,+ 0.021034,+ -0.014712,+ -0.043321,+ -0.026456,+ -0.001868,+ 0.045459,+ 0.037092,+ 0.032058,+ -0.089875,+ 0.001625,+ 0.027908,+ 0.028072,+ -0.047954,+ 0.005912,+ -0.054589,+ 0.021176,+ 0.015582,+ 0.000927,+ 0.000694,+ -0.028277,+ -0.007012,+ 0.018294,+ -0.029804,+ 0.005433,+ 0.040077,+ -0.008968,+ -0.020565,+ -0.006377,+ 0.040173,+ 0.026311,+ -0.016995+ ],+ [+ 0.023582,+ 0.01021,+ -0.036282,+ 0.062173,+ -0.024303,+ 0.001351,+ 0.031331,+ -0.017259,+ 0.011454,+ 0.034669,+ 0.000175,+ -0.00369,+ 0.036723,+ -0.029826,+ 0.000464,+ -0.041013,+ 0.011865,+ -0.044155,+ 0.006992,+ -0.04714,+ -0.039124,+ 0.020205,+ -0.009949,+ -0.088214,+ -0.102792,+ -0.017662,+ -0.006912,+ -0.045517,+ -0.008686,+ -0.006036,+ 0.016435,+ -0.005654+ ]+ ],+ "cosine": [+ [+ 1.0,+ 0.654727,+ 0.130212,+ 0.165476+ ],+ [+ 0.654727,+ 1.0,+ 0.2212,+ 0.345787+ ],+ [+ 0.130212,+ 0.2212,+ 1.0,+ 0.236942+ ],+ [+ 0.165476,+ 0.345787,+ 0.236942,+ 1.0+ ]+ ]+ }+}diff --git a/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-large-v1.json b/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-large-v1.jsonnew file mode 100644index 000000000..7fb60fbc9--- /dev/null+++ b/packages/sie_server/tests/adapters/goldens/gliformer/knowledgator__gliformer-large-v1.json@@ -0,0 +1,1903 @@+{+ "model": "knowledgator/gliformer-large-v1",+ "revision": "d0a4e53d09cebe6bc963dd9be319d4279084bb2d",+ "generated_with": {+ "gliformer": "0.1.2",+ "gliner": "0.2.26",+ "transformers": "4.57.6",+ "torch": "2.9.1+cu129",+ "device": "cpu",+ "dtype": "float32",+ "max_length": 2048+ },+ "texts": [+ "Alice Johnson works at Acme Corp in London. She joined in March 2021 as a senior software engineer.",+ "Apple announced the iPhone 17 in Cupertino on Tuesday; Tim Cook called it the best phone ever made.",+ "The refund request from Maria Lopez for order 4471 was denied because the item was returned after 45 days.",+ "Dr. Maria Rossi prescribed 20 mg of atorvastatin to the patient at St. Mary's Hospital in Boston."+ ],+ "cases": [+ {+ "name": "entities",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ]+ },+ "reference_call": {+ "threshold": 0.5,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ]+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9998767971992493+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9994814991950989+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9995360374450684+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9935759902000427+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9998397827148438+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9999034404754639+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9999773502349854+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9999021291732788+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9999574422836304+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.99932861328125+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.5843880772590637+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.8513447642326355+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9331271648406982+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9897504448890686+ }+ ]+ ]+ }+ },+ {+ "name": "classification",+ "request": {+ "labels": [+ "positive",+ "negative",+ "neutral"+ ],+ "options": {+ "classification_task": "sentiment"+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ]+ }+ },+ "reference_output": {+ "classification": [+ [+ [+ {+ "class_name": "neutral",+ "score": 0.9999978542327881+ }+ ]+ ],+ [+ [+ {+ "class_name": "positive",+ "score": 0.9999637603759766+ }+ ]+ ],+ [+ [+ {+ "class_name": "negative",+ "score": 0.9996945858001709+ }+ ]+ ],+ [+ [+ {+ "class_name": "neutral",+ "score": 0.9999997615814209+ }+ ]+ ]+ ]+ }+ },+ {+ "name": "classification_multi_label",+ "request": {+ "labels": [+ "business",+ "technology",+ "health",+ "customer support"+ ],+ "options": {+ "classification_task": "topic",+ "multi_label": true,+ "threshold": 0.3+ }+ },+ "reference_call": {+ "threshold": 0.3,+ "classes": {+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ },+ "multi_label": true+ },+ "reference_output": {+ "classification": [+ [+ [+ {+ "class_name": "business",+ "score": 0.9999669790267944+ },+ {+ "class_name": "technology",+ "score": 0.9999895095825195+ }+ ]+ ],+ [+ [+ {+ "class_name": "business",+ "score": 0.9999209642410278+ },+ {+ "class_name": "technology",+ "score": 0.9999951124191284+ }+ ]+ ],+ [+ [+ {+ "class_name": "business",+ "score": 0.9999752044677734+ },+ {+ "class_name": "customer support",+ "score": 0.9978201389312744+ }+ ]+ ],+ [+ [+ {+ "class_name": "health",+ "score": 0.9999105930328369+ }+ ]+ ]+ ]+ }+ },+ {+ "name": "relations",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "options": {+ "relation_labels": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ]+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9987393021583557+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9873842597007751+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9995819926261902+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9758943319320679+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9998785257339478+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9992956519126892+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9996736645698547+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9999173879623413+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9998824596405029+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.9973179697990417+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.9330511093139648+ },+ {+ "start": 98,+ "end": 105,+ "text": "45 days",+ "label": "date",+ "score": 0.5899508595466614+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.8081309795379639+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9582934975624084+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9933713674545288+ }+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9994638562202454+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.7631438374519348+ }+ ],+ [+ {+ "head": {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.7859895825386047+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.8529713153839111+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.9261034727096558+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.962810218334198+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.7573511600494385+ }+ ]+ ]+ }+ },+ {+ "name": "output_schema",+ "request": {+ "output_schema": {+ "type": "object",+ "properties": {+ "customer": {+ "type": "string"+ },+ "order number": {+ "type": "string"+ },+ "decision": {+ "type": "string",+ "enum": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "reasons": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "people": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "role": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "decision": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "structures": {+ "$root": {+ "customer": "str",+ "order number": "str",+ "reasons": [+ "str"+ ],+ "people": [+ {+ "name": "str",+ "role": "str"+ }+ ]+ }+ }+ },+ "reference_output": {+ "classification": [+ [+ []+ ],+ [+ []+ ],+ [+ [+ {+ "class_name": "denied",+ "score": 0.9999984502792358+ }+ ]+ ],+ [+ []+ ]+ ],+ "structuring": [+ {},+ {},+ {+ "customer": "Maria Lopez",+ "order number": "4471",+ "reasons": [+ "the item was returned after 45 days"+ ],+ "people": []+ },+ {+ "people": [+ {+ "name": "Dr. Maria Rossi",+ "role": "patient"+ }+ ]+ }+ ]+ }+ },+ {+ "name": "combined",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "output_schema": {+ "type": "object",+ "properties": {+ "customer": {+ "type": "string"+ },+ "order number": {+ "type": "string"+ },+ "decision": {+ "type": "string",+ "enum": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "reasons": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "people": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "role": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "options": {+ "relation_labels": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "classes": {+ "decision": [+ "approved",+ "denied",+ "escalated"+ ]+ },+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "structures": {+ "$root": {+ "customer": "str",+ "order number": "str",+ "reasons": [+ "str"+ ],+ "people": [+ {+ "name": "str",+ "role": "str"+ }+ ]+ }+ }+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9068577885627747+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9726057052612305+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9990512728691101+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.9930821657180786+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9996482729911804+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9916577935218811+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.998358428478241+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9974197745323181+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9065317511558533+ }+ ],+ [],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.8101463913917542+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9370404481887817+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9881975054740906+ }+ ]+ ],+ "classification": [+ [+ []+ ],+ [+ []+ ],+ [+ [+ {+ "class_name": "denied",+ "score": 0.9999984502792358+ }+ ]+ ],+ [+ []+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9993993043899536+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.732470691204071+ }+ ],+ [+ {+ "head": {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "type": "product",+ "entity_idx": 1+ },+ "tail": {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6606683135032654+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.5672048926353455+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 4+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.6815407276153564+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.7189285159111023+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.8436221480369568+ }+ ]+ ],+ "structuring": [+ {+ "people": [+ {+ "name": "Alice Johnson",+ "role": "senior software engineer"+ }+ ]+ },+ {+ "people": [+ {+ "name": "Tim Cook",+ "role": null+ }+ ]+ },+ {+ "customer": "Maria Lopez",+ "order number": "4471",+ "reasons": [+ "the item was returned after 45 days"+ ],+ "people": []+ },+ {+ "people": [+ {+ "name": "Dr. Maria Rossi",+ "role": null+ }+ ]+ }+ ]+ }+ },+ {+ "name": "label_groups",+ "request": {+ "labels": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "options": {+ "label_groups": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ],+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "entities": [+ "person",+ "organization",+ "location",+ "date",+ "product"+ ],+ "classes": {+ "sentiment": [+ "positive",+ "negative",+ "neutral"+ ],+ "topic": [+ "business",+ "technology",+ "health",+ "customer support"+ ]+ }+ },+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9925716519355774+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9946449398994446+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9888066649436951+ },+ {+ "start": 58,+ "end": 68,+ "text": "March 2021",+ "label": "date",+ "score": 0.998511016368866+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9985560774803162+ },+ {+ "start": 20,+ "end": 29,+ "text": "iPhone 17",+ "label": "product",+ "score": 0.9922420382499695+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.9986973404884338+ },+ {+ "start": 46,+ "end": 53,+ "text": "Tuesday",+ "label": "date",+ "score": 0.9944829940795898+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.9987714290618896+ }+ ],+ [+ {+ "start": 24,+ "end": 35,+ "text": "Maria Lopez",+ "label": "person",+ "score": 0.9915483593940735+ },+ {+ "start": 40,+ "end": 50,+ "text": "order 4471",+ "label": "product",+ "score": 0.5302085280418396+ }+ ],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.7507876753807068+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.7106178998947144+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9165005683898926+ }+ ]+ ],+ "classification": [+ [+ [+ {+ "class_name": "neutral",+ "score": 0.999975323677063+ }+ ],+ [+ {+ "class_name": "technology",+ "score": 0.9999498128890991+ }+ ]+ ],+ [+ [+ {+ "class_name": "positive",+ "score": 0.9998509883880615+ }+ ],+ [+ {+ "class_name": "technology",+ "score": 0.9997633099555969+ }+ ]+ ],+ [+ [+ {+ "class_name": "negative",+ "score": 0.9987047910690308+ }+ ],+ []+ ],+ [+ [+ {+ "class_name": "neutral",+ "score": 0.9999550580978394+ }+ ],+ []+ ]+ ]+ }+ },+ {+ "name": "nested_objects",+ "request": {+ "output_schema": {+ "type": "object",+ "properties": {+ "patient": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "hospital": {+ "type": "string"+ }+ }+ },+ "medications": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "drug": {+ "type": "string"+ },+ "dose": {+ "type": "string"+ }+ },+ "required": [+ "drug"+ ]+ }+ },+ "employer": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "location": {+ "type": "object",+ "properties": {+ "city": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ }+ },+ "reference_call": {+ "threshold": 0.5,+ "structures": {+ "$root": {+ "patient": {+ "name": "str",+ "hospital": "str"+ },+ "medications": [+ {+ "drug": "str",+ "dose": "str"+ }+ ],+ "employer": {+ "name": "str",+ "location": {+ "city": "str"+ }+ }+ }+ }+ },+ "reference_output": {+ "structuring": [+ {+ "patient": {+ "name": null,+ "hospital": null+ },+ "employer": {+ "name": "Acme Corp",+ "location": {+ "city": "London"+ }+ },+ "medications": []+ },+ {+ "patient": {+ "name": null,+ "hospital": null+ },+ "employer": {+ "name": "Apple",+ "location": {+ "city": "Cupertino"+ }+ },+ "medications": []+ },+ {+ "patient": {+ "name": "Maria Lopez",+ "hospital": null+ },+ "employer": {+ "name": null,+ "location": {+ "city": null+ }+ },+ "medications": []+ },+ {+ "patient": {+ "name": null,+ "hospital": "St. Mary's Hospital"+ },+ "employer": {+ "name": null,+ "location": {+ "city": null+ }+ },+ "medications": []+ }+ ]+ }+ },+ {+ "name": "metadata_entities",+ "request": {+ "labels": [+ "works at",+ "located in",+ "chief executive of"+ ],+ "item_metadata": [+ {+ "entities": [+ {+ "text": "Alice Johnson",+ "label": "person",+ "start": 0,+ "end": 13+ },+ {+ "text": "Acme Corp",+ "label": "organization",+ "start": 23,+ "end": 32+ },+ {+ "text": "London",+ "label": "location",+ "start": 36,+ "end": 42+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Apple",+ "label": "organization",+ "start": 0,+ "end": 5+ },+ {+ "text": "Cupertino",+ "label": "location",+ "start": 33,+ "end": 42+ },+ {+ "text": "Tim Cook",+ "label": "person",+ "start": 55,+ "end": 63+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Maria Lopez",+ "label": "person",+ "start": 24,+ "end": 35+ }+ ]+ },+ {+ "entities": [+ {+ "text": "Dr. Maria Rossi",+ "label": "person",+ "start": 0,+ "end": 15+ },+ {+ "text": "St. Mary's Hospital",+ "label": "organization",+ "start": 67,+ "end": 86+ },+ {+ "text": "Boston",+ "label": "location",+ "start": 90,+ "end": 96+ }+ ]+ }+ ]+ },+ "reference_calls": [+ {+ "texts": [+ 0,+ 1,+ 3+ ],+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "location",+ "organization",+ "person"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "threshold": 0.5+ },+ {+ "texts": [+ 2+ ],+ "joint_relations": [+ {+ "name": null,+ "entities": [+ "person"+ ],+ "relations": [+ "works at",+ "located in",+ "chief executive of"+ ]+ }+ ],+ "threshold": 0.5+ }+ ],+ "reference_output": {+ "ner": [+ [+ {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "label": "person",+ "score": 0.9990215301513672+ },+ {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "label": "organization",+ "score": 0.9978700280189514+ },+ {+ "start": 36,+ "end": 42,+ "text": "London",+ "label": "location",+ "score": 0.9994988441467285+ }+ ],+ [+ {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "label": "organization",+ "score": 0.9996793270111084+ },+ {+ "start": 33,+ "end": 42,+ "text": "Cupertino",+ "label": "location",+ "score": 0.99973064661026+ },+ {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "label": "person",+ "score": 0.999915599822998+ }+ ],+ [],+ [+ {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "label": "person",+ "score": 0.8099659085273743+ },+ {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "label": "organization",+ "score": 0.9975439310073853+ },+ {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "label": "location",+ "score": 0.9967013001441956+ }+ ]+ ],+ "joint_relex": [+ [+ {+ "head": {+ "start": 0,+ "end": 13,+ "text": "Alice Johnson",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9980450868606567+ },+ {+ "head": {+ "start": 23,+ "end": 32,+ "text": "Acme Corp",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 36,+ "end": 42,+ "text": "London",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.764033317565918+ }+ ],+ [+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 2+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "works at",+ "score": 0.7611127495765686+ },+ {+ "head": {+ "start": 55,+ "end": 63,+ "text": "Tim Cook",+ "type": "person",+ "entity_idx": 2+ },+ "tail": {+ "start": 0,+ "end": 5,+ "text": "Apple",+ "type": "organization",+ "entity_idx": 0+ },+ "relation": "chief executive of",+ "score": 0.8956109285354614+ }+ ],+ [],+ [+ {+ "head": {+ "start": 0,+ "end": 15,+ "text": "Dr. Maria Rossi",+ "type": "person",+ "entity_idx": 0+ },+ "tail": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "relation": "works at",+ "score": 0.9763638973236084+ },+ {+ "head": {+ "start": 67,+ "end": 86,+ "text": "St. Mary's Hospital",+ "type": "organization",+ "entity_idx": 1+ },+ "tail": {+ "start": 90,+ "end": 96,+ "text": "Boston",+ "type": "location",+ "entity_idx": 2+ },+ "relation": "located in",+ "score": 0.6636325716972351+ }+ ]+ ]+ }+ }+ ],+ "embeddings": {+ "dim": 1024,+ "normalized_head": [+ [+ -0.048274,+ -0.042245,+ 0.020828,+ -0.022514,+ 0.063466,+ -0.002253,+ -0.037165,+ 0.043451,+ 0.02293,+ -0.01989,+ -0.021476,+ 0.033343,+ 0.040874,+ 0.048559,+ 0.017767,+ 0.000988,+ 0.054801,+ 0.025347,+ 0.025628,+ -0.012038,+ -0.048238,+ 0.033274,+ 0.003743,+ 0.033795,+ -0.002384,+ -0.072969,+ 0.035888,+ -0.011528,+ -0.020964,+ 0.050398,+ -0.00644,+ -0.001955+ ],+ [+ 0.023209,+ 0.058308,+ 0.023163,+ 0.00988,+ 0.037186,+ -0.042714,+ 0.014437,+ -0.004709,+ -0.03417,+ -0.006492,+ 0.014016,+ -0.025312,+ 0.003912,+ 0.011054,+ -0.001653,+ -0.030831,+ -0.030826,+ 0.011967,+ -0.01363,+ 0.022215,+ -0.062613,+ 0.010707,+ 0.019382,+ -0.009367,+ 0.00097,+ -0.037388,+ 0.018624,+ 0.009415,+ 0.015478,+ 0.074882,+ -0.004471,+ 0.004161+ ],+ [+ 0.011783,+ 0.044841,+ -0.038799,+ -0.021239,+ -0.016072,+ -0.002069,+ 0.079381,+ -0.023015,+ 0.008147,+ -0.040652,+ -0.013548,+ -0.027166,+ -0.008465,+ 0.046796,+ 0.011518,+ 0.05939,+ 0.009594,+ 0.045295,+ -0.000107,+ 0.033195,+ 0.011422,+ 0.007373,+ 0.038636,+ -0.015302,+ -0.103892,+ -0.017001,+ -0.007259,+ 0.058597,+ -0.013602,+ 0.003185,+ -0.013143,+ -0.026835+ ],+ [+ -0.028888,+ 0.020682,+ -0.000302,+ -0.015209,+ 0.011817,+ 0.002169,+ -0.036218,+ 0.004677,+ 0.034832,+ -0.076623,+ -0.062508,+ -0.024005,+ 0.011855,+ 0.072109,+ 0.019781,+ -0.013007,+ 0.043965,+ 0.042299,+ -0.00415,+ 0.031842,+ -0.050734,+ -0.006522,+ 0.041467,+ 0.029409,+ -0.016265,+ -0.044029,+ 0.007611,+ -0.001802,+ 0.008936,+ 0.005164,+ 0.001659,+ 0.010808+ ]+ ],+ "cosine": [+ [+ 1.0,+ 0.382373,+ 0.105036,+ 0.462791+ ],+ [+ 0.382373,+ 1.0,+ 0.0647,+ 0.24265+ ],+ [+ 0.105036,+ 0.0647,+ 1.0,+ 0.364309+ ],+ [+ 0.462791,+ 0.24265,+ 0.364309,+ 1.0+ ]+ ]+ }+}diff --git a/packages/sie_server/tests/adapters/test_gliformer.py b/packages/sie_server/tests/adapters/test_gliformer.pynew file mode 100644index 000000000..038bd7052--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliformer.py@@ -0,0 +1,1525 @@+"""Contract tests for the GLiFormer adapter (no model weights)."""++from __future__ import annotations++import subprocess+import sys+import time+from pathlib import Path+from types import ModuleType, SimpleNamespace+from typing import Any, Literal+from unittest.mock import MagicMock, patch++import numpy as np+import pytest+import torch+import yaml+from pydantic import BaseModel+from sie_server.adapters.gliformer import adapter as adapter_module+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.inference_output import ExtractItemError+from sie_server.core.loader import load_adapter, load_model_configs+from sie_server.types.inputs import InvalidInputError, Item++_SERVER_ROOT = Path(__file__).resolve().parents[2]+_MODELS_DIR = _SERVER_ROOT / "models"+_MODEL_IDS = {"knowledgator/gliformer-base-v1": 768, "knowledgator/gliformer-large-v1": 1024}+++class _FakeTokenizer:+ """One subword per word; two special tokens per sequence."""++ def __init__(self) -> None:+ self.calls: list[list[list[str]]] = []++ def __call__(self, sequences: list[list[str]], **_: Any) -> dict[str, Any]:+ self.calls.append(sequences)+ return {"input_ids": [[1] * len(words) for words in sequences]}++ @staticmethod+ def num_special_tokens_to_add(pair: bool = False) -> int:+ return 2+++def _fake_model(results: dict[str, Any], *, prompt_words: int = 3, max_len: int = 2048) -> MagicMock:+ """A stand-in for a loaded GLiFormer whose task prompt is ``prompt_words`` words."""+ model = MagicMock()+ model.inference.return_value = results+ model.config = SimpleNamespace(max_len=max_len)+ model.prepare_inputs.side_effect = lambda texts: ([text.split() for text in texts], [], [])+ model._build_inference_input.side_effect = lambda words, **_: [{"tokenized_text": w} for w in words]+ processor = model.data_processor+ processor.collate_raw_batch.side_effect = lambda items: {+ "tokens": [item["tokenized_text"] for item in items],+ "classes_mapping": None,+ }+ processor.prepare_inputs.side_effect = lambda tokens, _mapping: (+ [["P"] * prompt_words + list(words) for words in tokens],+ [prompt_words] * len(tokens),+ )+ processor.transformer_tokenizer = _FakeTokenizer()+ return model+++def _adapter(results: dict[str, Any], *, max_len: int = 2048, **kwargs: Any) -> tuple[GLiFormerAdapter, MagicMock]:+ adapter = GLiFormerAdapter("test-model", **kwargs)+ adapter._model = _fake_model(results, max_len=max_len)+ adapter._tokenizer = adapter._model.data_processor.transformer_tokenizer+ adapter._normalize_structures = lambda structures: structures+ adapter._build_formatter = lambda structures: None+ return adapter, adapter._model+++def _ner(text: str, span: str, label: str, score: float = 0.9) -> dict[str, Any]:+ start = text.index(span)+ return {"start": start, "end": start + len(span), "text": span, "label": label, "score": score}+++def _relation(head: str, relation: str, tail: str, score: float) -> dict[str, Any]:+ return {"head": {"text": head}, "tail": {"text": tail}, "relation": relation, "score": score}+++def _inference_kwargs(model: MagicMock) -> dict[str, Any]:+ return model.inference.call_args.kwargs+++# -- Request routing -------------------------------------------------------------+++def test_labels_run_entity_recognition_with_document_token_counts() -> None:+ text = "Alice works at Acme"+ adapter, model = _adapter({"ner": [[_ner(text, "Acme", "organization", 0.8), _ner(text, "Alice", "person")]]})++ output = adapter.extract([Item(text=text)], labels=["person", " organization "])++ assert output.entities == [+ [+ {"text": "Alice", "label": "person", "score": 0.9, "start": 0, "end": 5},+ {"text": "Acme", "label": "organization", "score": 0.8, "start": 15, "end": 19},+ ]+ ]+ assert output.classifications is None+ assert output.relations is None+ assert output.data is None+ # [CLS] + four document words + [SEP]; the three prompt words are not billed.+ assert output.input_token_counts == [6]+ model.inference.assert_called_once_with(+ [text],+ entities=["person", "organization"],+ classes=None,+ joint_relations=None,+ structures=None,+ threshold=0.5,+ flat_ner=True,+ multi_label=False,+ batch_size=1,+ )+++def test_classification_task_matches_gliner2_contract() -> None:+ adapter, model = _adapter(+ {+ "classification": [+ [[{"class_name": "review", "score": 0.4}, {"class_name": "block", "score": 0.7}]],+ [[]],+ ]+ }+ )++ output = adapter.extract(+ [Item(text="first"), Item(text="second")],+ labels=["allow", "review", "block"],+ options={"classification_task": "moderation", "multi_label": True, "threshold": 0.3},+ )++ assert output.entities == [[], []]+ assert output.classifications == [+ [{"label": "block", "score": 0.7}, {"label": "review", "score": 0.4}],+ [],+ ]+ kwargs = _inference_kwargs(model)+ assert kwargs["classes"] == {"moderation": ["allow", "review", "block"]}+ assert kwargs["entities"] is None+ assert (kwargs["threshold"], kwargs["multi_label"]) == (0.3, True)+++def test_relation_labels_run_joint_extraction_over_label_entity_types() -> None:+ text = "Alice works at Acme in London"+ adapter, model = _adapter(+ {+ "ner": [[_ner(text, "Alice", "person"), _ner(text, "Acme", "organization")]],+ "joint_relex": [+ [+ _relation("Acme", "located in", "London", 0.6),+ _relation("Alice", "works at", "Acme", 0.9),+ ]+ ],+ }+ )++ output = adapter.extract(+ [Item(text=text)], labels=["person", "organization"], options={"relation_labels": ["works at"]}+ )++ assert [entity["text"] for entity in output.entities[0]] == ["Alice", "Acme"]+ assert output.relations == [+ [+ {"head": "Alice", "tail": "Acme", "relation": "works at", "score": 0.9},+ {"head": "Acme", "tail": "London", "relation": "located in", "score": 0.6},+ ]+ ]+ kwargs = _inference_kwargs(model)+ assert kwargs["entities"] is None+ assert kwargs["joint_relations"] == {None: {"entities": ["person", "organization"], "relations": ["works at"]}}++[email protected]("supplied", [False, True])+def test_relation_threshold_filters_relations_only(supplied: bool) -> None:+ text = "Alice works at Acme in London"+ alice, acme = _ner(text, "Alice", "person", 0.6), _ner(text, "Acme", "organization", 0.6)+ adapter, model = _adapter(+ {+ "ner": [[alice, acme]],+ "joint_relex": [+ [+ _relation("Alice", "works at", "Acme", 0.9),+ _relation("Alice", "located in", "Acme", 0.7),+ _relation("Acme", "works at", "Alice", 0.6),+ ]+ ],+ }+ )+ relation_types = ["works at", "located in"]+ options = {"relation_threshold": 0.7}++ if supplied:+ item = Item(text=text, metadata={"entities": [alice, acme]})+ output = adapter.extract([item], labels=relation_types, options=options)+ else:+ output = adapter.extract(+ [Item(text=text)],+ labels=["person", "organization"],+ options={**options, "relation_labels": relation_types},+ )++ # Kept only above relation_threshold, as the decoder keeps scores above threshold.+ assert output.relations == [[{"head": "Alice", "tail": "Acme", "relation": "works at", "score": 0.9}]]+ assert [entity["text"] for entity in output.entities[0]] == ["Alice", "Acme"]+ assert _inference_kwargs(model)["threshold"] == 0.5++[email protected]("relation_labels", [None, []])+def test_no_relation_labels_run_entity_recognition_only(relation_labels: list[str] | None) -> None:+ text = "Alice works at Acme"+ adapter, model = _adapter({"ner": [[_ner(text, "Alice", "person")]]})++ output = adapter.extract([Item(text=text)], labels=["person"], options={"relation_labels": relation_labels})++ assert output.relations is None+ assert [entity["text"] for entity in output.entities[0]] == ["Alice"]+ assert _inference_kwargs(model)["entities"] == ["person"]+++def test_relation_threshold_cannot_lower_the_decoding_threshold() -> None:+ adapter, model = _adapter({"ner": [[]], "joint_relex": [[]]})+ options = {"relation_labels": ["knows"], "threshold": 0.5}++ with pytest.raises(InvalidInputError, match="relation_threshold must be at least threshold"):+ adapter.extract([Item(text="Ada met Bo")], labels=["person"], options={**options, "relation_threshold": 0.3})+ model.inference.assert_not_called()++ adapter.extract([Item(text="Ada met Bo")], labels=["person"], options={**options, "relation_threshold": 0.5})+ model.inference.assert_called_once()+++def test_metadata_entities_use_the_shared_relation_contract() -> None:+ first = "Ada founded Acme"+ second = "Grace joined Beta in Paris"+ adapter, model = _adapter({})+ model.inference.side_effect = [+ {+ "ner": [[]],+ "joint_relex": [[_relation("Ada", "founded", "Acme", 0.8), _relation("Ada", "founded", "X", 0.9)]],+ },+ {"ner": [[]], "joint_relex": [[_relation("Grace", "joined", "Beta", 0.7)]]},+ ]+ items = [+ Item(+ text=first,+ metadata={+ "entities": [+ {"text": "Ada", "label": "person", "start": 0, "end": 3},+ {"text": "Acme", "label": "company", "start": 12, "end": 16},+ ]+ },+ ),+ Item(+ text=second,+ metadata={+ "entities": [+ {"text": "Grace", "label": "person", "start": 0, "end": 5},+ {"text": "Paris", "label": "city", "start": 21, "end": 26},+ ]+ },+ ),+ ]++ output = adapter.extract(items, labels=["founded", "joined"])++ assert output.entities[0][1] == {"text": "Acme", "label": "company", "score": 1.0, "start": 12, "end": 16}+ # Endpoints outside the supplied entities are not answers.+ assert output.relations == [[{"head": "Ada", "tail": "Acme", "relation": "founded", "score": 0.8}], []]+ calls = [call.kwargs["joint_relations"] for call in model.inference.call_args_list]+ # Each item's entity types, in a canonical order.+ assert calls == [+ {None: {"entities": ["company", "person"], "relations": ["founded", "joined"]}},+ {None: {"entities": ["city", "person"], "relations": ["founded", "joined"]}},+ ]+++def test_output_schema_combines_structuring_and_enum_classification_in_one_pass() -> None:+ text = "Refund for Maria Lopez on order 4471 was denied."+ schema = {+ "type": "object",+ "properties": {+ "customer": {"type": "string"},+ "decision": {"type": "string", "enum": ["approved", "denied"]},+ "reasons": {"type": "array", "items": {"type": "string"}},+ "$amount": {"type": "string"},+ },+ "required": ["decision"],+ }+ adapter, model = _adapter(+ {+ "ner": [[_ner(text, "Maria Lopez", "person")]],+ "classification": [[[{"class_name": "denied", "score": 0.95}]]],+ "structuring": [{"customer": "Maria Lopez", "reasons": [], "$amount": None}],+ }+ )++ output = adapter.extract([Item(text=text)], labels=["person"], output_schema=schema)++ assert output.data == [{"customer": "Maria Lopez", "decision": "denied"}]+ assert output.errors is None+ assert [entity["text"] for entity in output.entities[0]] == ["Maria Lopez"]+ model.inference.assert_called_once()+ kwargs = _inference_kwargs(model)+ assert kwargs["classes"] == {"decision": ["approved", "denied"]}+ assert kwargs["structures"] == {"$root": {"customer": "str", "reasons": ["str"], "$$amount": "str"}}+ assert kwargs["entities"] == ["person"]+++def test_structuring_output_goes_through_the_upstream_formatter() -> None:+ schema = {"type": "object", "properties": {"customer": {"type": "string"}}}+ adapter, _ = _adapter({"structuring": [{"customer": ["Maria Lopez", "Tim Cook"]}]})+ formatter = MagicMock()+ formatter.format_batch.return_value = [{"customer": "Maria Lopez"}]+ adapter._build_formatter = MagicMock(return_value=formatter)++ output = adapter.extract([Item(text="Maria Lopez and Tim Cook")], output_schema=schema)++ assert output.data == [{"customer": "Maria Lopez"}]+ adapter._build_formatter.assert_called_once_with({"$root": {"customer": "str"}})+ formatter.format_batch.assert_called_once_with([{"customer": ["Maria Lopez", "Tim Cook"]}])+++def test_missing_required_property_is_a_per_item_error() -> None:+ schema = {+ "type": "object",+ "properties": {"customer": {"type": "string"}, "decision": {"type": "string", "enum": ["yes", "no"]}},+ "required": ["decision"],+ }+ adapter, _ = _adapter(+ {+ "classification": [[[]], [[{"class_name": "yes", "score": 0.9}]]],+ "structuring": [{"customer": "Ann"}, {}],+ }+ )++ output = adapter.extract([Item(text="Ann asked"), Item(text="Approved")], output_schema=schema)++ assert output.data == [{}, {"decision": "yes"}]+ assert output.errors == [+ ExtractItemError(+ code="INFERENCE_ERROR",+ message="GLiFormer did not extract required output_schema properties: ['decision']",+ ),+ None,+ ]+ # The errored item bills nothing; "Approved" is one word plus two specials.+ assert output.input_token_counts == [0, 3]+++def test_missing_required_property_blanks_every_task_output_and_bills_nothing() -> None:+ text = "Tim Cook runs Apple"+ schema = {+ "type": "object",+ "properties": {"ceo": {"type": "string"}, "tone": {"type": "string", "enum": ["calm", "tense"]}},+ "required": ["ceo"],+ }+ adapter, _ = _adapter(+ {+ "ner": [[_ner(text, "Tim Cook", "person")], [_ner(text, "Apple", "organization")]],+ "joint_relex": [+ [_relation("Tim Cook", "runs", "Apple", 0.9)],+ [_relation("Tim Cook", "runs", "Apple", 0.8)],+ ],+ "classification": [[[{"class_name": "calm", "score": 0.9}]], [[{"class_name": "tense", "score": 0.7}]]],+ "structuring": [{}, {"ceo": "Tim Cook"}],+ }+ )++ output = adapter.extract(+ [Item(text=text), Item(text=text)],+ labels=["person", "organization"],+ output_schema=schema,+ options={"relation_labels": ["runs"]},+ )++ assert output.errors is not None+ assert [error is not None for error in output.errors] == [True, False]+ assert output.entities[0] == []+ assert output.relations is not None+ assert output.relations[0] == []+ assert output.data == [{}, {"ceo": "Tim Cook", "tone": "tense"}]+ assert output.entities[1] != []+ assert output.relations[1] != []+ assert output.input_token_counts == [0, 6]+++def test_classification_task_and_enum_properties_share_one_forward_pass() -> None:+ schema = {"type": "object", "properties": {"urgency": {"type": "string", "enum": ["high", "low"]}}}+ adapter, model = _adapter(+ {+ "classification": [+ [[{"class_name": "negative", "score": 0.8}], [{"class_name": "high", "score": 0.7}]],+ ]+ }+ )++ output = adapter.extract(+ [Item(text="The server is down again!")],+ labels=["positive", "negative"],+ output_schema=schema,+ options={"classification_task": "sentiment"},+ )++ assert output.classifications == [[{"label": "negative", "score": 0.8}]]+ assert output.data == [{"urgency": "high"}]+ assert _inference_kwargs(model)["classes"] == {"sentiment": ["positive", "negative"], "urgency": ["high", "low"]}+ assert _inference_kwargs(model)["structures"] is None+++def test_label_groups_return_gliclass_style_classifications_only() -> None:+ adapter, model = _adapter(+ {+ "ner": [[]],+ "classification": [+ [+ [{"class_name": "billing", "score": 0.9}],+ [{"class_name": "high", "score": 0.6}, {"class_name": "low", "score": 0.55}],+ [],+ ]+ ],+ }+ )++ output = adapter.extract(+ [Item(text="I was charged twice")],+ labels=["person"],+ options={+ "label_groups": {+ "topic": ["billing", "bug report"],+ "urgency": ["low", "high"],+ "needs human": ["yes", "no"],+ },+ "classification_type": "multi-label",+ },+ )++ # GLiFormer scores only labels that pass the threshold, so there is no+ # per-group distribution to report in ``data``.+ assert output.data is None+ assert output.classifications == [+ [+ {"label": "topic.billing", "score": 0.9},+ {"label": "urgency.high", "score": 0.6},+ {"label": "urgency.low", "score": 0.55},+ ]+ ]+ kwargs = _inference_kwargs(model)+ assert kwargs["classes"] == {+ "topic": ["billing", "bug report"],+ "urgency": ["low", "high"],+ "needs human": ["yes", "no"],+ }+ assert kwargs["entities"] == ["person"]+ assert kwargs["multi_label"] is True+++def test_classification_output_outside_the_requested_labels_is_a_per_item_error() -> None:+ adapter, _ = _adapter({"classification": [[[{"class_name": "other", "score": 0.9}]]]})+ output = adapter.extract([Item(text="hello")], labels=["a", "b"], options={"classification_task": "t"})+ assert output.classifications == [[]]+ assert output.errors == [ExtractItemError(code="INFERENCE_ERROR", message=adapter_module._ERR_ITEM_OUTPUT)]+ assert output.input_token_counts == [0]+++def test_options_passed_through_as_sent_keep_their_order() -> None:+ adapter, model = _adapter({"classification": [[[], []]]})+ options = {"label_groups": {"urgency": ["low", "high"], "topic": ["jobs"]}}+ adapter.extract([Item(text="hello")], options=options)+ assert list(_inference_kwargs(model)["classes"]) == ["urgency", "topic"]+++def test_instruction_is_accepted_and_ignored() -> None:+ adapter, model = _adapter({"ner": [[]]})+ adapter.extract([Item(text="hello world")], labels=["person"], instruction="ignored")+ assert "instruction" not in _inference_kwargs(model)+++# -- Request validation ------------------------------------------------------------+++ ("kwargs", "match"),+ [+ ({}, "requires labels, label_groups, or output_schema"),+ ({"options": {"label_groups": {}}}, "label_groups must be a non-empty object"),+ ({"options": {"label_groups": {"topic": []}}}, "must be a non-empty list"),+ ({"options": {"label_groups": {"topic": ["a", "a"]}}}, "must be unique"),+ (+ {"labels": ["a"], "options": {"classification_task": "t", "label_groups": {"g": ["x"]}}},+ "label_groups cannot be combined with classification_task",+ ),+ (+ {+ "options": {"label_groups": {"g": ["x"]}},+ "output_schema": {"type": "object", "properties": {"n": {"type": "string"}}},+ },+ "label_groups cannot be combined with output_schema",+ ),+ ({"labels": ["a"], "options": {"classification_type": "softmax"}}, "classification_type must be"),+ (+ {"labels": ["a"], "options": {"classification_type": "multi-label", "multi_label": False}},+ "contradicts classification_type",+ ),+ ({"options": {"classification_task": "topic"}}, "classification_task requires labels"),+ ({"options": {"relation_labels": ["works at"]}}, "relation_labels require labels"),+ (+ {"labels": ["a"], "options": {"classification_task": "topic", "relation_labels": ["r"]}},+ "cannot be combined",+ ),+ ({"labels": ["a"], "options": {"threshold": 1.5}}, "between 0 and 1"),+ ({"labels": ["a"], "options": {"threshold": -0.1}}, "between 0 and 1"),+ ({"labels": ["a"], "options": {"threshold": True}}, "between 0 and 1"),+ ({"labels": ["a"], "options": {"threshold": 0}}, "at least 0.1"),+ ({"labels": ["a"], "options": {"threshold": 0.0999}}, "at least 0.1"),+ ({"labels": ["a"], "options": {"multi_label": "yes"}}, "multi_label must be boolean"),+ ({"labels": ["a"], "options": {"flat_ner": 1}}, "flat_ner must be boolean"),+ ({"labels": ["a", "a"]}, "labels must be unique"),+ ({"labels": ["a", " "]}, "labels must be non-empty strings"),+ ({"labels": ["a"], "options": {"relation_labels": "works at"}}, "relation_labels must be a non-empty list"),+ ({"labels": ["a"], "options": {"relation_labels": ""}}, "relation_labels must be a non-empty list"),+ ({"labels": ["a"], "options": {"relation_labels": False}}, "relation_labels must be a non-empty list"),+ ({"labels": ["a"], "options": {"relations": ["works at"]}}, "options.relation_labels, not options.relations"),+ ({"labels": ["a"], "options": {"relations": []}}, "options.relation_labels, not options.relations"),+ ({"labels": ["a"], "options": {"relation_threshold": 1.5}}, "relation_threshold must be a number between"),+ ({"labels": ["a"], "options": {"relation_threshold": False}}, "relation_threshold must be a number between"),+ ({"labels": ["a"], "options": {"threshold": 10**1000}}, "threshold must be a number between"),+ ({"labels": ["a"], "options": {"relation_threshold": 10**1000}}, "relation_threshold must be a number between"),+ ({"labels": ["a"], "options": {"classification_task": " "}}, "classification_task must be a non-empty string"),+ (+ {+ "labels": ["x"],+ "options": {"classification_task": "urgency"},+ "output_schema": {"type": "object", "properties": {"urgency": {"enum": ["high", "low"]}}},+ },+ "must differ from output_schema enum",+ ),+ ],+)+def test_invalid_requests_are_rejected(kwargs: dict[str, Any], match: str) -> None:+ adapter, model = _adapter({})+ with pytest.raises(InvalidInputError, match=match):+ adapter.extract([Item(text="hello world")], **kwargs)+ model.inference.assert_not_called()++[email protected](("text", "match"), [(None, "requires text"), (" ", "non-blank text")])+def test_items_require_non_blank_text(text: str | None, match: str) -> None:+ adapter, _ = _adapter({})+ with pytest.raises(InvalidInputError, match=match):+ adapter.extract([Item(text=text)], labels=["person"])+++def test_metadata_entities_must_cover_every_item_and_exclude_other_relation_modes() -> None:+ adapter, _ = _adapter({})+ tagged = Item(text="Ada founded Acme", metadata={"entities": [{"text": "Ada", "start": 0, "end": 3}]})+ with pytest.raises(InvalidInputError, match="every item metadata"):+ adapter.extract([tagged, Item(text="Grace founded Beta")], labels=["founded"])+ with pytest.raises(InvalidInputError, match="cannot be combined"):+ adapter.extract([tagged], labels=["founded"], options={"relation_labels": ["founded"]})+ bad_offsets = Item(text="Ada founded Acme", metadata={"entities": [{"text": "Ada", "start": 1, "end": 4}]})+ with pytest.raises(InvalidInputError, match="valid character offsets"):+ adapter.extract([bad_offsets], labels=["founded"])+ for score in (2.0, float("nan"), 10**1000):+ bad_score = Item(+ text="Ada founded Acme", metadata={"entities": [{"text": "Ada", "start": 0, "end": 3, "score": score}]}+ )+ with pytest.raises(InvalidInputError, match="relation entity score must be"):+ adapter.extract([bad_score], labels=["founded"])+++# -- Model output validation and metering -----------------------------------------+++ "bad_entity",+ [+ {"start": 0, "end": 4, "text": "Bob", "label": "person", "score": 0.9},+ {"start": 0, "end": 5, "text": "Alice", "label": "person", "score": 1.5},+ "not an entity",+ ],+)+def test_malformed_output_for_one_item_fails_only_that_item(bad_entity: Any) -> None:+ texts = ["Alice works here", "Bob works there"]+ adapter, _ = _adapter({"ner": [[bad_entity], [_ner(texts[1], "Bob", "person")]]})++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert output.entities[0] == []+ assert [entity["text"] for entity in output.entities[1]] == ["Bob"]+ assert output.errors == [ExtractItemError(code="INFERENCE_ERROR", message=adapter_module._ERR_ITEM_OUTPUT), None]+ # Errored items bill nothing.+ assert output.input_token_counts == [0, 5]+++def test_output_not_aligned_with_the_batch_is_an_internal_error() -> None:+ adapter, _ = _adapter({"ner": [[], []]})+ with pytest.raises(RuntimeError, match="malformed ner") as info:+ adapter.extract([Item(text="Alice works here")], labels=["person"])+ # A ValueError would be reported to the caller as a 400.+ assert not isinstance(info.value, ValueError)+++def test_non_finite_scores_fail_only_the_documents_that_produce_them() -> None:+ texts = ["Alice works here", "poison pill text", "Bob works there"]+ adapter, model = _adapter({})++ def inference(batch: list[str], **_: Any) -> dict[str, Any]:+ if "poison pill text" in batch:+ raise adapter_module._NonFiniteScoresError("GLiFormer produced non-finite scores")+ return {"ner": [[_ner(text, text.split()[0], "person")] for text in batch]}++ model.inference.side_effect = inference++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ # The shared pass fails, then the chunk is split in halves until the+ # failing document runs alone.+ assert [call.args[0] for call in model.inference.call_args_list] == [+ texts,+ texts[:1],+ texts[1:],+ texts[1:2],+ texts[2:],+ ]+ assert [[entity["text"] for entity in entities] for entities in output.entities] == [["Alice"], [], ["Bob"]]+ assert output.errors is not None+ assert [error is not None for error in output.errors] == [False, True, False]+ assert output.input_token_counts == [5, 0, 5]+++def test_structured_output_that_cannot_be_formatted_fails_only_its_item() -> None:+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}+ adapter, _ = _adapter({"structuring": [{"name": "Ann"}, {"name": "Bob"}]})+ formatter = MagicMock()+ formatter.format_batch.side_effect = lambda rows: (+ [{"name": "Bob"}] if rows == [{"name": "Bob"}] else (_ for _ in ()).throw(ValueError("bad value"))+ )+ adapter._build_formatter = MagicMock(return_value=formatter)++ output = adapter.extract([Item(text="Ann asked"), Item(text="Bob asked")], output_schema=schema)++ assert output.data == [{}, {"name": "Bob"}]+ assert output.errors is not None+ assert [error is not None for error in output.errors] == [True, False]+ assert output.input_token_counts == [0, 4]+++def test_score_outputs_are_decoded_in_float32() -> None:+ logits = torch.tensor([[9.0, 8.5]], dtype=torch.float16)+ # The problem being fixed: in float16 both labels saturate to 1.0, and+ # single-label argmax then picks whichever comes first.+ assert torch.sigmoid(logits.float()).half().tolist() == [[1.0, 1.0]]+ embedding = torch.zeros(2, dtype=torch.float16)+ output = {"cat_logits": logits, "words_embedding": embedding, "span_mask": torch.tensor([True]), "batch_size": 1}++ result = adapter_module._upcast_score_outputs(MagicMock(), (), output)++ assert result["cat_logits"].dtype == torch.float32+ probabilities = torch.sigmoid(result["cat_logits"])[0]+ assert probabilities[0] > probabilities[1]+ assert result["words_embedding"] is embedding+ assert result["batch_size"] == 1+++def test_masked_scores_pass_but_nan_and_positive_infinity_fail() -> None:+ masked = {"joint_rel_logits": torch.tensor([[float("-inf"), 1.0]], dtype=torch.float16)}+ assert adapter_module._upcast_score_outputs(MagicMock(), (), masked) is masked+ for bad in (float("nan"), float("inf")):+ with pytest.raises(RuntimeError, match="non-finite scores"):+ adapter_module._upcast_score_outputs(MagicMock(), (), {"span_logits": torch.tensor([bad, 0.0])})+ assert adapter_module._upcast_score_outputs(MagicMock(), (), (1, 2)) == (1, 2)+++_SPAN_FIELD_SCHEMA = {"type": "object", "properties": {"name": {"type": "string"}}}+_ENUM_ONLY_SCHEMA = {"type": "object", "properties": {"decision": {"type": "string", "enum": ["approve", "deny"]}}}+_MIXED_SCHEMA = {+ "type": "object",+ "properties": {"name": {"type": "string"}, "decision": {"type": "string", "enum": ["approve", "deny"]}},+}+++ "request_kwargs",+ [+ {"labels": ["a", "b"], "options": {"classification_task": "t"}},+ {"options": {"label_groups": {"g": ["a", "b"], "h": ["c", "d"]}}},+ {"output_schema": _ENUM_ONLY_SCHEMA},+ {"options": {"label_groups": {"g": ["a", "b"]}, "multi_label": True}},+ ],+)[email protected]("threshold", [0, 0.0, 0.05])+def test_classification_only_requests_accept_any_threshold(request_kwargs: dict[str, Any], threshold: float) -> None:+ adapter, model = _adapter({"classification": [[[{"class_name": "a", "score": 0.02}], []]]})+ options = {**request_kwargs.get("options", {}), "threshold": threshold}++ adapter.extract([Item(text="hello")], **{**request_kwargs, "options": options})++ # 0 reaches the package as the smallest positive threshold: it reads 0 as+ # "unset" and would fall back to 0.5.+ assert _inference_kwargs(model)["threshold"] == pytest.approx(max(threshold, 1e-6))+++ "request_kwargs",+ [+ {"labels": ["person"]},+ {"labels": ["person"], "options": {"relation_labels": ["knows"]}},+ {"output_schema": _SPAN_FIELD_SCHEMA},+ {"labels": ["knows"], "items_metadata": True},+ ],+)+def test_span_requests_need_the_threshold_floor(request_kwargs: dict[str, Any]) -> None:+ adapter, model = _adapter({"ner": [[]], "joint_relex": [[]], "structuring": [{}]})+ kwargs = {key: value for key, value in request_kwargs.items() if key != "items_metadata"}+ metadata = {"entities": [{"text": "Ada", "label": "person", "start": 0, "end": 3}]}+ item = Item(text="Ada met Bo", metadata=metadata if "items_metadata" in request_kwargs else None)++ with pytest.raises(InvalidInputError, match=r"at least 0\.1"):+ adapter.extract([item], **{**kwargs, "options": {**kwargs.get("options", {}), "threshold": 0.05}})+ model.inference.assert_not_called()++ adapter.extract([item], **{**kwargs, "options": {**kwargs.get("options", {}), "threshold": 0.1}})+ assert _inference_kwargs(model)["threshold"] == pytest.approx(0.1)+++ "request_kwargs",+ [+ {"labels": ["person"], "options": {"label_groups": {"g": ["a", "b"]}}},+ {"output_schema": _MIXED_SCHEMA},+ {"labels": ["person"], "output_schema": _ENUM_ONLY_SCHEMA},+ ],+)+def test_mixed_requests_apply_the_floor_to_their_single_threshold(request_kwargs: dict[str, Any]) -> None:+ adapter, model = _adapter({})+ options = {**request_kwargs.get("options", {}), "threshold": 0.0}+ with pytest.raises(InvalidInputError, match=r"at least 0\.1"):+ adapter.extract([Item(text="hello")], **{**request_kwargs, "options": options})+ model.inference.assert_not_called()+++def test_configured_threshold_is_range_checked() -> None:+ assert GLiFormerAdapter("test-model", threshold=0.0)._threshold == 0.0+ with pytest.raises(InvalidInputError, match="between 0 and 1"):+ GLiFormerAdapter("test-model", threshold=1.5)+++def test_nan_bisection_costs_logarithmic_passes() -> None:+ texts = [f"document {index}" for index in range(32)]+ adapter, model = _adapter({})++ def inference(batch: list[str], **_: Any) -> dict[str, Any]:+ if "document 17" in batch:+ raise adapter_module._NonFiniteScoresError("GLiFormer produced non-finite scores")+ return {"ner": [[] for _ in batch]}++ model.inference.side_effect = inference++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ # 1 failed pass + 2 per halving level (log2 32 = 5): 11 passes, not 33.+ assert model.inference.call_count == 11+ assert output.errors is not None+ assert [index for index, error in enumerate(output.errors) if error is not None] == [17]+++def test_widespread_non_finite_scores_cost_at_most_n_plus_three_passes() -> None:+ texts = [f"document {index}" for index in range(32)]+ adapter, model = _adapter({})++ def inference(batch: list[str], **_: Any) -> dict[str, Any]:+ raise adapter_module._NonFiniteScoresError("GLiFormer produced non-finite scores")++ model.inference.side_effect = inference++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ # The full chunk, both halves, then each document alone.+ assert model.inference.call_count == 32 + 3+ assert output.errors is not None+ assert all(error is not None for error in output.errors)+ assert output.input_token_counts == [0] * 32+++ ("lengths", "budget", "chunks"),+ [+ ([5, 5, 20, 3], 20, [[0, 1], [2], [3]]),+ ([50], 20, [[0]]),+ ([4, 4, 4, 4], 16, [[0, 1, 2, 3]]),+ ([], 16, []),+ ],+)+def test_token_budget_chunks_bound_padded_tokens(lengths: list[int], budget: int, chunks: list[list[int]]) -> None:+ assert adapter_module._token_budget_chunks(lengths, budget) == chunks+++def test_inference_is_split_into_padded_token_chunks() -> None:+ texts = ["Alice works here", "Bob works there", "Carol stays home"]+ adapter, model = _adapter({}, inference_batch_tokens=16)+ model.inference.side_effect = lambda batch, **_: {+ "ner": [[_ner(text, text.split()[0], "person")] for text in batch]+ }++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ # Every fake sequence is 8 tokens: 3 prompt + special + 3 document + special.+ assert [call.args[0] for call in model.inference.call_args_list] == [texts[:2], texts[2:]]+ assert [call.kwargs["batch_size"] for call in model.inference.call_args_list] == [2, 1]+ assert [[entity["text"] for entity in entities] for entities in output.entities] == [["Alice"], ["Bob"], ["Carol"]]+ assert output.input_token_counts == [5, 5, 5]+++def test_documents_are_billed_up_to_the_window_left_by_the_prompt() -> None:+ adapter, _ = _adapter({"ner": [[], []]}, max_len=10)++ output = adapter.extract([Item(text="one two"), Item(text=" ".join(["word"] * 50))], labels=["person"])++ # Window 10 = 3 prompt + 2 special + at most 5 document tokens.+ assert output.input_token_counts == [4, 7]+++def test_relation_requests_bound_candidate_pairs_per_pass() -> None:+ adapter, model = _adapter({})+ model.inference.side_effect = lambda batch, **_: {"ner": [[] for _ in batch], "joint_relex": [[] for _ in batch]}++ adapter.extract(+ [Item(text=f"text number {index}") for index in range(20)],+ labels=["person"],+ options={"relation_labels": ["knows"]},+ )++ # 100 relation entities per document -> 9900 pairs; 131072 pairs per pass.+ assert [call.kwargs["batch_size"] for call in model.inference.call_args_list] == [13, 7]+++def test_relation_types_are_bounded() -> None:+ adapter, model = _adapter({})+ with pytest.raises(InvalidInputError, match="at most 20 relation types"):+ adapter.extract(+ [Item(text="hello world")], labels=["person"], options={"relation_labels": [f"r{i}" for i in range(21)]}+ )+ supplied = Item(+ text="Ada met Bo", metadata={"entities": [{"text": "Ada", "label": "person", "start": 0, "end": 3}]}+ )+ with pytest.raises(InvalidInputError, match="at most 20 relation types"):+ adapter.extract([supplied], labels=[f"r{i}" for i in range(21)])+ model.inference.assert_not_called()+++def test_outputs_are_decoded_from_host_memory() -> None:+ logits = torch.zeros(1, 2, 3, dtype=torch.float16)+ output = {+ "joint_rel_logits": logits,+ "joint_rel_idx": torch.zeros(1, 2, 2, dtype=torch.long),+ "words_embedding": torch.zeros(1, 2, dtype=torch.float16),+ "batch_size": 1,+ }++ result = adapter_module._upcast_score_outputs(MagicMock(), (), output)++ assert all(value.device.type == "cpu" for value in result.values() if isinstance(value, torch.Tensor))+ assert result["joint_rel_logits"].dtype == torch.float32+ assert result["words_embedding"].dtype == torch.float16+ assert result["batch_size"] == 1++[email protected](("current", "expected"), [(None, 100), (40, 40), (500, 100)])+def test_relation_candidates_are_limited_at_load(current: int | None, expected: int) -> None:+ head = SimpleNamespace(max_relation_entities=current)+ adapter_module._limit_relation_entities(SimpleNamespace(heads={"joint_relex": head, "ner": object()}))+ assert head.max_relation_entities == expected+++def test_relation_limit_fails_closed_without_a_relation_head() -> None:+ for model in (SimpleNamespace(heads={"ner": object()}), SimpleNamespace()):+ with pytest.raises(RuntimeError, match="no joint relation head"):+ adapter_module._limit_relation_entities(model)+++def test_supplied_entity_label_order_does_not_create_groups() -> None:+ adapter, model = _adapter({})+ model.inference.side_effect = lambda batch, **_: {"ner": [[] for _ in batch], "joint_relex": [[] for _ in batch]}+ orders = (["person", "company"], ["company", "person"])+ items = [+ Item(+ text="Ada founded Acme",+ metadata={+ "entities": [+ {+ "text": "Ada" if label == "person" else "Acme",+ "label": label,+ "start": 0 if label == "person" else 12,+ "end": 3 if label == "person" else 16,+ }+ for label in order+ ]+ },+ )+ for order in orders+ ]++ adapter.extract(items, labels=["founded"])++ assert model.inference.call_count == 1+ assert model.inference.call_args.kwargs["batch_size"] == 2+++def test_distinct_supplied_label_sets_are_capped() -> None:+ adapter, model = _adapter({})+ items = [+ Item(text="Ada met Bo", metadata={"entities": [{"text": "Ada", "label": f"t{index}", "start": 0, "end": 3}]})+ for index in range(65)+ ]+ with pytest.raises(InvalidInputError, match="at most 64 distinct sets"):+ adapter.extract(items, labels=["met"])+ model.inference.assert_not_called()+ model.data_processor.collate_raw_batch.assert_not_called()++[email protected]("budget", [0, -1, 1.5, True])+def test_inference_batch_tokens_must_be_a_positive_integer(budget: object) -> None:+ with pytest.raises(ValueError, match="inference_batch_tokens"):+ GLiFormerAdapter("test-model", inference_batch_tokens=budget) # type: ignore[arg-type]+++def test_prompt_that_exhausts_the_window_is_rejected() -> None:+ adapter, model = _adapter({"ner": [[]]}, max_len=5)+ with pytest.raises(InvalidInputError, match="leaves no document tokens"):+ adapter.extract([Item(text="Alice works here")], labels=["person"])+ model.inference.assert_not_called()+++def test_prompt_over_budget_is_rejected_before_any_document_is_tokenized() -> None:+ adapter, model = _adapter({"ner": [[]]}, max_prompt_tokens=2)+ tokenizer = model.data_processor.transformer_tokenizer++ with pytest.raises(InvalidInputError, match="task prompt needs 3 tokens"):+ adapter.extract([Item(text="Alice works here")] * 64, labels=["person"])++ # Only the prompt itself was tokenized, once.+ assert tokenizer.calls == [[["P", "P", "P"]]]+ model.inference.assert_not_called()+++def test_every_task_group_is_measured_before_inference_runs() -> None:+ adapter, model = _adapter({}, max_prompt_tokens=3)+ prompt_words = {("a",): 3, ("b",): 4}++ def prepare_inputs(tokens: list[list[str]], _mapping: Any) -> tuple[list[list[str]], list[int]]:+ types = model._build_inference_input.call_args.kwargs["joint_relations"][None]["entities"]+ count = prompt_words[tuple(types)]+ return [["P"] * count + list(words) for words in tokens], [count] * len(tokens)++ model.data_processor.prepare_inputs.side_effect = prepare_inputs+ items = [+ Item(text="Ada met Bo", metadata={"entities": [{"text": "Ada", "label": "a", "start": 0, "end": 3}]}),+ Item(text="Ada met Bo", metadata={"entities": [{"text": "Bo", "label": "b", "start": 8, "end": 10}]}),+ ]++ with pytest.raises(InvalidInputError, match="task prompt needs 4 tokens"):+ adapter.extract(items, labels=["met"])+ model.inference.assert_not_called()+++def test_prompt_build_failure_is_an_internal_error() -> None:+ adapter, model = _adapter({"ner": [[]]})+ model.data_processor.collate_raw_batch.side_effect = KeyError("processor drift")+ with pytest.raises(RuntimeError, match="could not build the task prompt") as info:+ adapter.extract([Item(text="Alice works here")], labels=["person"])+ assert not isinstance(info.value, ValueError)+ model.inference.assert_not_called()+++ ("kwargs", "match"),+ [+ ({"labels": ["x" * 129]}, "at most 128 characters"),+ ({"labels": ["a"], "options": {"relation_labels": ["r" * 129]}}, "at most 128 characters"),+ ({"labels": ["a"], "options": {"classification_task": "t" * 129}}, "at most 128 characters"),+ ({"options": {"label_groups": {"g" * 129: ["a"]}}}, "at most 128 characters"),+ ({"options": {"label_groups": {"g": ["a" * 129]}}}, "at most 128 characters"),+ (+ {"labels": [f"e{i}" for i in range(600)], "options": {"relation_labels": [f"r{i}" for i in range(401)]}},+ "in total",+ ),+ ({"options": {"label_groups": {f"g{i}": ["a", "b"] for i in range(334)}}}, "in total"),+ (+ {"options": {"label_groups": {f"g{i}": [f"l{j}" for j in range(10)] for i in range(101)}}},+ "at most 1000 labels",+ ),+ ],+)+def test_prompt_labels_are_bounded(kwargs: dict[str, Any], match: str) -> None:+ adapter, model = _adapter({})+ with pytest.raises(InvalidInputError, match=match):+ adapter.extract([Item(text="hello world")], **kwargs)+ model.inference.assert_not_called()+++def test_supplied_entities_are_bounded() -> None:+ adapter, model = _adapter({})+ text = "Ada founded Acme"+ too_long = Item(text=text, metadata={"entities": [{"text": "Ada", "label": "p" * 129, "start": 0, "end": 3}]})+ with pytest.raises(InvalidInputError, match="at most 128 characters"):+ adapter.extract([too_long], labels=["founded"])+ too_many = Item(+ text=text,+ metadata={"entities": [{"text": "Ada", "label": "person", "start": 0, "end": 3}] * 1001},+ )+ with pytest.raises(InvalidInputError, match="at most 1000 entities"):+ adapter.extract([too_many], labels=["founded"])+ distinct = [+ Item(text=text, metadata={"entities": [{"text": "Ada", "label": f"t{i}-{j}", "start": 0, "end": 3}]})+ for i in range(2)+ for j in range(500)+ ]+ with pytest.raises(InvalidInputError, match="in total"):+ adapter.extract(distinct, labels=["founded"])+ model.inference.assert_not_called()+++def test_caller_text_echoed_in_errors_is_clipped() -> None:+ adapter, _ = _adapter({})+ name = "n" * 10_000+ with pytest.raises(InvalidInputError) as info:+ adapter.extract([Item(text="hello")], options={"label_groups": {"ok": ["a", "a"], name: ["b"]}})+ assert len(str(info.value)) < 300+ schema = {"type": "object", "properties": {"a": {"type": "object", "properties": {"b": {"format": "x" * 10_000}}}}}+ with pytest.raises(InvalidInputError) as info:+ compile_output_schema(+ {"type": "object", "properties": {"p" * 100: schema, "q": {"$ref": "#/$defs/" + "z" * 5000}}}+ )+ assert len(str(info.value)) < 400+++def test_metering_normalizes_structuring_templates_like_inference() -> None:+ adapter, model = _adapter({"structuring": [{"name": "Ann"}]})+ adapter._normalize_structures = MagicMock(side_effect=lambda structures: {"normalized": True})+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}++ adapter.extract([Item(text="Ann asked")], output_schema=schema)++ adapter._normalize_structures.assert_called_once_with({"$root": {"name": "str"}})+ assert model._build_inference_input.call_args.kwargs["structures"] == {"normalized": True}+ assert _inference_kwargs(model)["structures"] == {"$root": {"name": "str"}}+++# -- Encode --------------------------------------------------------------------------+++def test_encode_returns_normalized_dense_embeddings_with_token_counts() -> None:+ adapter, model = _adapter({})+ model.embed_text.return_value = torch.tensor([[3.0, 4.0], [0.0, 2.0]])+ adapter._tokenizer = MagicMock(return_value={"input_ids": [[1, 2, 3], [1, 2]]})++ output = adapter.encode([Item(text="a b"), Item(text="c")], ["dense"], is_query=True)++ np.testing.assert_allclose(output.dense, [[0.6, 0.8], [0.0, 1.0]])+ assert output.is_query is True+ assert output.extra["input_token_counts"] == [3, 2]+ model.embed_text.assert_called_once_with(["a b", "c"], batch_size=2)+ adapter._tokenizer.assert_called_once_with(["a b", "c"], truncation=True)++ raw = adapter.encode([Item(text="a b"), Item(text="c")], ["dense"], options={"normalize": False})+ np.testing.assert_allclose(raw.dense, [[3.0, 4.0], [0.0, 2.0]])+++def test_encode_is_split_into_padded_token_chunks() -> None:+ adapter, model = _adapter({}, inference_batch_tokens=6)+ model.embed_text.side_effect = lambda texts, batch_size: torch.ones(len(texts), 2)+ adapter._tokenizer = MagicMock(return_value={"input_ids": [[1, 2, 3], [1, 2], [1, 2, 3, 4]]})++ output = adapter.encode([Item(text="a b"), Item(text="c"), Item(text="d e f")], ["dense"])++ assert [call.kwargs["batch_size"] for call in model.embed_text.call_args_list] == [2, 1]+ assert output.dense.shape == (3, 2)+ assert output.extra["input_token_counts"] == [3, 2, 4]+++def test_encode_rejects_non_finite_embeddings() -> None:+ adapter, model = _adapter({})+ model.embed_text.return_value = torch.tensor([[float("nan"), 1.0]], dtype=torch.float16)+ adapter._tokenizer = MagicMock(return_value={"input_ids": [[1, 2]]})+ with pytest.raises(RuntimeError, match="non-finite embeddings"):+ adapter.encode([Item(text="a b")], ["dense"])+++def test_encode_rejects_non_dense_outputs() -> None:+ adapter, _ = _adapter({})+ with pytest.raises(InvalidInputError, match="only dense"):+ adapter.encode([Item(text="a")], ["dense", "sparse"])+++# -- Loading ---------------------------------------------------------------------------+++def _fake_gliformer_module(model: MagicMock) -> ModuleType:+ module = ModuleType("gliformer")+ module.GLiFormer = MagicMock() # type: ignore[attr-defined]+ module.GLiFormer.from_pretrained.return_value = model+ module.processing = SimpleNamespace( # type: ignore[attr-defined]+ schema=SimpleNamespace(+ normalize_structuring_schemas="normalizer", build_structuring_output_formatter="formatter"+ )+ )+ return module+++ ("device", "precision", "dtype"),+ [+ ("cpu", None, torch.float32),+ ("cuda:0", None, torch.float16),+ ("cuda:0", "bfloat16", torch.bfloat16),+ ],+)+def test_load_pins_snapshot_and_places_model(device: str, precision: str | None, dtype: torch.dtype) -> None:+ model = MagicMock()+ model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))+ relation_head = SimpleNamespace(max_relation_entities=None)+ model.model.heads = {"joint_relex": relation_head}+ tokenizer = model.data_processor.transformer_tokenizer+ precision_kwargs = {} if precision is None else {"compute_precision": precision}+ adapter = GLiFormerAdapter(+ "knowledgator/gliformer-base-v1",+ revision="a" * 40,+ max_seq_length=2048,+ dense_dim=768,+ **precision_kwargs, # type: ignore[arg-type]+ )+ module = _fake_gliformer_module(model)++ with (+ patch.dict(sys.modules, {"gliformer": module}),+ patch.object(adapter_module, "snapshot_download", return_value="/staged/gliformer") as download,+ ):+ adapter.load(device)++ download.assert_called_once_with(+ repo_id="knowledgator/gliformer-base-v1",+ revision="a" * 40,+ ignore_patterns=["*.gif"],+ )+ module.GLiFormer.from_pretrained.assert_called_once_with(+ "/staged/gliformer",+ load_tokenizer=True,+ map_location="cpu",+ max_length=2048,+ )+ model.to.assert_called_once_with(device=device, dtype=dtype)+ model.eval.assert_called_once_with()+ model.model.register_forward_hook.assert_called_once_with(adapter_module._upcast_score_outputs)+ assert relation_head.max_relation_entities == 100+ assert tokenizer.model_max_length == 2048+ assert adapter._tokenizer is tokenizer+ assert adapter._normalize_structures == "normalizer"+ assert adapter._build_formatter == "formatter"++ adapter.unload()+ assert adapter._model is None+ assert adapter._tokenizer is None+++def test_load_rejects_embedding_dimension_mismatch() -> None:+ model = MagicMock()+ model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))+ model.model.heads = {"joint_relex": SimpleNamespace(max_relation_entities=None)}+ adapter = GLiFormerAdapter("/local/checkpoint", dense_dim=1024)+ with (+ patch.dict(sys.modules, {"gliformer": _fake_gliformer_module(model)}),+ patch.object(adapter_module.Path, "is_dir", return_value=True),+ pytest.raises(ValueError, match="dimension mismatch"),+ ):+ adapter.load("cpu")+++class _FakeAutoMapping:+ """The parts of transformers' lazy ``MODEL_MAPPING`` the adapter inspects."""++ def __init__(self, extra: dict[Any, Any], builtin: dict[Any, Any]) -> None:+ self._extra_content = extra+ self._reverse_config_mapping = {config.__name__: config.__name__.lower() for config in builtin}+ self._model_mapping = {config.__name__.lower(): model.__name__ for config, model in builtin.items()}+ self._builtin = builtin++ def __getitem__(self, config: Any) -> Any:+ return self._extra_content.get(config) or self._builtin[config]+++_GLIFORMER_QWEN3 = type("GLiFormerQwen3Model", (), {"__module__": "gliformer.backbones.qwen3"})+++def test_auto_model_overrides_of_builtin_configs_are_dropped(monkeypatch: pytest.MonkeyPatch) -> None:+ new_config = type("LayoutDebertaConfig", (), {})+ gliformer_layout = type("Layout", (), {"__module__": "gliformer.backbones.deberta_2d"})+ other_config = type("Qwen2Config", (), {})+ other_override = type("Custom", (), {"__module__": "someone.else"})+ mapping = _FakeAutoMapping(+ extra={+ adapter_module.Qwen3Config: _GLIFORMER_QWEN3,+ new_config: gliformer_layout,+ other_config: other_override,+ },+ builtin={adapter_module.Qwen3Config: adapter_module.Qwen3Model, other_config: object},+ )+ monkeypatch.setattr(adapter_module.modeling_auto, "MODEL_MAPPING", mapping)++ adapter_module._drop_builtin_auto_model_overrides()++ assert mapping._extra_content == {new_config: gliformer_layout, other_config: other_override}+ assert mapping[adapter_module.Qwen3Config] is adapter_module.Qwen3Model+++def test_auto_model_restore_fails_closed_when_qwen3_is_still_overridden(monkeypatch: pytest.MonkeyPatch) -> None:+ mapping = _FakeAutoMapping(extra={}, builtin={adapter_module.Qwen3Config: _GLIFORMER_QWEN3})+ monkeypatch.setattr(adapter_module.modeling_auto, "MODEL_MAPPING", mapping)+ with pytest.raises(RuntimeError, match="no longer resolves to Qwen3Model"):+ adapter_module._drop_builtin_auto_model_overrides()+++def test_auto_model_restore_fails_closed_on_unknown_mapping_layout(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(adapter_module.modeling_auto, "MODEL_MAPPING", SimpleNamespace())+ with pytest.raises(RuntimeError, match="Cannot inspect"):+ adapter_module._drop_builtin_auto_model_overrides()+++def test_importing_gliformer_through_the_adapter_keeps_transformers_auto_models() -> None:+ # Fresh interpreter: the package registers its classes once per process.+ script = (+ "from sie_server.adapters.gliformer.adapter import _import_gliformer\n"+ "_import_gliformer()\n"+ "from transformers import Qwen3Config, Qwen3Model\n"+ "from transformers.models.auto.modeling_auto import MODEL_MAPPING\n"+ "from gliformer.backbones import LayoutDebertaConfig, LayoutDebertaModel\n"+ "assert MODEL_MAPPING[Qwen3Config] is Qwen3Model, MODEL_MAPPING[Qwen3Config]\n"+ "assert MODEL_MAPPING[LayoutDebertaConfig] is LayoutDebertaModel\n"+ )+ result = subprocess.run( # noqa: S603 — fixed interpreter and script+ [sys.executable, "-c", script], capture_output=True, text=True, timeout=600, check=False+ )+ assert result.returncode == 0, result.stderr[-4000:]+++# -- output_schema compilation -----------------------------------------------------------+++class _Employee(BaseModel):+ name: str+ role: str | None = None+++class _Company(BaseModel):+ name: str+ sector: str | None = None+ employees: list[_Employee]+ status: Literal["active", "closed"]+++def test_pydantic_json_schema_compiles_to_nested_template_and_choice_group() -> None:+ plan = compile_output_schema(_Company.model_json_schema())++ assert plan.structures == {+ "$root": {"name": "str", "sector": "str", "employees": [{"name": "str", "role": "str"}]},+ }+ assert plan.choice_groups == {"status": ["active", "closed"]}+++def test_structured_output_drops_unextracted_values_and_incomplete_records() -> None:+ plan = compile_output_schema(_Company.model_json_schema())+ raw = {+ "name": "Acme",+ "sector": None,+ "employees": [{"name": "Ann", "role": None}, {"name": None, "role": "cook"}, {}],+ "unexpected": "value",+ }++ data, missing = shape_structured_output(plan, raw, {"status": "active"})++ assert data == {"name": "Acme", "employees": [{"name": "Ann"}], "status": "active"}+ assert missing == []+ data, missing = shape_structured_output(plan, {}, {})+ assert (data, missing) == ({}, ["name", "employees", "status"])+++def test_nested_objects_lacking_required_values_are_discarded() -> None:+ schema = {+ "type": "object",+ "properties": {+ "title": {"type": "string"},+ "address": {+ "type": "object",+ "properties": {"street": {"type": "string"}, "city": {"type": "string"}},+ "required": ["city"],+ },+ },+ }+ plan = compile_output_schema(schema)+ assert plan.structures == {"$root": {"title": "str", "address": {"street": "str", "city": "str"}}}+ assert shape_structured_output(plan, {"title": "HQ", "address": {"street": "1 Main St"}}, {}) == (+ {"title": "HQ"},+ [],+ )+++def test_single_valued_fields_keep_the_best_of_several_candidates() -> None:+ schema = {+ "type": "object",+ "properties": {+ "customer": {"type": "string"},+ "address": {"type": "object", "properties": {"city": {"type": "string"}}},+ "tags": {"type": "array", "items": {"type": "string"}},+ },+ }+ plan = compile_output_schema(schema)+ raw = {+ "customer": [None, "Maria Lopez", "Tim Cook"],+ "address": [{"city": "Boston"}, {"city": "London"}],+ "tags": ["refund", "late"],+ }++ assert shape_structured_output(plan, raw, {}) == (+ {"customer": "Maria Lopez", "address": {"city": "Boston"}, "tags": ["refund", "late"]},+ [],+ )++[email protected]("value", [[3], 3, {"a": "b"}])+def test_structured_output_with_wrong_shapes_is_rejected(value: object) -> None:+ plan = compile_output_schema({"type": "object", "properties": {"name": {"type": "string"}}})+ with pytest.raises(RuntimeError, match="malformed structured output"):+ shape_structured_output(plan, {"name": value}, {})+++def test_optional_types_and_annotations_are_accepted() -> None:+ schema = {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "title": "Ticket",+ "description": "A support ticket",+ "additionalProperties": False,+ "properties": {+ "summary": {"type": ["string", "null"], "description": "One line", "default": None},+ "tags": {"anyOf": [{"type": "array", "items": {"type": "string"}}, {"type": "null"}]},+ "!urgent": {"type": "string", "examples": ["yes"]},+ },+ }+ plan = compile_output_schema(schema)+ assert plan.structures == {"$root": {"summary": "str", "tags": ["str"], "!!urgent": "str"}}+++ ("schema", "match"),+ [+ ({"type": "array", "items": {"type": "string"}}, "root type must be object"),+ ({"type": "object", "properties": {}}, "non-empty properties"),+ ({"type": "object", "properties": {"age": {"type": "integer"}}}, "supports string"),+ ({"type": "object", "properties": {"n": {"type": "string", "format": "date"}}}, "unsupported keywords"),+ ({"type": "object", "properties": {"a.b": {"type": "string"}}}, "contain no '.'"),+ ({"type": "object", "properties": {"n": {"type": "string"}}, "required": ["m"]}, "required must list"),+ (+ {"type": "object", "properties": {"n": {"type": "string"}}, "additionalProperties": {"type": "string"}},+ "additionalProperties must be boolean",+ ),+ (+ {+ "type": "object",+ "properties": {+ "p": {"type": "object", "properties": {"s": {"type": "string", "enum": ["a", "b"]}}},+ },+ },+ "only at the schema root",+ ),+ (+ {"type": "object", "properties": {"t": {"type": "array", "items": {"type": "string", "enum": ["a"]}}}},+ "arrays of enum values",+ ),+ ({"type": "object", "properties": {"s": {"type": "string", "enum": ["a", "a"]}}}, "unique non-empty"),+ ({"type": "object", "properties": {"s": {"enum": [1, 2]}}}, "unique non-empty strings"),+ ({"type": "object", "properties": {"s": {"$ref": "#/$defs/Missing"}}}, "unresolvable \\$ref"),+ (+ {+ "$defs": {"Node": {"type": "object", "properties": {"child": {"$ref": "#/$defs/Node"}}}},+ "type": "object",+ "properties": {"root": {"$ref": "#/$defs/Node"}},+ },+ "recursive",+ ),+ (+ {"type": "object", "properties": {"s": {"anyOf": [{"type": "string"}, {"type": "object"}]}}},+ "optional \\(nullable\\) type",+ ),+ ],+)+def test_unsupported_output_schemas_are_rejected(schema: dict[str, Any], match: str) -> None:+ with pytest.raises(InvalidInputError, match=match):+ compile_output_schema(schema)+++ "properties",+ [+ {"fields": {"type": "string"}, "description": {"type": "string"}},+ {"children": {"type": "string"}},+ {+ "people": {+ "type": "array",+ "items": {"type": "object", "properties": {"required_fields": {"type": "string"}}},+ }+ },+ ],+)+def test_objects_that_read_as_legacy_descriptors_are_rejected(properties: dict[str, Any]) -> None:+ with pytest.raises(InvalidInputError, match="cannot consist only of properties named"):+ compile_output_schema({"type": "object", "properties": properties})+++def test_descriptor_words_mixed_with_other_properties_are_accepted() -> None:+ schema = {"type": "object", "properties": {"fields": {"type": "string"}, "name": {"type": "string"}}}+ assert compile_output_schema(schema).structures == {"$root": {"fields": "str", "name": "str"}}+ lone = {"type": "object", "properties": {"description": {"type": "string"}}}+ assert compile_output_schema(lone).structures == {"$root": {"description": "str"}}+++def _fan_out_schema(depth: int, fan: int = 2) -> dict[str, Any]:+ defs: dict[str, Any] = {}+ for level in range(depth):+ defs[f"A{level}"] = {+ "type": "object",+ "properties": {f"p{j}": {"$ref": f"#/$defs/A{level + 1}"} for j in range(fan)},+ }+ defs[f"A{depth}"] = {"type": "object", "properties": {"leaf": {"type": "string"}}}+ return {"type": "object", "properties": {"root": {"$ref": "#/$defs/A0"}}, "$defs": defs}+++def test_shared_ref_fan_out_is_rejected_while_compiling() -> None:+ started = time.perf_counter()+ with pytest.raises(InvalidInputError, match="more than 1000 properties"):+ compile_output_schema(_fan_out_schema(20))+ assert time.perf_counter() - started < 0.5+++def test_ref_expansions_are_capped() -> None:+ # 40 properties, each resolving a 30-step alias chain: 1200 expansions.+ defs: dict[str, Any] = {f"C{i}": {"$ref": f"#/$defs/C{i + 1}"} for i in range(29)}+ defs["C29"] = {"type": "string"}+ schema = {+ "type": "object",+ "properties": {f"p{i}": {"$ref": "#/$defs/C0"} for i in range(40)},+ "$defs": defs,+ }+ with pytest.raises(InvalidInputError, match=r"expands more than 1000 \$ref values"):+ compile_output_schema(schema)+++def test_ref_chains_are_capped() -> None:+ defs: dict[str, Any] = {f"A{i}": {"$ref": f"#/$defs/A{i + 1}"} for i in range(40)}+ defs["A40"] = {"type": "string"}+ schema = {"type": "object", "properties": {"x": {"$ref": "#/$defs/A0"}}, "$defs": defs}+ with pytest.raises(InvalidInputError, match="chains more than 32"):+ compile_output_schema(schema)+++def test_object_nesting_is_capped() -> None:+ def nested(levels: int) -> dict[str, Any]:+ node: dict[str, Any] = {"type": "string"}+ for _ in range(levels):+ node = {"type": "object", "properties": {"a": node}}+ return node++ compile_output_schema(nested(32))+ with pytest.raises(InvalidInputError, match="more than 32 levels"):+ compile_output_schema(nested(33))+ with pytest.raises(InvalidInputError, match="nest objects and arrays at most"):+ compile_output_schema(nested(500))+++ "properties",+ [+ {"n" * 129: {"type": "string"}},+ {"status": {"type": "string", "enum": ["ok", "c" * 129]}},+ ],+)+def test_schema_names_and_choices_are_bounded(properties: dict[str, Any]) -> None:+ with pytest.raises(InvalidInputError, match="at most 128 characters"):+ compile_output_schema({"type": "object", "properties": properties})+++def test_output_schema_property_count_is_capped() -> None:+ schema = {"type": "object", "properties": {f"field {index}": {"type": "string"} for index in range(1001)}}+ with pytest.raises(InvalidInputError, match="more than 1000 properties"):+ compile_output_schema(schema)+++# -- Catalog and bundle wiring --------------------------------------------------------------++[email protected](("model_id", "dim"), sorted(_MODEL_IDS.items()))+def test_catalog_configs_route_to_the_adapter(model_id: str, dim: int) -> None:+ config = load_model_configs(_MODELS_DIR)[model_id]+ assert config.hf_revision is not None+ assert len(config.hf_revision) == 40+ assert config.tasks.extract is not None+ assert config.tasks.encode is not None+ assert config.tasks.encode.dense is not None+ assert config.tasks.encode.dense.dim == dim+ adapter = load_adapter(config, _MODELS_DIR, device="cpu")+ assert isinstance(adapter, GLiFormerAdapter)+ assert adapter._revision == config.hf_revision+ assert adapter._max_seq_length == config.max_sequence_length+ assert adapter._compute_precision == "float16"+ assert adapter.dims.dense == dim+++def test_default_bundle_ships_the_adapter_and_its_pinned_package() -> None:+ bundle = yaml.safe_load((_SERVER_ROOT / "bundles" / "default.yaml").read_text())+ pyproject = (_SERVER_ROOT / "pyproject.toml").read_text()+ assert "sie_server.adapters.gliformer.adapter" in bundle["adapters"]+ assert bundle["deps"]["gliformer"] == "==0.1.2"+ assert '"gliformer==0.1.2"' in pyprojectdiff --git a/packages/sie_server/tests/adapters/test_gliformer_parity.py b/packages/sie_server/tests/adapters/test_gliformer_parity.pynew file mode 100644index 000000000..32d190d30--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliformer_parity.py@@ -0,0 +1,193 @@+"""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++[email protected](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}"++[email protected]("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+ )diff --git a/packages/sie_server/tests/api/test_extract.py b/packages/sie_server/tests/api/test_extract.pyindex 2774983f7..341c647ce 100644--- a/packages/sie_server/tests/api/test_extract.py+++ b/packages/sie_server/tests/api/test_extract.py@@ -24,8 +24,11 @@ from sie_server.config.model import ()from sie_server.core.extract_cost import (MAX_EXTRACT_LABELS,+ MAX_OUTPUT_SCHEMA_DEPTH,+ MAX_OUTPUT_SCHEMA_VALUES,build_extract_prepared_items,extract_item_cost,+ output_schema_shape_error,)from sie_server.core.inference_output import ExtractItemError, ExtractOutputfrom sie_server.core.registry import ModelRegistry@@ -422,6 +425,40 @@ class TestExtractEndpoint:assert str(MAX_EXTRACT_LABELS) in data["detail"]["message"]assert "labels" in data["detail"]["message"]+ def test_extract_overly_deep_output_schema_rejected(self, client: TestClient) -> None:+ """A schema nested past the bound is a 400 at ingress.++ The worker's batching key and adapter compilers walk the schema+ recursively; hundreds of levels would otherwise surface as a+ RecursionError inside the worker instead of a 400.+ """+ schema: dict[str, Any] = {"type": "string"}+ for _ in range(400):+ schema = {"type": "object", "properties": {"a": schema}}+ response = client.post(+ "/v1/extract/test-extractor",+ json={"items": [{"text": "Apple Inc."}], "params": {"output_schema": schema}},+ headers=JSON_HEADERS,+ )+ assert response.status_code == 400+ data = response.json()+ assert data["detail"]["code"] == "INVALID_INPUT"+ assert str(MAX_OUTPUT_SCHEMA_DEPTH) in data["detail"]["message"]++ def test_output_schema_shape_limits(self) -> None:+ def nested(levels: int) -> dict[str, Any]:+ node: dict[str, Any] = {}+ for _ in range(levels - 1):+ node = {"a": node}+ return node++ assert output_schema_shape_error(nested(MAX_OUTPUT_SCHEMA_DEPTH)) is None+ assert "nest" in (output_schema_shape_error(nested(MAX_OUTPUT_SCHEMA_DEPTH + 1)) or "")+ assert output_schema_shape_error(nested(5000)) is not None # iterative: no RecursionError+ wide = {"properties": {f"p{i}": {"type": "string"} for i in range(MAX_OUTPUT_SCHEMA_VALUES)}}+ assert "at most" in (output_schema_shape_error(wide) or "")+ assert output_schema_shape_error({"type": "object", "properties": {"n": {"type": "string"}}}) is None+def test_extract_at_cap_labels_accepted(self, client: TestClient) -> None:"""A labels list exactly at the cap is accepted."""response = client.post(diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex cdac8ed11..d7794cd01 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -1027,6 +1027,24 @@ def test_knowledgator_gliclass_small_v1_0_scores() -> None:assert scores == pytest.approx({"bug report": 0.76369, "feature request": 0.23616, "billing": 0.000144}, abs=1e-4)+def test_knowledgator_gliformer_base_v1_extract() -> None:+ _assert_extract("knowledgator/gliformer-base-v1", _NER_LABELS, ["location", "organization", "person"])+++def test_knowledgator_gliformer_base_v1_dense() -> None:+ _assert_dense("knowledgator/gliformer-base-v1", 768, [-0.0447998046875, 0.00933074951171875, -0.0070648193359375])+++def test_knowledgator_gliformer_large_v1_extract() -> None:+ _assert_extract("knowledgator/gliformer-large-v1", _NER_LABELS, ["location", "organization", "person"])+++def test_knowledgator_gliformer_large_v1_dense() -> None:+ _assert_dense(+ "knowledgator/gliformer-large-v1", 1024, [-0.0003440380096435547, -0.032867431640625, 0.0215911865234375]+ )++def test_knowledgator_gliner_bi_base_v2_0_extract() -> None:_assert_extract("knowledgator/gliner-bi-base-v2.0", _NER_LABELS, ["location", "organization", "person"])diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex 814095e8c..d6c0b831a 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -499,6 +499,31 @@ class TestProcessEncodeBatch:assert inner == {"dense": [0.1, 0.2]}mock_encode.assert_awaited_once()+ @pytest.mark.asyncio+ async def test_overly_deep_output_schema_is_isolated_as_invalid_input(self) -> None:+ reg = _make_registry()+ worker = AsyncMock()+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(WorkerResult(output=ExtractOutput(entities=[[]]), timing=RequestTiming()))+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])+ reg.start_worker = AsyncMock(return_value=worker)+ schema: dict = {"type": "string"}+ for _ in range(400):+ schema = {"type": "object", "properties": {"a": schema}}+ deep = _extract_item(wiid="deep.0")+ deep.output_schema = schema++ outcome = await QueueExecutor(reg).process_extract_batch(+ ProcessExtractBatchRequest(model_id="test/model", items=[deep, _extract_item(wiid="ok.0")])+ )++ by_id = {item.work_item_id: item for item in outcome.outcomes}+ assert by_id["deep.0"].disposition == "publish_error_and_ack"+ assert by_id["deep.0"].error_code == "INVALID_INPUT"+ assert by_id["ok.0"].disposition == "publish_and_ack"+ submitted = worker.submit_extract_preformed_batch.await_args.args[0]+ assert [request.output_schema for request in submitted] == [None]+@pytest.mark.asyncioasync def test_malformed_item_isolated_as_invalid_input(self) -> None:"""A typed-decode failure on one item in a sub-group is isolated as andiff --git a/uv.lock b/uv.lockindex 409cd3462..9a4c05699 100644--- a/uv.lock+++ b/uv.lock@@ -1332,6 +1332,27 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/52/3f/0b4e6253a14af7bd1e7306f0b1a8dc6af607caa4a9868015234ee94ad27c/gliclass-0.1.17-py3-none-any.whl", hash = "sha256:330c89e4fb39b50cc9c62d52c44dc7c5a13303883680706c71b598ecf88ab354", size = 48821 },]+[[package]]+name = "gliformer"+version = "0.1.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "accelerate" },+ { name = "gliner" },+ { name = "huggingface-hub" },+ { name = "numpy" },+ { name = "pillow" },+ { name = "pydantic" },+ { name = "scipy" },+ { name = "torch", version = "2.9.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },+ { name = "torch", version = "2.9.1+cu129", source = { registry = "https://download.pytorch.org/whl/cu129" }, marker = "sys_platform == 'linux'" },+ { name = "transformers" },+]+sdist = { url = "https://files.pythonhosted.org/packages/5e/a7/c0e8c23f576de77c3fd323a045cb56fb4d8821e7c13be7b06ca5c0435d5d/gliformer-0.1.2.tar.gz", hash = "sha256:7b1ae88206dcddce33dacf60f750f509d4188d07f6aa82a7df40d4a1134f800b", size = 422264 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/3c/06/49c0c4eefd7672025909359ed534a862ea8217fc1e08460ee8957d5cc25b/gliformer-0.1.2-py3-none-any.whl", hash = "sha256:b9a1194b56fc0ab193fef919ad68d0b3086ce2fe3f0b4392ce26873139ac8768", size = 435508 },+]+[[package]]name = "gliner"version = "0.2.26"@@ -4826,6 +4847,7 @@ dependencies = [{ name = "fastapi" },{ name = "flagembedding" },{ name = "gliclass" },+ { name = "gliformer" },{ name = "gliner" },{ name = "gliner2" },{ name = "glirel" },@@ -4895,6 +4917,7 @@ requires-dist = [{ name = "flagembedding", specifier = ">=1.3,<2" },{ name = "flash-attn", marker = "sys_platform == 'linux' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.11/flash_attn-2.7.4+cu129torch2.9-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl" },{ name = "gliclass", specifier = ">=0.1.17,<1" },+ { name = "gliformer", specifier = "==0.1.2" },{ name = "gliner", specifier = ">=0.2.26,<1" },{ name = "gliner2", specifier = ">=1.3.1,<2" },{ name = "glirel", specifier = ">=1.0,<2" },