Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(gliner2): count compiled inference prompts (#794)

svonavaf3b34e2dd88d
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/_prompt.py b/packages/sie_server/src/sie_server/adapters/gliner2/_prompt.py
new file mode 100644
index 000000000..9d16ec497
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/_prompt.py
@@ -0,0 +1,67 @@
+"""Count the inference prompt with GLiNER2's own schema compiler."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from copy import copy, deepcopy
+from typing import Any
+
+
+def prompt_counter(processor: Any) -> Callable[[Any], int]:
+ """An independent inference compiler using the loaded tokenizer's settings.
+
+ Tokenizers and word caches are mutable, so make a private tokenizer once
+ per load, not per request. Keep the serving processor's mode and caches
+ untouched. The copied processor's tokenizer cache is rebound explicitly:
+ deepcopy of an LRU callable would still refer to the serving tokenizer.
+ """
+ inference = copy(processor)
+ inference.tokenizer = deepcopy(processor.tokenizer)
+ inference.word_splitter = deepcopy(processor.word_splitter)
+ inference.sampling_config = deepcopy(processor.sampling_config)
+ inference._token_cache = deepcopy(processor._token_cache)
+ inference._tokenize_cached = inference.tokenizer.tokenize
+ inference.change_mode(is_training=False)
+
+ def count(schema: Any) -> int:
+ # The public single-record entry point deep-copies the schema and
+ # propagates errors, unlike 1.x's batch-collator fallback. Empty text
+ # adds no synthetic period: all ids are prompt markers, schema strings,
+ # separator and (for structured choices) the document-side prefix.
+ compiled_schema = deepcopy(schema.build())
+ if compiled_schema.get("classifications"):
+ return _classification_tokens(inference, compiled_schema)
+ record = inference.transform_and_format("", compiled_schema)
+ return len(record.input_ids)
+
+ return count
+
+
+def _classification_tokens(processor: Any, schema: dict[str, Any]) -> int:
+ """Render the plain single-task schema accepted by the generic adapter.
+
+ The upstream inference compiler selects ``random.choice(["both"])`` even
+ though there is only one possible mode. Call its rendering/encoding stages
+ directly for this schema so counting does not advance process-global RNG.
+ These options affect classification postprocessing, not its prompt. Refuse
+ extensions here rather than silently ignoring new prompt-bearing fields.
+ """
+ tasks = schema["classifications"]
+ if len(tasks) != 1 or any(schema.get(key) for key in ("entities", "relations", "json_structures")):
+ raise RuntimeError("GLiNER2 prompt counter requires a single classification task")
+ task = tasks[0]
+ if set(task) - {"task", "labels", "multi_label", "cls_threshold", "true_label"}:
+ raise RuntimeError("GLiNER2 classification prompt schema changed")
+ tokens = processor._transform_schema(task["task"], task["labels"], processor.L_TOKEN, example_mode="both")
+ return len(processor._format_input_with_mapping([tokens], [])["input_ids"])
+
+
+def structure_schema(model: Any, structures: dict[str, list[str]]) -> Any:
+ """Use the same field parser and schema builder as ``batch_extract_json``."""
+ schema = model.create_schema()
+ for parent, fields in structures.items():
+ builder = schema.structure(parent)
+ for spec in fields:
+ name, dtype, choices, description = model._parse_field_spec(spec)
+ builder.field(name, dtype=dtype, choices=choices, description=description)
+ return schema
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
index 0a04a0dfa..7df8305f6 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
@@ -25,6 +25,7 @@ from sie_server.adapters._word_window import (
quadratic_attention,
subword_budget,
)
+from sie_server.adapters.gliner2._prompt import prompt_counter, structure_schema
from sie_server.adapters.gliner2.words import linear_equivalent
from sie_server.core.inference_output import ExtractItemError, ExtractOutput
from sie_server.types.inputs import InvalidInputError, Item
@@ -55,14 +56,7 @@ _WORD_CACHE_SIZE = 16384
_CACHED_WORD_CHARS = 32
# Rows gliner2 puts in one forward pass when not told otherwise.
_PACKAGE_BATCH_SIZE = 8
-# Task prompt tokens per label or task name beyond its own tokens: gliner2
-# marks each entity type or class with one token, and builds one structure of
-# about ten tokens around each relation type.
-_PROMPT_TOKENS_PER_ENTRY = 2
-_PROMPT_TOKENS_PER_RELATION = 12
_SENTENCE_END = (".", "!", "?")
-# The prompt's own markers, [SEP_TEXT], and the tokenizer's specials.
-_ROW_OVERHEAD_TOKENS = 8
_DEBERTA_CONFIG = {"model_type": "deberta-v2"}
# Classification reads a text longer than one window as overlapping windows of
# the same size (see ``_classification_windows``). A window starts this many
@@ -97,7 +91,9 @@ class GLiNER2Adapter(BaseAdapter):
names, descriptions and choices), which gliner2 encodes with every document
and does not bill, may take at most ``max_prompt_tokens`` tokens (default
2048), and each label, task name, field name or choice at most 128
- characters; a longer prompt is rejected with ``INVALID_INPUT``.
+ characters; a longer prompt is rejected with ``INVALID_INPUT``. Prompt
+ counts use the loaded inference schema compiler, including its markers,
+ descriptions and choice prefixes, without changing document token usage.
gliner2 reads at most ``max_seq_length`` words of a document. Entity,
relation and structured extraction read that first window. Classification
@@ -115,7 +111,7 @@ class GLiNER2Adapter(BaseAdapter):
spec: ClassVar[AdapterSpec] = AdapterSpec(
inputs=("text",),
outputs=("json",),
- unload_fields=("_model",),
+ unload_fields=("_model", "_count_prompt"),
)
def __init__(
@@ -172,6 +168,7 @@ class GLiNER2Adapter(BaseAdapter):
self._revision = revision
self._model: Any = None
+ self._count_prompt: Callable[[Any], int] | None = None
# How the loaded gliner2 splits words (see ``_model_text``); None until loaded.
self._lower_text_first: bool | None = None
# The splitter gliner2 reads words with, bounded to the window it reads (see ``_window``).
@@ -206,6 +203,8 @@ class GLiNER2Adapter(BaseAdapter):
)
encoder = getattr(model, "encoder", None)
self._use_linear_word_splitter(model.processor, getattr(encoder, "config", None))
+ # Counts belong to this processor/tokenizer, not a previous load.
+ self._prompt_limit = PromptLimit("GLiNER2", self._prompt_limit.max_tokens)
self._model = model
def _use_linear_word_splitter(self, processor: Any, encoder_config: Any = None) -> None:
@@ -231,6 +230,7 @@ class GLiNER2Adapter(BaseAdapter):
)
# An unknown encoder is taken to be DeBERTa, the encoder of every GLiNER2 checkpoint.
config = encoder_config if encoder_config is not None else _DEBERTA_CONFIG
+ count_prompt = prompt_counter(processor)
tokenize = self._bounded_tokenization(processor)
count_subwords = SubwordCounter(lambda words: [len(tokenize(word)) for word in words])
max_words = self._max_seq_length or _DEFAULT_MAX_WORDS
@@ -245,6 +245,7 @@ class GLiNER2Adapter(BaseAdapter):
self._word_splitter = windowed
self._count_subwords = count_subwords
self._quadratic_attention = quadratic_attention(config)
+ self._count_prompt = count_prompt
@staticmethod
def _bounded_tokenization(processor: Any) -> Callable[[str], list[str]]:
@@ -293,13 +294,14 @@ class GLiNER2Adapter(BaseAdapter):
raise InvalidInputError("GLiNER2 structured extraction does not accept classification_task")
structures = self._json_schema_to_structures(output_schema)
specs = [spec for fields in structures.values() for spec in fields]
- # A field's choices are listed in its structure, and each again in a prefix before the document.
choices = [
choice for definition in output_schema["properties"].values() for choice in definition.get("enum") or []
]
check_label_chars("GLiNER2", "output_schema property names", output_schema["properties"])
check_label_chars("GLiNER2", "output_schema enum values", choices)
- prompt = self._prompt_tokens(specs, key=("json", tuple(specs)), extra=len(choices))
+ prompt = self._prompt_tokens(
+ specs, key=("json", tuple(specs)), schema=lambda: structure_schema(self._model, structures)
+ )
reads = [self._read(text) for text in texts]
windows = [(model_text, subwords) for model_text, subwords, _ in reads]
input_token_counts = self._doc_input_token_counts(texts)
@@ -346,7 +348,9 @@ class GLiNER2Adapter(BaseAdapter):
]
check_label_chars("GLiNER2", "labels", normalized_labels)
prompt = self._prompt_tokens(
- normalized_labels, per_entry=_PROMPT_TOKENS_PER_RELATION, key=("relations", tuple(normalized_labels))
+ normalized_labels,
+ key=("relations", tuple(normalized_labels)),
+ schema=lambda: self._model.create_schema().relations(normalized_labels),
)
reads = [self._read(text) for text in texts]
windows = [(model_text, subwords) for model_text, subwords, _ in reads]
@@ -390,7 +394,10 @@ class GLiNER2Adapter(BaseAdapter):
positive_label = self._effective_positive_label(opts, normalized_labels)
prompt = self._prompt_tokens(
[classification_task, *normalized_labels],
- key=("classification", classification_task, tuple(normalized_labels)),
+ key=("classification", classification_task, tuple(normalized_labels), multi_label, effective_threshold),
+ schema=lambda: self._model.create_schema().classification(
+ classification_task, normalized_labels, multi_label=multi_label, cls_threshold=effective_threshold
+ ),
)
reads = [self._read(text) for text in texts]
input_token_counts = self._doc_input_token_counts(texts)
@@ -430,7 +437,11 @@ class GLiNER2Adapter(BaseAdapter):
)
check_label_chars("GLiNER2", "labels", normalized_labels)
- prompt = self._prompt_tokens(normalized_labels, key=("entities", tuple(normalized_labels)))
+ prompt = self._prompt_tokens(
+ normalized_labels,
+ key=("entities", tuple(normalized_labels)),
+ schema=lambda: self._model.create_schema().entities(normalized_labels),
+ )
reads = [self._read(text) for text in texts]
windows = [(model_text, subwords) for model_text, subwords, _ in reads]
input_token_counts = self._doc_input_token_counts(texts)
@@ -595,30 +606,24 @@ class GLiNER2Adapter(BaseAdapter):
entries: list[str],
*,
key: tuple[Any, ...],
- per_entry: int = _PROMPT_TOKENS_PER_ENTRY,
- extra: int = 0,
- ) -> int | None:
- """Estimated tokens of the task prompt gliner2 builds from ``entries``, checked against the limit.
+ schema: Callable[[], Any],
+ ) -> int:
+ """Tokens of the actual compiled inference prompt, checked before document work.
- Each label, class label, relation type and schema field is counted
- with the tokens gliner2 adds around it, plus ``extra`` (a token per
- field choice, which gliner2 lists again before the document). None when words are
- not counted (no bounded splitter is installed); the prompt's
- characters are still checked.
+ Build and compile only after the aggregate character check. The result
+ includes markers, descriptions, JSON choice prefixes and the document
+ separator; it is used for admission/batch planning, not reported usage.
Raises:
InvalidInputError: The prompt takes more than ``max_prompt_tokens``.
"""
- count = self._count_subwords
- strings = [entry for entry in entries if isinstance(entry, str)]
def tokens() -> int:
- if count is None:
- return 0
- return sum(count(strings)) + per_entry * len(strings) + extra + _ROW_OVERHEAD_TOKENS
+ if self._count_prompt is None:
+ raise RuntimeError("GLiNER2 prompt counter is not loaded")
+ return self._count_prompt(schema())
- prompt = self._prompt_limit.check(strings, tokens, (per_entry, extra, *key))
- return prompt if count is not None else None
+ return self._prompt_limit.check(entries, tokens, key)
def _row_tokens(self, windows: list[tuple[str, int | None]], prompt: int | None) -> list[int] | None:
"""Estimated tokens of each item's encoder row: the task prompt, then the words it reads.
diff --git a/packages/sie_server/tests/adapters/test_gliner2.py b/packages/sie_server/tests/adapters/test_gliner2.py
index c320ddbf3..318d63f3b 100644
--- a/packages/sie_server/tests/adapters/test_gliner2.py
+++ b/packages/sie_server/tests/adapters/test_gliner2.py
@@ -22,6 +22,8 @@ def test_classification_mode_maps_single_label_confidence() -> None:
default_labels=["safe", "unsafe"],
)
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.classify_text.return_value = {"prompt_safety": {"label": "unsafe", "confidence": 0.91}}
output = adapter.extract(
@@ -52,6 +54,8 @@ def test_request_labels_override_configured_defaults() -> None:
default_labels=["safe", "unsafe"],
)
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.classify_text.return_value = {"prompt_safety": {"label": "review", "confidence": 0.7}}
adapter.extract(
@@ -72,6 +76,8 @@ def test_configured_default_labels_are_validated(default_labels: Any) -> None:
def test_classification_mode_maps_batch_multi_label_runtime_overrides() -> None:
adapter = GLiNER2Adapter("test-model", classification_task="prompt_safety")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.batch_classify_text.return_value = [
{
"jailbreak_detection": [
@@ -121,6 +127,8 @@ def test_classification_mode_maps_batch_multi_label_runtime_overrides() -> None:
def test_entity_mode_remains_the_default() -> None:
adapter = GLiNER2Adapter("test-model")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.extract_entities.return_value = {
"entities": {
"person": [
@@ -158,6 +166,8 @@ def test_entity_mode_remains_the_default() -> None:
def test_classification_task_rejects_empty_runtime_override() -> None:
adapter = GLiNER2Adapter("test-model", classification_task="prompt_safety")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
with pytest.raises(ValueError, match="classification_task must be a non-empty string"):
adapter.extract(
@@ -170,6 +180,8 @@ def test_classification_task_rejects_empty_runtime_override() -> None:
def test_multi_label_rejects_non_boolean_runtime_values() -> None:
adapter = GLiNER2Adapter("test-model", classification_task="prompt_safety")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
with pytest.raises(ValueError, match="multi_label must be boolean"):
adapter.extract(
@@ -183,6 +195,8 @@ def test_multi_label_rejects_non_boolean_runtime_values() -> None:
def test_classification_rejects_invalid_confidence(confidence: object) -> None:
adapter = GLiNER2Adapter("test-model", classification_task="prompt_safety")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.classify_text.return_value = {"prompt_safety": {"label": "safe", "confidence": confidence}}
with pytest.raises(ValueError, match="invalid classification confidence"):
@@ -224,6 +238,8 @@ def test_gliguard_profile_executes_without_request_labels() -> None:
adapter = load_adapter(config, models_dir, device="cpu")
assert isinstance(adapter, GLiNER2ClassificationAdapter)
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._model.classify_text.return_value = {"prompt_safety": {"label": "safe", "confidence": 0.8}}
output = adapter.extract([Item(text="Write a birthday greeting")])
@@ -243,6 +259,8 @@ def _adapter_with_counting_model(*, max_seq_length: int = 512) -> tuple[GLiNER2A
model = MagicMock()
model.processor.tokenizer.return_value = {"input_ids": [[1, 2, 3]]}
adapter._model = model
+ adapter._count_prompt = lambda _schema: 8
+ model._parse_field_spec.return_value = ("name", "str", None, None)
return adapter, model
@@ -706,7 +724,11 @@ def test_multi_label_windows_pool_each_label_to_its_highest_confidence() -> None
def _linear_processor() -> Any:
"""A processor with gliner2 1.x's word splitter and one subword per word."""
return SimpleNamespace(
- word_splitter=_Gliner2V1WordSplitter(), tokenizer=SimpleNamespace(tokenize=lambda word: [word])
+ word_splitter=_Gliner2V1WordSplitter(),
+ tokenizer=SimpleNamespace(tokenize=lambda word: [word]),
+ sampling_config=None,
+ _token_cache={},
+ change_mode=MagicMock(),
)
@@ -715,6 +737,8 @@ def test_multi_label_classification_of_a_long_text_filters_pooled_labels_by_the_
adapter._use_linear_word_splitter(_linear_processor())
model = MagicMock()
adapter._model = model
+ adapter._count_prompt = lambda _schema: 8
+ model._parse_field_spec.return_value = ("name", "str", None, None)
model.batch_classify_text.return_value = [
{"jailbreak": [{"label": "benign", "confidence": 0.3}]}, # gliner2's fallback below the threshold
{"jailbreak": [{"label": "prompt_injection", "confidence": 0.8}]},
diff --git a/packages/sie_server/tests/adapters/test_gliner2_complete_text.py b/packages/sie_server/tests/adapters/test_gliner2_complete_text.py
index 81d445561..3a4169f0a 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_complete_text.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_complete_text.py
@@ -25,6 +25,8 @@ def _adapter(*, lower: bool = True, max_words: int = 8, max_subwords: int = 1000
model = MagicMock()
model.processor.tokenizer = _Tokenizer()
adapter._model = model
+ adapter._count_prompt = lambda _schema: 8
+ model._parse_field_spec.return_value = ("name", "str", None, None)
adapter._lower_text_first = lower
adapter._word_splitter = WindowedSplitter(
LinearWordSplitter(lower_text_first=lower),
diff --git a/packages/sie_server/tests/adapters/test_gliner2_input_errors.py b/packages/sie_server/tests/adapters/test_gliner2_input_errors.py
index 7ff93f118..4ba919ffd 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_input_errors.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_input_errors.py
@@ -40,6 +40,7 @@ def test_invalid_request_is_invalid_input_on_the_queue_path(
) -> None:
adapter = GLiNER2Adapter("test-model")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
item = Item(text="Alice works at Acme.", metadata=metadata)
with pytest.raises(ValueError, match="GLiNER2") as error:
@@ -71,6 +72,7 @@ def test_invalid_request_is_invalid_input_on_the_queue_path(
def test_invalid_model_result_remains_an_inference_error_on_the_queue_path() -> None:
adapter = GLiNER2Adapter("test-model")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
adapter._model.extract_entities.return_value = {
"entities": {"PERSON": [{"text": "Alice", "start": 0, "end": 5, "confidence": "bad"}]},
}
diff --git a/packages/sie_server/tests/adapters/test_gliner2_long_text.py b/packages/sie_server/tests/adapters/test_gliner2_long_text.py
index 2c1bf8dd6..d5ec76385 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_long_text.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_long_text.py
@@ -21,7 +21,7 @@ from unittest.mock import MagicMock
import pytest
from sie_server.adapters._word_window import ATTENTION_BUDGET, MAX_WORD_CHARS, WindowedSplitter, subword_budget
-from sie_server.adapters.gliner2.adapter import _PROMPT_TOKENS_PER_RELATION, _SUBWORDS_PER_WORD, GLiNER2Adapter
+from sie_server.adapters.gliner2.adapter import _SUBWORDS_PER_WORD, GLiNER2Adapter
from sie_server.adapters.gliner2.classification import GLiNER2ClassificationAdapter
from sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitter
from sie_server.types.inputs import InvalidInputError, Item
@@ -81,6 +81,13 @@ class PackageModel:
self.processor = processor
self.inputs: list[Any] = []
+ @staticmethod
+ def create_schema() -> Any:
+ return gliner2_engine.Schema()
+
+ def _parse_field_spec(self, spec: str) -> Any:
+ return gliner2_engine.GLiNER2._parse_field_spec(None, spec)
+
def _collate(self, texts: list[str], schema: Any, max_len: int | None) -> None:
self.inputs.append(self.processor.collate_fn_inference([(text, schema) for text in texts], max_len=max_len))
@@ -392,7 +399,9 @@ def test_relation_rows_run_in_passes_within_the_attention_budget() -> None:
adapter.extract([Item(text=text, metadata={"entities": entities}) for _ in range(8)], labels=labels)
- prompt = adapter._prompt_tokens(labels, per_entry=_PROMPT_TOKENS_PER_RELATION, key=("relations", tuple(labels)))
+ prompt = adapter._prompt_tokens(
+ labels, key=("relations", tuple(labels)), schema=lambda: model.create_schema().relations(labels)
+ )
estimated = adapter._row_tokens([adapter._window(text)], prompt)
assert estimated is not None
for batch in model.inputs:
@@ -635,6 +644,7 @@ def test_a_batch_of_fitting_texts_makes_the_same_single_call() -> None:
positive_label="unsafe",
)
model = MagicMock()
+ model.create_schema.side_effect = gliner2_engine.Schema
adapter._use_linear_word_splitter(make_processor())
adapter._model = model
model.batch_classify_text.return_value = [
diff --git a/packages/sie_server/tests/adapters/test_gliner2_lora.py b/packages/sie_server/tests/adapters/test_gliner2_lora.py
index 74b1eae5f..110fecdee 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_lora.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_lora.py
@@ -745,7 +745,7 @@ def test_base_and_overlong_item_metering_match_generic_adapter(raw_model, tmp_pa
assert baseline["input_token_counts"][0] > 0
adapter = GLiNER2EntityLoraAdapter("generated-local", lora_paths=paths, threshold=0, max_seq_length=64)
adapter._model = raw_model
- for attr in ("_word_splitter", "_count_subwords", "_lower_text_first", "_quadratic_attention"):
+ for attr in ("_word_splitter", "_count_subwords", "_count_prompt", "_lower_text_first", "_quadratic_attention"):
setattr(adapter, attr, getattr(ordinary, attr))
adapter._lora.bind(raw_model)
assert msgspec.to_builtins(adapter.extract(items, labels=LABELS)) == baseline
diff --git a/packages/sie_server/tests/adapters/test_gliner2_prompt.py b/packages/sie_server/tests/adapters/test_gliner2_prompt.py
new file mode 100644
index 000000000..5389c4621
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner2_prompt.py
@@ -0,0 +1,302 @@
+"""Exact prompt admission against the installed GLiNER2 inference compiler.
+
+No model weights: the real convenience methods and collator compile every row;
+only the encoder is replaced. These tests also run unchanged against 1.3.1,
+1.3.2 and the transformers5 bundle's GLiNER2 2.0.0.
+"""
+
+from __future__ import annotations
+
+import copy
+import gc
+import random
+import weakref
+from types import MethodType, SimpleNamespace
+from typing import Any
+from unittest.mock import Mock
+
+import pytest
+from sie_server.adapters._prompt_limit import PromptLimit
+from sie_server.adapters.gliner2._prompt import prompt_counter, structure_schema
+from sie_server.adapters.gliner2.adapter import GLiNER2Adapter
+from sie_server.types.inputs import InvalidInputError, Item
+
+from .test_gliner2_long_text import gliner2_engine, make_adapter, make_processor
+
+_TEXT = "Alice works at Acme."
+_LABELS = ["person", "organization"]
+_STRUCTURES = {
+ "_sie_root": [
+ "name::str::The person's full name",
+ "kind::[very long first choice|other choice]::str::The person's role",
+ "aliases::list",
+ ]
+}
+_TASKS = {"sentiment": {"labels": ["yes", "no"], "multi_label": True, "cls_threshold": 0.25}}
+
+
+def _cache_info(processor: Any) -> Any:
+ cached = getattr(processor, "_tokenize_cached", None)
+ return cached.cache_info() if cached is not None else None
+
+
+def native_model(processor: Any) -> Any:
+ """Real runtime schema construction, with its final batch extraction captured."""
+ model = SimpleNamespace(processor=processor, batches=[], schemas=[])
+ runtime = gliner2_engine.GLiNER2
+ for name in ("create_schema", "_parse_field_spec", "_json_schema", "_classification_schema"):
+ if hasattr(runtime, name):
+ setattr(model, name, MethodType(getattr(runtime, name), model))
+
+ def capture(texts: list[str], schema: Any, *_args: Any, **_kwargs: Any) -> list[dict[str, Any]]:
+ model.schemas.append(copy.deepcopy(schema.build()))
+ model.batches.append(processor.collate_fn_inference([(text, schema) for text in texts]))
+ return [{} for _ in texts]
+
+ model.batch_extract = capture
+ return model
+
+
+def schemas(task: str, model: Any) -> tuple[Any, str, Any]:
+ if task == "entities":
+ return model.create_schema().entities(_LABELS), "batch_extract_entities", _LABELS
+ if task == "relations":
+ return model.create_schema().relations(_LABELS), "batch_extract_relations", _LABELS
+ if task == "structured":
+ return structure_schema(model, _STRUCTURES), "batch_extract_json", _STRUCTURES
+ return (
+ model.create_schema().classification("sentiment", **_TASKS["sentiment"]),
+ "batch_classify_text",
+ _TASKS,
+ )
+
+
[email protected]("task", ["entities", "relations", "classification", "structured"])
[email protected]("text", [_TEXT, "", "( ) [SEP_TEXT] café İ"])
+def test_count_matches_real_convenience_collator_prefix(task: str, text: str) -> None:
+ processor = make_processor()
+ model = native_model(processor)
+ schema, method, arguments = schemas(task, model)
+ before = copy.deepcopy(schema.build())
+ getattr(gliner2_engine.GLiNER2, method)(model, [text], arguments)
+ assert model.schemas == [before]
+ # Use the exact empty-record compiler as an independent prefix oracle.
+ empty = processor.transform_and_format("", copy.deepcopy(before))
+ count = prompt_counter(processor)(schema)
+ assert count == len(empty.input_ids) > 0
+ batch = model.batches[0]
+ assert batch.input_ids[0, :count].tolist() == empty.input_ids
+ assert batch.original_lengths[0] > count
+ assert schema.build() == before
+ # JSON choices are on the document side of SEP_TEXT and still count.
+ if task == "structured":
+ assert empty.text_tokens
+ schema_only = sum(kind != "text" for kind, *_rest in empty.mapped_indices)
+ assert count > schema_only
+
+
[email protected]("task", ["entities", "relations", "classification", "structured"])
+def test_count_is_deterministic_without_global_rng_or_serving_state_writes(
+ monkeypatch: pytest.MonkeyPatch, task: str
+) -> None:
+ processor = make_processor()
+ processor.is_training = True
+ processor.sampling_config.max_num_labels = 1
+ model = native_model(processor)
+ schema, _, _ = schemas(task, model)
+ state = copy.deepcopy(processor.__dict__)
+ cache_info = _cache_info(processor)
+ rng = random.getstate()
+ count = prompt_counter(processor)
+ for method in ("choice", "random", "shuffle", "sample", "betavariate"):
+ monkeypatch.setattr(random, method, Mock(side_effect=AssertionError("counter used process RNG")))
+ assert count(schema) == count(schema) > 0
+ assert processor.is_training is True
+ assert processor.sampling_config == state["sampling_config"]
+ assert processor.tokenizer.vocab == state["tokenizer"].vocab
+ assert processor._token_cache == state["_token_cache"]
+ assert _cache_info(processor) == cache_info
+ assert random.getstate() == rng
+
+
[email protected]("task", ["entities", "relations", "classification", "structured"])
+def test_large_prompt_is_not_truncated_by_training_sampling_or_document_limit(task: str) -> None:
+ processor = make_processor()
+ processor.is_training = True
+ processor.sampling_config.max_num_labels = 1
+ model = native_model(processor)
+ labels = [f"label{n:04d}" for n in range(1200)]
+ if task == "structured":
+ schema = structure_schema(model, {"_sie_root": [f"field{n:04d}::str::value description" for n in range(1200)]})
+ elif task == "classification":
+ schema = model.create_schema().classification("topic", labels)
+ else:
+ schema = getattr(model.create_schema(), task)(labels)
+ count = prompt_counter(processor)(schema)
+ assert count > 1200
+ # Inference's document max_len never clips schema/prefix tokens.
+ processor.change_mode(is_training=False)
+ batch = processor.collate_fn_inference([(_TEXT, schema)], max_len=1)
+ assert batch.original_lengths[0] == count + len(processor.tokenizer.tokenize("alice"))
+ with pytest.raises(InvalidInputError, match="at most 100 tokens"):
+ PromptLimit("GLiNER2", 100).check(["short"], lambda: count, task)
+
+
[email protected]("task", ["entities", "relations", "classification", "structured"])
+def test_exact_boundary_accepts_equal_rejects_one_less_before_document_work(
+ monkeypatch: pytest.MonkeyPatch, task: str
+) -> None:
+ adapter, model = make_adapter()
+ kwargs: dict[str, Any] = {"labels": _LABELS}
+ item = Item(text=_TEXT)
+ if task == "relations":
+ item.metadata = {"entities": [{"text": "Alice", "start": 0, "end": 5}]}
+ elif task == "classification":
+ kwargs["options"] = {"classification_task": "topic"}
+ elif task == "structured":
+ kwargs = {
+ "output_schema": {
+ "type": "object",
+ "properties": {"field": {"type": "string", "enum": ["first choice", "second choice"]}},
+ }
+ }
+ adapter.extract([item], **kwargs)
+ count = model.inputs[0].original_lengths[0] - sum(
+ len(model.processor.tokenizer.tokenize(word))
+ for word, *_rest in model.processor.word_splitter(_TEXT, lower=True)
+ )
+ assert list(adapter._prompt_limit._counts.values()) == [count]
+ assert count > 1
+ adapter._prompt_limit = PromptLimit("GLiNER2", count)
+ assert adapter.extract([item], **kwargs).errors is None
+ model.inputs.clear()
+ adapter._prompt_limit = PromptLimit("GLiNER2", count - 1)
+ for name in ("_read", "_doc_input_token_counts", "_classification_windows", "_windowed_input_token_counts"):
+ monkeypatch.setattr(adapter, name, Mock(side_effect=AssertionError("document work before rejection")))
+ for _ in range(2):
+ with pytest.raises(InvalidInputError, match=f"take {count} tokens"):
+ adapter.extract([item], **kwargs)
+ assert model.inputs == []
+
+
+def test_compiler_exception_is_not_replaced_with_fallback_or_cached(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, model = make_adapter()
+ # The copy uses the actual type's method, so failure must propagate.
+ monkeypatch.setattr(type(model.processor), "transform_and_format", Mock(side_effect=ValueError("broken schema")))
+ monkeypatch.setattr(adapter, "_read", Mock(side_effect=AssertionError("document read")))
+ for _ in range(2):
+ with pytest.raises(ValueError, match="broken schema"):
+ adapter.extract([Item(text=_TEXT)], labels=_LABELS)
+ assert not adapter._prompt_limit._counts
+ assert model.inputs == []
+
+
+def test_extended_classification_contract_is_not_silently_ignored() -> None:
+ processor = make_processor()
+ schema = native_model(processor).create_schema().classification("topic", ["yes"], prompt="new prompt")
+ with pytest.raises(RuntimeError, match="schema changed"):
+ prompt_counter(processor)(schema)
+
+
+def test_aggregate_character_limit_precedes_schema_build_and_compilation() -> None:
+ adapter, model = make_adapter(max_prompt_tokens=20)
+ model.create_schema = Mock(side_effect=AssertionError("schema build before character admission"))
+ with pytest.raises(InvalidInputError, match="characters"):
+ adapter.extract(
+ [Item(text=_TEXT)],
+ output_schema={"type": "object", "properties": {"field": {"type": "string", "description": "d" * 1000}}},
+ )
+ model.create_schema.assert_not_called()
+
+
+def test_cache_preserves_task_and_order_and_does_not_retain_strings() -> None:
+ adapter, _ = make_adapter()
+ count = Mock(wraps=adapter._count_prompt)
+ adapter._count_prompt = count
+ for labels in (["one", "two"], ["two", "one"], ["one", "two"]):
+ adapter.extract([Item(text=_TEXT)], labels=labels)
+ assert count.call_count == 2
+ for n in range(270):
+ adapter.extract([Item(text=_TEXT)], labels=[f"label {n}"])
+ assert len(adapter._prompt_limit._counts) == 256
+ assert all(
+ type(key) is bytes and len(key) == 32 and type(value) is int
+ for key, value in adapter._prompt_limit._counts.items()
+ )
+
+
+def test_private_fast_tokenizer_state_and_cache_are_independent(tmp_path: Any) -> None:
+ transformers = pytest.importorskip("transformers")
+ processor_module = pytest.importorskip("gliner2.processor")
+ vocab = tmp_path / "vocab.txt"
+ vocab.write_text("[PAD]\n[UNK]\n[CLS]\n[SEP]\n[MASK]\nalice\nperson\n", encoding="utf-8")
+ tokenizer = transformers.BertTokenizerFast(vocab_file=str(vocab))
+ processor = processor_module.SchemaTransformer(tokenizer=tokenizer)
+ processor.tokenizer.backend_tokenizer.enable_truncation(1)
+ before = processor.tokenizer.backend_tokenizer.to_str()
+ cache = _cache_info(processor)
+ counter = prompt_counter(processor)
+ schema = native_model(processor).create_schema().entities(["person"])
+ assert counter(schema) > 1
+ assert processor.tokenizer.backend_tokenizer.to_str() == before
+ assert _cache_info(processor) == cache
+
+
+def test_load_resets_counts_and_unload_releases_private_compiler(monkeypatch: pytest.MonkeyPatch) -> None:
+ first = native_model(make_processor())
+ second = native_model(make_processor())
+ models = iter([first, second])
+ package = pytest.importorskip("gliner2")
+ monkeypatch.setattr(package.GLiNER2, "from_pretrained", lambda *_args, **_kwargs: next(models))
+ adapter = GLiNER2Adapter("fake", compute_precision="float32")
+ adapter.load("cpu")
+ assert adapter._count_prompt is not None
+ counter_ref = weakref.ref(adapter._count_prompt)
+ adapter._prompt_tokens(
+ _LABELS, key=("entities", tuple(_LABELS)), schema=lambda: first.create_schema().entities(_LABELS)
+ )
+ assert len(adapter._prompt_limit._counts) == 1
+ adapter.unload()
+ gc.collect()
+ assert adapter._model is None
+ assert adapter._count_prompt is None
+ assert counter_ref() is None
+ adapter.load("cpu")
+ assert not adapter._prompt_limit._counts
+ assert adapter._model is second
+ adapter.unload()
+
+
+def test_repeated_choice_tokens_defeat_the_old_estimate() -> None:
+ adapter, model = make_adapter()
+ choices = [f"long choice number {n:02d}" for n in range(20)]
+ output_schema = {"type": "object", "properties": {"kind": {"type": "string", "enum": choices}}}
+ structures = adapter._json_schema_to_structures(output_schema)
+ specs = structures["_sie_root"]
+ actual = prompt_counter(model.processor)(structure_schema(model, structures))
+ assert adapter._count_subwords is not None
+ old_estimate = sum(adapter._count_subwords(specs)) + 2 * len(specs) + len(choices) + 8
+ assert actual > old_estimate
+ adapter._prompt_limit = PromptLimit("GLiNER2", old_estimate)
+ with pytest.raises(InvalidInputError, match=f"take {actual} tokens"):
+ adapter.extract([Item(text=_TEXT)], output_schema=output_schema)
+ assert model.inputs == []
+
+
+def test_schema_and_labels_remain_unchanged_across_repeated_calls() -> None:
+ adapter, _ = make_adapter()
+ output_schema = {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "description": "x::y", "enum": ["first value", "second value"]},
+ "name": {"type": "string", "title": "Full name"},
+ },
+ }
+ before = copy.deepcopy(output_schema)
+ for _ in range(2):
+ adapter.extract([Item(text=_TEXT)], output_schema=output_schema)
+ assert output_schema == before
+ labels = [" one ", "two"]
+ original = labels.copy()
+ adapter.extract([Item(text=_TEXT)], labels=labels)
+ assert labels == original
diff --git a/packages/sie_server/tests/adapters/test_gliner2_validation_order.py b/packages/sie_server/tests/adapters/test_gliner2_validation_order.py
index 9abb3dc1b..f63111ff6 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_validation_order.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_validation_order.py
@@ -19,7 +19,8 @@ _SCHEMA = {"type": "object", "properties": {"name": {"type": "string"}}}
def _adapter(*, max_prompt_tokens: int = 2048) -> GLiNER2Adapter:
adapter = GLiNER2Adapter("test", max_seq_length=8, max_prompt_tokens=max_prompt_tokens)
adapter._model = MagicMock()
- adapter._count_subwords = MagicMock(side_effect=lambda values: [len(value) for value in values])
+ adapter._model._parse_field_spec.return_value = ("name", "str", None, None)
+ adapter._count_prompt = MagicMock(return_value=8)
return adapter
@@ -111,8 +112,8 @@ def test_token_limit_checks_only_the_prompt_and_reuses_its_cached_rejection(
monkeypatch: pytest.MonkeyPatch, task: str
) -> None:
adapter = _adapter(max_prompt_tokens=16)
- count = MagicMock(side_effect=lambda values: [100] * len(values))
- adapter._count_subwords = count
+ count = MagicMock(return_value=100)
+ adapter._count_prompt = count
guards = _forbid_document_work(monkeypatch, adapter)
items, kwargs = _request(task)
@@ -121,7 +122,7 @@ def test_token_limit_checks_only_the_prompt_and_reuses_its_cached_rejection(
adapter.extract(items, **kwargs)
count.assert_called_once()
- assert all(_TEXT not in value for value in count.call_args.args[0])
+ assert _TEXT not in repr(count.call_args)
for guard in guards:
guard.assert_not_called()
@@ -147,6 +148,7 @@ def test_existing_text_option_and_task_error_precedence(
def _responding_model() -> MagicMock:
model = MagicMock()
+ model._parse_field_spec.return_value = ("name", "str", None, None)
model.processor.tokenizer.side_effect = lambda texts, **_kwargs: {
"input_ids": [[1] * (len(text.split()) + 2) for text in texts]
}
@@ -232,8 +234,9 @@ def test_classification_subclass_preserves_defaults_and_early_prompt_validation(
"test", classification_task="topic", default_labels=["yes", "no"], max_seq_length=8, max_prompt_tokens=16
)
adapter._model = _responding_model()
+ adapter._count_prompt = lambda _schema: 8
if reject:
- adapter._count_subwords = lambda values: [100] * len(values)
+ adapter._count_prompt = lambda _schema: 100
guards = _forbid_document_work(monkeypatch, adapter)
with pytest.raises(InvalidInputError, match="at most 16 tokens"):
adapter.extract([Item(text=_TEXT)])
@@ -255,8 +258,9 @@ def test_entity_lora_subclass_keeps_selection_and_final_base_restoration(
controller = SimpleNamespace(lock=RLock(), select=MagicMock(), source=MagicMock(return_value="org/a"))
monkeypatch.setattr(adapter, "_lora", controller, raising=False)
adapter._model = _responding_model()
+ adapter._count_prompt = lambda _schema: 8
if reject:
- adapter._count_subwords = lambda values: [100] * len(values)
+ adapter._count_prompt = lambda _schema: 100
guards = _forbid_document_work(monkeypatch, adapter)
with pytest.raises(InvalidInputError, match="at most 16 tokens"):
adapter.extract([Item(text=_TEXT)], labels=["person"], options={"lora": "a"})
diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.py
index c9b8a8422..ba05e4f44 100644
--- a/packages/sie_server/tests/test_queue_executor.py
+++ b/packages/sie_server/tests/test_queue_executor.py
@@ -1627,6 +1627,7 @@ class TestProcessExtractBatch:
async def test_gliner2_invalid_request_does_not_fail_valid_sibling(self) -> None:
adapter = GLiNER2Adapter("test-model")
adapter._model = MagicMock()
+ adapter._count_prompt = lambda _schema: 8
adapter._model.extract_entities.return_value = {"entities": {}}
reg = _make_registry()
worker = AsyncMock()