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(server): split GLiNER2 documents in linear time (#371)

svonava359c4f08a900
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 deb379b89..602b133a1 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import math
+import re
import unicodedata
from numbers import Real
from pathlib import Path
@@ -12,6 +13,7 @@ from huggingface_hub import snapshot_download
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision
+from sie_server.adapters.gliner2.words import linear_equivalent, word_spans
from sie_server.core.inference_output import ExtractOutput
from sie_server.types.inputs import Item
from sie_server.types.responses import Classification, Entity, Relation
@@ -19,6 +21,14 @@ 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)")
class GLiNER2Adapter(BaseAdapter):
@@ -89,6 +99,8 @@ class GLiNER2Adapter(BaseAdapter):
self._revision = revision
self._model: Any = None
+ # How the loaded gliner2 splits words (see ``_model_text``); None until loaded.
+ self._lower_text_first: bool | None = None
self._device: str | None = None
def load(self, device: str) -> None:
@@ -109,11 +121,33 @@ class GLiNER2Adapter(BaseAdapter):
model_path = snapshot_download(repo_id=model_path, revision=self._revision)
use_quantize = device != "cpu" and self._compute_precision == "float16"
- self._model = GLiNER2.from_pretrained(
+ model = GLiNER2.from_pretrained(
model_path,
map_location=device,
quantize=use_quantize,
)
+ self._use_linear_word_splitter(model.processor)
+ self._model = model
+
+ def _use_linear_word_splitter(self, processor: Any) -> None:
+ """Split words with a linear-time equivalent of gliner2's splitter.
+
+ gliner2's word-splitting regex takes time quadratic in the length of a
+ run of e-mail address characters (``"...."``, ``"a.a.a."``), on the
+ thread that serves every request.
+
+ Raises:
+ RuntimeError: gliner2's splitter is not the one this adapter has an
+ equivalent for.
+ """
+ splitter = linear_equivalent(processor.word_splitter)
+ if splitter is None:
+ raise RuntimeError(
+ f"GLiNER2 has no linear-time equivalent of {type(processor.word_splitter).__name__}; "
+ "gliner2's word splitter changed"
+ )
+ processor.word_splitter = splitter
+ self._lower_text_first = splitter.lower_text_first
def extract(
self,
@@ -128,6 +162,8 @@ class GLiNER2Adapter(BaseAdapter):
"""Extract entities, relations, classifications, or flat structured data."""
self._check_loaded()
texts = [self._extract_text(item) for item in items]
+ # gliner2 reads only the first max_len words of a text, after splitting all of it.
+ model_texts = [self._model_text(text) for text in texts]
opts = options or {}
effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold))
classification_task = opts.get("classification_task", self._classification_task)
@@ -144,7 +180,7 @@ class GLiNER2Adapter(BaseAdapter):
structures = self._json_schema_to_structures(output_schema)
with torch.inference_mode():
raw_results = self._model.batch_extract_json(
- texts,
+ model_texts,
structures,
batch_size=len(texts),
threshold=effective_threshold,
@@ -169,7 +205,7 @@ class GLiNER2Adapter(BaseAdapter):
]
with torch.inference_mode():
raw_results = self._model.batch_extract_relations(
- texts,
+ model_texts,
normalized_labels,
batch_size=len(texts),
threshold=effective_threshold,
@@ -190,7 +226,7 @@ class GLiNER2Adapter(BaseAdapter):
if not isinstance(classification_task, str) or not classification_task.strip():
raise ValueError("GLiNER2 classification_task must be a non-empty string")
return self._classify(
- texts,
+ model_texts,
normalized_labels,
task=classification_task,
multi_label=multi_label,
@@ -202,7 +238,7 @@ class GLiNER2Adapter(BaseAdapter):
if len(texts) == 1:
raw_results = [
self._model.extract_entities(
- texts[0],
+ model_texts[0],
normalized_labels,
threshold=effective_threshold,
include_confidence=True,
@@ -212,7 +248,7 @@ class GLiNER2Adapter(BaseAdapter):
]
else:
raw_results = self._model.batch_extract_entities(
- texts,
+ model_texts,
normalized_labels,
threshold=effective_threshold,
include_confidence=True,
@@ -623,19 +659,103 @@ class GLiNER2Adapter(BaseAdapter):
elif not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValueError(f"GLiNER2 structured extraction property {name!r} must be an array of strings")
+ def _model_text(self, text: str) -> str:
+ """The prefix of ``text`` holding every word gliner2 reads from it, or ``text``.
+
+ gliner2 splits all of a text into words and keeps the first ``max_len``.
+ The prefix ending where the last kept word ends (with the whitespace
+ after it) gives it the same words at the same offsets, since no word
+ crosses that point. gliner2 1.x
+ splits the lowercased text and indexes the original with those offsets,
+ so the prefix ends at the lowercased offset; it is used only when its
+ lowercase starts the lowercased text (a final sigma can lowercase
+ differently at the cut). gliner2 2.x splits the text as given.
+ """
+ limit = self._max_seq_length
+ if limit is None or len(text) <= limit or self._lower_text_first is None: # a word has a character
+ return text
+ source = text.lower() if self._lower_text_first else text
+ cut = None
+ for count, (_, end) in enumerate(word_spans(source), start=1):
+ if count == limit:
+ cut = end
+ break
+ if cut is not None and cut < len(source) and source[cut].isspace():
+ # Keep the separator: gliner2 ends a text without a sentence end with
+ # ".", which a URL word (running to whitespace) would absorb.
+ cut += 1
+ if cut is None or cut >= len(text):
+ return text
+ prefix = text[:cut]
+ if self._lower_text_first and not source.startswith(prefix.lower()):
+ return text
+ return prefix
+
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:
- encoded = tokenizer(
- texts,
- add_special_tokens=True,
- truncation=self._max_seq_length is not None,
- max_length=self._max_seq_length,
- )
- counts = [len(ids) for ids in encoded["input_ids"]]
+ 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
- return counts if len(counts) == len(texts) else 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 _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()
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/words.py b/packages/sie_server/src/sie_server/adapters/gliner2/words.py
new file mode 100644
index 000000000..33dddaaba
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/words.py
@@ -0,0 +1,136 @@
+r"""A linear-time equivalent of gliner2's whitespace word splitter.
+
+gliner2 splits a document into words with one regular expression
+(``WhitespaceTokenSplitter``), matched case-insensitively::
+
+ https?://[^\s]+ | www\.[^\s]+ a URL
+ [a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,} an e-mail address
+ @[a-z0-9_]+ a mention
+ \w+(?:[-_]\w+)* a word
+ \S any other character
+
+The e-mail alternative is tried at every word. Its local part runs over every
+e-mail character ahead of the word before failing on the missing ``@``, so a run
+of n such characters (``"...."``, ``"a.a.a."``) costs O(n^2): splitting 64 KiB
+of ``"."`` takes about 17 seconds, on the thread that serves every request.
+
+``word_spans`` yields the same matches in linear time. It tries the alternatives
+in the same order and decides the e-mail alternative without rescanning: a local
+part can only end at the first non-e-mail character after the word start, which
+is the end of the maximal run of e-mail characters holding it, so each such run
+is scanned once, and the domain after an ``@`` is matched once.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Callable, Iterator
+from typing import Any
+
+# gliner2's pattern (WhitespaceTokenSplitter._PATTERN), with its flags.
+PACKAGE_PATTERN = re.compile(
+ r"""(?:https?://[^\s]+|www\.[^\s]+)
+ |[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}
+ |@[a-z0-9_]+
+ |\w+(?:[-_]\w+)*
+ |\S""",
+ re.VERBOSE | re.IGNORECASE,
+)
+
+_START = re.compile(r"\S")
+_URL = re.compile(r"https?://[^\s]+|www\.[^\s]+", re.IGNORECASE)
+_LOCAL = re.compile(r"[a-z0-9._%+-]+", re.IGNORECASE)
+_DOMAIN = re.compile(r"[a-z0-9.-]+\.[a-z]{2,}", re.IGNORECASE)
+_OTHER = re.compile(r"@[a-z0-9_]+|\w+(?:[-_]\w+)*|\S", re.IGNORECASE)
+
+WordSplitter = Callable[..., Iterator[tuple[str, int, int]]]
+
+
+def word_spans(text: str) -> Iterator[tuple[int, int]]:
+ """``(start, end)`` of each match of ``PACKAGE_PATTERN.finditer(text)``, in linear time."""
+ size = len(text)
+ position = 0
+ local_end = 0 # end of the run of e-mail characters holding the current word start
+ email_end: int | None = None # where an e-mail address starting in that run ends, if one does
+ while (start := _START.search(text, position)) is not None:
+ begin = start.start()
+ if (url := _URL.match(text, begin)) is not None:
+ end = url.end()
+ else:
+ if begin >= local_end:
+ local = _LOCAL.match(text, begin)
+ local_end = begin if local is None else local.end()
+ email_end = None
+ if local_end > begin and local_end < size and text[local_end] == "@":
+ domain = _DOMAIN.match(text, local_end + 1)
+ email_end = None if domain is None else domain.end()
+ if begin < local_end and email_end is not None:
+ end = email_end
+ else:
+ other = _OTHER.match(text, begin)
+ end = other.end() if other is not None else begin + 1
+ yield begin, end
+ position = end
+
+
+class LinearWordSplitter:
+ """Drop-in for gliner2's ``WhitespaceTokenSplitter``: the same words, in linear time.
+
+ gliner2 1.x lowercases the text and then splits it; gliner2 2.x splits the
+ text as given and lowercases each word (offsets then always index the text).
+ ``lower_text_first`` selects the 1.x behavior.
+ """
+
+ __slots__ = ("lower_text_first",)
+
+ def __init__(self, *, lower_text_first: bool) -> None:
+ self.lower_text_first = lower_text_first
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ if lower and self.lower_text_first:
+ text = text.lower()
+ for begin, end in word_spans(text):
+ yield text[begin:end], begin, end
+ return
+ for begin, end in word_spans(text):
+ word = text[begin:end]
+ yield (word.lower() if lower else word), begin, end
+
+
+# Texts on which the two lowercasing behaviors (and a different pattern) disagree.
+_PROBES = (
+ "\u0130stanbul and \u03a3\u038a\u03a3\u03a5\u03a6\u039f\u03a3 met at https://Example.com/x?y=1, "
+ "mail [email protected] @Team_1 x-y_z 3.14 ...@ a@b",
+ "Stra\u00dfe \u01c5emal \ufb01ne KELVIN\u212a na\u00efve",
+)
+
+
+def linear_equivalent(splitter: Any) -> LinearWordSplitter | None:
+ """A ``LinearWordSplitter`` that yields exactly what gliner2's ``splitter`` yields, or None.
+
+ None unless ``splitter`` is gliner2's ``WhitespaceTokenSplitter`` with the
+ pattern above, and one of the two lowercasing behaviors reproduces it on
+ probe texts.
+ """
+ pattern = getattr(type(splitter), "_PATTERN", None)
+ if (
+ type(splitter).__name__ != "WhitespaceTokenSplitter"
+ or not isinstance(pattern, re.Pattern)
+ or _normalized(pattern.pattern) != _normalized(PACKAGE_PATTERN.pattern)
+ or pattern.flags != PACKAGE_PATTERN.flags
+ ):
+ return None
+ for lower_text_first in (False, True):
+ candidate = LinearWordSplitter(lower_text_first=lower_text_first)
+ if all(
+ list(candidate(probe, lower)) == list(splitter(probe, lower))
+ for probe in _PROBES
+ for lower in (True, False)
+ ):
+ return candidate
+ return None
+
+
+def _normalized(pattern: str) -> str:
+ """A verbose pattern without its layout whitespace (this pattern has no escaped spaces)."""
+ return "".join(pattern.split())
diff --git a/packages/sie_server/tests/adapters/test_gliner2.py b/packages/sie_server/tests/adapters/test_gliner2.py
index 13294e191..cf438da47 100644
--- a/packages/sie_server/tests/adapters/test_gliner2.py
+++ b/packages/sie_server/tests/adapters/test_gliner2.py
@@ -1,4 +1,5 @@
import sys
+from collections.abc import Iterator
from pathlib import Path
from types import ModuleType
from typing import Any
@@ -8,6 +9,7 @@ import pytest
import yaml
from sie_server.adapters.gliner2.adapter import GLiNER2Adapter
from sie_server.adapters.gliner2.classification import GLiNER2ClassificationAdapter
+from sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitter
from sie_server.core.loader import load_adapter, load_model_configs
from sie_server.types.inputs import Item
@@ -240,10 +242,27 @@ def _adapter_with_counting_model(*, max_seq_length: int = 512) -> tuple[GLiNER2A
return adapter, model
+class _Gliner2V1WordSplitter:
+ """gliner2 1.x's word splitter: lowercase the text, then match the package pattern."""
+
+ _PATTERN = PACKAGE_PATTERN
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ if lower:
+ text = text.lower()
+ for match in self._PATTERN.finditer(text):
+ yield match.group(), match.start(), match.end()
+
+
+_Gliner2V1WordSplitter.__name__ = "WhitespaceTokenSplitter"
+
+
def test_load_resolves_every_file_from_pinned_snapshot() -> None:
fake_module = ModuleType("gliner2")
fake_class = MagicMock()
- fake_class.from_pretrained.return_value = MagicMock()
+ model = MagicMock()
+ model.processor.word_splitter = _Gliner2V1WordSplitter()
+ fake_class.from_pretrained.return_value = model
fake_module.GLiNER2 = fake_class
adapter = GLiNER2Adapter("fastino/gliner2-base-v1", revision="a" * 40)
@@ -265,6 +284,8 @@ def test_load_resolves_every_file_from_pinned_snapshot() -> None:
map_location="cpu",
quantize=False,
)
+ assert isinstance(model.processor.word_splitter, LinearWordSplitter)
+ assert model.processor.word_splitter.lower_text_first
def test_entity_offsets_use_python_unicode_character_indices() -> None:
diff --git a/packages/sie_server/tests/adapters/test_gliner2_long_text.py b/packages/sie_server/tests/adapters/test_gliner2_long_text.py
new file mode 100644
index 000000000..7ffa04f1d
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner2_long_text.py
@@ -0,0 +1,252 @@
+"""Long and pathological documents in the GLiNER2 adapter (gliner2 1.x).
+
+gliner2 lowercases a document, splits all of it into words with a regex that
+takes quadratic time on runs like ``"...."``, and keeps the first ``max_len``
+words. The adapter splits in linear time and hands gliner2 only the prefix
+holding those words. These tests use gliner2's real processor with a stand-in
+tokenizer: the prefix must give gliner2 exactly the input the whole text gives.
+"""
+
+from __future__ import annotations
+
+import re
+import time
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from sie_server.adapters.gliner2.adapter import 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 Item
+
+gliner2_processor = pytest.importorskip("gliner2.processor")
+gliner2_engine = pytest.importorskip("gliner2.inference.engine")
+
+MiB = 1024 * 1024
+_PIECE = re.compile(r"\S{1,3}")
+
+
+class FakeTokenizer:
+ """Pieces of up to three non-space characters; ids are stable per piece."""
+
+ def __init__(self) -> None:
+ self.vocab: dict[str, int] = {}
+
+ def add_special_tokens(self, tokens: dict[str, list[str]]) -> None:
+ for token in tokens["additional_special_tokens"]:
+ self.vocab.setdefault(token, len(self.vocab))
+
+ def tokenize(self, text: str) -> list[str]:
+ if text in self.vocab:
+ return [text]
+ return _PIECE.findall(text)
+
+ def convert_tokens_to_ids(self, tokens: str | list[str]) -> int | list[int]:
+ if isinstance(tokens, str):
+ return self.vocab.setdefault(tokens, len(self.vocab))
+ return [self.vocab.setdefault(token, len(self.vocab)) for token in tokens]
+
+ def __call__(
+ self,
+ text: str | list[str],
+ *,
+ add_special_tokens: bool,
+ truncation: bool = False,
+ max_length: int | None = None,
+ ) -> dict[str, Any]:
+ def encode(one: str) -> list[int]:
+ ids = [0, *range(1, len(_PIECE.findall(one)) + 1), 0]
+ return ids[:max_length] if truncation and max_length is not None else ids
+
+ return {"input_ids": [encode(one) for one in text] if isinstance(text, list) else encode(text)}
+
+
+def make_processor() -> Any:
+ processor = gliner2_processor.SchemaTransformer(tokenizer=FakeTokenizer())
+ processor.change_mode(is_training=False)
+ return processor
+
+
+class PackageModel:
+ """gliner2's preprocessing for each extract method, without the encoder."""
+
+ def __init__(self, processor: Any) -> None:
+ self.processor = processor
+ self.inputs: list[Any] = []
+
+ 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))
+
+ def extract_entities(self, text: str, labels: list[str], *, max_len: int | None, **_: Any) -> dict[str, Any]:
+ self._collate([text], gliner2_engine.Schema().entities(labels), max_len)
+ return {"entities": {}}
+
+ def batch_extract_entities(
+ self, texts: list[str], labels: list[str], *, max_len: int | None, **_: Any
+ ) -> list[Any]:
+ self._collate(texts, gliner2_engine.Schema().entities(labels), max_len)
+ return [{"entities": {}} for _ in texts]
+
+ def classify_text(self, text: str, tasks: dict[str, Any], *, max_len: int | None, **_: Any) -> dict[str, Any]:
+ return self.batch_classify_text([text], tasks, max_len=max_len)[0]
+
+ def batch_classify_text(
+ self, texts: list[str], tasks: dict[str, Any], *, max_len: int | None, **_: Any
+ ) -> list[Any]:
+ ((name, config),) = tasks.items()
+ self._collate(texts, gliner2_engine.Schema().classification(name, config["labels"]), max_len)
+ return [{name: {"label": config["labels"][0], "confidence": 0.9}} for _ in texts]
+
+
+def make_adapter(cls: type[GLiNER2Adapter] = GLiNER2Adapter, **kwargs: Any) -> tuple[GLiNER2Adapter, PackageModel]:
+ adapter = cls("fake/gliner2", max_seq_length=512, **kwargs)
+ model = PackageModel(make_processor())
+ adapter._use_linear_word_splitter(model.processor)
+ adapter._model = model
+ return adapter, model
+
+
+def collated(processor: Any, text: str, max_len: int) -> tuple[Any, ...]:
+ batch = processor.collate_fn_inference([(text, gliner2_engine.Schema().entities(["person"]))], max_len=max_len)
+ return (
+ batch.input_ids.tolist(),
+ batch.text_tokens,
+ batch.start_mappings,
+ batch.end_mappings,
+ )
+
+
+LONG_TEXTS = [
+ " ".join(f"Sentence {i} mentions Dr. Priya Raman of Novartis in Basel." for i in range(40)),
+ "\u8bf7\u5e2e\u6211\u53d6\u6d88\u8ba2\u5355\uff0c\u6211\u4e0d\u60f3\u8981\u4e86\u3002" * 40,
+ "\u0130stanbul " * 30 + "Ankara " * 30,
+ "\u039f\u0394\u039f\u03a3'\u0391 " * 40,
+ "\u0391\u03a3'\u0391\u03a3'\u0391\u03a3'" * 40,
+ "mail [email protected], see https://example.com/x?y=z and @team; " * 20,
+ "x" * 5000 + " tail words here",
+ ". " * 400 + "end",
+ "." * 5000,
+ "a." * 3000,
+ "see http://example.com/a?b=c " * 60,
+ "www.example.org\tthen text\n" * 60,
+]
+LONG_TEXT_IDS = [
+ "prose",
+ "cjk",
+ "dotted-capital-i",
+ "final-sigma",
+ "sigma-apostrophes",
+ "email-url",
+ "long-word",
+ "spaced-dots",
+ "dots",
+ "a-dots",
+ "url-at-cut",
+ "www-at-cut",
+]
+
+
+class Gliner2V2Splitter:
+ """gliner2 2.x's splitter: match the text as given, lowercase each word."""
+
+ _PATTERN = PACKAGE_PATTERN
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ for match in self._PATTERN.finditer(text):
+ word = match.group()
+ yield (word.lower() if lower else word), match.start(), match.end()
+
+
+Gliner2V2Splitter.__name__ = "WhitespaceTokenSplitter"
+
+
[email protected]("splitting", ["gliner2-1.x", "gliner2-2.x"])
[email protected]("max_len", [7, 64])
[email protected]("text", LONG_TEXTS, ids=LONG_TEXT_IDS)
+def test_the_prefix_gives_gliner2_the_same_input_as_the_whole_text(text: str, max_len: int, splitting: str) -> None:
+ adapter = GLiNER2Adapter("fake/gliner2", max_seq_length=max_len)
+ processor = make_processor()
+ if splitting == "gliner2-2.x":
+ processor.word_splitter = Gliner2V2Splitter()
+ reference = collated(processor, text, max_len) # gliner2's own splitter, on the whole text
+
+ adapter._use_linear_word_splitter(processor)
+ prefix = adapter._model_text(text)
+
+ assert text.startswith(prefix)
+ assert collated(processor, prefix, max_len) == reference
+ assert collated(processor, text, max_len) == reference # and the linear splitter on the whole text
+
+
[email protected]("max_len", [1, 2])
+def test_a_url_at_the_cut_keeps_its_separator(max_len: int) -> None:
+ # gliner2 ends a text without a sentence end with ".", which a URL word would absorb.
+ text = "http://example.com rest of the text"
+ adapter = GLiNER2Adapter("fake/gliner2", max_seq_length=max_len)
+ processor = make_processor()
+ reference = collated(processor, text, max_len)
+ adapter._use_linear_word_splitter(processor)
+ assert collated(processor, adapter._model_text(text), max_len) == reference
+
+
+def test_prefixes_are_short_for_long_documents() -> None:
+ adapter, _ = make_adapter()
+ assert len(adapter._model_text("hello world. " * 100_000)) < 4000
+ assert len(adapter._model_text("." * MiB)) == 512
+ assert adapter._model_text("short text") == "short text"
+
+
+ "text",
+ [
+ "word " * 5000,
+ "\u8bf7\u5e2e\u6211\u53d6\u6d88\u8ba2\u5355\uff0c" * 3000,
+ "a" * 20_000,
+ "x " * 100,
+ ("prose words " * 2000) + "." * 50_000,
+ ],
+ 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
+
+
[email protected]("cls", [GLiNER2Adapter, GLiNER2ClassificationAdapter])
+ "text",
+ ["." * (2 * MiB), "a." * MiB, "hello world. " * (2 * MiB // 13), "%" * (2 * MiB - 2) + "@x"],
+ ids=["dots", "a-dots", "prose", "local-run-then-at"],
+)
+def test_pathological_documents_run_in_bounded_time(cls: type[GLiNER2Adapter], text: str) -> None:
+ adapter, model = make_adapter(cls, classification_task="prompt_safety", default_labels=["safe", "unsafe"])
+ started = time.perf_counter()
+ output = adapter.extract([Item(text=text)])
+ classify_seconds = time.perf_counter() - started
+ started = time.perf_counter()
+ entities = adapter.extract([Item(text=text), Item(text="Priya Raman works at Novartis")], labels=["person"])
+ extract_seconds = time.perf_counter() - started
+
+ assert output.input_token_counts == [512]
+ assert entities.input_token_counts is not None
+ assert entities.input_token_counts[0] == 512
+ assert len(model.inputs[-1].text_tokens[0]) == 512
+ # gliner2's own splitter takes minutes to hours on these texts.
+ assert classify_seconds < 1.0
+ assert extract_seconds < 1.0
+
+
+def test_load_refuses_a_word_splitter_it_has_no_equivalent_for() -> None:
+ processor = SimpleNamespace(word_splitter=MagicMock())
+ with pytest.raises(RuntimeError, match="linear-time equivalent"):
+ GLiNER2Adapter("fake/gliner2")._use_linear_word_splitter(processor)
+
+
+def test_the_processor_gets_the_linear_splitter() -> None:
+ _, model = make_adapter()
+ assert isinstance(model.processor.word_splitter, LinearWordSplitter)
+ assert model.processor.word_splitter.lower_text_first
diff --git a/packages/sie_server/tests/adapters/test_gliner2_words.py b/packages/sie_server/tests/adapters/test_gliner2_words.py
new file mode 100644
index 000000000..c4a74bf66
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner2_words.py
@@ -0,0 +1,175 @@
+"""The linear-time word splitter yields exactly what gliner2's ``WhitespaceTokenSplitter`` yields.
+
+The reference splitters below are gliner2's own code (1.3.2 ``gliner2.processor``
+and 2.0.0 ``gliner2.processing.word_splitter``), copied verbatim; the installed
+package's splitter is checked too.
+"""
+
+from __future__ import annotations
+
+import random
+import re
+import time
+from collections.abc import Iterator
+
+import pytest
+from sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitter, linear_equivalent, word_spans
+
+
+class WhitespaceTokenSplitter:
+ """gliner2 2.0.0's splitter: match the text, lowercase each word."""
+
+ __slots__ = ()
+ _PATTERN = re.compile(
+ r"""(?:https?://[^\s]+|www\.[^\s]+)
+ |[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}
+ |@[a-z0-9_]+
+ |\w+(?:[-_]\w+)*
+ |\S""",
+ re.VERBOSE | re.IGNORECASE,
+ )
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ for m in self._PATTERN.finditer(text):
+ token = m.group()
+ yield (token.lower() if lower else token), m.start(), m.end()
+
+
+class Gliner2V1Splitter(WhitespaceTokenSplitter):
+ """gliner2 1.3.2's splitter: lowercase the text, then match it."""
+
+ __slots__ = ()
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ if lower:
+ text = text.lower()
+ for m in self._PATTERN.finditer(text):
+ yield m.group(), m.start(), m.end()
+
+
+Gliner2V1Splitter.__name__ = "WhitespaceTokenSplitter"
+
+CORPUS = [
+ "",
+ " ",
+ "My subscription renewed on April 15 for 5,400 yen after the service was already down. Can I get a refund?",
+ "Guest in room 1408 says the AC has been out since yesterday; they want to move tonight or leave!",
+ ("Das Paket kam besch\u00e4digt an, bitte schicken Sie Ersatz. Ich brauche es bis Freitag, sonst storniere ich!"),
+ (
+ "\u8bf7\u5e2e\u6211\u53d6\u6d88\u8ba2\u5355\uff0c\u6211\u4e0d\u60f3\u8981\u4e86\u3002\u9000\u6b3e\u4ec0\u4e48\u65f6\u5019\u5230\u8d26\uff1f"
+ ),
+ ("Visit https://example.com/a?b=c or www.Example.org/x, mail [email protected], ping @support_team!"),
+ "user@host [email protected] [email protected] [email protected]. ....@ [email protected] @@@ a@@b.cc @a_b-c foo@bar",
+ "state-of-the-art under_score e-mail co-op x--y a_-b -lead trail- __init__ 3.14 1,000,000 v2.0.1",
+ "Tabs\tand\nnewlines\r\nand\u00a0no-break\u2003em spaces\u200bzero-width",
+ (
+ "\u0130stanbul \u03a3\u038a\u03a3\u03a5\u03a6\u039f\u03a3 \u039f\u0394\u039f\u03a3'\u0391 Stra\u00dfe "
+ "\u01c5emal \ufb01ne KELVIN\u212a na\u00efve \u017fun"
+ ),
+ (
+ "emoji \U0001f600\U0001f44d\U0001f3fd and flags \U0001f1eb\U0001f1f7, arrows \u2192, math \u2211\u222b,"
+ " CJK \u6f22\u5b57\u304b\u306a\u30ab\u30ca\ud55c\uad6d\uc5b4"
+ ),
+ '{"subject": "Login broken", "body": "Error 500 since the update.", "tags": ["urgent", "web"]}',
+ (
+ "a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a."
+ " ..................................................................................................."
+ ". %+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_%+-_@xxxxxxxxxx"
+ ),
+ "HTTP://UPPER.CASE/Path WWW.UPPER.ORG http:// https:/ www. wwwx.org",
+]
+
+
+def _spans(splitter: object, text: str, lower: bool) -> list[tuple[str, int, int]]:
+ return list(splitter(text, lower)) # ty:ignore[call-non-callable]
+
+
[email protected]("text", CORPUS)
+def test_word_spans_match_the_package_pattern(text: str) -> None:
+ assert list(word_spans(text)) == [(m.start(), m.end()) for m in PACKAGE_PATTERN.finditer(text)]
+
+
[email protected]("text", CORPUS)
[email protected]("lower", [True, False])
+def test_splitters_match_both_gliner2_versions(text: str, lower: bool) -> None:
+ v2 = linear_equivalent(WhitespaceTokenSplitter())
+ v1 = linear_equivalent(Gliner2V1Splitter())
+ assert v2 is not None
+ assert v1 is not None
+ assert not v2.lower_text_first
+ assert v1.lower_text_first
+ assert _spans(v2, text, lower) == _spans(WhitespaceTokenSplitter(), text, lower)
+ assert _spans(v1, text, lower) == _spans(Gliner2V1Splitter(), text, lower)
+
+
+def test_fuzzed_texts_split_identically() -> None:
+ alphabet = [*"aZ9._%+-@:/ \t\nwhtps_", "http://", "https://", "www.", ".com", "@x.io", "\u0130", "\u017f"]
+ alphabet += ["\u212a", "\u00e9", "\u4e2d", "\uff0c", "--", "\u00a0", "\u200b", "\U0001f600", "\u01c5"]
+ alphabet += ["\u00df", "\u03a3", "'"]
+ rng = random.Random(0) # noqa: S311 -- deterministic test data
+ for _ in range(20_000):
+ text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 40)))
+ assert list(word_spans(text)) == [(m.start(), m.end()) for m in PACKAGE_PATTERN.finditer(text)], text
+
+
+def test_the_installed_gliner2_splitter_has_a_linear_equivalent() -> None:
+ gliner2 = pytest.importorskip("gliner2")
+ major = int(gliner2.__version__.split(".")[0])
+ if major >= 2:
+ from gliner2.processing.word_splitter import (
+ WhitespaceTokenSplitter as Installed, # ty:ignore[unresolved-import]
+ )
+ else:
+ from gliner2.processor import WhitespaceTokenSplitter as Installed # ty:ignore[unresolved-import]
+ installed = Installed()
+ linear = linear_equivalent(installed)
+ assert linear is not None
+ assert linear.lower_text_first == (major < 2)
+ for text in CORPUS:
+ for lower in (True, False):
+ assert _spans(linear, text, lower) == _spans(installed, text, lower)
+
+
+def test_other_splitters_have_no_linear_equivalent() -> None:
+ class CharLevelSplitter:
+ _PATTERN = re.compile(r"[A-Za-z0-9@._\-+]+|\S")
+
+ def __call__(self, text: str, lower: bool = True) -> Iterator[tuple[str, int, int]]:
+ yield from ()
+
+ class WhitespaceTokenSplitterLookalike(WhitespaceTokenSplitter):
+ _PATTERN = re.compile(r"\S+", re.VERBOSE | re.IGNORECASE)
+
+ WhitespaceTokenSplitterLookalike.__name__ = "WhitespaceTokenSplitter"
+ assert linear_equivalent(CharLevelSplitter()) is None
+ assert linear_equivalent(WhitespaceTokenSplitterLookalike()) is None
+ assert linear_equivalent(lambda text, lower=True: iter(())) is None
+
+
+ "text",
+ [
+ "." * (2 * 1024 * 1024),
+ "a." * (1024 * 1024),
+ "%" * (2 * 1024 * 1024 - 2) + "@x",
+ "a@" * (1024 * 1024),
+ ". " * (1024 * 1024),
+ ],
+ ids=["dots", "a-dots", "local-run-then-at", "at-chain", "spaced-dots"],
+)
+def test_splitting_is_linear(text: str) -> None:
+ started = time.perf_counter()
+ first = [span for _, span in zip(range(2048), word_spans(text), strict=False)]
+ assert len(first) == 2048
+ assert time.perf_counter() - started < 1.0 # the package's regex takes minutes to hours on these
+
+ started = time.perf_counter()
+ count = sum(1 for _ in word_spans(text[: 256 * 1024]))
+ assert count > 0
+ assert time.perf_counter() - started < 2.0
+
+
+def test_lower_text_first_offsets_index_the_lowered_text() -> None:
+ text = "İstanbul x"
+ assert list(LinearWordSplitter(lower_text_first=True)(text)) == list(Gliner2V1Splitter()(text))
+ assert list(LinearWordSplitter(lower_text_first=False)(text)) == list(WhitespaceTokenSplitter()(text))