Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(server): relations from GLiNER relex models, plus GLiNER bi-encoder v2 and PII models (#356)

svonava5914e9111443
diff --git a/README.md b/README.md
index f506d95c2..974645d21 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), [`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), [`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) |
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 6fb16504f..8e58cafae 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -34,6 +34,30 @@ for entry in scores["scores"]:
print(entry["item_id"], entry["score"])
```
+## Entities and relations
+
+GLiNER models extract entity spans for the labels you pass. Joint
+entity-relation models such as `knowledgator/gliner-relex-large-v1.0` also
+return relations between those entities when you name relation types in
+`options`:
+
+```python
+result = client.extract(
+ "knowledgator/gliner-relex-large-v1.0",
+ Item(text="Steve Jobs founded Apple in Cupertino."),
+ labels=["person", "organization", "location"],
+ options={"relation_labels": ["founded", "located in"], "relation_threshold": 0.7},
+)
+for relation in result["relations"]:
+ print(relation["head"], relation["relation"], relation["tail"], relation["score"])
+```
+
+Without `relation_labels` these models return entities only. Relations are
+scored among at most 100 entity candidates per item, taken in document order,
+so a very long document may not get relations for its later entities; its
+entities are still all returned. `threshold` and `relation_threshold` must be
+between 0 and 1, and these models need a `threshold` of at least 0.1.
+
## Zero-shot classification
GLiClass models (`knowledgator/gliclass-*` and the `knowledgator/opir-*`
diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yaml
index 10ce4bd1d..3613dc5c5 100644
--- a/packages/sie_server/bundles/default.yaml
+++ b/packages/sie_server/bundles/default.yaml
@@ -73,8 +73,8 @@ deps:
pillow: '==12.3.0'
# grounding_dino
requests: ''
- # gliner, gliner_bi
- gliner: '>=0.2,<1'
+ # gliner, gliner_bi (0.2.26: first release that loads the relex checkpoints)
+ gliner: '>=0.2.26,<1'
# gliner2
gliner2: '>=1.3.1,<2'
# glirel
diff --git a/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml b/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml
index 1ac17321b..c9d9fbe08 100644
--- a/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml
+++ b/packages/sie_server/models/knowledgator__gliner-bi-base-v2.0.yaml
@@ -1,6 +1,8 @@
sie_id: knowledgator/gliner-bi-base-v2.0
hf_id: knowledgator/gliner-bi-base-v2.0
hf_revision: 3fdae58db008a8b4e0a803a920ce9bf6566aceed
+hf_tokenizer_dependencies:
+ BAAI/bge-small-en-v1.5: 5c38ec7c405ec4b44b94cc5a9bb96e735b38267a
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/knowledgator__gliner-bi-edge-v2.0.yaml b/packages/sie_server/models/knowledgator__gliner-bi-edge-v2.0.yaml
new file mode 100644
index 000000000..bfb1873de
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-bi-edge-v2.0.yaml
@@ -0,0 +1,25 @@
+sie_id: knowledgator/gliner-bi-edge-v2.0
+hf_id: knowledgator/gliner-bi-edge-v2.0
+hf_revision: 3a401e4902d93df04971c795fb1f42f37801aced
+hf_tokenizer_dependencies:
+ sentence-transformers/all-MiniLM-L6-v2: 1110a243fdf4706b3f48f1d95db1a4f5529b4d41
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 1024
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: float16
+ adapter_path: sie_server.adapters.gliner_bi:GLiNERBiAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
+ precompute_labels: true
diff --git a/packages/sie_server/models/knowledgator__gliner-bi-large-v2.0.yaml b/packages/sie_server/models/knowledgator__gliner-bi-large-v2.0.yaml
new file mode 100644
index 000000000..248efa44b
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-bi-large-v2.0.yaml
@@ -0,0 +1,25 @@
+sie_id: knowledgator/gliner-bi-large-v2.0
+hf_id: knowledgator/gliner-bi-large-v2.0
+hf_revision: 71eec1d5fe57684cd6669ad8a1e1e3e7401a9a55
+hf_tokenizer_dependencies:
+ BAAI/bge-base-en-v1.5: a5beb1e3e68b9ab74eb54cfd186867f64f240e1a
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 1024
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: float16
+ adapter_path: sie_server.adapters.gliner_bi:GLiNERBiAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
+ precompute_labels: true
diff --git a/packages/sie_server/models/knowledgator__gliner-bi-small-v2.0.yaml b/packages/sie_server/models/knowledgator__gliner-bi-small-v2.0.yaml
new file mode 100644
index 000000000..3da02073a
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-bi-small-v2.0.yaml
@@ -0,0 +1,25 @@
+sie_id: knowledgator/gliner-bi-small-v2.0
+hf_id: knowledgator/gliner-bi-small-v2.0
+hf_revision: 3d74c1bf459b8b1c0be1ecbddd679416ce005418
+hf_tokenizer_dependencies:
+ sentence-transformers/all-MiniLM-L12-v2: a50ef00143b4d5391434df20ae11632588ac25be
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 1024
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: float16
+ adapter_path: sie_server.adapters.gliner_bi:GLiNERBiAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
+ precompute_labels: true
diff --git a/packages/sie_server/models/knowledgator__gliner-pii-base-v1.0.yaml b/packages/sie_server/models/knowledgator__gliner-pii-base-v1.0.yaml
new file mode 100644
index 000000000..1fced24a4
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-pii-base-v1.0.yaml
@@ -0,0 +1,22 @@
+sie_id: knowledgator/gliner-pii-base-v1.0
+hf_id: knowledgator/gliner-pii-base-v1.0
+hf_revision: 61726e0ad791dcab3e29339bbec3ad42ded65641
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 2048
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: null
+ adapter_path: sie_server.adapters.gliner:GLiNERAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
diff --git a/packages/sie_server/models/knowledgator__gliner-pii-edge-v1.0.yaml b/packages/sie_server/models/knowledgator__gliner-pii-edge-v1.0.yaml
new file mode 100644
index 000000000..284d08d7c
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-pii-edge-v1.0.yaml
@@ -0,0 +1,22 @@
+sie_id: knowledgator/gliner-pii-edge-v1.0
+hf_id: knowledgator/gliner-pii-edge-v1.0
+hf_revision: 9b7f39b0a2da971a5beea78d35f1539d4009c891
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 2048
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: null
+ adapter_path: sie_server.adapters.gliner:GLiNERAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
diff --git a/packages/sie_server/models/knowledgator__gliner-pii-large-v1.0.yaml b/packages/sie_server/models/knowledgator__gliner-pii-large-v1.0.yaml
new file mode 100644
index 000000000..0666d8d7a
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-pii-large-v1.0.yaml
@@ -0,0 +1,22 @@
+sie_id: knowledgator/gliner-pii-large-v1.0
+hf_id: knowledgator/gliner-pii-large-v1.0
+hf_revision: f847f54fbc97ad6e78bfa20ed9c5e5d5c43327b9
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 768
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: null
+ adapter_path: sie_server.adapters.gliner:GLiNERAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
diff --git a/packages/sie_server/models/knowledgator__gliner-pii-small-v1.0.yaml b/packages/sie_server/models/knowledgator__gliner-pii-small-v1.0.yaml
new file mode 100644
index 000000000..ba551c5ad
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-pii-small-v1.0.yaml
@@ -0,0 +1,22 @@
+sie_id: knowledgator/gliner-pii-small-v1.0
+hf_id: knowledgator/gliner-pii-small-v1.0
+hf_revision: d21aad5b4a7ec82b3d0970fd1ac74a12c087d85e
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 2048
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: null
+ adapter_path: sie_server.adapters.gliner:GLiNERAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ threshold: 0.3
diff --git a/packages/sie_server/models/knowledgator__gliner-relex-large-v1.0.yaml b/packages/sie_server/models/knowledgator__gliner-relex-large-v1.0.yaml
new file mode 100644
index 000000000..7b03656fc
--- /dev/null
+++ b/packages/sie_server/models/knowledgator__gliner-relex-large-v1.0.yaml
@@ -0,0 +1,23 @@
+sie_id: knowledgator/gliner-relex-large-v1.0
+hf_id: knowledgator/gliner-relex-large-v1.0
+hf_revision: 4aedc9226a5ac9e2f6b5ea3e91c1ee577c88a290
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+max_sequence_length: 2048
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: null
+ adapter_path: sie_server.adapters.gliner:GLiNERAdapter
+ adapter_options:
+ loadtime: {}
+ runtime:
+ # Model card: relation scores are most precise at 0.7-0.9.
+ relation_threshold: 0.7
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 2e1aed445..d6d70f80a 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -44,7 +44,8 @@ dependencies = [
# authority: only what this distribution declares reaches a resolved lock
# and therefore a built image. gliner2 lived in the bundle alone and so
# never shipped, killing three extract cells at model load (#2873).
- "gliner>=0.2,<1",
+ # 0.2.26 is the first release that loads the joint entity-relation checkpoints.
+ "gliner>=0.2.26,<1",
"gliner2>=1.3.1,<2",
"glirel>=1.0,<2",
# 0.1.17 adds the cross-attention scorer and pass-through pooling used by
diff --git a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
index 9e7961a73..d41433061 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
@@ -12,8 +12,15 @@ Reference models:
- urchade/gliner_small-v2.1 (English, smaller/faster)
- numind/NuNER_Zero (token-based, requires merge_adjacent_entities=True)
- numind/NuNER_Zero-span (span-based, works without merging)
+- knowledgator/gliner-relex-large-v1.0 (joint entities and relations)
+
+Joint entity-relation ("relex") models also extract relations between the
+entities they find when a request names relation types in
+``options["relation_labels"]``. Without it they return entities only.
"""
+import math
+from numbers import Real
from pathlib import Path
from typing import Any, ClassVar
@@ -22,14 +29,33 @@ import torch
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.core.extract_cost import MAX_EXTRACT_LABELS
from sie_server.core.inference_output import ExtractOutput
-from sie_server.types.inputs import Item
-from sie_server.types.responses import Entity
+from sie_server.types.inputs import InvalidInputError, Item
+from sie_server.types.responses import Entity, Relation
# Error messages
_ERR_REQUIRES_LABELS = "GLiNER requires labels parameter for extraction"
_ERR_REQUIRES_NON_BLANK_TEXT = "GLiNER requires non-blank text for extraction"
_ERR_PROMPT_EXHAUSTS_DOCUMENT = "GLiNER label prompt leaves no document tokens for extraction"
+# Joint entity-relation models score every ordered pair of entity candidates
+# inside the forward pass, so memory grows with the square of the candidate
+# count. Candidates are the spans above the entity threshold, which a caller
+# controls, and a long document can have thousands. Keep at most this many per
+# item (in document order) for relation scoring; entity output is unaffected.
+_MAX_RELATION_CANDIDATES = 100
+_ERR_CANDIDATE_LAYOUT = "gliner returned an unsupported span candidate layout; the relation candidate cap cannot apply"
+# Models with an adjacency layer use this threshold to pick entity pairs; never
+# let it fall below the library's usual value because of a low entity threshold.
+_MIN_ADJACENCY_THRESHOLD = 0.5
+# Relex models turn every span above the entity threshold into a relation
+# candidate inside the forward pass. Near zero that is nearly every span of the
+# document, so relex requests need at least this entity threshold.
+_MIN_RELEX_THRESHOLD = 0.1
+_ERR_NO_RELATIONS = (
+ "This GLiNER model does not extract relations; options.relation_labels needs a joint "
+ "entity-relation model such as knowledgator/gliner-relex-large-v1.0"
+)
class GLiNERAdapter(BaseAdapter):
@@ -66,6 +92,7 @@ class GLiNERAdapter(BaseAdapter):
flat_ner: bool = True,
multi_label: bool = False,
merge_adjacent_entities: bool = False,
+ relation_threshold: float | None = None,
compute_precision: ComputePrecision = "float16",
revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
@@ -79,6 +106,9 @@ class GLiNERAdapter(BaseAdapter):
multi_label: If True, allow same span to have multiple labels.
merge_adjacent_entities: If True, merge adjacent entities with same label.
Required for token-based models like numind/NuNER_Zero.
+ relation_threshold: Minimum relation score (0-1) for joint
+ entity-relation models. None uses the entity threshold, as the
+ gliner library does.
compute_precision: Compute precision for inference.
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading model artifacts.
@@ -90,11 +120,14 @@ class GLiNERAdapter(BaseAdapter):
self._flat_ner = flat_ner
self._multi_label = multi_label
self._merge_adjacent_entities = merge_adjacent_entities
+ self._relation_threshold = relation_threshold
self._compute_precision = compute_precision
self._revision = revision
self._model: Any = None # GLiNER model type
self._device: str | None = None
+ # True for joint entity-relation models, whose config names a relations layer.
+ self._extracts_relations = False
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -129,6 +162,9 @@ class GLiNERAdapter(BaseAdapter):
self._model = self._model.to(device)
else:
self._model = self._model.to(device, dtype=dtype)
+ self._extracts_relations = getattr(self._model.config, "relations_layer", None) is not None
+ if self._extracts_relations:
+ _cap_relation_candidates(self._model.model, _MAX_RELATION_CANDIDATES)
def extract(
self,
@@ -150,7 +186,9 @@ class GLiNERAdapter(BaseAdapter):
instruction: Unused for GLiNER (included for interface compatibility).
options: Adapter options to override model config defaults.
Supported: threshold (float), flat_ner (bool), multi_label (bool),
- merge_adjacent_entities (bool).
+ merge_adjacent_entities (bool). Joint entity-relation models
+ also take relation_labels (list of relation types to extract
+ between the found entities) and relation_threshold (float).
Returns:
List of dicts, one per item, each containing:
@@ -160,43 +198,75 @@ class GLiNERAdapter(BaseAdapter):
- "score": Confidence score (0-1)
- "start": Start character offset
- "end": End character offset
+ - "relations": With relation_labels, relation triples between the
+ extracted entities (head and tail entity text, relation type, score).
- "data": Empty dict (GLiNER doesn't produce structured data)
Raises:
RuntimeError: If model not loaded.
- ValueError: If labels not provided or items lack text.
+ InvalidInputError: If labels are missing, items lack text, options
+ are malformed, relation options are sent to a model without
+ relations, or the label and relation prompt leaves no room
+ for the document.
"""
self._check_loaded()
if not labels:
- raise ValueError(_ERR_REQUIRES_LABELS)
+ raise InvalidInputError(_ERR_REQUIRES_LABELS)
+
+ opts = options or {}
+ relation_labels = self._validate_relation_labels(opts.get("relation_labels"), labels)
+ if relation_labels and not self._extracts_relations:
+ raise InvalidInputError(_ERR_NO_RELATIONS)
# Extract texts from all items
texts = [self._extract_text(item) for item in items]
if any(not text.strip() for text in texts):
- raise ValueError(_ERR_REQUIRES_NON_BLANK_TEXT)
+ raise InvalidInputError(_ERR_REQUIRES_NON_BLANK_TEXT)
# Meter the exact post-word-truncation document window before GPU work.
# Besides producing the authoritative terminal counts, this rejects a
# finite-tokenizer prompt that leaves no represented document subword.
- input_token_counts = self._doc_input_token_counts(texts, labels)
+ input_token_counts = self._doc_input_token_counts(texts, labels, relation_labels)
# Get options with fallback to model defaults
- opts = options or {}
- effective_threshold = opts.get("threshold", self._threshold)
+ effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold), "threshold")
+ if self._extracts_relations and effective_threshold < _MIN_RELEX_THRESHOLD:
+ raise InvalidInputError(
+ f"GLiNER entity-relation models need a threshold of at least {_MIN_RELEX_THRESHOLD}"
+ )
effective_flat_ner = opts.get("flat_ner", self._flat_ner)
effective_multi_label = opts.get("multi_label", self._multi_label)
merge_adjacent = opts.get("merge_adjacent_entities", self._merge_adjacent_entities)
+ # Joint entity-relation models return (entities, relations) unless told
+ # otherwise, so always say which one is wanted. Other GLiNER models keep
+ # exactly the call they have always had.
+ relation_kwargs: dict[str, Any] = {}
+ if self._extracts_relations:
+ relation_kwargs["relations"] = relation_labels
+ relation_kwargs["return_relations"] = bool(relation_labels)
+ relation_kwargs["adjacency_threshold"] = max(effective_threshold, _MIN_ADJACENCY_THRESHOLD)
+ relation_threshold = self._validate_relation_threshold(
+ opts.get("relation_threshold", self._relation_threshold)
+ )
+ if relation_labels and relation_threshold is not None:
+ relation_kwargs["relation_threshold"] = relation_threshold
+
# Use batch prediction for efficiency (24x speedup vs single item loop)
with torch.inference_mode():
- batch_entities = self._model.inference(
+ prediction = self._model.inference(
texts,
labels,
threshold=effective_threshold,
flat_ner=effective_flat_ner,
multi_label=effective_multi_label,
+ **relation_kwargs,
)
+ if relation_labels:
+ batch_entities, batch_relations = prediction
+ else:
+ batch_entities, batch_relations = prediction, None
# Convert to our format
all_entities = []
@@ -219,9 +289,72 @@ class GLiNERAdapter(BaseAdapter):
all_entities.append(entity_results)
- return ExtractOutput(entities=all_entities, input_token_counts=input_token_counts)
+ all_relations = None
+ if batch_relations is not None:
+ if len(batch_relations) != len(texts):
+ raise ValueError("GLiNER returned relations for a different number of items")
+ all_relations = [self._format_relations(relations) for relations in batch_relations]
+
+ return ExtractOutput(entities=all_entities, relations=all_relations, input_token_counts=input_token_counts)
+
+ @staticmethod
+ def _validate_relation_labels(value: Any, labels: list[str]) -> list[str]:
+ """Return the requested relation types (empty when none were asked for)."""
+ if value is None:
+ return []
+ if not isinstance(value, (list, tuple)):
+ raise InvalidInputError("GLiNER relation_labels must be a list of relation types")
+ if any(not isinstance(label, str) or not label.strip() for label in value):
+ raise InvalidInputError("GLiNER relation_labels must be non-empty strings")
+ relation_labels = [label.strip() for label in value]
+ if len(set(relation_labels)) != len(relation_labels):
+ raise InvalidInputError("GLiNER relation_labels must be unique")
+ if len(relation_labels) + len(labels) > MAX_EXTRACT_LABELS:
+ raise InvalidInputError(
+ f"GLiNER labels and relation_labels must contain at most {MAX_EXTRACT_LABELS} entries together"
+ )
+ return relation_labels
+
+ @classmethod
+ def _validate_relation_threshold(cls, value: Any) -> float | None:
+ if value is None:
+ return None
+ return cls._validate_threshold(value, "relation_threshold")
+
+ @staticmethod
+ def _validate_threshold(value: Any, name: str) -> float:
+ message = f"GLiNER {name} must be a finite number between 0 and 1"
+ if isinstance(value, bool) or not isinstance(value, Real):
+ 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
+
+ @staticmethod
+ def _format_relations(relations: list[dict[str, Any]] | None) -> list[Relation]:
+ """Convert gliner relation dicts to SIE relations, highest score first."""
+ formatted = [
+ Relation(
+ head=relation["head"]["text"],
+ tail=relation["tail"]["text"],
+ relation=relation["relation"],
+ score=float(relation["score"]),
+ )
+ for relation in relations or []
+ ]
+ formatted.sort(key=lambda r: (-r["score"], r["relation"], r["head"], r["tail"]))
+ return formatted
- def _doc_input_token_counts(self, texts: list[str], labels: list[str]) -> list[int] | None:
+ def _doc_input_token_counts(
+ self,
+ texts: list[str],
+ labels: list[str],
+ relation_labels: list[str] | None = None,
+ ) -> list[int] | None:
"""Count the document subwords represented by GLiNER's real processor.
Classic GLiNER first splits and truncates each document in WORDS, then
@@ -235,7 +368,8 @@ class GLiNERAdapter(BaseAdapter):
words. Attention masking excludes padding; tokenizer specials remain
billable, matching the existing document-token contract. Batches match
GLiNER inference's default batch size so a finite tokenizer cap is
- observed identically.
+ observed identically. Joint entity-relation models also put the
+ relation types in the prompt, so they are passed through as well.
"""
processor = getattr(self._model, "data_processor", None)
prepare_inputs = getattr(self._model, "prepare_inputs", None)
@@ -249,13 +383,25 @@ class GLiNERAdapter(BaseAdapter):
counts: list[int] = []
has_document_subwords: list[bool] = []
for start in range(0, len(raw_items), 8):
- raw_batch = processor.collate_raw_batch(
- raw_items[start : start + 8],
- entity_types=labels,
- )
- retained_words = raw_batch["tokens"]
- entity_mappings = raw_batch["classes_to_id"]
- encoded = processor.tokenize_inputs(retained_words, entity_mappings)
+ if self._extracts_relations:
+ raw_batch = processor.collate_raw_batch(
+ raw_items[start : start + 8],
+ entity_types=labels,
+ relation_types=relation_labels or [],
+ )
+ retained_words = raw_batch["tokens"]
+ entity_mappings = raw_batch["classes_to_id"]
+ encoded = processor.tokenize_inputs(
+ retained_words, entity_mappings, relations=raw_batch["rel_class_to_ids"]
+ )
+ else:
+ raw_batch = processor.collate_raw_batch(
+ raw_items[start : start + 8],
+ entity_types=labels,
+ )
+ retained_words = raw_batch["tokens"]
+ entity_mappings = raw_batch["classes_to_id"]
+ encoded = processor.tokenize_inputs(retained_words, entity_mappings)
for batch_index in range(len(retained_words)):
word_ids = encoded.word_ids(batch_index)
attention_mask = encoded["attention_mask"][batch_index].tolist()
@@ -294,7 +440,7 @@ class GLiNERAdapter(BaseAdapter):
if len(counts) != len(texts) or len(has_document_subwords) != len(texts):
return None
if not all(has_document_subwords):
- raise ValueError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)
+ raise InvalidInputError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)
return counts
def _merge_entities(self, entities: list[Entity], text: str) -> list[Entity]:
@@ -358,5 +504,53 @@ class GLiNERAdapter(BaseAdapter):
def _extract_text(self, item: Item) -> str:
"""Extract text from an item."""
if item.text is None:
- raise ValueError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER adapter"))
+ raise InvalidInputError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER adapter"))
return item.text
+
+
+def _cap_relation_candidates(model: Any, limit: int) -> None:
+ """Keep at most ``limit`` entity candidates per item for relation scoring.
+
+ gliner's relex models pass every span above the entity threshold to the
+ relation layers, which build every ordered pair of candidates.
+ ``represent_spans`` returns the candidate representations, validity mask,
+ and span boundaries packed at the front of each row, so slicing those
+ tensors to their first ``limit`` columns bounds everything downstream to
+ ``limit`` candidates (and ``limit**2`` pairs) per item. Entities are
+ decoded from the span scores, so entity output does not change; relations
+ among candidates past the first ``limit`` (in document order) are dropped.
+ Any other output layout raises instead of running uncapped.
+ """
+ represent_spans = model.represent_spans
+
+ def capped(*args: Any, **kwargs: Any) -> Any:
+ outputs = represent_spans(*args, **kwargs)
+ if not _has_candidate_layout(outputs):
+ raise RuntimeError(_ERR_CANDIDATE_LAYOUT)
+ width = outputs[2].size(1)
+ if width <= limit:
+ return outputs
+ sliced = list(outputs)
+ for index in range(1, len(sliced)):
+ value = sliced[index]
+ if isinstance(value, torch.Tensor) and value.dim() >= 2 and value.size(1) == width:
+ sliced[index] = value[:, :limit]
+ return tuple(sliced)
+
+ model.represent_spans = capped
+
+
+def _has_candidate_layout(outputs: Any) -> bool:
+ """Whether ``represent_spans`` returned (scores, reps, mask, spans, ...) as the cap expects."""
+ if not isinstance(outputs, tuple) or len(outputs) < 4:
+ return False
+ reps, mask, spans = outputs[1:4]
+ return (
+ isinstance(mask, torch.Tensor)
+ and mask.dim() == 2
+ and isinstance(reps, torch.Tensor)
+ and reps.dim() == 3
+ and isinstance(spans, torch.Tensor)
+ and spans.dim() == 3
+ and reps.shape[:2] == mask.shape == spans.shape[:2]
+ )
diff --git a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
index b2fb8fa1d..0cb85bb00 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
@@ -1,6 +1,8 @@
import logging
+import math
import threading
from collections import OrderedDict
+from numbers import Real
from pathlib import Path
from typing import Any, ClassVar
@@ -10,17 +12,30 @@ 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.core.inference_output import ExtractOutput
-from sie_server.types.inputs import Item
+from sie_server.types.inputs import InvalidInputError, Item
from sie_server.types.responses import Entity
logger = logging.getLogger(__name__)
_ERR_REQUIRES_LABELS = "GLiNER-bi requires labels parameter for extraction"
+_ERR_NO_RELATIONS = "GLiNER bi-encoder models do not extract relations; options.relation_labels is not supported"
# Maximum number of distinct label-set embeddings to cache.
_LABEL_CACHE_MAX_SIZE = 64
+def _validate_threshold(value: Any) -> None:
+ message = "GLiNER-bi threshold must be a finite number between 0 and 1"
+ if isinstance(value, bool) or not isinstance(value, Real):
+ 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)
+
+
class GLiNERBiAdapter(BaseAdapter):
"""Adapter for GLiNER bi-encoder models with pre-computed label embedding caching.
@@ -87,11 +102,12 @@ class GLiNERBiAdapter(BaseAdapter):
self._model: Any = None
self._device: str | None = None
- # LRU cache: frozenset(labels) -> pre-computed label embeddings.
+ # LRU cache: labels in request order -> pre-computed label embeddings.
+ # The embeddings are positional, so the key must keep the order.
# Protected by _cache_lock for thread safety (defensive — the
# current ModelWorker uses a single-worker executor, but this
# guards against future architectural changes).
- self._label_cache: OrderedDict[frozenset[str], Any] = OrderedDict()
+ self._label_cache: OrderedDict[tuple[str, ...], Any] = OrderedDict()
self._cache_lock = threading.Lock()
def load(self, device: str) -> None:
@@ -186,11 +202,15 @@ class GLiNERBiAdapter(BaseAdapter):
self._check_loaded()
if not labels:
- raise ValueError(_ERR_REQUIRES_LABELS)
+ raise InvalidInputError(_ERR_REQUIRES_LABELS)
+
+ opts = options or {}
+ if opts.get("relation_labels"):
+ raise InvalidInputError(_ERR_NO_RELATIONS)
+ _validate_threshold(opts.get("threshold", self._threshold))
texts = [self._extract_text(item) for item in items]
- opts = options or {}
effective_threshold = opts.get("threshold", self._threshold)
effective_flat_ner = opts.get("flat_ner", self._flat_ner)
effective_multi_label = opts.get("multi_label", self._multi_label)
@@ -231,7 +251,42 @@ class GLiNERBiAdapter(BaseAdapter):
)
all_entities.append(entity_results)
- return ExtractOutput(entities=all_entities)
+ return ExtractOutput(entities=all_entities, input_token_counts=self._doc_input_token_counts(texts, labels))
+
+ def _doc_input_token_counts(self, texts: list[str], labels: list[str]) -> list[int] | None:
+ """Count the document tokens the bi-encoder actually encodes, per item.
+
+ A bi-encoder encodes labels separately, so its text input is the
+ document alone. Delegate word splitting and max-length word truncation
+ to the pinned GLiNER processor, then count the attended tokens of the
+ retained window, special tokens included, as the GLiNER adapter does.
+ Batches match GLiNER inference's default batch size. GLiNER skips
+ whitespace-only documents without encoding them, so they count zero.
+ """
+ processor = getattr(self._model, "data_processor", None)
+ prepare_inputs = getattr(self._model, "prepare_inputs", None)
+ prepare_base_input = getattr(self._model, "prepare_base_input", None)
+ if processor is None or prepare_inputs is None or prepare_base_input is None:
+ return None
+ encoded_positions = [index for index, text in enumerate(texts) if text.strip()]
+ counts = [0] * len(texts)
+ if not encoded_positions:
+ return counts
+ try:
+ split_texts, _, _ = prepare_inputs([texts[index] for index in encoded_positions])
+ raw_items = prepare_base_input(split_texts)
+ encoded_counts: list[int] = []
+ for start in range(0, len(raw_items), 8):
+ raw_batch = processor.collate_raw_batch(raw_items[start : start + 8], entity_types=labels)
+ encoded = processor.tokenize_inputs(raw_batch["tokens"])
+ encoded_counts.extend(int(sum(mask)) for mask in encoded["attention_mask"].tolist())
+ except Exception: # noqa: BLE001 -- metering must never fail an extraction
+ return None
+ if len(encoded_counts) != len(encoded_positions):
+ return None
+ for index, count in zip(encoded_positions, encoded_counts, strict=True):
+ counts[index] = count
+ return counts
def _predict_with_cached_embeds(
self,
@@ -244,7 +299,8 @@ class GLiNERBiAdapter(BaseAdapter):
) -> list[list[dict[str, Any]]]:
"""Run prediction using pre-computed label embeddings.
- Caches label embeddings keyed by the label set. When a cache hit
+ Caches label embeddings keyed by the ordered label list, because the
+ embeddings are matched to labels by position. When a cache hit
occurs, the label encoder is skipped entirely — only the text encoder
and span decoder run.
@@ -258,7 +314,7 @@ class GLiNERBiAdapter(BaseAdapter):
Returns:
List of entity dicts per text (same format as ``GLiNER.inference``).
"""
- cache_key = frozenset(labels)
+ cache_key = tuple(labels)
with self._cache_lock:
if cache_key in self._label_cache:
@@ -290,5 +346,5 @@ class GLiNERBiAdapter(BaseAdapter):
def _extract_text(self, item: Item) -> str:
"""Extract text from an item."""
if item.text is None:
- raise ValueError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER-bi adapter"))
+ raise InvalidInputError(ERR_REQUIRES_TEXT.format(adapter_name="GLiNER-bi adapter"))
return item.text
diff --git a/packages/sie_server/tests/adapters/test_gliner_bi_label_cache.py b/packages/sie_server/tests/adapters/test_gliner_bi_label_cache.py
new file mode 100644
index 000000000..131a7a994
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner_bi_label_cache.py
@@ -0,0 +1,39 @@
+"""The GLiNER bi-encoder label-embedding cache must keep labels and embeddings aligned."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from sie_server.adapters.gliner_bi import GLiNERBiAdapter
+from sie_server.types.inputs import Item
+
+
+class _FakeBiEncoder:
+ def __init__(self) -> None:
+ self.encoded: list[list[str]] = []
+ self.predicted: list[tuple[list[str], list[str]]] = []
+
+ def encode_labels(self, labels: list[str], batch_size: int = 8) -> list[str]:
+ self.encoded.append(list(labels))
+ return [f"embedding of {label}" for label in labels]
+
+ def batch_predict_with_embeds(
+ self, texts: list[str], embeds: list[str], labels: list[str], **_: Any
+ ) -> list[list[dict[str, Any]]]:
+ self.predicted.append((list(embeds), list(labels)))
+ return [[] for _ in texts]
+
+
+def test_reordered_labels_get_their_own_embeddings() -> None:
+ adapter = GLiNERBiAdapter("test-model", precompute_labels=True)
+ model = _FakeBiEncoder()
+ adapter._model = model
+ adapter._device = "cpu"
+
+ for labels in (["person", "city"], ["city", "person"], ["person", "city"]):
+ adapter.extract([Item(text="Ada lives in Paris")], labels=labels)
+
+ for embeds, labels in model.predicted:
+ assert embeds == [f"embedding of {label}" for label in labels]
+ # The third request repeats the first label order and reuses its cached embeddings.
+ assert model.encoded == [["person", "city"], ["city", "person"]]
diff --git a/packages/sie_server/tests/adapters/test_gliner_bi_metering.py b/packages/sie_server/tests/adapters/test_gliner_bi_metering.py
new file mode 100644
index 000000000..d54ed6290
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner_bi_metering.py
@@ -0,0 +1,73 @@
+"""The GLiNER bi-encoder adapter reports the document tokens it encodes."""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import torch
+from sie_server.adapters.gliner_bi import GLiNERBiAdapter
+from sie_server.types.inputs import Item
+
+
+class _BiProcessor:
+ def __init__(self) -> None:
+ self.tokenized: list[list[list[str]]] = []
+
+ def collate_raw_batch(self, batch: list[dict[str, Any]], *, entity_types: list[str]) -> dict[str, Any]:
+ return {"tokens": [item["tokenized_text"][:4] for item in batch]}
+
+ def tokenize_inputs(self, texts: list[list[str]], entities: Any = None) -> dict[str, Any]:
+ assert entities is None
+ self.tokenized.append(texts)
+ longest = max(len(words) for words in texts) + 2
+ return {"attention_mask": torch.tensor([[1] * (len(w) + 2) + [0] * (longest - len(w) - 2) for w in texts])}
+
+
+def test_bi_encoder_reports_document_token_counts() -> None:
+ processor = _BiProcessor()
+ adapter = GLiNERBiAdapter("test-model", precompute_labels=False)
+ model = MagicMock()
+ model.data_processor = processor
+ model.prepare_inputs.side_effect = lambda texts: ([t.split() for t in texts], [], [])
+ model.prepare_base_input.side_effect = lambda words: [{"tokenized_text": w, "ner": None} for w in words]
+ model.inference.return_value = [[], []]
+ adapter._model = model
+ adapter._device = "cpu"
+
+ output = adapter.extract([Item(text="Ada lives in Paris today"), Item(text="Hi")], labels=["person"])
+
+ # Word window of 4 plus CLS/SEP, and 1 word plus CLS/SEP.
+ assert output.input_token_counts == [6, 3]
+
+
+def test_bi_encoder_counts_whitespace_only_documents_as_zero() -> None:
+ processor = _BiProcessor()
+ adapter = GLiNERBiAdapter("test-model", precompute_labels=False)
+ model = MagicMock()
+ model.data_processor = processor
+ model.prepare_inputs.side_effect = lambda texts: ([t.split() for t in texts], [], [])
+ model.prepare_base_input.side_effect = lambda words: [{"tokenized_text": w, "ner": None} for w in words]
+ model.inference.return_value = [[], [], []]
+ adapter._model = model
+ adapter._device = "cpu"
+
+ output = adapter.extract([Item(text=" "), Item(text="Hi"), Item(text="\n")], labels=["person"])
+
+ # GLiNER skips whitespace-only documents, so only "Hi" is encoded.
+ assert output.input_token_counts == [0, 3, 0]
+ assert processor.tokenized == [[["Hi"]]]
+
+
+def test_bi_encoder_counts_an_all_whitespace_batch_as_zero() -> None:
+ adapter = GLiNERBiAdapter("test-model", precompute_labels=False)
+ model = MagicMock()
+ model.data_processor = _BiProcessor()
+ model.inference.return_value = [[]]
+ adapter._model = model
+ adapter._device = "cpu"
+
+ output = adapter.extract([Item(text=" ")], labels=["person"])
+
+ assert output.input_token_counts == [0]
+ model.prepare_inputs.assert_not_called()
diff --git a/packages/sie_server/tests/adapters/test_gliner_metering.py b/packages/sie_server/tests/adapters/test_gliner_metering.py
index 397844afd..966aabe34 100644
--- a/packages/sie_server/tests/adapters/test_gliner_metering.py
+++ b/packages/sie_server/tests/adapters/test_gliner_metering.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock
import pytest
import torch
from sie_server.adapters.gliner import GLiNERAdapter
-from sie_server.types.inputs import Item
+from sie_server.types.inputs import InvalidInputError, Item
class FakeEncoding:
@@ -142,7 +142,7 @@ def test_extract_rejects_blank_document_before_inference() -> None:
def test_extract_rejects_prompt_that_leaves_no_document_subword() -> None:
adapter = adapter_with_processor(FakeProcessor(tokenizer_word_limit=4))
- with pytest.raises(ValueError, match="leaves no document tokens"):
+ with pytest.raises(InvalidInputError, match="leaves no document tokens"):
adapter.extract([Item(text="represented")], labels=["entity"])
adapter._model.inference.assert_not_called()
diff --git a/packages/sie_server/tests/adapters/test_gliner_relations.py b/packages/sie_server/tests/adapters/test_gliner_relations.py
new file mode 100644
index 000000000..95a5e0950
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner_relations.py
@@ -0,0 +1,420 @@
+"""Relation extraction through the GLiNER adapter (joint entity-relation models)."""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from sie_server.adapters.gliner import GLiNERAdapter, _cap_relation_candidates
+from sie_server.adapters.gliner_bi import GLiNERBiAdapter
+from sie_server.core.worker.handlers.extract import ExtractHandler
+from sie_server.types.inputs import InvalidInputError, Item
+
+_TEXT = "Steve Jobs founded Apple in Cupertino."
+_LABELS = ["person", "organization", "location"]
+_ENTITIES = [
+ {"start": 0, "end": 10, "text": "Steve Jobs", "label": "person", "score": 0.91},
+ {"start": 19, "end": 24, "text": "Apple", "label": "organization", "score": 0.88},
+ {"start": 28, "end": 37, "text": "Cupertino", "label": "location", "score": 0.8},
+]
+
+
+def _endpoint(entity: dict[str, Any], index: int) -> dict[str, Any]:
+ return {
+ "start": entity["start"],
+ "end": entity["end"],
+ "text": entity["text"],
+ "type": entity["label"],
+ "entity_idx": index,
+ }
+
+
+_RELATIONS = [
+ {"head": _endpoint(_ENTITIES[0], 0), "tail": _endpoint(_ENTITIES[1], 1), "relation": "founded", "score": 0.72},
+ {"head": _endpoint(_ENTITIES[1], 1), "tail": _endpoint(_ENTITIES[2], 2), "relation": "located in", "score": 0.93},
+]
+
+
+def _adapter(result: Any, *, relex: bool) -> GLiNERAdapter:
+ adapter = GLiNERAdapter("test-model")
+ model = MagicMock()
+ model.data_processor = None # no metering in these tests
+ model.inference.return_value = result
+ adapter._model = model
+ adapter._device = "cpu"
+ adapter._extracts_relations = relex
+ return adapter
+
+
+def _inference(adapter: GLiNERAdapter) -> MagicMock:
+ inference = adapter._model.inference
+ assert isinstance(inference, MagicMock)
+ return inference
+
+
+def test_models_without_relations_keep_their_inference_call() -> None:
+ adapter = _adapter([list(_ENTITIES)], relex=False)
+
+ output = adapter.extract([Item(text=_TEXT)], labels=list(_LABELS))
+
+ _inference(adapter).assert_called_once_with([_TEXT], _LABELS, threshold=0.5, flat_ner=True, multi_label=False)
+ assert [entity["text"] for entity in output.entities[0]] == ["Steve Jobs", "Apple", "Cupertino"]
+ assert output.relations is None
+
+
+def test_relex_model_without_relation_labels_returns_entities_only() -> None:
+ adapter = _adapter([list(_ENTITIES)], relex=True)
+
+ output = adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_threshold": 0.9})
+
+ _inference(adapter).assert_called_once_with(
+ [_TEXT],
+ _LABELS,
+ threshold=0.5,
+ flat_ner=True,
+ multi_label=False,
+ relations=[],
+ return_relations=False,
+ adjacency_threshold=0.5,
+ )
+ assert len(output.entities[0]) == 3
+ assert output.relations is None
+
+
+def test_relation_labels_return_relations_between_found_entities() -> None:
+ adapter = _adapter(([list(_ENTITIES)], [list(_RELATIONS)]), relex=True)
+
+ output = adapter.extract(
+ [Item(text=_TEXT)],
+ labels=list(_LABELS),
+ options={"relation_labels": [" founded ", "located in"], "relation_threshold": 0.6, "threshold": 0.4},
+ )
+
+ _inference(adapter).assert_called_once_with(
+ [_TEXT],
+ _LABELS,
+ threshold=0.4,
+ flat_ner=True,
+ multi_label=False,
+ relations=["founded", "located in"],
+ return_relations=True,
+ adjacency_threshold=0.5,
+ relation_threshold=0.6,
+ )
+ assert output.relations == [
+ [
+ {"head": "Apple", "tail": "Cupertino", "relation": "located in", "score": 0.93},
+ {"head": "Steve Jobs", "tail": "Apple", "relation": "founded", "score": 0.72},
+ ]
+ ]
+ assert len(output.entities[0]) == 3
+
+
+def test_relation_threshold_defaults_to_the_config_then_the_library() -> None:
+ adapter = _adapter(([[]], [[]]), relex=True)
+
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded"]})
+ assert "relation_threshold" not in _inference(adapter).call_args.kwargs
+
+ adapter._relation_threshold = 0.75
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded"]})
+ assert _inference(adapter).call_args.kwargs["relation_threshold"] == 0.75
+
+
+def test_relation_labels_batch_by_order_and_reach_the_adapter_as_sent() -> None:
+ handler = ExtractHandler()
+
+ def metadata(relation_labels: list[str]) -> MagicMock:
+ meta = MagicMock()
+ meta.labels = list(_LABELS)
+ meta.output_schema = None
+ meta.instruction = None
+ meta.options = {"relation_labels": relation_labels, "relation_threshold": 0.7}
+ return meta
+
+ founded_first = metadata(["founded", "located in"])
+ same = metadata(["founded", "located in"])
+ located_first = metadata(["located in", "founded"])
+ assert handler.make_config_key(founded_first) == handler.make_config_key(same)
+ assert handler.make_config_key(founded_first) != handler.make_config_key(located_first)
+
+ adapter = _adapter(([[], []], [[], []]), relex=True)
+ output = handler.run_inference(
+ adapter,
+ [Item(text=_TEXT), Item(text=_TEXT)],
+ handler.make_config_key(located_first),
+ None,
+ [located_first, located_first],
+ )
+
+ assert _inference(adapter).call_args.kwargs["relations"] == ["located in", "founded"]
+ assert output.relations == [[], []]
+
+
+def test_relation_labels_need_a_relation_model() -> None:
+ adapter = _adapter([[]], relex=False)
+
+ with pytest.raises(InvalidInputError, match="does not extract relations"):
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded"]})
+
+ _inference(adapter).assert_not_called()
+
+
+ ("relation_labels", "match"),
+ [
+ ("founded", "must be a list"),
+ ([""], "non-empty strings"),
+ ([3], "non-empty strings"),
+ (["founded", " founded"], "unique"),
+ ([f"relation {index}" for index in range(998)], "at most 1000"),
+ ],
+)
+def test_malformed_relation_labels_are_rejected(relation_labels: object, match: str) -> None:
+ adapter = _adapter(([[]], [[]]), relex=True)
+
+ with pytest.raises(InvalidInputError, match=match):
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": relation_labels})
+
+
[email protected]("threshold", [True, "0.5", -0.1, 1.5, float("nan"), 10**1000])
+def test_malformed_relation_threshold_is_rejected(threshold: object) -> None:
+ adapter = _adapter(([[]], [[]]), relex=True)
+
+ with pytest.raises(InvalidInputError, match="relation_threshold"):
+ adapter.extract(
+ [Item(text=_TEXT)],
+ labels=list(_LABELS),
+ options={"relation_labels": ["founded"], "relation_threshold": threshold},
+ )
+
+
+def test_relation_count_mismatch_is_an_internal_error() -> None:
+ adapter = _adapter(([[]], []), relex=True)
+
+ with pytest.raises(ValueError, match="different number of items") as raised:
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded"]})
+ assert not isinstance(raised.value, InvalidInputError)
+
+
+def test_bi_encoder_models_reject_relation_labels() -> None:
+ adapter = GLiNERBiAdapter("test-model")
+ adapter._model = MagicMock()
+ adapter._device = "cpu"
+
+ with pytest.raises(InvalidInputError, match="do not extract relations"):
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded"]})
+
+ adapter._model.inference.assert_not_called()
+ adapter._model.batch_predict_with_embeds.assert_not_called()
+
+
+class _Encoding:
+ def __init__(self, word_ids: list[list[int | None]], words_masks: list[list[int]]) -> None:
+ self._word_ids = word_ids
+ self._tensors = {
+ "attention_mask": [torch.ones(len(ids), dtype=torch.long) for ids in word_ids],
+ "words_mask": [torch.tensor(mask, dtype=torch.long) for mask in words_masks],
+ }
+
+ def word_ids(self, batch_index: int) -> list[int | None]:
+ return self._word_ids[batch_index]
+
+ def __getitem__(self, key: str) -> list[torch.Tensor]:
+ return self._tensors[key]
+
+
+class _RelexProcessor:
+ """Prompt = entity markers, SEP, relation markers, SEP (as gliner's relex processors build it)."""
+
+ def __init__(self) -> None:
+ self.collate_calls: list[dict[str, Any]] = []
+ self.tokenize_calls: list[Any] = []
+
+ def collate_raw_batch(
+ self, batch: list[dict[str, Any]], *, entity_types: list[str], relation_types: list[str]
+ ) -> dict[str, Any]:
+ self.collate_calls.append({"entity_types": entity_types, "relation_types": relation_types})
+ return {
+ "tokens": [item["tokenized_text"] for item in batch],
+ "classes_to_id": {label: index for index, label in enumerate(entity_types, start=1)},
+ "rel_class_to_ids": {label: index for index, label in enumerate(relation_types, start=1)},
+ }
+
+ def tokenize_inputs(
+ self, texts: list[list[str]], entity_mappings: dict[str, int], relations: dict[str, int]
+ ) -> _Encoding:
+ self.tokenize_calls.append(relations)
+ prompt = len(entity_mappings) * 2 + 1 + len(relations) * 2 + 1
+ word_ids: list[list[int | None]] = []
+ words_masks: list[list[int]] = []
+ for words in texts:
+ ids: list[int | None] = [None, *range(prompt)]
+ mask = [0] * (prompt + 1)
+ for position, _word in enumerate(words):
+ ids.append(prompt + position)
+ mask.append(position + 1)
+ ids.append(None)
+ mask.append(0)
+ word_ids.append(ids)
+ words_masks.append(mask)
+ return _Encoding(word_ids, words_masks)
+
+
+def test_relex_metering_passes_relation_types_to_the_processor() -> None:
+ processor = _RelexProcessor()
+ adapter = _adapter(([list(_ENTITIES)], [list(_RELATIONS)]), relex=True)
+ model = adapter._model
+ model.data_processor = processor
+ model.prepare_inputs.side_effect = lambda texts: ([text.split() for text in texts], [[]], [[]])
+ model.prepare_base_input.side_effect = lambda texts: [{"tokenized_text": words, "ner": None} for words in texts]
+
+ output = adapter.extract(
+ [Item(text=_TEXT)], labels=list(_LABELS), options={"relation_labels": ["founded", "located in"]}
+ )
+
+ assert processor.collate_calls == [{"entity_types": _LABELS, "relation_types": ["founded", "located in"]}]
+ assert processor.tokenize_calls == [{"founded": 1, "located in": 2}]
+ # 6 document words plus CLS and SEP; the entity and relation prompt is not billed.
+ assert output.input_token_counts == [8]
+
+
[email protected]("threshold", [True, "0.3", -0.01, 1.01, float("nan"), 10**1000])
+def test_entity_threshold_is_validated(threshold: object) -> None:
+ adapter = _adapter([[]], relex=False)
+
+ with pytest.raises(InvalidInputError, match="GLiNER threshold"):
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"threshold": threshold})
+
+ _inference(adapter).assert_not_called()
+
+
+def test_a_low_entity_threshold_keeps_the_adjacency_floor() -> None:
+ adapter = _adapter(([[]], [[]]), relex=True)
+
+ adapter.extract(
+ [Item(text=_TEXT)], labels=list(_LABELS), options={"threshold": 0.2, "relation_labels": ["founded"]}
+ )
+
+ kwargs = _inference(adapter).call_args.kwargs
+ assert kwargs["threshold"] == 0.2
+ assert kwargs["adjacency_threshold"] == 0.5
+
+
[email protected]("options", [{"threshold": 0.0}, {"threshold": 0.05, "relation_labels": ["founded"]}])
+def test_relex_models_refuse_a_near_zero_entity_threshold(options: dict[str, Any]) -> None:
+ adapter = _adapter(([[]], [[]]), relex=True)
+
+ with pytest.raises(InvalidInputError, match=r"at least 0\.1"):
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options=options)
+
+ _inference(adapter).assert_not_called()
+
+
+def test_other_gliner_models_accept_a_zero_threshold() -> None:
+ adapter = _adapter([[]], relex=False)
+
+ adapter.extract([Item(text=_TEXT)], labels=list(_LABELS), options={"threshold": 0.0})
+
+ assert _inference(adapter).call_args.kwargs["threshold"] == 0.0
+
+
+ ("items", "labels", "match"),
+ [
+ ([Item(text="Ada")], [], "requires labels"),
+ ([Item(text=" ")], ["person"], "non-blank text"),
+ ([Item()], ["person"], "requires"),
+ ],
+)
+def test_caller_errors_are_invalid_input(items: list[Item], labels: list[str], match: str) -> None:
+ adapter = _adapter([[]], relex=False)
+
+ with pytest.raises(InvalidInputError, match=match):
+ adapter.extract(items, labels=labels)
+
+
+class _SpanModel:
+ """Minimal stand-in for gliner's relex model: candidates packed at the front."""
+
+ def __init__(self, valid_per_row: list[int], width: int, dim: int = 4) -> None:
+ self.valid_per_row = valid_per_row
+ self.width = width
+ self.dim = dim
+
+ def represent_spans(self, *args: Any, **kwargs: Any) -> tuple[Any, ...]:
+ rows = [[1] * n + [0] * (self.width - n) for n in self.valid_per_row]
+ mask = torch.tensor(rows, dtype=torch.long)
+ reps = torch.arange(len(rows) * self.width * self.dim, dtype=torch.float32).view(
+ len(rows), self.width, self.dim
+ )
+ spans = torch.zeros(len(rows), self.width, 2, dtype=torch.long)
+ scores = torch.zeros(len(rows), self.width, 3) # size(1) == width too; must stay whole
+ return (scores, reps, mask, spans)
+
+
+def test_relation_candidates_are_sliced_per_item() -> None:
+ model = _SpanModel([150, 3], width=150)
+ _, full_reps, _, _ = model.represent_spans()
+ _cap_relation_candidates(model, 100)
+
+ scores, reps, mask, spans = model.represent_spans("words", "mask", "prompts")
+
+ assert tuple(scores.shape) == (2, 150, 3)
+ assert tuple(reps.shape) == (2, 100, 4)
+ assert tuple(mask.shape) == (2, 100)
+ assert tuple(spans.shape) == (2, 100, 2)
+ assert torch.equal(reps, full_reps[:, :100])
+ assert mask.sum(dim=1).tolist() == [100, 3]
+
+
+def test_relation_candidates_under_the_cap_are_untouched() -> None:
+ model = _SpanModel([5, 3], width=5)
+ original = model.represent_spans("x")
+ _cap_relation_candidates(model, 100)
+
+ capped = model.represent_spans("x")
+ assert all(torch.equal(a, b) for a, b in zip(original, capped, strict=True))
+
+
+ "outputs",
+ [
+ (torch.zeros(1, 150, 3), torch.zeros(1, 150, 4), None, None),
+ (torch.zeros(1, 150, 3), torch.zeros(1, 150, 4), torch.ones(1, 150)),
+ (torch.zeros(1, 150, 3), torch.zeros(1, 120, 4), torch.ones(1, 150), torch.zeros(1, 150, 2)),
+ [torch.zeros(1, 150, 3), torch.zeros(1, 150, 4), torch.ones(1, 150), torch.zeros(1, 150, 2)],
+ ],
+)
+def test_an_unknown_candidate_layout_fails_closed(outputs: Any) -> None:
+ model = MagicMock()
+ model.represent_spans.return_value = outputs
+ _cap_relation_candidates(model, 100)
+
+ with pytest.raises(RuntimeError, match="candidate layout"):
+ model.represent_spans("words", "mask", "prompts")
+
+
+def test_bi_encoder_caller_errors_are_invalid_input() -> None:
+ adapter = GLiNERBiAdapter("test-model")
+ adapter._model = MagicMock()
+ adapter._device = "cpu"
+
+ with pytest.raises(InvalidInputError, match="requires labels"):
+ adapter.extract([Item(text="Ada")], labels=[])
+ with pytest.raises(InvalidInputError):
+ adapter.extract([Item()], labels=["person"])
+
+
[email protected]("threshold", ["0.3", True, -0.1, 1.5, float("nan")])
+def test_bi_encoder_threshold_is_validated(threshold: object) -> None:
+ adapter = GLiNERBiAdapter("test-model")
+ adapter._model = MagicMock()
+ adapter._device = "cpu"
+
+ with pytest.raises(InvalidInputError, match="GLiNER-bi threshold"):
+ adapter.extract([Item(text="Ada")], labels=["person"], options={"threshold": threshold})
+
+ adapter._model.inference.assert_not_called()
diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.py
index 633ebd5a8..cdac8ed11 100644
--- a/packages/sie_server/tests/test_all_models.py
+++ b/packages/sie_server/tests/test_all_models.py
@@ -1031,6 +1031,77 @@ def test_knowledgator_gliner_bi_base_v2_0_extract() -> None:
_assert_extract("knowledgator/gliner-bi-base-v2.0", _NER_LABELS, ["location", "organization", "person"])
+def test_knowledgator_gliner_bi_edge_v2_0_extract() -> None:
+ _assert_extract("knowledgator/gliner-bi-edge-v2.0", _NER_LABELS, ["location", "organization", "person"])
+
+
+def test_knowledgator_gliner_bi_large_v2_0_extract() -> None:
+ _assert_extract("knowledgator/gliner-bi-large-v2.0", _NER_LABELS, ["location", "organization", "person"])
+
+
+def test_knowledgator_gliner_bi_small_v2_0_extract() -> None:
+ _assert_extract("knowledgator/gliner-bi-small-v2.0", _NER_LABELS, ["location", "organization", "person"])
+
+
+_PII_TEXT = "Contact John Smith at [email protected] or +1 555 010 9999."
+# The model card's label vocabulary; threshold 0.3 matches the served default.
+_PII_LABELS = ["name", "email address", "phone number"]
+
+
+_PII_NAME = ("name", "John Smith")
+_PII_EMAIL = ("email address", "[email protected]")
+_PII_PHONE = ("phone number", "+1 555 010 9999")
+
+
+def _assert_pii(adapter: Any, expected: set[tuple[str, str]]) -> None:
+ output = adapter.extract([Item(text=_PII_TEXT)], labels=_PII_LABELS, options={"threshold": 0.3})
+ assert {(entity["label"], entity["text"]) for entity in output.entities[0]} == expected
+
+
+def test_knowledgator_gliner_pii_base_v1_0_extract() -> None:
+ _assert_pii(_get_adapter("knowledgator/gliner-pii-base-v1.0"), {_PII_NAME, _PII_EMAIL, _PII_PHONE})
+
+
+def test_knowledgator_gliner_pii_edge_v1_0_extract() -> None:
+ _assert_pii(_get_adapter("knowledgator/gliner-pii-edge-v1.0"), {_PII_NAME, _PII_EMAIL, _PII_PHONE})
+
+
+def test_knowledgator_gliner_pii_large_v1_0_extract() -> None:
+ # The large model scores the name 0.17 on this text, below the 0.3 threshold.
+ _assert_pii(_get_adapter("knowledgator/gliner-pii-large-v1.0"), {_PII_EMAIL, _PII_PHONE})
+
+
+def test_knowledgator_gliner_pii_small_v1_0_extract() -> None:
+ # The small model scores the email 0.29 on this text, just below the 0.3 threshold.
+ _assert_pii(_get_adapter("knowledgator/gliner-pii-small-v1.0"), {_PII_NAME, _PII_PHONE})
+
+
+_RELEX_TEXT = "Steve Jobs founded Apple in Cupertino."
+_RELEX_RELATIONS = ["founded", "located in"]
+
+
+def _assert_relex(adapter: Any) -> None:
+ entities_only = adapter.extract([Item(text=_RELEX_TEXT)], labels=_NER_LABELS)
+ assert entities_only.relations is None
+ assert {e["text"] for e in entities_only.entities[0]} >= {"Steve Jobs", "Apple"}
+
+ # relation_threshold 0.7 matches the served default.
+ output = adapter.extract(
+ [Item(text=_RELEX_TEXT)],
+ labels=_NER_LABELS,
+ options={"relation_labels": _RELEX_RELATIONS, "relation_threshold": 0.7},
+ )
+ assert output.relations is not None
+ entity_texts = {e["text"] for e in output.entities[0]}
+ triples = {(r["head"], r["relation"], r["tail"]) for r in output.relations[0]}
+ assert ("Steve Jobs", "founded", "Apple") in triples
+ assert all(r["head"] in entity_texts and r["tail"] in entity_texts for r in output.relations[0])
+
+
+def test_knowledgator_gliner_relex_large_v1_0_extract() -> None:
+ _assert_relex(_get_adapter("knowledgator/gliner-relex-large-v1.0"))
+
+
def test_knowledgator_modern_gliner_bi_base_v1_0_extract() -> None:
_assert_extract("knowledgator/modern-gliner-bi-base-v1.0", _NER_LABELS, ["location", "organization", "person"])
diff --git a/uv.lock b/uv.lock
index ba8f9ffa5..409cd3462 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4895,7 +4895,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 = "gliner", specifier = ">=0.2,<1" },
+ { name = "gliner", specifier = ">=0.2.26,<1" },
{ name = "gliner2", specifier = ">=1.3.1,<2" },
{ name = "glirel", specifier = ">=1.0,<2" },
{ name = "httpx", specifier = ">=0.28.1" },