Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): meter compiled GLiNER2 document windows (#797)
svonavab68fe3607c5c
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.pyindex 7df8305f6..d7aabe4df 100644--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py@@ -34,14 +34,6 @@ from sie_server.types.responses import Classification, Entity, Relation_ERR_REQUIRES_LABELS = "GLiNER2 requires labels parameter for extraction"_STRUCTURE_NAME = "_sie_root"_STRUCTURE_DELIMITERS = ("::", "|", "[", "]")-# Metering tokenizes a prefix of this many characters per token of the window-# (then 4x more, up to the whole text) and stops once the prefix alone fills-# the window.-_METER_CHARS_PER_TOKEN = 16-_METER_MARGIN_TOKENS = 64-# A space after a non-space character, matched in reversed text: the tokenizers-# of these checkpoints split pre-tokens at spaces, after normalizing whitespace.-_SPACE_AFTER_TEXT = re.compile(r" (?=\S)")# Words a document is read up to when the model config sets no max_seq_length._DEFAULT_MAX_WORDS = 512# Subword tokens a document may take per word it reads. The GLiNER2 checkpoints@@ -99,7 +91,9 @@ class GLiNER2Adapter(BaseAdapter):relation and structured extraction read that first window. Classificationreads all of a longer text, as overlapping windows of that many words, andpools the windows' results into one (see ``pool_window_classifications``);- a text that fits one window is classified exactly as before.+ a text that fits one window is classified exactly as before. Usage counts+ the document subwords encoded in every window, including repeated overlap,+ and excludes the schema prompt, document separator and padding.Reference models:- fastino/gliner2-base-v1@@ -304,7 +298,7 @@ class GLiNER2Adapter(BaseAdapter):)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)+ input_token_counts = self._doc_input_token_counts(windows)rows = self._row_tokens(windows, prompt)with torch.inference_mode():raw_results, errors, input_token_counts = self._run_complete(@@ -354,7 +348,7 @@ class GLiNER2Adapter(BaseAdapter):)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)+ input_token_counts = self._doc_input_token_counts(windows)rows = self._row_tokens(windows, prompt)with torch.inference_mode():raw_results, errors, input_token_counts = self._run_complete(@@ -400,10 +394,8 @@ class GLiNER2Adapter(BaseAdapter):),)reads = [self._read(text) for text in texts]- input_token_counts = self._doc_input_token_counts(texts)item_windows = [self._classification_windows(text, read) for text, read in zip(texts, reads, strict=True)]- if any(len(one) > 1 for one in item_windows):- input_token_counts = self._windowed_input_token_counts(texts, item_windows)+ input_token_counts = self._windowed_input_token_counts(item_windows)return self._classify(item_windows,normalized_labels,@@ -444,7 +436,7 @@ class GLiNER2Adapter(BaseAdapter):)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)+ input_token_counts = self._doc_input_token_counts(windows)with torch.inference_mode():raw_results, errors, input_token_counts = self._run_complete(texts,@@ -1133,28 +1125,19 @@ class GLiNER2Adapter(BaseAdapter):return readsize *= 2- def _windowed_input_token_counts(- self, texts: list[str], item_windows: list[list[tuple[str, int | None]]]- ) -> list[int] | None:- """Input tokens of each item classified in ``item_windows``.+ def _windowed_input_token_counts(self, item_windows: list[list[tuple[str, int | None]]]) -> list[int] | None:+ """Sum the document subwords encoded for every classification window.- A text read in one window is metered as before. A text read in several- is metered as the sum of its windows, each as the same text sent alone- is metered (its tokens up to ``max_seq_length``), so the words two- windows share count twice: the model encodes them twice.+ Shared words count once per window that reads them. Counts come from+ the existing bounded reader, not a second whole-text tokenization.+ Schema tokens, the document separator and batch padding are excluded."""- metered = [- [text] if len(windows) == 1 else [model_text for model_text, _ in windows]- for text, windows in zip(texts, item_windows, strict=True)- ]- counts = self._doc_input_token_counts([one for parts in metered for one in parts])- if counts is None:- return Nonetotals = []- offset = 0- for parts in metered:- totals.append(sum(counts[offset : offset + len(parts)]))- offset += len(parts)+ for windows in item_windows:+ counts = self._doc_input_token_counts(windows)+ if counts is None:+ return None+ totals.append(sum(counts))return totalsdef _effective_positive_label(self, options: dict[str, Any], labels: list[str]) -> str | None:@@ -1176,74 +1159,17 @@ class GLiNER2Adapter(BaseAdapter):raise InvalidInputError("GLiNER2 positive_label must be one of the labels")return label- def _doc_input_token_counts(self, texts: list[str]) -> list[int] | None:- processor = getattr(self._model, "processor", None)- tokenizer = getattr(processor, "tokenizer", None)- if tokenizer is None:- return None- limit = self._max_seq_length- try:- counts: list[int | None] = [None] * len(texts)- short = [index for index, text in enumerate(texts) if limit is None or len(text) <= _meter_budget(limit)]- if short:- encoded = tokenizer(- [texts[index] for index in short],- add_special_tokens=True,- truncation=limit is not None,- max_length=limit,- )- ids = encoded["input_ids"]- if len(ids) != len(short):- return None- for index, row in zip(short, ids, strict=True):- counts[index] = len(row)- if limit is not None:- for index, text in enumerate(texts):- if counts[index] is None:- counts[index] = self._long_doc_input_tokens(tokenizer, text, limit)- except Exception: # noqa: BLE001 -- metering must not fail extraction- return None- complete = [count for count in counts if count is not None]- return complete if len(complete) == len(texts) else None-@staticmethod- def _long_doc_input_tokens(tokenizer: Any, text: str, limit: int) -> int:- """Tokens of a long ``text`` with special tokens, truncated to ``limit``.-- Tokenizing a multi-megabyte text takes about a second, so prefixes are- tokenized first, from ``_METER_CHARS_PER_TOKEN`` characters per window- token up. A prefix ending just before a space tokenizes like the start of- the text (these tokenizers split pre-tokens at spaces), so once it fills- the window, so does the text. Without a space in the second half of the- prefix, the prefix must fill the window with ``_METER_MARGIN_TOKENS`` to- spare, for the tokens at its cut.- """- budget = _meter_budget(limit)- while budget < len(text):- cut = _last_space(text, budget)- if cut is not None:- if _token_count(tokenizer, text[:cut]) >= limit:- return limit- elif _token_count(tokenizer, text[:budget]) >= limit + _METER_MARGIN_TOKENS:- return limit- budget *= 4- encoded = tokenizer(text, add_special_tokens=True, truncation=True, max_length=limit)- return len(encoded["input_ids"])---def _meter_budget(limit: int) -> int:- return limit * _METER_CHARS_PER_TOKEN-+ def _doc_input_token_counts(windows: list[tuple[str, int | None]]) -> list[int] | None:+ """Reuse the subwords of each document window actually sent to gliner2.-def _token_count(tokenizer: Any, text: str) -> int:- return len(tokenizer(text, add_special_tokens=True)["input_ids"])---def _last_space(text: str, end: int) -> int | None:- """Index of the last space after a non-space character in the second half of ``text[:end]``, or None."""- begin = end // 2- match = _SPACE_AFTER_TEXT.search(text[begin:end][::-1])- return None if match is None else end - 1 - match.start()+ ``max_seq_length`` limits words, not subwords. The reader already+ counts their per-word tokenization, including the package's sentence+ end when read; gliner2 adds no separate CLS/SEP tokens to that document.+ A missing bounded reader leaves usage unknown rather than guessing.+ """+ counts = [subwords for _, subwords in windows if subwords is not None]+ return counts if len(counts) == len(windows) else Nonedef pool_window_classifications(diff --git a/packages/sie_server/tests/adapters/test_gliner2.py b/packages/sie_server/tests/adapters/test_gliner2.pyindex 318d63f3b..5f76ac3c9 100644--- a/packages/sie_server/tests/adapters/test_gliner2.py+++ b/packages/sie_server/tests/adapters/test_gliner2.py@@ -2,7 +2,7 @@ import sysfrom collections.abc import Iteratorfrom pathlib import Pathfrom types import ModuleType, SimpleNamespace-from typing import Any+from typing import Any, castfrom unittest.mock import MagicMock, patchimport pytest@@ -257,7 +257,7 @@ def test_classification_routing_seam_reuses_general_implementation() -> None:def _adapter_with_counting_model(*, max_seq_length: int = 512) -> tuple[GLiNER2Adapter, MagicMock]:adapter = GLiNER2Adapter("test-model", max_seq_length=max_seq_length)model = MagicMock()- model.processor.tokenizer.return_value = {"input_ids": [[1, 2, 3]]}+ cast("Any", adapter)._read = lambda text: (text, 3, None)adapter._model = modeladapter._count_prompt = lambda _schema: 8model._parse_field_spec.return_value = ("name", "str", None, None)diff --git a/packages/sie_server/tests/adapters/test_gliner2_complete_text.py b/packages/sie_server/tests/adapters/test_gliner2_complete_text.pyindex 3a4169f0a..7393b638c 100644--- a/packages/sie_server/tests/adapters/test_gliner2_complete_text.py+++ b/packages/sie_server/tests/adapters/test_gliner2_complete_text.py@@ -1,7 +1,7 @@from __future__ import annotationsimport math-from typing import Any+from typing import Any, castfrom unittest.mock import MagicMockimport pytest@@ -90,7 +90,7 @@ def test_overlong_items_fail_without_losing_short_items_or_their_positions(task:None,"INPUT_TOO_LONG",]- assert output.input_token_counts == [4, 0, 4, 0]+ assert output.input_token_counts == [5, 0, 4, 0]assert output.entities[1] == output.entities[3] == []if task == "entities":assert [output.entities[i][0]["text"] for i in [0, 2]] == ["Alice", "Bob"]@@ -111,7 +111,7 @@ def test_overlong_items_fail_without_losing_short_items_or_their_positions(task:handler = ExtractHandler()assembled = handler.assemble_output({i: handler.slice_output(output, i) for i in range(4)}, batch_size=4)- assert assembled.input_token_counts == [4, 0, 4, 0]+ assert assembled.input_token_counts == [5, 0, 4, 0]formatted = handler.format_output(assembled)assert "error" not in formatted[0]assert "error" not in formatted[2]@@ -205,7 +205,7 @@ def test_queue_outcome_preserves_length_error_and_zero_billing(index: int) -> Noelse:assert "error" not in resultassert result["entities"][0]["text"] == "Alice"- assert outcome.units.input_tokens == 4+ assert outcome.units.input_tokens == 5def test_queue_length_error_keeps_zero_billing_when_sibling_metering_fails() -> None:@@ -216,7 +216,7 @@ def test_queue_length_error_keeps_zero_billing_when_sibling_metering_fails() ->from sie_server.queue_executor import _extract_success_outcomeadapter, _ = _adapter()- adapter._doc_input_token_counts = lambda _texts: None+ cast("Any", adapter)._doc_input_token_counts = lambda _windows: Noneitems = [Item(text="word " * 20), Item(text="Alice Acme")]output = adapter.extract(items, labels=["person"])assert output.input_token_counts is Nonediff --git a/packages/sie_server/tests/adapters/test_gliner2_long_text.py b/packages/sie_server/tests/adapters/test_gliner2_long_text.pyindex d5ec76385..2bf671b65 100644--- a/packages/sie_server/tests/adapters/test_gliner2_long_text.py+++ b/packages/sie_server/tests/adapters/test_gliner2_long_text.py@@ -459,10 +459,13 @@ def test_prefixes_are_short_for_long_documents() -> None:],ids=["words", "cjk", "one-run", "short", "prose-then-dots"],)-def test_metering_long_documents_counts_what_tokenizing_all_of_them_counts(text: str) -> None:- tokenizer = FakeTokenizer()- full = len(tokenizer(text, add_special_tokens=True, truncation=True, max_length=512)["input_ids"])- assert GLiNER2Adapter._long_doc_input_tokens(tokenizer, text, 512) == full+def test_metering_reuses_the_bounded_document_compiler_count(text: str) -> None:+ adapter, model = make_adapter()+ window = adapter._window(text)+ schema = gliner2_engine.Schema().entities(["person"])+ batch = model.processor.collate_fn_inference([(window[0], schema)], max_len=512)+ prompt = model.processor.transform_and_format("", schema.build())+ assert adapter._doc_input_token_counts([window]) == [batch.original_lengths[0] - len(prompt.input_ids)]@pytest.mark.parametrize("cls", [GLiNER2Adapter, GLiNER2ClassificationAdapter])@@ -631,7 +634,7 @@ def test_a_text_that_fits_the_window_is_classified_exactly_as_before(text: str)assert batch.input_ids.tolist() == expected_input.input_ids.tolist()assert batch.text_tokens == expected_input.text_tokensassert output.classifications == [[{"label": "safe", "score": 1.0 - (0.01 + len(model.rows[0]) / 100_000)}]]- assert output.input_token_counts == adapter._doc_input_token_counts([text])+ assert output.input_token_counts == adapter._doc_input_token_counts([adapter._window(text)])assert adapter._classification_windows(text, adapter._read(text)) == [adapter._window(text)]@@ -723,18 +726,18 @@ def test_metering_counts_every_window_a_long_text_is_read_in() -> None:text = benign_email(1500, planted_at=1420)adapter, _ = make_guard()windows = adapter._classification_windows(text, adapter._read(text))- per_window = adapter._doc_input_token_counts([model_text for model_text, _ in windows])+ per_window = adapter._doc_input_token_counts(windows)assert per_window is not Noneoutput = adapter.extract([Item(text=text), Item(text="Write a birthday greeting.")])- assert output.input_token_counts == [- sum(per_window),- adapter._doc_input_token_counts(["Write a birthday greeting."])[0],- ]- # Each window is metered as the same text sent alone, up to max_seq_length tokens; the overlaps count twice.- assert per_window == [512, 512, 512, per_window[-1]]- assert 0 < per_window[-1] < 512+ short = adapter._doc_input_token_counts([adapter._window("Write a birthday greeting.")])+ assert short is not None+ assert output.input_token_counts == [sum(per_window), short[0]]+ # Every encoded subword is charged, even when 512 words take more than 512+ # tokens. The shared 64 words are charged in each window that encodes them.+ assert all(count > 512 for count in per_window[:3])+ assert 0 < per_window[-1] < per_window[0]def test_a_text_longer_than_the_window_cap_is_rejected_before_the_model_runs(monkeypatch: pytest.MonkeyPatch) -> None:@@ -823,3 +826,82 @@ def test_long_item_rejection_uses_the_pinned_package_processor(task: str) -> Nonassert output.errors[0].code == "INPUT_TOO_LONG"assert output.input_token_counts == [0]assert not model.inputs++[email protected]("task", ["entities", "relations", "structured", "classification"])[email protected]("text", ["", "Alice Acme", "Alice Acme.", "İstanbul 東京 café!"])+def test_usage_equals_compiled_document_without_prompt_or_padding(task: str, text: str) -> None:+ adapter, model = make_adapter()+ items = [Item(text=text), Item(text="Alice Acme " + "electroencephalography " * 100 + ".")]+ kwargs: dict[str, Any] = {"labels": ["person"]}+ schema = gliner2_engine.Schema().entities(["person"])+ if task == "relations":+ # Relations require real nonempty caller spans; use the shared Acme suffix.+ items = [+ Item(+ text=(one.text or "") + " Acme",+ metadata={+ "entities": [{"text": "Acme", "start": len(one.text or "") + 1, "end": len(one.text or "") + 5}]+ },+ )+ for one in items+ ]+ kwargs = {"labels": ["knows"]}+ schema = gliner2_engine.Schema().relations(["knows"])+ elif task == "structured":+ kwargs = {+ "output_schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "A long description",+ "enum": ["first option", "second option"],+ }+ },+ }+ }+ schema = gliner2_engine.Schema()+ schema.structure("_sie_root").field(+ "name", dtype="str", choices=["first option", "second option"], description="A long description"+ )+ elif task == "classification":+ kwargs = {"labels": ["yes", "no"], "options": {"classification_task": "topic"}}+ schema = gliner2_engine.Schema().classification("topic", ["yes", "no"])++ output = adapter.extract(items, **kwargs)++ prefix = model.processor.transform_and_format("", schema.build())+ compiled = [length - len(prefix.input_ids) for batch in model.inputs for length in batch.original_lengths]+ assert output.input_token_counts == compiled+ assert output.errors is None+ assert compiled[1] > 512 # A word limit must not become a token cap.+ assert any(batch.input_ids.shape[1] > min(batch.original_lengths) for batch in model.inputs)+++def test_usage_never_calls_the_whole_text_tokenizer_again(monkeypatch: pytest.MonkeyPatch) -> None:+ adapter, model = make_guard()+ monkeypatch.setattr(FakeTokenizer, "__call__", MagicMock(side_effect=AssertionError("second tokenization")))+ texts = ["electroencephalography " * 1000 + ".", "Hello."]+ output = adapter.extract([Item(text=text) for text in texts])+ schema = gliner2_engine.Schema().classification("prompt_safety", ["safe", "unsafe"])+ prompt = len(model.processor.transform_and_format("", schema.build()).input_ids)+ # Forward planning may reorder rows by size; join the short row by its+ # actual document words, not its position in the planned passes.+ document_rows = [+ (tokens, length - prompt)+ for batch in model.inputs+ for tokens, length in zip(batch.text_tokens, batch.original_lengths, strict=True)+ ]+ short = [count for tokens, count in document_rows if tokens == ["hello", "."]]+ assert len(short) == 1+ assert output.input_token_counts == [sum(count for _, count in document_rows) - short[0], short[0]]+ assert len(document_rows) > len(texts)+++def test_missing_window_counts_remain_unknown() -> None:+ adapter = GLiNER2Adapter("test")+ assert adapter._doc_input_token_counts([("known", 6), ("unknown", None)]) is None+ assert adapter._windowed_input_token_counts([[("known", 6)], [("unknown", None)]]) is None+ assert adapter._doc_input_token_counts([]) == []+ assert adapter._windowed_input_token_counts([]) == []diff --git a/packages/sie_server/tests/adapters/test_gliner2_validation_order.py b/packages/sie_server/tests/adapters/test_gliner2_validation_order.pyindex f63111ff6..d0aa3ac3f 100644--- a/packages/sie_server/tests/adapters/test_gliner2_validation_order.py+++ b/packages/sie_server/tests/adapters/test_gliner2_validation_order.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom threading import RLockfrom types import SimpleNamespace-from typing import Any+from typing import Any, castfrom unittest.mock import MagicMock, callimport pytest@@ -19,6 +19,7 @@ _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()+ cast("Any", adapter)._read = lambda text: (text, 4, None)adapter._model._parse_field_spec.return_value = ("name", "str", None, None)adapter._count_prompt = MagicMock(return_value=8)return adapter@@ -234,6 +235,7 @@ 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()+ cast("Any", adapter)._read = lambda text: (text, 4, None)adapter._count_prompt = lambda _schema: 8if reject:adapter._count_prompt = lambda _schema: 100@@ -258,6 +260,7 @@ 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()+ cast("Any", adapter)._read = lambda text: (text, 4, None)adapter._count_prompt = lambda _schema: 8if reject:adapter._count_prompt = lambda _schema: 100