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): support native GLiNER2 entity descriptions (#605)

svonava461f8dc5131b
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index 81251c9c0..251c4ee4d 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -483,27 +483,40 @@ with SIEClient("http://localhost:8080") as client:
"fastino/gliner2.5-base-v1",
{"text": "Ada joined Acme in London."},
labels=["person", "organization", "location"],
- options={"threshold": 0.5},
+ options={
+ "threshold": 0.5,
+ "entity_descriptions": {
+ "person": "Named human, including surname aliases.",
+ "organization": "Named company or public institution.",
+ },
+ },
)
- print(result.entities)
+ print(result["entities"])
```
The profiles allow one complete 4,096-token encoder row, including the schema
prompt. The prompt may take up to 2,048 tokens, and each label at most 128
-characters. Descriptive string labels are preserved exactly, except reserved
-prompt markers such as `[SEP_TEXT]`, which are rejected. Inputs that do
-not fit return per-item `INPUT_TOO_LONG` errors; split long documents into
-deliberate smaller items instead of relying on prefix truncation. Entity
+characters. Labels are literal names and are returned exactly. Optional
+`options.entity_descriptions` maps any subset of those exact names to string
+descriptions in the native schema's separate prompt channel. Unspecified
+labels remain undescribed; omitting the option or using an empty mapping keeps
+the existing label-list behavior. Unknown keys, non-string values and reserved
+prompt markers such as `[SEP_TEXT]` in labels or descriptions are rejected.
+Inputs that do not fit return per-item `INPUT_TOO_LONG` errors; split long
+documents into deliberate smaller items instead of relying on prefix truncation. Entity
offsets index the original text. Usage counts the native document segment,
-including the processor's sentence-end punctuation; schema labels and markers
-are not billed. Failed items count zero. These new profiles default to
-float32; another precision is an explicit profile setting.
+including the processor's sentence-end punctuation; schema labels, descriptions
+and markers are not billed. Failed items count zero. These new profiles default
+to float32; another precision is an explicit profile setting.
Before native preprocessing, the adapter also bounds each source to 64
characters and four native words per configured row token, with at most 4,096
characters per word. The label list may contain at most `max_prompt_tokens`
-entries and 32 times that many characters in total. Inputs beyond these
-admission limits fail explicitly before collation or inference.
+entries. Each description and the combined label/description text are bounded
+to 32 times `max_prompt_tokens` characters, counting label names repeated in
+description prefixes. Inputs beyond these character and word bounds fail
+explicitly before collation or inference. Descriptions also count toward the
+actual 2,048-token prompt and complete 4,096-token row; they are not truncated.
### Privacy Filter extraction
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/entities.py b/packages/sie_server/src/sie_server/adapters/gliner2/entities.py
index 906aba199..f7c6a50a0 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/entities.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/entities.py
@@ -57,14 +57,16 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
including its appended terminal punctuation. ``data`` also records the
full encoded-row and prompt counts. Failed items bill zero tokens.
- Entity labels are exact strings, including descriptive names, case and
- punctuation, except reserved prompt markers, with at most 128 characters
- per label. Admission also bounds
+ Entity labels are exact names, preserving case and punctuation, except
+ reserved prompt markers, with at most 128 characters per label. Optional
+ ``options.entity_descriptions`` maps existing labels to guidance in the
+ native schema's separate description channel. Admission also bounds
source preprocessing to 64 characters and four words per row-budget token,
with at most 4096 characters per word. The prompt allows at most one label
- and 32 label characters per prompt-budget token. Exceeding any admission
+ and 32 combined label/description characters per prompt-budget token,
+ including labels repeated in description prefixes. Exceeding any admission
bound rejects the complete item before native collation or inference.
- Runtime options accept only the native ``threshold`` in [0, 1]. This
+ Runtime options also accept the native ``threshold`` in [0, 1]. This
adapter does not perform classification, relations, JSON extraction or
automatic source windowing.
"""
@@ -173,10 +175,20 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
if output_schema is not None or instruction is not None:
raise InvalidInputError("GLiNER2 entities accepts labels, without output_schema or instruction")
opts = options or {}
- if set(opts) - {"threshold"}:
- raise InvalidInputError("GLiNER2 entities supports only the threshold runtime option")
+ if set(opts) - {"threshold", "entity_descriptions"}:
+ raise InvalidInputError(
+ "GLiNER2 entities supports only the threshold and entity_descriptions runtime options"
+ )
threshold = self._validate_threshold(opts.get("threshold", self._threshold))
effective_labels = self._validate_labels(self._default_labels if labels is None else labels)
+ descriptions = (
+ self._validate_descriptions(opts["entity_descriptions"], effective_labels)
+ if "entity_descriptions" in opts
+ else {}
+ )
+ entity_types = (
+ {label: descriptions.get(label, {}) for label in effective_labels} if descriptions else effective_labels
+ )
entities: list[list[Entity]] = [[] for _ in items]
data: list[dict[str, Any]] = [{} for _ in items]
@@ -184,8 +196,8 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
counts = [0] * len(items)
accepted: list[tuple[int, str, int, int, int]] = []
with self._tokenizer_guard():
- prompt_failure = self._prompt_admission_failure(effective_labels)
- schema = self._model.create_schema().entities(effective_labels).build() if prompt_failure is None else None
+ prompt_failure = self._prompt_admission_failure(effective_labels, descriptions)
+ schema = self._model.create_schema().entities(entity_types).build() if prompt_failure is None else None
for index, item in enumerate(items):
text = item.text
if not isinstance(text, str):
@@ -211,7 +223,11 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
message=(
f"GLiNER2 entities needs {row_tokens} encoded tokens including {prompt_tokens} prompt tokens; "
f"limits are {self._max_seq_length} per complete row and {self._max_prompt_tokens} per prompt. "
- "Send a shorter source window or fewer or shorter labels."
+ + (
+ "Send a shorter source window or fewer or shorter labels or descriptions."
+ if descriptions
+ else "Send a shorter source window or fewer or shorter labels."
+ )
),
)
continue
@@ -229,7 +245,7 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
sources = [accepted[row][1] for row in group]
results = self._model.batch_extract_entities(
sources,
- effective_labels,
+ entity_types,
batch_size=len(sources),
threshold=threshold,
include_confidence=True,
@@ -293,15 +309,29 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
"""Counts come from request-qualified native rows in ``extract``."""
_ = items
- def _prompt_admission_failure(self, labels: list[str]) -> str | None:
- if len(labels) > self._max_prompt_tokens or sum(len(label) for label in labels) > (
- self._max_prompt_tokens * MAX_PROMPT_CHARS_PER_TOKEN
- ):
+ def _prompt_admission_failure(self, labels: list[str], descriptions: dict[str, str]) -> str | None:
+ max_chars = self._max_prompt_tokens * MAX_PROMPT_CHARS_PER_TOKEN
+ prompt_chars = sum(len(label) for label in labels)
+ if len(labels) > self._max_prompt_tokens or prompt_chars > max_chars:
return (
f"GLiNER2 entities permits at most {self._max_prompt_tokens} labels and "
- f"{self._max_prompt_tokens * MAX_PROMPT_CHARS_PER_TOKEN} total label characters. "
+ f"{max_chars} total label characters. "
"Send fewer or shorter labels."
)
+ if descriptions:
+ if any(len(description) > max_chars for description in descriptions.values()):
+ return (
+ f"GLiNER2 entities permits at most {max_chars} characters per description. "
+ "Send shorter descriptions."
+ )
+ # Native description prefixes repeat each described label name.
+ prompt_chars += sum(len(label) + len(description) for label, description in descriptions.items())
+ if prompt_chars > max_chars:
+ return (
+ f"GLiNER2 entities permits at most {self._max_prompt_tokens} labels and "
+ f"{max_chars} total label and description characters, including repeated label names. "
+ "Send fewer or shorter labels or descriptions."
+ )
return None
def _source_admission_failure(self, text: str) -> str | None:
@@ -352,6 +382,24 @@ class GLiNER2EntitiesAdapter(BaseAdapter):
check_label_chars("GLiNER2 entities", "labels", labels)
return labels
+ @staticmethod
+ def _validate_descriptions(value: object, labels: list[str]) -> dict[str, str]:
+ if not isinstance(value, dict):
+ raise InvalidInputError("GLiNER2 entity_descriptions must be an object mapping existing labels to strings")
+ label_names = set(labels)
+ descriptions: dict[str, str] = {}
+ for label, description in value.items():
+ if not isinstance(label, str) or label not in label_names:
+ raise InvalidInputError("GLiNER2 entity_descriptions keys must exactly match existing labels")
+ if not isinstance(description, str):
+ raise InvalidInputError("GLiNER2 entity_descriptions values must be strings")
+ if any(marker in description for marker in MARKERS):
+ raise InvalidInputError(
+ "GLiNER2 entity descriptions may not contain structural tokens of the model's prompt"
+ )
+ descriptions[label] = description
+ return descriptions
+
@staticmethod
def _flatten_entities(result: Any, text: str, labels: list[str]) -> list[Entity]:
if not isinstance(result, dict) or not isinstance(result.get("entities"), dict):
diff --git a/packages/sie_server/tests/adapters/test_gliner2_entities.py b/packages/sie_server/tests/adapters/test_gliner2_entities.py
index fbba1539e..95793d058 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_entities.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_entities.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import sys
from collections.abc import Callable, Iterator
+from copy import deepcopy
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any
@@ -18,6 +19,8 @@ from sie_server.adapters.gliner2.entities import GLiNER2EntitiesAdapter
from sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitter
from sie_server.types.inputs import InvalidInputError, Item
+EntityTypes = list[str] | dict[str, str | dict[str, Any]]
+
class WhitespaceTokenSplitter:
"""The pinned native splitter's original-source lowercasing contract."""
@@ -44,13 +47,19 @@ class ToyTokenizer:
class ToySchema:
def __init__(self) -> None:
self.labels: list[str] = []
+ self.descriptions: dict[str, str] = {}
- def entities(self, labels: list[str]) -> ToySchema:
+ def entities(self, labels: EntityTypes) -> ToySchema:
self.labels = list(labels)
+ if isinstance(labels, dict):
+ self.descriptions = {label: value for label, value in labels.items() if isinstance(value, str)}
return self
def build(self) -> dict[str, Any]:
- return {"entities": dict.fromkeys(self.labels, "")}
+ schema: dict[str, Any] = {"entities": dict.fromkeys(self.labels, "")}
+ if self.descriptions:
+ schema["entity_descriptions"] = self.descriptions.copy()
+ return schema
class ToyProcessor:
@@ -81,6 +90,9 @@ class ToyProcessor:
for index, label in enumerate(schema["entities"]):
mappings.append(("schema", index + 1, 0))
mappings.extend([("schema", index + 1, 0)] * len(self._tokenize_cached(label)))
+ for label, description in schema.get("entity_descriptions", {}).items():
+ mappings.append(("schema", 0, 0))
+ mappings.extend([("schema", 0, 0)] * len(self._tokenize_cached(f"{label}: {description}")))
mappings.append(("sep", 0, 1))
for index, (word, _, _) in enumerate(words):
mappings.extend([("text", index, 1)] * len(self._tokenize_cached(word)))
@@ -100,15 +112,15 @@ class ToyModel:
self.processor = ToyProcessor()
self.to = Mock()
self.eval = Mock()
- self.calls: list[tuple[list[str], list[str], dict[str, Any]]] = []
+ self.calls: list[tuple[list[str], EntityTypes, dict[str, Any]]] = []
self.results: dict[str, Any] = {}
self.batch_result: Any = None
def create_schema(self) -> ToySchema:
return ToySchema()
- def batch_extract_entities(self, texts: list[str], labels: list[str], **kwargs: Any) -> Any:
- self.calls.append((texts, list(labels), kwargs))
+ def batch_extract_entities(self, texts: list[str], labels: EntityTypes, **kwargs: Any) -> Any:
+ self.calls.append((texts, deepcopy(labels), kwargs))
if self.batch_result is not None:
return self.batch_result
return [self.results.get(text, {"entities": {}}) for text in texts]
@@ -133,7 +145,7 @@ def loaded(native_loader: tuple[Mock, Mock, ToyModel]) -> tuple[GLiNER2EntitiesA
return adapter, native_loader[2]
-def native_counts(model: ToyModel, text: str, labels: list[str]) -> tuple[int, int, int]:
+def native_counts(model: ToyModel, text: str, labels: EntityTypes) -> tuple[int, int, int]:
batch = model.processor.collate_fn_inference([(text, ToySchema().entities(labels).build())])
document = sum(mapping[0] == "text" for mapping in batch.mapped_indices[0])
return batch.original_lengths[0], document, batch.original_lengths[0] - document
@@ -253,6 +265,165 @@ def test_full_source_exact_labels_and_native_api(loaded: tuple[GLiNER2EntitiesAd
assert document_tokens < row_tokens
[email protected]("options", [None, {"threshold": 0.5}, {"entity_descriptions": {}}])
+def test_absent_or_empty_descriptions_keep_native_list_and_response(loaded, options):
+ adapter, model = loaded
+ text = "Zoë."
+ labels = ["person"]
+ model.results[text] = {"entities": {"person": [span(text, 0, 3)]}}
+ output = adapter.extract([Item(text=text)], labels=labels, options=options)
+ assert model.calls[0][1] == labels
+ assert isinstance(model.calls[0][1], list)
+ assert model.processor.calls[0][1] == {"entities": {"person": ""}}
+ assert output.entities == [[{"text": "Zoë", "label": "person", "score": 0.9, "start": 0, "end": 3}]]
+ assert output.input_token_counts == [4]
+
+
[email protected]("architecture", ["span", "boundary"])
+def test_partial_descriptions_preserve_label_order_spans_and_document_billing(loaded, architecture):
+ adapter, model = loaded
+ adapter._architecture = architecture
+ model.architecture = architecture
+ text = "İpek joined Acme."
+ labels = ["person", "organization", "location"]
+ descriptions = {"organization": "Named company or agency.", "person": "Named human, including surname aliases."}
+ options = {"threshold": 0.7, "entity_descriptions": descriptions}
+ original = deepcopy(options)
+ entity_types = {"person": descriptions["person"], "organization": descriptions["organization"], "location": {}}
+ model.results[text] = {"entities": {"person": [span(text, 0, 4, confidence=0.8)]}}
+ plain_row, document, plain_prompt = native_counts(model, text, labels)
+ row, described_document, prompt = native_counts(model, text, entity_types)
+ model.processor.calls.clear()
+
+ output = adapter.extract([Item(text=text)], labels=labels, options=options)
+
+ assert options == original
+ assert described_document == document
+ assert row > plain_row
+ assert prompt > plain_prompt
+ assert output.input_token_counts == [document]
+ assert output.data == [{"encoded_row_token_count": row, "schema_prompt_token_count": prompt}]
+ assert output.entities == [[{"text": "İpek", "label": "person", "score": 0.8, "start": 0, "end": 4}]]
+ assert model.processor.calls[0][1] == {
+ "entities": dict.fromkeys(labels, ""),
+ "entity_descriptions": {"person": descriptions["person"], "organization": descriptions["organization"]},
+ }
+ assert model.calls[0][1] == entity_types
+ assert list(model.calls[0][1]) == labels
+ assert model.calls[0][2] == {
+ "batch_size": 1,
+ "threshold": 0.7,
+ "include_confidence": True,
+ "include_spans": True,
+ "max_len": None,
+ }
+
+
+def test_descriptions_are_request_local_and_do_not_rename_default_labels(loaded):
+ adapter, model = loaded
+ adapter._default_labels = ["Exact Person"]
+ adapter.extract([Item(text="Alice.")], options={"entity_descriptions": {"Exact Person": "Named human."}})
+ adapter.extract([Item(text="Alice.")])
+ assert model.calls[0][1] == {"Exact Person": "Named human."}
+ assert model.calls[1][1] == ["Exact Person"]
+ assert model.processor.calls[1][1] == {"entities": {"Exact Person": ""}}
+ assert adapter._default_labels == ["Exact Person"]
+
+
+ "descriptions",
+ [
+ None,
+ [],
+ "guidance",
+ {"Person": "guidance"},
+ {1: "guidance"},
+ {"person": None},
+ {"person": 1},
+ {"person": True},
+ {"person": []},
+ {"person": {"description": "guidance"}},
+ ],
+)
+def test_malformed_description_mapping_fails_before_schema_or_forward(loaded, descriptions):
+ adapter, model = loaded
+ model.create_schema = Mock(side_effect=AssertionError("malformed descriptions must not reach native code"))
+ with pytest.raises(InvalidInputError, match="entity_descriptions"):
+ adapter.extract([Item(text="Alice.")], labels=["person"], options={"entity_descriptions": descriptions})
+ model.create_schema.assert_not_called()
+ assert model.processor.calls == []
+ assert model.calls == []
+
+
[email protected]("marker", MARKERS)
+def test_description_structural_markers_fail_before_schema_or_forward(loaded, marker):
+ adapter, model = loaded
+ model.create_schema = Mock(side_effect=AssertionError("structural descriptions must not reach native code"))
+ with pytest.raises(InvalidInputError, match="structural tokens"):
+ adapter.extract(
+ [Item(text="Alice.")], labels=["person"], options={"entity_descriptions": {"person": f"Name {marker}."}}
+ )
+ model.create_schema.assert_not_called()
+ assert model.processor.calls == []
+ assert model.calls == []
+
+
+ "description", ["", "Named human; aliases, 東京 and accents. [ordinary] {name}: https://example.org — " * 3]
+)
+def test_legitimate_descriptions_are_not_limited_to_label_length_or_vocabulary(loaded, description):
+ adapter, model = loaded
+ output = adapter.extract(
+ [Item(text="Alice.")], labels=["person"], options={"entity_descriptions": {"person": description}}
+ )
+ assert output.errors is None
+ assert model.calls[0][1] == {"person": description}
+
+
[email protected]("kind", ["single", "combined", "repeated_label"])
+def test_description_character_budget_rejects_before_collation_with_zero_usage(loaded, kind):
+ adapter, model = loaded
+ adapter._max_prompt_tokens = 2
+ if kind == "single":
+ labels, descriptions = ["x"], {"x": "d" * 65}
+ elif kind == "combined":
+ labels, descriptions = ["x", "y"], {"x": "d" * 31, "y": "d" * 30}
+ else:
+ labels, descriptions = ["x" * 32], {"x" * 32: "d"}
+ model.create_schema = Mock(side_effect=AssertionError("oversize prompt must not reach native code"))
+ output = adapter.extract([Item(text="Alice.")], labels=labels, options={"entity_descriptions": descriptions})
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+ assert output.entities == [[]]
+ assert output.input_token_counts == [0]
+ model.create_schema.assert_not_called()
+ assert model.processor.calls == []
+ assert model.calls == []
+
+
[email protected]("budget", ["row", "prompt"])
+def test_actual_encoded_description_overflow_never_runs_or_bills(loaded, budget):
+ adapter, model = loaded
+ labels = ["person"]
+ description = "Named human."
+ row, _, prompt = native_counts(model, "Alice.", {"person": description})
+ if budget == "row":
+ adapter._max_seq_length = row - 1
+ else:
+ adapter._max_prompt_tokens = prompt - 1
+ model.processor.calls.clear()
+ plain = adapter.extract([Item(text="Alice.")], labels=labels)
+ assert plain.errors is None
+ model.calls.clear()
+ output = adapter.extract(
+ [Item(text="Alice.")], labels=labels, options={"entity_descriptions": {"person": description}}
+ )
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+ assert output.entities == [[]]
+ assert output.input_token_counts == [0]
+ assert model.calls == []
+ assert model.config.max_len == 1
+
+
def test_exact_limit_and_one_subword_overflow(loaded: tuple[GLiNER2EntitiesAdapter, ToyModel]) -> None:
adapter, model = loaded
labels = ["person"]