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): bound subword length of long words in GLiNER adapters (#380)
svonava894a0175749e
diff --git a/packages/sie_server/src/sie_server/adapters/_word_window.py b/packages/sie_server/src/sie_server/adapters/_word_window.pynew file mode 100644index 000000000..cd1bd456f--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/_word_window.py@@ -0,0 +1,315 @@+"""Bound the words a GLiNER-family model reads by subword tokens as well as by count.++GLiNER, GLiNER2 and GLiREL split a document into words, keep the first+``max_len`` of them, and give the encoder every subword token of each kept+word. ``max_len`` counts words, so it does not bound the encoder input: one+unbroken run of characters (a long number, hash or base64 string, a URL, or+text in a script the tokenizer splits into single characters) is one word of+about as many subwords as it has characters, and the encoder's time and memory+grow with the square of its input.++``read_window`` reads a document's words lazily and returns the part a model+reads:++* A word longer than ``MAX_WORD_CHARS`` characters is read as consecutive+ pieces of at most that many characters. Each piece is a word with the offsets+ of its own characters, so a span found in it maps back to the text.+* Reading stops after ``max_words`` words, or before the first word that would+ take the document past ``max_subwords`` subword tokens. The first word is+ always read, so no document is left empty.++``subword_budget`` allows a number of subwords per word of a model's word+window: ``SUBWORDS_PER_WORD`` by default, which holds ordinary text in the+languages these tokenizers read. Prose, code, CSV and JSON logs run at 1 to 2.4+subwords per word, other European languages and Korean at up to 3.2, and+Chinese or Japanese at about 4 to 6 for the multilingual checkpoints. The budget+is capped at ``MAX_DOCUMENT_SUBWORDS`` (``DEBERTA_MAX_DOCUMENT_SUBWORDS`` for+DeBERTa encoders, whose attention materializes score matrices of the square of+the row length), and within the position table of encoders with absolute+positions.++``plan_forwards`` splits a batch into forward passes whose rows times the+square of their longest row stay within ``ATTENTION_BUDGET``, so that the+attention memory of a pass stays bounded for a batch of long rows too.+"""++from __future__ import annotations++from collections import Counter, OrderedDict+from collections.abc import Callable, Iterable, Iterator, Sequence+from dataclasses import dataclass+from itertools import islice+from typing import Any++# A longer word is read in pieces of this many characters.+MAX_WORD_CHARS = 256+# Subword tokens a document may take per word of the model's word window.+SUBWORDS_PER_WORD = 8+# Most document subwords a model reads...+MAX_DOCUMENT_SUBWORDS = 8192+# ...and for DeBERTa encoders: one such row takes about 2 GiB of attention scores at float16.+DEBERTA_MAX_DOCUMENT_SUBWORDS = 4096+# Rows times the square of the longest row's tokens in one forward pass of a DeBERTa encoder.+ATTENTION_BUDGET = DEBERTA_MAX_DOCUMENT_SUBWORDS * DEBERTA_MAX_DOCUMENT_SUBWORDS+# Tokens an encoder with absolute positions adds around a document ([CLS], [SEP], position offsets).+_SPECIAL_POSITIONS = 4+# Words are counted in blocks, so reading stops at most one block past the window.+_READ_BLOCK = 64+_COUNT_CACHE_SIZE = 16384+_QUADRATIC_ATTENTION_TYPES = frozenset({"deberta", "deberta-v2"})+# Encoders with a learned table of absolute positions. transformers 5 no longer+# writes ``position_embedding_type`` for them, so the model type decides.+_ABSOLUTE_POSITION_TYPES = frozenset(+ {"albert", "bert", "camembert", "distilbert", "electra", "mpnet", "roberta", "xlm-roberta"}+)++Word = tuple[str, int, int]+CountSubwords = Callable[[Sequence[str]], Sequence[int]]+++def _config_value(config: Any, key: str) -> Any:+ if isinstance(config, dict):+ return config.get(key)+ return getattr(config, key, None)+++def quadratic_attention(encoder_config: Any) -> bool:+ """Whether the encoder materializes full attention score matrices (DeBERTa)."""+ return _config_value(encoder_config, "model_type") in _QUADRATIC_ATTENTION_TYPES+++def absolute_positions(encoder_config: Any) -> int | None:+ """The size of the encoder's absolute position table, or None when positions are relative or rotary."""+ positions = _config_value(encoder_config, "max_position_embeddings")+ if not isinstance(positions, int) or isinstance(positions, bool):+ return None+ kind = _config_value(encoder_config, "position_embedding_type")+ if kind == "absolute" or (kind is None and _config_value(encoder_config, "model_type") in _ABSOLUTE_POSITION_TYPES):+ return positions+ return None+++def subword_budget(max_words: int, encoder_config: Any = None, *, per_word: int = SUBWORDS_PER_WORD) -> int:+ """Subword tokens a document may take in a model reading at most ``max_words`` words."""+ cap = DEBERTA_MAX_DOCUMENT_SUBWORDS if quadratic_attention(encoder_config) else MAX_DOCUMENT_SUBWORDS+ positions = absolute_positions(encoder_config)+ if positions is not None:+ cap = min(cap, positions - _SPECIAL_POSITIONS)+ return max(1, min(per_word * max_words, cap))+++@dataclass(frozen=True, slots=True)+class Window:+ """The words of a document a model reads."""++ words: list[Word]+ subwords: int+ # ``text[:cut]`` gives the same window: the end of the word holding the+ # first piece not read (or, when the word count ran out, the last piece+ # read). None when every word was read.+ cut: int | None+++def pieces(words: Iterable[Word], text: str, max_chars: int = MAX_WORD_CHARS) -> Iterator[tuple[str, int, int, int]]:+ """``(word, start, end, word_end)``: each word, a longer word as pieces of at most ``max_chars`` characters.++ ``word_end`` is the end of the word a piece comes from. A splitter that+ changes a word's length (gliner2 2.x lowercases each word, and ``"\u0130"``+ lowercases to two characters) is cut on the text's characters instead.+ """+ for word, start, end in words:+ if end - start <= max_chars:+ yield word, start, end, end+ continue+ source, lower = word, False+ if len(word) != end - start:+ source = text[start:end]+ lower = word == source.lower()+ for offset in range(0, end - start, max_chars):+ piece = source[offset : offset + max_chars]+ yield (piece.lower() if lower else piece), start + offset, start + offset + len(piece), end+++def read_window(+ text: str,+ words: Iterable[Word],+ *,+ max_words: int,+ max_subwords: int,+ count_subwords: CountSubwords,+) -> Window:+ """The words of ``text`` a model reads: see the module docstring.++ ``words`` are ``text``'s words as ``(word, start, end)``, read lazily, and+ ``count_subwords`` gives the subword tokens of each of a list of words.+ """+ source = pieces(words, text)+ kept: list[Word] = []+ subwords = 0+ last_word_end = 0+ while len(kept) < max_words:+ block = list(islice(source, min(_READ_BLOCK, max_words - len(kept))))+ if not block:+ return Window(kept, subwords, None)+ counts = count_subwords([word for word, _, _, _ in block])+ if len(counts) != len(block):+ raise RuntimeError("subword counts do not match the words counted")+ for (word, start, end, word_end), count in zip(block, counts, strict=True):+ if kept and subwords + count > max_subwords:+ return Window(kept, subwords, word_end)+ kept.append((word, start, end))+ subwords += count+ last_word_end = word_end+ if next(source, None) is None:+ return Window(kept, subwords, None)+ return Window(kept, subwords, last_word_end)+++class WindowedSplitter:+ """A word splitter that yields only the window of each text a model reads.++ Wraps ``splitter`` (called as ``splitter(text, *args, **kwargs)`` and+ yielding ``(word, start, end)``), so a library that splits and truncates+ a document itself reads the bounded window.+ """++ __slots__ = ("count_subwords", "max_subwords", "max_words", "splitter")++ def __init__(self, splitter: Any, *, max_words: int, max_subwords: int, count_subwords: CountSubwords) -> None:+ self.splitter = splitter+ self.max_words = max_words+ self.max_subwords = max_subwords+ self.count_subwords = count_subwords++ def __call__(self, text: str, *args: Any, **kwargs: Any) -> Iterator[Word]:+ return iter(self.window(text, *args, **kwargs).words)++ def window(self, text: str, *args: Any, **kwargs: Any) -> Window:+ return read_window(+ text,+ self.splitter(text, *args, **kwargs),+ max_words=self.max_words,+ max_subwords=self.max_subwords,+ count_subwords=self.count_subwords,+ )+++class SubwordCounter:+ """Subword counts of words, from ``count`` (a list of words at a time), with the recent ones kept.++ Only words of at most ``MAX_WORD_CHARS`` characters (every piece a window+ reads) are kept, so the cache holds at most ``size`` such words.+ """++ __slots__ = ("_cache", "_count", "_size")++ def __init__(self, count: CountSubwords, size: int = _COUNT_CACHE_SIZE) -> None:+ self._count = count+ self._cache: OrderedDict[str, int] = OrderedDict()+ self._size = size++ def __call__(self, words: Sequence[str]) -> list[int]:+ missing = list(dict.fromkeys(word for word in words if word not in self._cache))+ counted: dict[str, int] = {}+ if missing:+ counts = self._count(missing)+ if len(counts) != len(missing):+ raise RuntimeError("subword counts do not match the words counted")+ counted = {word: int(count) for word, count in zip(missing, counts, strict=True)}+ result = []+ for word in words:+ if word in counted:+ count = counted[word]+ if len(word) <= MAX_WORD_CHARS:+ self._cache[word] = count+ else:+ count = self._cache[word]+ self._cache.move_to_end(word)+ result.append(count)+ while len(self._cache) > self._size:+ self._cache.popitem(last=False)+ return result+++def split_word_counter(tokenizer: Any) -> CountSubwords:+ """Subwords per word as ``tokenizer`` encodes a list of words (``is_split_into_words``)."""++ def count(words: Sequence[str]) -> list[int]:+ if not words:+ return []+ try:+ encoding = tokenizer(list(words), is_split_into_words=True, add_special_tokens=False)+ word_ids = encoding.word_ids()+ except (AttributeError, ValueError, TypeError): # a tokenizer without word alignment+ return [len(tokenizer.tokenize(word)) for word in words]+ per_word = Counter(index for index in word_ids if index is not None)+ return [per_word.get(index, 0) for index in range(len(words))]++ return count+++def plan_forwards(+ row_tokens: Sequence[int],+ *,+ rows_per_pass: int,+ budget: int = ATTENTION_BUDGET,+) -> list[list[int]] | None:+ """Row indices to run as separate forward passes, or None when the batch fits as it is.++ The batch fits when every run of ``rows_per_pass`` consecutive rows (the+ passes a library forms) keeps its row count times the square of its+ longest row within ``budget``. Otherwise rows are grouped by length: a+ group adds rows, shortest first, while its count times the square of its+ longest row stays within ``budget``, it holds at most ``rows_per_pass``,+ and no row is more than twice as long as its shortest (so short rows are+ not padded to long ones). A row too long to share a pass runs alone.+ """+ size = max(1, rows_per_pass)+ chunks = [row_tokens[start : start + size] for start in range(0, len(row_tokens), size)]+ if all(len(chunk) * max(chunk) ** 2 <= budget for chunk in chunks):+ return None+ groups: list[list[int]] = []+ current: list[int] = []+ for index in sorted(range(len(row_tokens)), key=lambda row: row_tokens[row]):+ longest = row_tokens[index]+ if current and (+ len(current) >= size+ or (len(current) + 1) * longest * longest > budget+ or longest > 2 * row_tokens[current[0]]+ ):+ groups.append(current)+ current = []+ current.append(index)+ if current:+ groups.append(current)+ return groups+++def bound_gliner_words(model: Any) -> bool:+ """Make a loaded ``gliner`` model read the bounded window of each document.++ ``gliner`` splits a document with ``data_processor.words_splitter`` (in+ ``prepare_inputs``, which inference and the adapters' metering share),+ keeps ``config.max_len`` words, and encodes every subword of each. The+ splitter is wrapped in a ``WindowedSplitter`` counting subwords as the+ model's tokenizer encodes split words. An encoder with absolute positions+ also gets its tokenizer capped at its position table, so that a long label+ prompt is truncated rather than run past the table.++ Returns whether the encoder's attention memory grows with the square of a+ row (DeBERTa), for ``plan_forwards``.+ """+ processor = model.data_processor+ encoder_config = getattr(model.config, "encoder_config", None)+ max_words = int(model.config.max_len)+ tokenizer = processor.transformer_tokenizer+ processor.words_splitter = WindowedSplitter(+ processor.words_splitter,+ max_words=max_words,+ max_subwords=subword_budget(max_words, encoder_config),+ count_subwords=SubwordCounter(split_word_counter(tokenizer)),+ )+ positions = absolute_positions(encoder_config)+ if positions is not None and tokenizer.model_max_length > positions:+ tokenizer.model_max_length = positions+ return quadratic_attention(encoder_config)diff --git a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner/__init__.pyindex d41433061..4bb803f7c 100644--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py@@ -29,6 +29,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters._word_window import bound_gliner_words, plan_forwardsfrom sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.inference_output import ExtractOutputfrom sie_server.types.inputs import InvalidInputError, Item@@ -52,6 +53,8 @@ _MIN_ADJACENCY_THRESHOLD = 0.5# candidate inside the forward pass. Near zero that is nearly every span of the# document, so relex requests need at least this entity threshold._MIN_RELEX_THRESHOLD = 0.1+# Rows gliner's inference (and the meter, which mirrors it) puts in one forward pass.+_GLINER_BATCH_SIZE = 8_ERR_NO_RELATIONS = ("This GLiNER model does not extract relations; options.relation_labels needs a joint ""entity-relation model such as knowledgator/gliner-relex-large-v1.0"@@ -128,6 +131,8 @@ class GLiNERAdapter(BaseAdapter):self._device: str | None = None# True for joint entity-relation models, whose config names a relations layer.self._extracts_relations = False+ # True when the encoder's attention memory grows with the square of a row (see ``_inference``).+ self._quadratic_attention = Falsedef load(self, device: str) -> None:"""Load the model onto the specified device.@@ -165,6 +170,9 @@ class GLiNERAdapter(BaseAdapter):self._extracts_relations = getattr(self._model.config, "relations_layer", None) is not Noneif self._extracts_relations:_cap_relation_candidates(self._model.model, _MAX_RELATION_CANDIDATES)+ # gliner's max_len counts words, whatever their subwords: read at most a+ # bounded number of subwords too, with a long word in pieces.+ self._quadratic_attention = bound_gliner_words(self._model)def extract(self,@@ -227,7 +235,7 @@ class GLiNERAdapter(BaseAdapter):# Meter the exact post-word-truncation document window before GPU work.# Besides producing the authoritative terminal counts, this rejects a# finite-tokenizer prompt that leaves no represented document subword.- input_token_counts = self._doc_input_token_counts(texts, labels, relation_labels)+ input_token_counts, row_tokens = self._meter(texts, labels, relation_labels)# Get options with fallback to model defaultseffective_threshold = self._validate_threshold(opts.get("threshold", self._threshold), "threshold")@@ -255,18 +263,16 @@ class GLiNERAdapter(BaseAdapter):# Use batch prediction for efficiency (24x speedup vs single item loop)with torch.inference_mode():- prediction = self._model.inference(+ batch_entities, batch_relations = self._inference(texts,labels,+ row_tokens,+ returns_relations=bool(relation_labels),threshold=effective_threshold,flat_ner=effective_flat_ner,multi_label=effective_multi_label,**relation_kwargs,)- if relation_labels:- batch_entities, batch_relations = prediction- else:- batch_entities, batch_relations = prediction, None# Convert to our formatall_entities = []@@ -349,13 +355,60 @@ class GLiNERAdapter(BaseAdapter):formatted.sort(key=lambda r: (-r["score"], r["relation"], r["head"], r["tail"]))return formatted+ def _inference(+ self,+ texts: list[str],+ labels: list[str],+ row_tokens: list[int] | None,+ *,+ returns_relations: bool,+ **kwargs: Any,+ ) -> tuple[list[Any], list[Any] | None]:+ """Run gliner inference, in several calls when one forward pass would hold too long a batch.++ gliner pads each pass of up to ``_GLINER_BATCH_SIZE`` rows to its+ longest row, and a DeBERTa encoder's attention memory grows with rows+ times the square of that length, so rows are grouped by length within+ ``_word_window.ATTENTION_BUDGET`` (see ``plan_forwards``). A batch that+ fits runs in one call, exactly as before. Returns entities and, when+ requested, relations per item.+ """+ groups = None+ if row_tokens is not None and self._quadratic_attention:+ groups = plan_forwards(row_tokens, rows_per_pass=_GLINER_BATCH_SIZE)+ if groups is None:+ groups = [list(range(len(texts)))]+ entities: list[Any] = [None] * len(texts)+ relations: list[Any] | None = [None] * len(texts) if returns_relations else None+ for group in groups:+ prediction = self._model.inference([texts[index] for index in group], labels, **kwargs)+ group_entities, group_relations = prediction if returns_relations else (prediction, None)+ if len(group_entities) != len(group) or (+ group_relations is not None and len(group_relations) != len(group)+ ):+ raise ValueError("GLiNER returned predictions for a different number of items")+ for position, index in enumerate(group):+ entities[index] = group_entities[position]+ if relations is not None and group_relations is not None:+ relations[index] = group_relations[position]+ return entities, relations+def _doc_input_token_counts(self,texts: list[str],labels: list[str],relation_labels: list[str] | None = None,) -> list[int] | None:- """Count the document subwords represented by GLiNER's real processor.+ """Count the document subwords represented by GLiNER's real processor (see ``_meter``)."""+ return self._meter(texts, labels, relation_labels)[0]++ def _meter(+ self,+ texts: list[str],+ labels: list[str],+ relation_labels: list[str] | None = None,+ ) -> tuple[list[int] | None, list[int] | None]:+ """Count the document subwords represented by GLiNER's real processor, and each row's tokens.Classic GLiNER first splits and truncates each document in WORDS, thenprepends the label prompt and transformer-tokenizes that retained word@@ -370,17 +423,23 @@ class GLiNERAdapter(BaseAdapter):GLiNER inference's default batch size so a finite tokenizer cap isobserved identically. Joint entity-relation models also put therelation types in the prompt, so they are passed through as well.++ The word splitter is the bounded one installed at load, so the counts+ are of the window gliner reads. The second list holds every row's+ attended tokens (prompt included), for planning forward passes.+ Both are None when the processor cannot be metered."""processor = getattr(self._model, "data_processor", None)prepare_inputs = getattr(self._model, "prepare_inputs", None)prepare_base_input = getattr(self._model, "prepare_base_input", None)if processor is None or prepare_inputs is None or prepare_base_input is None:- return None+ return None, Nonetry:split_texts, _, _ = prepare_inputs(texts)raw_items = prepare_base_input(split_texts)counts: list[int] = []+ rows: list[int] = []has_document_subwords: list[bool] = []for start in range(0, len(raw_items), 8):if self._extracts_relations:@@ -407,7 +466,8 @@ class GLiNERAdapter(BaseAdapter):attention_mask = encoded["attention_mask"][batch_index].tolist()words_mask = encoded["words_mask"][batch_index].tolist()if len(word_ids) != len(attention_mask) or len(word_ids) != len(words_mask):- return None+ return None, None+ rows.append(sum(1 for attended in attention_mask if attended))first_document_index = next((index for index, word_mask in enumerate(words_mask) if word_mask > 0),None,@@ -436,12 +496,12 @@ class GLiNERAdapter(BaseAdapter):))except Exception: # noqa: BLE001 — metering must never fail an extraction- return None- if len(counts) != len(texts) or len(has_document_subwords) != len(texts):- return None+ return None, None+ if len(counts) != len(texts) or len(has_document_subwords) != len(texts) or len(rows) != len(texts):+ return None, Noneif not all(has_document_subwords):raise InvalidInputError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)- return counts+ return counts, rowsdef _merge_entities(self, entities: list[Entity], text: str) -> list[Entity]:"""Merge adjacent entities with the same label.diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.pyindex 602b133a1..911acb6d8 100644--- a/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/gliner2/adapter.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport mathimport reimport unicodedata+from collections.abc import Callable, Iterable+from functools import lru_cachefrom numbers import Realfrom pathlib import Pathfrom typing import Any, ClassVar@@ -13,7 +15,14 @@ from huggingface_hub import snapshot_downloadfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision-from sie_server.adapters.gliner2.words import linear_equivalent, word_spans+from sie_server.adapters._word_window import (+ SubwordCounter,+ WindowedSplitter,+ plan_forwards,+ quadratic_attention,+ subword_budget,+)+from sie_server.adapters.gliner2.words import linear_equivalentfrom sie_server.core.inference_output import ExtractOutputfrom sie_server.types.inputs import Itemfrom sie_server.types.responses import Classification, Entity, Relation@@ -29,6 +38,29 @@ _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+# read English: prose, code, CSV and JSON logs run at up to 2.4 subwords per word,+# other European languages at up to 3.2. GLiNER2 reads a URL as one word, so a+# document made mostly of long links is read only up to the budget.+_SUBWORDS_PER_WORD = 4+# gliner2 keeps the tokens of every word it tokenizes in an LRU of 50,000+# entries. Only words of at most _CACHED_WORD_CHARS characters are kept here, so+# the cache stays within a few tens of MB; a longer word is tokenized each time.+_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"}class GLiNER2Adapter(BaseAdapter):@@ -101,6 +133,11 @@ class GLiNER2Adapter(BaseAdapter):self._model: Any = 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``).+ self._word_splitter: WindowedSplitter | None = None+ self._count_subwords: Callable[[list[str]], list[int]] | None = None+ # Whether the encoder's attention memory grows with the square of a row (see ``_run_planned``).+ self._quadratic_attention = Trueself._device: str | None = Nonedef load(self, device: str) -> None:@@ -126,15 +163,20 @@ class GLiNER2Adapter(BaseAdapter):map_location=device,quantize=use_quantize,)- self._use_linear_word_splitter(model.processor)+ encoder = getattr(model, "encoder", None)+ self._use_linear_word_splitter(model.processor, getattr(encoder, "config", None))self._model = model- def _use_linear_word_splitter(self, processor: Any) -> None:- """Split words with a linear-time equivalent of gliner2's splitter.+ def _use_linear_word_splitter(self, processor: Any, encoder_config: Any = None) -> None:+ """Split words with a linear-time equivalent of gliner2's splitter, bounded to the window gliner2 reads.gliner2's word-splitting regex takes time quadratic in the length of arun of e-mail address characters (``"...."``, ``"a.a.a."``), on the- thread that serves every request.+ thread that serves every request. gliner2 also reads ``max_len`` words+ whatever their length, so the splitter yields only the window of+ ``_word_window.read_window``: a word longer than 256 characters in+ pieces, and at most ``_SUBWORDS_PER_WORD`` subword tokens per word of+ the window.Raises:RuntimeError: gliner2's splitter is not the one this adapter has an@@ -146,8 +188,40 @@ class GLiNER2Adapter(BaseAdapter):f"GLiNER2 has no linear-time equivalent of {type(processor.word_splitter).__name__}; ""gliner2's word splitter changed")- processor.word_splitter = splitter+ # 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+ 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+ windowed = WindowedSplitter(+ splitter,+ max_words=max_words,+ max_subwords=subword_budget(max_words, config, per_word=_SUBWORDS_PER_WORD),+ count_subwords=count_subwords,+ )+ processor.word_splitter = windowedself._lower_text_first = splitter.lower_text_first+ self._word_splitter = windowed+ self._count_subwords = count_subwords+ self._quadratic_attention = quadratic_attention(config)++ @staticmethod+ def _bounded_tokenization(processor: Any) -> Callable[[str], list[str]]:+ """Tokenize words as gliner2 does, keeping only short words' tokens.++ gliner2 caches the tokens of every word it tokenizes, however long, for+ the adapter's lifetime; its cache is replaced by one that keeps words+ of at most ``_CACHED_WORD_CHARS`` characters.+ """+ tokenize = processor.tokenizer.tokenize+ cached = lru_cache(maxsize=_WORD_CACHE_SIZE)(tokenize)++ def tokenize_word(word: str) -> list[str]:+ return cached(word) if len(word) <= _CACHED_WORD_CHARS else tokenize(word)++ if hasattr(processor, "_tokenize_cached"):+ processor._tokenize_cached = tokenize_word+ return tokenize_worddef extract(self,@@ -162,8 +236,9 @@ 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]+ # gliner2 reads a bounded window of words: pass it only the prefix holding them.+ windows = [self._window(text) for text in texts]+ model_texts = [model_text for model_text, _ in windows]opts = options or {}effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold))classification_task = opts.get("classification_task", self._classification_task)@@ -178,15 +253,23 @@ class GLiNER2Adapter(BaseAdapter):if classification_task is not None:raise ValueError("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 read twice: in its structure and in a prefix before the document.+ rows = self._row_tokens(windows, specs + specs)with torch.inference_mode():- raw_results = self._model.batch_extract_json(+ raw_results = self._run_planned(model_texts,- structures,- batch_size=len(texts),- threshold=effective_threshold,- include_confidence=False,- include_spans=False,- max_len=self._max_seq_length,+ rows,+ lambda batch: self._model.batch_extract_json(+ batch,+ structures,+ batch_size=len(batch),+ threshold=effective_threshold,+ include_confidence=False,+ include_spans=False,+ max_len=self._max_seq_length,+ ),+ rows_per_pass=len(texts),)return ExtractOutput(entities=[[] for _ in texts],@@ -203,15 +286,21 @@ class GLiNER2Adapter(BaseAdapter):normalized_entities = [self._normalize_input_entities(item, entities or []) for item, entities in zip(items, relation_entities)]+ rows = self._row_tokens(windows, normalized_labels, per_entry=_PROMPT_TOKENS_PER_RELATION)with torch.inference_mode():- raw_results = self._model.batch_extract_relations(+ raw_results = self._run_planned(model_texts,- normalized_labels,- batch_size=len(texts),- threshold=effective_threshold,- include_confidence=True,- include_spans=True,- max_len=self._max_seq_length,+ rows,+ lambda batch: self._model.batch_extract_relations(+ batch,+ normalized_labels,+ batch_size=len(batch),+ threshold=effective_threshold,+ include_confidence=True,+ include_spans=True,+ max_len=self._max_seq_length,+ ),+ rows_per_pass=len(texts),)return ExtractOutput(entities=normalized_entities,@@ -232,13 +321,14 @@ class GLiNER2Adapter(BaseAdapter):multi_label=multi_label,threshold=effective_threshold,input_token_counts=input_token_counts,+ rows=self._row_tokens(windows, [classification_task, *normalized_labels]),)- with torch.inference_mode():- if len(texts) == 1:- raw_results = [+ def extract_entities(batch: list[str]) -> list[Any]:+ if len(batch) == 1:+ return [self._model.extract_entities(- model_texts[0],+ batch[0],normalized_labels,threshold=effective_threshold,include_confidence=True,@@ -246,15 +336,22 @@ class GLiNER2Adapter(BaseAdapter):max_len=self._max_seq_length,)]- else:- raw_results = self._model.batch_extract_entities(- model_texts,- normalized_labels,- threshold=effective_threshold,- include_confidence=True,- include_spans=True,- max_len=self._max_seq_length,- )+ return self._model.batch_extract_entities(+ batch,+ normalized_labels,+ threshold=effective_threshold,+ include_confidence=True,+ include_spans=True,+ max_len=self._max_seq_length,+ )++ with torch.inference_mode():+ raw_results = self._run_planned(+ model_texts,+ self._row_tokens(windows, normalized_labels),+ extract_entities,+ rows_per_pass=1 if len(texts) == 1 else _PACKAGE_BATCH_SIZE,+ )all_entities = [self._flatten_entities(result, text=text) for text, result in zip(texts, raw_results)]return ExtractOutput(entities=all_entities, input_token_counts=input_token_counts)@@ -268,6 +365,7 @@ class GLiNER2Adapter(BaseAdapter):multi_label: bool,threshold: float,input_token_counts: list[int] | None,+ rows: list[int] | None = None,) -> ExtractOutput:"""Run one GLiNER2 classification schema and normalize its results."""tasks = {@@ -278,25 +376,32 @@ class GLiNER2Adapter(BaseAdapter):}}- with torch.inference_mode():- if len(texts) == 1:- raw_results = [+ def classify(batch: list[str]) -> list[Any]:+ if len(batch) == 1:+ return [self._model.classify_text(- texts[0],+ batch[0],tasks,threshold=threshold,include_confidence=True,max_len=self._max_seq_length,)]- else:- raw_results = self._model.batch_classify_text(- texts,- tasks,- threshold=threshold,- include_confidence=True,- max_len=self._max_seq_length,- )+ return self._model.batch_classify_text(+ batch,+ tasks,+ threshold=threshold,+ include_confidence=True,+ max_len=self._max_seq_length,+ )++ with torch.inference_mode():+ raw_results = self._run_planned(+ texts,+ rows,+ classify,+ rows_per_pass=1 if len(texts) == 1 else _PACKAGE_BATCH_SIZE,+ )all_classifications = [self._flatten_classifications(result, task=task, threshold=threshold) for result in raw_results@@ -307,6 +412,51 @@ class GLiNER2Adapter(BaseAdapter):input_token_counts=input_token_counts,)+ def _row_tokens(+ self,+ windows: list[tuple[str, int | None]],+ prompt_entries: Iterable[str],+ *,+ per_entry: int = _PROMPT_TOKENS_PER_ENTRY,+ ) -> list[int] | None:+ """Estimated tokens of each item's encoder row: the task prompt, then the words it reads.++ None when the words were not counted (no bounded splitter is installed).+ """+ count = self._count_subwords+ if count is None or any(subwords is None for _, subwords in windows):+ return None+ entries = [entry for entry in prompt_entries if isinstance(entry, str)]+ prompt = sum(count(entries)) + per_entry * len(entries) + _ROW_OVERHEAD_TOKENS+ return [prompt + (subwords or 0) for _, subwords in windows]++ def _run_planned(+ self,+ texts: list[str],+ rows: list[int] | None,+ run: Callable[[list[str]], list[Any]],+ *,+ rows_per_pass: int,+ ) -> list[Any]:+ """``run(texts)``, split into several calls when one forward pass would hold too long a batch.++ gliner2 pads a pass to its longest row, and a DeBERTa encoder's+ attention memory grows with rows times the square of that length, so+ rows are grouped by length within ``_word_window.ATTENTION_BUDGET``+ (see ``plan_forwards``). A batch that fits runs exactly as before.+ """+ groups = plan_forwards(rows, rows_per_pass=rows_per_pass) if rows and self._quadratic_attention else None+ if groups is None:+ return list(run(texts))+ results: list[Any] = [None] * len(texts)+ for group in groups:+ group_results = list(run([texts[index] for index in group]))+ if len(group_results) != len(group):+ raise ValueError("GLiNER2 returned results for a different number of items")+ for index, result in zip(group, group_results, strict=True):+ results[index] = result+ return results+@classmethoddef _flatten_classifications(cls,@@ -660,36 +810,48 @@ class GLiNER2Adapter(BaseAdapter):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.+ """The prefix of ``text`` holding every word gliner2 reads from it, or ``text``."""+ return self._window(text)[0]++ def _window(self, text: str) -> tuple[str, int | None]:+ """``(model text, subwords)``: the prefix of ``text`` gliner2 reads the same words from, and their subwords.++ gliner2 splits a text into words (with the bounded splitter installed+ at load, which yields only the window it reads) and keeps the first+ ``max_len``. ``Window.cut`` is where a prefix gives the same window:+ the end of the word holding the last piece read, or the first piece+ not read. No word crosses that point, so the prefix splits into the+ same words at the same offsets. 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 lowercasing keeps the text's+ length and the prefix's lowercase starts the lowercased text (a final+ sigma can lowercase differently at the cut). gliner2 2.x splits the+ text as given. The window is read from the text as gliner2 reads it,+ with the "." it appends to a text without a sentence end. The+ subwords are None when no bounded splitter is installed."""- 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+ splitter = self._word_splitter+ if splitter is None:+ return text, None+ # gliner2 ends a text without a sentence end with ".", and reads that too.+ window = splitter.window(text if text.endswith(_SENTENCE_END) else text + ".", lower=True)+ cut = window.cut+ if cut is None:+ return text, window.subwordssource = 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():+ if len(source) != len(text):+ # Offsets into the lowercased text do not index this one.+ return text, window.subwords+ if 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+ if cut >= len(text):+ return text, window.subwordsprefix = text[:cut]if self._lower_text_first and not source.startswith(prefix.lower()):- return text- return prefix+ return text, window.subwords+ return prefix, window.subwordsdef _doc_input_token_counts(self, texts: list[str]) -> list[int] | None:processor = getattr(self._model, "processor", None)diff --git a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.pyindex 0cb85bb00..f70959ff6 100644--- a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py@@ -11,6 +11,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters._word_window import bound_gliner_words, plan_forwardsfrom sie_server.core.inference_output import ExtractOutputfrom sie_server.types.inputs import InvalidInputError, Itemfrom sie_server.types.responses import Entity@@ -22,6 +23,8 @@ _ERR_NO_RELATIONS = "GLiNER bi-encoder models do not extract relations; options.# Maximum number of distinct label-set embeddings to cache._LABEL_CACHE_MAX_SIZE = 64+# Rows gliner's inference (and the meter, which mirrors it) puts in one forward pass.+_GLINER_BATCH_SIZE = 8def _validate_threshold(value: Any) -> None:@@ -102,6 +105,8 @@ class GLiNERBiAdapter(BaseAdapter):self._model: Any = Noneself._device: str | None = None+ # True when the text encoder's attention memory grows with the square of a row.+ self._quadratic_attention = False# LRU cache: labels in request order -> pre-computed label embeddings.# The embeddings are positional, so the key must keep the order.# Protected by _cache_lock for thread safety (defensive — the@@ -156,6 +161,9 @@ class GLiNERBiAdapter(BaseAdapter):self._model = self._model.to(device)else:self._model = self._model.to(device, dtype=dtype)+ # gliner's max_len counts words, whatever their subwords: read at most a+ # bounded number of subwords too, with a long word in pieces.+ self._quadratic_attention = bound_gliner_words(self._model)# Clear any stale label cache from a prior loadself._label_cache.clear()@@ -215,25 +223,41 @@ class GLiNERBiAdapter(BaseAdapter):effective_flat_ner = opts.get("flat_ner", self._flat_ner)effective_multi_label = opts.get("multi_label", self._multi_label)use_precompute = opts.get("precompute_labels", self._precompute_labels)+ # A bi-encoder's row is the document alone, so its metered tokens are its row tokens.+ input_token_counts = self._doc_input_token_counts(texts, labels)- with torch.inference_mode():+ def predict(batch: list[str]) -> list[Any]:if use_precompute:- batch_entities = self._predict_with_cached_embeds(- texts,+ return self._predict_with_cached_embeds(+ batch,labels,threshold=effective_threshold,flat_ner=effective_flat_ner,multi_label=effective_multi_label,)+ # Fall back to standard GLiNER inference path+ return self._model.inference(+ batch,+ labels,+ threshold=effective_threshold,+ flat_ner=effective_flat_ner,+ multi_label=effective_multi_label,+ )++ groups = None+ if input_token_counts is not None and self._quadratic_attention:+ groups = plan_forwards(input_token_counts, rows_per_pass=_GLINER_BATCH_SIZE)+ with torch.inference_mode():+ if groups is None:+ batch_entities = predict(texts)else:- # Fall back to standard GLiNER inference path- batch_entities = self._model.inference(- texts,- labels,- threshold=effective_threshold,- flat_ner=effective_flat_ner,- multi_label=effective_multi_label,- )+ batch_entities: list[Any] = [[] for _ in texts]+ for group in groups:+ group_entities = predict([texts[index] for index in group])+ if len(group_entities) != len(group):+ raise ValueError("GLiNER-bi returned predictions for a different number of items")+ for index, entities in zip(group, group_entities, strict=True):+ batch_entities[index] = entities# Convert to SIE Entity format (same as GLiNERAdapter)all_entities: list[list[Entity]] = []@@ -251,13 +275,14 @@ class GLiNERBiAdapter(BaseAdapter):)all_entities.append(entity_results)- return ExtractOutput(entities=all_entities, input_token_counts=self._doc_input_token_counts(texts, labels))+ return ExtractOutput(entities=all_entities, input_token_counts=input_token_counts)def _doc_input_token_counts(self, texts: list[str], labels: list[str]) -> list[int] | None:"""Count the document tokens the bi-encoder actually encodes, per item.A bi-encoder encodes labels separately, so its text input is the- document alone. Delegate word splitting and max-length word truncation+ document alone. Delegate word splitting (the bounded splitter installed+ at load) and max-length word truncationto the pinned GLiNER processor, then count the attended tokens of theretained window, special tokens included, as the GLiNER adapter does.Batches match GLiNER inference's default batch size. GLiNER skipsdiff --git a/packages/sie_server/src/sie_server/adapters/glirel/__init__.py b/packages/sie_server/src/sie_server/adapters/glirel/__init__.pyindex f97951ec2..9d5df2d26 100644--- a/packages/sie_server/src/sie_server/adapters/glirel/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/glirel/__init__.py@@ -10,6 +10,7 @@ Reference models:"""import re+from collections.abc import Iteratorfrom pathlib import Pathfrom typing import Any, ClassVar@@ -18,14 +19,18 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters._word_window import SubwordCounter, WindowedSplitter, split_word_counter, subword_budgetfrom sie_server.core.inference_output import ExtractOutput-from sie_server.types.inputs import Item+from sie_server.types.inputs import InvalidInputError, Itemfrom sie_server.types.responses import Entity, Relation# Error messages_ERR_REQUIRES_LABELS = "GLiREL requires labels parameter for relation extraction"_ERR_REQUIRES_ENTITIES = "GLiREL requires entities in item metadata for relation extraction"_TOKEN_PATTERN = re.compile(r"\w+(?:[-_]\w+)*|\S")+# Subword tokens a text may take per word GLiREL reads: its checkpoints read+# English, whose prose, code and logs run at up to 2.4 subwords per word.+_SUBWORDS_PER_WORD = 4class GLiRELAdapter(BaseAdapter):@@ -89,6 +94,8 @@ class GLiRELAdapter(BaseAdapter):self._model: Any = None # GLiREL model typeself._device: str | None = None+ # The words of a text GLiREL reads (see ``_tokenize``); None until loaded.+ self._words: WindowedSplitter | None = Nonedef load(self, device: str) -> None:"""Load the model onto the specified device.@@ -113,6 +120,28 @@ class GLiRELAdapter(BaseAdapter):# Set eval modeself._model.eval()+ embeddings = self._model.token_rep_layer.bert_layer+ self._bound_words(+ embeddings.tokenizer,+ int(self._model.base_config.max_len),+ getattr(embeddings.model, "config", None),+ )++ def _bound_words(self, tokenizer: Any, max_words: int, encoder_config: Any = None) -> None:+ """Read at most ``max_words`` words of a text, and a bounded number of their subwords.++ GLiREL keeps its first ``max_len`` words and encodes every subword of+ each, without truncating; ``_word_window.read_window`` also reads a+ word longer than 256 characters in pieces and stops at the subword+ budget.+ """+ self._words = WindowedSplitter(+ _words,+ max_words=max_words,+ max_subwords=subword_budget(max_words, encoder_config, per_word=_SUBWORDS_PER_WORD),+ count_subwords=SubwordCounter(split_word_counter(tokenizer)),+ )+def extract(self,items: list[Item],@@ -149,14 +178,15 @@ class GLiRELAdapter(BaseAdapter):Raises:RuntimeError: If model not loaded.ValueError: If labels not provided or items lack entities.+ InvalidInputError: If an entity is not an object or has invalid offsets."""self._check_loaded()if not labels:raise ValueError(_ERR_REQUIRES_LABELS)- all_entities = []- all_relations = []+ # Check every item's entities before running any item.+ inputs: list[tuple[str, list[dict[str, Any]]]] = []for item in items:text = self._extract_text(item)entities = self._extract_entities(item)@@ -164,8 +194,17 @@ class GLiRELAdapter(BaseAdapter):if not entities:raise ValueError(_ERR_REQUIRES_ENTITIES)- tokens, token_offsets = self._tokenize(text)- ner_input = self._to_glirel_ner(entities, token_offsets)+ for entity in entities:+ self._validate_entity_span(entity, text)+ inputs.append((text, entities))++ all_entities = []+ all_relations = []+ for text, entities in inputs:+ tokens, token_offsets, read_end = self._tokenize(text)+ # Entities past the words GLiREL reads take no part, as when it truncates them itself.+ read_entities = [entity for entity in entities if self._is_read(entity, text, read_end)]+ ner_input = self._to_glirel_ner(read_entities, token_offsets)# Get options with fallback to model defaultsopts = options or {}@@ -173,20 +212,22 @@ class GLiRELAdapter(BaseAdapter):effective_top_k = opts.get("top_k", 10)# GLiREL expects pre-tokenized text and inclusive token offsets.- with torch.inference_mode():- raw_relations = self._model.predict_relations(- text=tokens,- labels=labels,- threshold=effective_threshold,- ner=ner_input,- top_k=effective_top_k,- )+ raw_relations = []+ if ner_input:+ with torch.inference_mode():+ raw_relations = self._model.predict_relations(+ text=tokens,+ labels=labels,+ threshold=effective_threshold,+ ner=ner_input,+ top_k=effective_top_k,+ )# Convert to proper Relation objectsitem_relations = []for rel in raw_relations:- head_text = self._relation_entity_text(rel, "head", entities, ner_input)- tail_text = self._relation_entity_text(rel, "tail", entities, ner_input)+ head_text = self._relation_entity_text(rel, "head", read_entities, ner_input)+ tail_text = self._relation_entity_text(rel, "tail", read_entities, ner_input)item_relations.append(Relation(@@ -228,11 +269,58 @@ class GLiRELAdapter(BaseAdapter):return []return metadata.get("entities", [])+ def _tokenize(self, text: str) -> tuple[list[str], list[tuple[int, int]], int]:+ """Tokenize text like GLiREL, keeping the words it reads: ``(words, offsets, end of the text read)``.++ Once loaded, the words are the bounded window of ``_bound_words``;+ before that, every word of the text.+ """+ if self._words is None:+ words, read_end = list(_words(text)), len(text)+ else:+ window = self._words.window(text)+ words = window.words+ read_end = len(text) if window.cut is None else words[-1][2]+ return [word for word, _, _ in words], [(start, end) for _, start, end in words], read_end++ @staticmethod+ def _validate_entity_span(entity: Any, text: str) -> None:+ """Check an entity's character offsets wherever it lies in the text.++ Raises:+ InvalidInputError: The entity is not an object, its offsets are not+ integers with ``0 <= start < end <= len(text)``, or they cover no+ text token.+ """+ if not isinstance(entity, dict):+ raise InvalidInputError("GLiREL entities must be objects")+ start = entity.get("start")+ end = entity.get("end")+ if (+ not isinstance(start, int)+ or isinstance(start, bool)+ or not isinstance(end, int)+ or isinstance(end, bool)+ or not 0 <= start < end <= len(text)+ ):+ msg = (+ "GLiREL entity metadata requires integer character offsets with "+ f"0 <= start < end <= {len(text)} (the text's length)"+ )+ raise InvalidInputError(msg)+ # Every non-space character is part of a GLiREL token.+ if not text[start:end].strip():+ msg = f"GLiREL entity span [{start}, {end}) does not cover any text token"+ raise InvalidInputError(msg)+@staticmethod- def _tokenize(text: str) -> tuple[list[str], list[tuple[int, int]]]:- """Tokenize text exactly like GLiREL and retain character offsets."""- matches = list(_TOKEN_PATTERN.finditer(text))- return [match.group() for match in matches], [(match.start(), match.end()) for match in matches]+ def _is_read(entity: dict[str, Any], text: str, read_end: int) -> bool:+ """Whether an entity lies in the text GLiREL reads (anything past it but spaces counts against it)."""+ start = entity["start"]+ end = entity["end"]+ if end <= read_end:+ return True+ return start < read_end and not text[read_end:end].strip()@staticmethoddef _to_glirel_ner(@@ -246,7 +334,7 @@ class GLiRELAdapter(BaseAdapter):end_char = entity.get("end")if not isinstance(start_char, int) or not isinstance(end_char, int) or start_char >= end_char:msg = "GLiREL entity metadata requires integer character offsets with start < end"- raise ValueError(msg)+ raise InvalidInputError(msg)covered_tokens = [index@@ -255,7 +343,7 @@ class GLiRELAdapter(BaseAdapter):]if not covered_tokens:msg = f"GLiREL entity span [{start_char}, {end_char}) does not cover any text token"- raise ValueError(msg)+ raise InvalidInputError(msg)ner_input.append([@@ -286,3 +374,9 @@ class GLiRELAdapter(BaseAdapter):relation_text = " ".join(str(token) for token in relation_text)relation_text = re.sub(r"\s+([,.;:!?%])", r"\1", relation_text)return str(relation_text)+++def _words(text: str) -> Iterator[tuple[str, int, int]]:+ """GLiREL's words of ``text`` with their character offsets."""+ for match in _TOKEN_PATTERN.finditer(text):+ yield match.group(), match.start(), match.end()diff --git a/packages/sie_server/tests/adapters/test_gliner2.py b/packages/sie_server/tests/adapters/test_gliner2.pyindex 5df300f8f..054a9cfea 100644--- a/packages/sie_server/tests/adapters/test_gliner2.py+++ b/packages/sie_server/tests/adapters/test_gliner2.py@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patchimport pytestimport yaml+from sie_server.adapters._word_window import WindowedSplitterfrom sie_server.adapters.gliner2.adapter import GLiNER2Adapterfrom sie_server.adapters.gliner2.classification import GLiNER2ClassificationAdapterfrom sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitter@@ -285,8 +286,10 @@ 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+ splitter = model.processor.word_splitter+ assert isinstance(splitter, WindowedSplitter)+ assert isinstance(splitter.splitter, LinearWordSplitter)+ assert splitter.splitter.lower_text_firstdef 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.pyindex 7ffa04f1d..3a5e0b3ec 100644--- a/packages/sie_server/tests/adapters/test_gliner2_long_text.py+++ b/packages/sie_server/tests/adapters/test_gliner2_long_text.py@@ -1,10 +1,13 @@"""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.+takes quadratic time on runs like ``"...."``, keeps the first ``max_len``+words, and encodes every subword of each. The adapter splits in linear time,+reads a word longer than 256 characters in pieces, stops at the subword budget,+and hands gliner2 only the prefix holding the words it reads. These tests use+gliner2's real processor with a stand-in tokenizer: the prefix must give+gliner2 exactly the input the whole text gives, ordinary text the input+gliner2's own splitter gives, and no text more subwords than the budget."""from __future__ import annotations@@ -17,7 +20,8 @@ from typing import Anyfrom unittest.mock import MagicMockimport pytest-from sie_server.adapters.gliner2.adapter import GLiNER2Adapter+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, GLiNER2Adapterfrom sie_server.adapters.gliner2.classification import GLiNER2ClassificationAdapterfrom sie_server.adapters.gliner2.words import PACKAGE_PATTERN, LinearWordSplitterfrom sie_server.types.inputs import Item@@ -100,11 +104,31 @@ class PackageModel: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 batch_extract_relations(+ self, texts: list[str], labels: list[str], *, max_len: int | None, **_: Any+ ) -> list[Any]:+ self._collate(texts, gliner2_engine.Schema().relations(labels), max_len)+ return [{"relation_extraction": {}} for _ in texts]-def make_adapter(cls: type[GLiNER2Adapter] = GLiNER2Adapter, **kwargs: Any) -> tuple[GLiNER2Adapter, PackageModel]:+ def batch_extract_json(+ self, texts: list[str], structures: dict[str, list[str]], *, max_len: int | None, **_: Any+ ) -> list[Any]:+ schema = gliner2_engine.Schema()+ for parent, fields in structures.items():+ builder = schema.structure(parent)+ for spec in fields:+ name, dtype, choices, description = gliner2_engine.GLiNER2._parse_field_spec(None, spec)+ builder.field(name, dtype=dtype, choices=choices, description=description)+ self._collate(texts, schema, max_len)+ return [{} for _ in texts]+++def make_adapter(+ cls: type[GLiNER2Adapter] = GLiNER2Adapter, *, encoder_config: Any = None, **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._use_linear_word_splitter(model.processor, encoder_config)adapter._model = modelreturn adapter, model@@ -126,11 +150,10 @@ LONG_TEXTS = ["\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,+ "a b c d e f see http://example.com/a?b=c " * 30,"www.example.org\tthen text\n" * 60,]LONG_TEXT_IDS = [@@ -140,7 +163,6 @@ LONG_TEXT_IDS = ["final-sigma","sigma-apostrophes","email-url",- "long-word","spaced-dots","dots","a-dots",@@ -163,6 +185,27 @@ class Gliner2V2Splitter:Gliner2V2Splitter.__name__ = "WhitespaceTokenSplitter"+# Texts with words longer than the window reads whole, or more subwords than it allows.+LONG_WORD_TEXTS = [+ "x" * 5000 + " tail words here",+ "Priya Raman " + "ab" * 3000 + " works at Novartis.",+ ("q" * 300 + " ") * 40,+ "k" * MAX_WORD_CHARS + " " + "k" * (MAX_WORD_CHARS + 1) + " end",+ "\u0130" * 300 + " stanbul",+ "see https://example.com/" + "p" * 600 + " and more",+ "mail " + "a." * 400 + "@example.com today",+]+LONG_WORD_IDS = [+ "long-word",+ "run-in-prose",+ "spaced-long-words",+ "at-the-piece-size",+ "dotted-capital-i",+ "url",+ "email",+]++@pytest.mark.parametrize("splitting", ["gliner2-1.x", "gliner2-2.x"])@pytest.mark.parametrize("max_len", [7, 64])@pytest.mark.parametrize("text", LONG_TEXTS, ids=LONG_TEXT_IDS)@@ -181,6 +224,190 @@ def test_the_prefix_gives_gliner2_the_same_input_as_the_whole_text(text: str, maassert collated(processor, text, max_len) == reference # and the linear splitter on the whole text[email protected]("splitting", ["gliner2-1.x", "gliner2-2.x"])[email protected]("max_len", [7, 64])[email protected]("text", LONG_WORD_TEXTS, ids=LONG_WORD_IDS)+def test_long_words_are_read_in_pieces_within_the_subword_budget(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()+ adapter._use_linear_word_splitter(processor)++ prefix = adapter._model_text(text)+ whole = collated(processor, text, max_len)++ assert text.startswith(prefix)+ assert collated(processor, prefix, max_len) == whole+ _, (words,), (starts,), (ends,) = whole+ subwords = [len(processor.tokenizer.tokenize(word)) for word in words]+ assert len(words) <= max_len+ assert (+ sum(subwords) <= subword_budget(max_len, per_word=_SUBWORDS_PER_WORD) or len(words) == 1+ ) # the first word is always read+ source = text.lower() if splitting == "gliner2-1.x" else text # what gliner2's offsets index+ for word, start, end in zip(words, starts, ends, strict=True):+ assert end - start <= MAX_WORD_CHARS+ if end <= len(source): # not the "." gliner2 appends+ assert word == source[start:end].lower()+++def test_a_long_word_is_read_in_consecutive_pieces() -> None:+ text = "ID " + "a1b2" * 200 + " belongs to Priya"+ adapter, model = make_adapter()++ adapter.extract([Item(text=text)], labels=["person"])++ batch = model.inputs[-1]+ assert batch.start_mappings[0][:6] == [0, 3, 259, 515, 771, 804]+ assert batch.end_mappings[0][:6] == [2, 259, 515, 771, 803, 811]+ assert "".join(batch.text_tokens[0][1:5]) == "a1b2" * 200+++def test_an_entity_in_a_long_word_keeps_its_offsets() -> None:+ text = "ID " + "a1b2" * 200 + " belongs to Priya"+ adapter, model = make_adapter()+ extract_entities = model.extract_entities++ def found_in_second_piece(text: str, labels: list[str], **kwargs: Any) -> dict[str, Any]:+ extract_entities(text, labels, **kwargs)+ batch = model.inputs[-1]+ start, end = batch.start_mappings[0][2], batch.end_mappings[0][2]+ return {"entities": {"id": [{"text": text[start:end], "start": start, "end": end, "confidence": 0.9}]}}++ model.extract_entities = found_in_second_piece # type: ignore[method-assign]+ output = adapter.extract([Item(text=text)], labels=["id"])++ assert output.entities == [[{"text": text[259:515], "label": "id", "score": 0.9, "start": 259, "end": 515}]]+++PATHOLOGICAL_WORDS = [+ "x" * (2 * MiB),+ "\u00e9" * MiB,+ "Priya Raman works at Novartis. " + "7" * (2 * MiB - 40),+ ("b" * 200 + " ") * (2 * MiB // 201),+ "\u8bf7\u5e2e\u6211\u53d6\u6d88\u8ba2\u5355" * (MiB // 7),+]+PATHOLOGICAL_WORD_IDS = ["letters", "accents", "digits-after-prose", "spaced-long-words", "cjk-run"]++[email protected]("cls", [GLiNER2Adapter, GLiNER2ClassificationAdapter])[email protected]("text", PATHOLOGICAL_WORDS, ids=PATHOLOGICAL_WORD_IDS)+def test_long_words_keep_the_encoder_input_within_the_subword_budget(cls: type[GLiNER2Adapter], text: str) -> None:+ adapter, model = make_adapter(cls, classification_task="prompt_safety", default_labels=["safe", "unsafe"])+ tokenize = model.processor.tokenizer.tokenize+ 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++ budget = subword_budget(512, per_word=_SUBWORDS_PER_WORD)+ rows = [+ (words, starts, ends)+ for batch in model.inputs+ for words, starts, ends in zip(batch.text_tokens, batch.start_mappings, batch.end_mappings, strict=True)+ ]+ assert len(rows) == 3+ for words, starts, ends in rows:+ assert sum(len(tokenize(word)) for word in words) <= budget+ assert all(end - start <= MAX_WORD_CHARS for start, end in zip(starts, ends, strict=True))+ assert all(batch.input_ids.shape[1] <= budget + 64 for batch in model.inputs) # the task prompt and specials+ assert ["priya", "raman", "works", "at", "novartis", "."] in [words for words, _, _ in rows]+ # Billing is unchanged: the document tokens up to max_seq_length.+ assert output.input_token_counts == [512]+ assert entities.input_token_counts is not None+ assert entities.input_token_counts[0] == 512+ assert classify_seconds < 1.0+ assert extract_seconds < 1.0+++def test_a_batch_of_long_rows_runs_in_passes_within_the_attention_budget() -> None:+ adapter, model = make_adapter(encoder_config={"model_type": "deberta-v2"})+ texts = [("w" * 200 + " ") * 400 for _ in range(6)] + ["Priya Raman works at Novartis"] * 6++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert len(output.entities) == len(texts)+ assert len(model.inputs) > 1+ for batch in model.inputs:+ rows, width = batch.input_ids.shape+ assert rows == 1 or rows * width**2 <= ATTENTION_BUDGET+ # The short rows run together, apart from the long ones.+ assert any(batch.input_ids.shape[0] == 6 and batch.input_ids.shape[1] < 64 for batch in model.inputs)+++def test_an_ordinary_batch_runs_in_one_pass() -> None:+ adapter, model = make_adapter(encoder_config={"model_type": "deberta-v2"})+ texts = [" ".join(f"Sentence {i} mentions Dr. Priya Raman of Novartis." for i in range(60))] * 8++ adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert len(model.inputs) == 1+ assert model.inputs[0].input_ids.shape[0] == 8++[email protected]("splitting", ["gliner2-1.x", "gliner2-2.x"])+ ("text", "max_len"),+ [+ (" ".join(["w"] * 510) + " http://", 512),+ ("\u0130 " + " ".join(["w"] * 507) + " see https:// more words here", 512),+ ("\u0130com https:// tail words", 6),+ ],+ ids=["url-without-sentence-end", "dotted-capital-i-then-url", "dotted-capital-i-short"],+)+def test_the_prefix_reads_what_gliner2_reads_with_its_sentence_end(text: str, max_len: int, splitting: str) -> None:+ # gliner2 appends "." to a text without a sentence end, and a URL word absorbs it.+ adapter = GLiNER2Adapter("fake/gliner2", max_seq_length=max_len)+ processor = make_processor()+ if splitting == "gliner2-2.x":+ processor.word_splitter = Gliner2V2Splitter()+ adapter._use_linear_word_splitter(processor)++ prefix = adapter._model_text(text)++ assert collated(processor, prefix, max_len) == collated(processor, text, max_len)+++def test_relation_rows_run_in_passes_within_the_attention_budget() -> None:+ # gliner2 builds a structure of about ten tokens around each relation type.+ adapter, model = make_adapter(encoder_config={"model_type": "deberta-v2"})+ labels = [f"rel{index}" for index in range(150)]+ text = " ".join(["abcdefghi"] * 400)+ entities = [{"text": "abcdefghi", "label": "x", "start": 0, "end": 9}]++ adapter.extract([Item(text=text, metadata={"entities": entities}) for _ in range(8)], labels=labels)++ estimated = adapter._row_tokens([adapter._window(text)] * 1, labels, per_entry=_PROMPT_TOKENS_PER_RELATION)+ assert estimated is not None+ for batch in model.inputs:+ rows, width = batch.input_ids.shape+ assert width <= estimated[0]+ assert rows == 1 or rows * width**2 <= ATTENTION_BUDGET+++def test_structured_rows_are_not_underestimated() -> None:+ adapter, model = make_adapter(encoder_config={"model_type": "deberta-v2"})+ schema = {+ "type": "object",+ "properties": {+ f"field{index}": {"type": "string", "enum": [f"choice{index}{option}" for option in "abcdef"]}+ for index in range(40)+ },+ }+ text = " ".join(["abcdefghi"] * 400)++ adapter.extract([Item(text=text)], output_schema=schema)++ structures = adapter._json_schema_to_structures(schema)+ specs = [spec for fields in structures.values() for spec in fields]+ estimated = adapter._row_tokens([adapter._window(text)], specs + specs)+ assert estimated is not None+ assert model.inputs[-1].input_ids.shape[1] <= estimated[0]++@pytest.mark.parametrize("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.@@ -246,7 +473,11 @@ def test_load_refuses_a_word_splitter_it_has_no_equivalent_for() -> None:GLiNER2Adapter("fake/gliner2")._use_linear_word_splitter(processor)-def test_the_processor_gets_the_linear_splitter() -> None:+def test_the_processor_gets_the_bounded_linear_splitter() -> None:_, model = make_adapter()- assert isinstance(model.processor.word_splitter, LinearWordSplitter)- assert model.processor.word_splitter.lower_text_first+ splitter = model.processor.word_splitter+ assert isinstance(splitter, WindowedSplitter)+ assert isinstance(splitter.splitter, LinearWordSplitter)+ assert splitter.splitter.lower_text_first+ assert splitter.max_words == 512+ assert splitter.max_subwords == subword_budget(512, per_word=_SUBWORDS_PER_WORD)diff --git a/packages/sie_server/tests/adapters/test_gliner_long_words.py b/packages/sie_server/tests/adapters/test_gliner_long_words.pynew file mode 100644index 000000000..11a01db86--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliner_long_words.py@@ -0,0 +1,371 @@+"""Long words in the GLiNER, GLiNER bi-encoder and GLiREL adapters.++These models keep a document's first ``max_len`` words and encode every+subword of each, so one long unbroken run made the encoder input unbounded.+The adapters now read words through ``_word_window``. These tests use gliner's+real processor with an in-memory tokenizer that gives one subword per+character, as DeBERTa tokenizers split a run of accented letters.+"""++from __future__ import annotations++import sys+import time+from types import ModuleType+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+from sie_server.adapters._word_window import (+ ATTENTION_BUDGET,+ MAX_WORD_CHARS,+ WindowedSplitter,+ subword_budget,+)+from sie_server.adapters.gliner import GLiNERAdapter+from sie_server.adapters.gliner_bi import GLiNERBiAdapter+from sie_server.adapters.glirel import _SUBWORDS_PER_WORD as GLIREL_SUBWORDS_PER_WORD+from sie_server.adapters.glirel import GLiRELAdapter+from sie_server.types.inputs import InvalidInputError, Item++gliner_config = pytest.importorskip("gliner.config")+gliner_processor = pytest.importorskip("gliner.data_processing.processor")+gliner_model = pytest.importorskip("gliner.model")+tokenizers = pytest.importorskip("tokenizers")+transformers = pytest.importorskip("transformers")++MiB = 1024 * 1024+MAX_LEN = 64+DEBERTA = {"model_type": "deberta-v2"}+MODERNBERT = {"model_type": "modernbert"}+BERT = {"model_type": "bert", "max_position_embeddings": 512}+++def char_tokenizer() -> Any:+ """A fast tokenizer that encodes each character of a word as one subword."""+ specials = ["[PAD]", "[UNK]", "[CLS]", "[SEP]"]+ vocab = {token: index for index, token in enumerate(specials)}+ for char in "abcdefghijklmnopqrstuvwxyz0123456789.,;:!?-_'\"()@/":+ vocab.setdefault(char, len(vocab))+ unknown, padding, first, last = "[UNK]", "[PAD]", "[CLS]", "[SEP]"+ backend = tokenizers.Tokenizer(tokenizers.models.WordLevel(vocab, unk_token=unknown))+ backend.pre_tokenizer = tokenizers.pre_tokenizers.Sequence(+ [+ tokenizers.pre_tokenizers.WhitespaceSplit(),+ tokenizers.pre_tokenizers.Split(tokenizers.Regex("."), "isolated"),+ ]+ )+ backend.post_processor = tokenizers.processors.TemplateProcessing(+ single="[CLS] $A [SEP]", special_tokens=[("[CLS]", 2), ("[SEP]", 3)]+ )+ tokenizer = transformers.PreTrainedTokenizerFast(+ tokenizer_object=backend, unk_token=unknown, pad_token=padding, cls_token=first, sep_token=last+ )+ tokenizer.add_special_tokens({"additional_special_tokens": ["<<ENT>>", "<<SEP>>"]})+ return tokenizer+++class FakeGLiNER:+ """gliner's preprocessing (word splitting, truncation, prompt, tokenization) around a stand-in encoder."""++ prepare_inputs = gliner_model.BaseEncoderGLiNER.prepare_inputs+ prepare_base_input = gliner_model.BaseEncoderGLiNER.prepare_base_input++ def __init__(+ self, encoder_config: dict[str, Any] | None, *, bi_encoder: bool = False, max_len: int = MAX_LEN+ ) -> None:+ self.config = gliner_config.GLiNERConfig(+ model_name="fake", max_len=max_len, encoder_config=dict(encoder_config) if encoder_config else None+ )+ self.config.relations_layer = None+ if bi_encoder:+ self.data_processor = gliner_processor.BiEncoderSpanProcessor(+ self.config, char_tokenizer(), None, char_tokenizer()+ )+ else:+ self.data_processor = gliner_processor.UniEncoderSpanProcessor(self.config, char_tokenizer(), None)+ self.calls: list[list[str]] = []++ def to(self, *args: Any, **kwargs: Any) -> FakeGLiNER:+ return self++ def inference(self, texts: list[str], labels: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]:+ self.calls.append(list(texts))+ return [[] for _ in texts]++ def encode_labels(self, labels: list[str], batch_size: int = 8) -> Any:+ return object()++ def batch_predict_with_embeds(self, texts: list[str], *args: Any, **kwargs: Any) -> list[list[dict[str, Any]]]:+ return self.inference(texts, [])+++def load(adapter_class: type[Any], model: FakeGLiNER) -> Any:+ module = ModuleType("gliner")+ module.GLiNER = MagicMock() # ty:ignore[unresolved-attribute]+ module.GLiNER.from_pretrained.return_value = model # ty:ignore[unresolved-attribute]+ adapter = adapter_class("fake/gliner")+ with patch.dict(sys.modules, {"gliner": module}):+ adapter.load("cpu")+ return adapter+++def encoded(model: FakeGLiNER, texts: list[str], labels: list[str]) -> list[list[int]]:+ """The token ids gliner would give the encoder: the label prompt, then the document."""+ split, _, _ = model.prepare_inputs(texts)+ batch = model.data_processor.collate_raw_batch(model.prepare_base_input(split), entity_types=labels)+ encoding = model.data_processor.tokenize_inputs(batch["tokens"], batch["classes_to_id"])+ return encoding["input_ids"].tolist()+++def encoded_rows(model: FakeGLiNER, texts: list[str], labels: list[str]) -> list[int]:+ """Tokens of each row gliner would give the encoder: the label prompt, then the document."""+ split, _, _ = model.prepare_inputs(texts)+ batch = model.data_processor.collate_raw_batch(model.prepare_base_input(split), entity_types=labels)+ encoded = model.data_processor.tokenize_inputs(batch["tokens"], batch["classes_to_id"])+ return [int(sum(mask)) for mask in encoded["attention_mask"].tolist()]+++ORDINARY = [+ "Priya Raman works at Novartis in Basel.",+ " ".join(f"Sentence {i} mentions Dr. Priya Raman of Novartis." for i in range(20)),+ "mail [email protected], see https://example.com/x?y=z and @team; " * 10,+ "\u8bf7\u5e2e\u6211\u53d6\u6d88\u8ba2\u5355\uff0c\u6211\u4e0d\u60f3\u8981\u4e86\u3002" * 20,+]+LONG = [+ "x" * (2 * MiB),+ "\u00e9" * MiB,+ "Priya Raman works at Novartis. " + "7" * MiB,+ ("b" * 200 + " ") * 5000,+]+LONG_IDS = ["letters", "accents", "digits-after-prose", "spaced-long-words"]++[email protected]("text", ORDINARY, ids=["short", "prose", "email-url", "cjk"])+def test_gliner_reads_ordinary_text_as_before(text: str) -> None:+ reference_model = FakeGLiNER(DEBERTA) # gliner's own word splitter+ reference_adapter = GLiNERAdapter("fake/gliner")+ reference_adapter._model = reference_model+ reference_counts = reference_adapter._doc_input_token_counts([text], ["person"])+ model = FakeGLiNER(DEBERTA)+ adapter = load(GLiNERAdapter, model)++ output = adapter.extract([Item(text=text)], labels=["person"])++ assert encoded(model, [text], ["person"]) == encoded(reference_model, [text], ["person"])+ assert output.input_token_counts == reference_counts+ assert model.calls == [[text]]++[email protected]("encoder_config", [DEBERTA, MODERNBERT], ids=["deberta", "modernbert"])[email protected]("text", LONG, ids=LONG_IDS)+def test_gliner_reads_long_words_within_the_subword_budget(text: str, encoder_config: dict[str, Any]) -> None:+ model = FakeGLiNER(encoder_config)+ adapter = load(GLiNERAdapter, model)+ budget = subword_budget(MAX_LEN, encoder_config)++ started = time.perf_counter()+ output = adapter.extract([Item(text=text), Item(text="Priya Raman works at Novartis.")], labels=["person"])+ seconds = time.perf_counter() - started++ (split,), starts, ends = model.prepare_inputs([text])+ assert isinstance(model.data_processor.words_splitter, WindowedSplitter)+ assert all(end - start <= MAX_WORD_CHARS for start, end in zip(starts[0], ends[0], strict=True))+ assert sum(len(word) for word in split) <= budget+ # The meter counts the document subwords gliner encodes (with [CLS] and [SEP]).+ assert output.input_token_counts == [sum(len(word) for word in split) + 2, 28]+ assert max(encoded_rows(model, [text], ["person"])) <= budget + 16+ assert seconds < 2.0+++def test_gliner_plans_forward_passes_for_long_rows_on_deberta() -> None:+ model = FakeGLiNER(DEBERTA, max_len=512)+ adapter = load(GLiNERAdapter, model)+ long_text = ("w" * 200 + " ") * 40+ texts = [long_text] * 8 + ["Priya Raman works at Novartis."] * 4+ rows = encoded_rows(model, texts, ["person"])++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert len(output.entities) == len(texts)+ assert sorted(text for call in model.calls for text in call) == sorted(texts)+ assert len(model.calls) > 2+ for call in model.calls:+ longest = max(rows[texts.index(text)] for text in call)+ assert len(call) <= 8+ assert len(call) == 1 or len(call) * longest**2 <= ATTENTION_BUDGET+++def test_gliner_keeps_one_call_for_long_rows_on_other_encoders() -> None:+ model = FakeGLiNER(MODERNBERT, max_len=512)+ adapter = load(GLiNERAdapter, model)+ texts = [("w" * 200 + " ") * 40] * 8++ adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert model.calls == [texts]+++def test_gliner_caps_an_absolute_position_encoder_at_its_position_table() -> None:+ model = FakeGLiNER(BERT)+ adapter = load(GLiNERAdapter, model)+ text = " ".join(["supercalifragilistic"] * MAX_LEN)++ output = adapter.extract([Item(text=text)], labels=["person"])++ assert model.data_processor.transformer_tokenizer.model_max_length == 512+ assert output.input_token_counts is not None+ assert output.input_token_counts[0] <= subword_budget(MAX_LEN, BERT) + 2+ assert max(encoded_rows(model, [text] * 2, ["person"] * 200)) <= 512++[email protected]("text", LONG, ids=LONG_IDS)+def test_gliner_bi_encoder_reads_long_words_within_the_subword_budget(text: str) -> None:+ model = FakeGLiNER(DEBERTA, bi_encoder=True)+ adapter = load(GLiNERBiAdapter, model)++ output = adapter.extract([Item(text=text), Item(text="Priya Raman works at Novartis.")], labels=["person"])++ (split,), _, _ = model.prepare_inputs([text])+ assert sum(len(word) for word in split) <= subword_budget(MAX_LEN, DEBERTA)+ assert output.input_token_counts is not None+ assert output.input_token_counts[1] == 28+++def test_gliner_bi_encoder_plans_forward_passes_for_long_rows_on_deberta() -> None:+ model = FakeGLiNER(DEBERTA, bi_encoder=True, max_len=512)+ adapter = load(GLiNERBiAdapter, model)+ texts = [("w" * 200 + " ") * 40] * 8 + ["Priya Raman works at Novartis."] * 4++ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])++ assert len(output.entities) == len(texts)+ assert len(model.calls) > 2+ assert sorted(text for call in model.calls for text in call) == sorted(texts)+++def glirel_adapter(max_words: int = MAX_LEN) -> tuple[GLiRELAdapter, MagicMock]:+ adapter = GLiRELAdapter("fake/glirel")+ adapter._model = MagicMock()+ adapter._model.predict_relations.return_value = []+ adapter._bound_words(char_tokenizer(), max_words, DEBERTA)+ return adapter, adapter._model.predict_relations+++def test_glirel_reads_long_words_within_the_subword_budget() -> None:+ adapter, predict = glirel_adapter()+ text = "Tim Cook leads Apple. " + "z" * MiB + " Later text."+ entities = [+ {"text": "Tim Cook", "label": "PERSON", "start": 0, "end": 8},+ {"text": "Apple", "label": "ORG", "start": 15, "end": 20},+ ]++ adapter.extract([Item(text=text, metadata={"entities": entities})], labels=["ceo_of"])++ tokens = predict.call_args.kwargs["text"]+ assert tokens[:5] == ["Tim", "Cook", "leads", "Apple", "."]+ assert all(len(token) <= MAX_WORD_CHARS for token in tokens)+ assert sum(len(token) for token in tokens) <= subword_budget(MAX_LEN, DEBERTA, per_word=GLIREL_SUBWORDS_PER_WORD)+ assert predict.call_args.kwargs["ner"] == [[0, 1, "PERSON", "Tim Cook"], [3, 3, "ORG", "Apple"]]+++def test_glirel_leaves_out_entities_past_the_words_it_reads() -> None:+ adapter, predict = glirel_adapter(max_words=4)+ text = "Tim Cook led Apple and then Microsoft hires Satya"+ entities = [+ {"text": "Tim Cook", "label": "PERSON", "start": 0, "end": 8},+ {"text": "Apple", "label": "ORG", "start": 13, "end": 18},+ {"text": "Microsoft", "label": "ORG", "start": 28, "end": 37},+ ]+ predict.return_value = [+ {+ "head_pos": [0, 2],+ "tail_pos": [3, 4],+ "head_text": ["Tim", "Cook"],+ "tail_text": ["Apple"],+ "label": "ceo_of",+ "score": 0.9,+ }+ ]++ output = adapter.extract([Item(text=text, metadata={"entities": entities})], labels=["ceo_of"])++ assert predict.call_args.kwargs["text"] == ["Tim", "Cook", "led", "Apple"]+ assert predict.call_args.kwargs["ner"] == [[0, 1, "PERSON", "Tim Cook"], [3, 3, "ORG", "Apple"]]+ assert output.relations == [[{"head": "Tim Cook", "tail": "Apple", "relation": "ceo_of", "score": 0.9}]]+ assert [entity["text"] for entity in output.entities[0]] == ["Tim Cook", "Apple", "Microsoft"]+++def test_glirel_skips_the_model_when_no_entity_is_read() -> None:+ adapter, predict = glirel_adapter(max_words=2)+ text = "Some words first, then Microsoft hires Satya"+ entities = [+ {"text": "Microsoft", "label": "ORG", "start": 23, "end": 32},+ {"text": "Satya", "label": "PERSON", "start": 39, "end": 44},+ ]++ output = adapter.extract([Item(text=text, metadata={"entities": entities})], labels=["ceo_of"])++ predict.assert_not_called()+ assert output.relations == [[]]+++def test_glirel_still_rejects_invalid_entity_offsets_past_the_words_it_reads() -> None:+ adapter, predict = glirel_adapter(max_words=2)+ text = "Tim Cook leads Apple"++ with pytest.raises(InvalidInputError, match="0 <= start < end"):+ adapter.extract(+ [Item(text=text, metadata={"entities": [{"text": "x", "label": "ORG", "start": 500, "end": 505}]})],+ labels=["ceo_of"],+ )+ with pytest.raises(InvalidInputError, match="does not cover any text token"):+ adapter.extract(+ [Item(text=text + " ", metadata={"entities": [{"text": " ", "label": "ORG", "start": 21, "end": 23}]})],+ labels=["ceo_of"],+ )+ predict.assert_not_called()+++def test_glirel_load_reads_through_the_bounded_window() -> None:+ model = MagicMock()+ model.to.return_value = model+ model.base_config.max_len = 512+ model.token_rep_layer.bert_layer.tokenizer = char_tokenizer()+ model.token_rep_layer.bert_layer.model.config = DEBERTA+ module = ModuleType("glirel")+ module.GLiREL = MagicMock() # ty:ignore[unresolved-attribute]+ module.GLiREL.from_pretrained.return_value = model # ty:ignore[unresolved-attribute]+ adapter = GLiRELAdapter("fake/glirel")++ with patch.dict(sys.modules, {"glirel": module}):+ adapter.load("cpu")++ assert adapter._words is not None+ assert adapter._words.max_words == 512+ assert adapter._words.max_subwords == subword_budget(512, DEBERTA, per_word=GLIREL_SUBWORDS_PER_WORD)+ tokens, _, _ = adapter._tokenize("Tim Cook " + "z" * MiB)+ assert sum(len(token) for token in tokens) <= adapter._words.max_subwords+++ ("start", "end"),+ [(0, 500), (-3, 4), (5, 2), (4, 4), (False, True), (0, True), ("0", 3), (0, 3.0)],+ ids=["past-the-end", "negative", "reversed", "empty", "booleans", "boolean-end", "string", "float"],+)+def test_glirel_rejects_invalid_entity_offsets_as_invalid_input(start: Any, end: Any) -> None:+ adapter, predict = glirel_adapter()+ good = Item(text="Tim Cook", metadata={"entities": [{"text": "Tim", "label": "PERSON", "start": 0, "end": 3}]})+ bad = Item(text="Tim Cook", metadata={"entities": [{"text": "Tim", "label": "PERSON", "start": start, "end": end}]})++ with pytest.raises(InvalidInputError, match="0 <= start < end <= 8"):+ adapter.extract([good, bad], labels=["ceo_of"])+ predict.assert_not_called()+++def test_glirel_rejects_an_entity_that_is_not_an_object() -> None:+ adapter, predict = glirel_adapter()++ with pytest.raises(InvalidInputError, match="must be objects"):+ adapter.extract([Item(text="Tim Cook", metadata={"entities": ["Tim"]})], labels=["ceo_of"])+ predict.assert_not_called()diff --git a/packages/sie_server/tests/adapters/test_word_window.py b/packages/sie_server/tests/adapters/test_word_window.pynew file mode 100644index 000000000..f411fa0ff--- /dev/null+++ b/packages/sie_server/tests/adapters/test_word_window.py@@ -0,0 +1,218 @@+"""The bounded word window GLiNER-family adapters read documents through."""++from __future__ import annotations++import re+from collections.abc import Iterator, Sequence+from typing import Any++import pytest+from sie_server.adapters._word_window import (+ ATTENTION_BUDGET,+ DEBERTA_MAX_DOCUMENT_SUBWORDS,+ MAX_DOCUMENT_SUBWORDS,+ MAX_WORD_CHARS,+ SUBWORDS_PER_WORD,+ SubwordCounter,+ WindowedSplitter,+ pieces,+ plan_forwards,+ read_window,+ split_word_counter,+ subword_budget,+)++_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")+++def words(text: str) -> Iterator[tuple[str, int, int]]:+ for match in _WORD.finditer(text):+ yield match.group(), match.start(), match.end()+++def per_char(batch: Sequence[str]) -> list[int]:+ """One subword per character, as DeBERTa tokenizers split a run of accented letters."""+ return [len(word) for word in batch]+++def window(text: str, *, max_words: int = 100, max_subwords: int = 1000) -> Any:+ return read_window(text, words(text), max_words=max_words, max_subwords=max_subwords, count_subwords=per_char)+++def test_short_words_pass_through() -> None:+ result = window("Priya Raman works at Novartis.")++ assert [word for word, _, _ in result.words] == ["Priya", "Raman", "works", "at", "Novartis", "."]+ assert result.subwords == 26+ assert result.cut is None+++def test_a_long_word_is_read_in_pieces_with_their_own_offsets() -> None:+ text = "id " + "x" * (2 * MAX_WORD_CHARS + 10) + " end"++ result = window(text, max_subwords=10_000)++ spans = [(start, end) for _, start, end in result.words]+ assert spans == [(0, 2), (3, 259), (259, 515), (515, 525), (526, 529)]+ assert all(word == text[start:end] for word, start, end in result.words)+ assert result.cut is None+++def test_reading_stops_before_the_word_that_passes_the_budget() -> None:+ text = "aaaa bbbb cccc dddd"++ result = window(text, max_subwords=10)++ assert [word for word, _, _ in result.words] == ["aaaa", "bbbb"]+ assert result.subwords == 8+ assert result.cut == 14 # the end of "cccc": text[:14] reads the same window+++def test_reading_stops_inside_a_long_word_at_the_budget() -> None:+ text = "go " + "y" * 1000 + " tail"++ result = window(text, max_subwords=600)++ assert [(start, end) for _, start, end in result.words] == [(0, 2), (3, 259), (259, 515)]+ assert result.subwords == 514+ assert result.cut == 1003 # the end of the long word+ assert window(text[: result.cut], max_subwords=600) == result+++def test_the_first_word_is_always_read() -> None:+ result = window("x" * 1000, max_subwords=5)++ assert [(start, end) for _, start, end in result.words] == [(0, MAX_WORD_CHARS)]+ assert result.subwords == MAX_WORD_CHARS+++def test_reading_stops_after_max_words() -> None:+ text = "a b c d e"++ assert [word for word, _, _ in window(text, max_words=3).words] == ["a", "b", "c"]+ assert window(text, max_words=3).cut == 5+ assert window("a b c", max_words=3).cut is None+ assert window("a b c ", max_words=3).cut is None+++def test_pieces_of_a_word_whose_lowercase_changes_length_follow_the_text() -> None:+ # gliner2 2.x lowercases each word; "\u0130" lowercases to two characters.+ text = "\u0130" * 300+ lowered = [(text.lower(), 0, 300)]++ result = list(pieces(lowered, text))++ assert [(start, end) for _, start, end, _ in result] == [(0, 256), (256, 300)]+ assert [word for word, _, _, _ in result] == [text[0:256].lower(), text[256:300].lower()]+ assert all(word_end == 300 for _, _, _, word_end in result)+++def test_the_windowed_splitter_passes_arguments_through() -> None:+ calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []++ def splitter(text: str, *args: Any, **kwargs: Any) -> Iterator[tuple[str, int, int]]:+ calls.append((text, args, kwargs))+ return words(text)++ windowed = WindowedSplitter(splitter, max_words=2, max_subwords=100, count_subwords=per_char)++ assert list(windowed("one two three", lower=True)) == [("one", 0, 3), ("two", 4, 7)]+ assert calls == [("one two three", (), {"lower": True})]+++def test_the_counter_counts_each_word_once_and_forgets_the_oldest() -> None:+ counted: list[list[str]] = []++ def count(batch: Sequence[str]) -> list[int]:+ counted.append(list(batch))+ return [len(word) for word in batch]++ counter = SubwordCounter(count, size=2)++ assert counter(["ab", "c", "ab"]) == [2, 1, 2]+ assert counter(["c", "ddd"]) == [1, 3]+ assert counter(["ab"]) == [2]+ assert counted == [["ab", "c"], ["ddd"], ["ab"]]+++class SplitWordTokenizer:+ """Two subwords per word, reported through ``word_ids`` as fast tokenizers do."""++ def __call__(self, words: list[str], *, is_split_into_words: bool, add_special_tokens: bool) -> Any:+ assert is_split_into_words+ assert not add_special_tokens+ ids = [index for index, word in enumerate(words) for _ in range(2 if word else 0)]+ return type("Encoding", (), {"word_ids": lambda self: ids})()+++def test_the_counter_keeps_no_word_longer_than_a_piece() -> None:+ counter = SubwordCounter(per_char)+ long_word = "q" * (MAX_WORD_CHARS + 1)++ assert counter([long_word, "ab", long_word]) == [MAX_WORD_CHARS + 1, 2, MAX_WORD_CHARS + 1]+ assert counter._cache == {"ab": 2}+++def test_split_words_are_counted_as_the_tokenizer_encodes_them() -> None:+ assert split_word_counter(SplitWordTokenizer())(["a", "", "bc"]) == [2, 0, 2]+++def test_a_slow_tokenizer_is_counted_word_by_word() -> None:+ class Slow:+ def __call__(self, *args: Any, **kwargs: Any) -> Any:+ raise ValueError("word_ids() is not available when using non-fast tokenizers")++ def tokenize(self, word: str) -> list[str]:+ return list(word)++ assert split_word_counter(Slow())(["ab", "cde"]) == [2, 3]+++def test_the_budget_allows_subwords_per_word_up_to_the_encoder_cap() -> None:+ assert subword_budget(512) == SUBWORDS_PER_WORD * 512+ assert subword_budget(512, per_word=4) == 2048+ assert subword_budget(2048) == MAX_DOCUMENT_SUBWORDS+ assert subword_budget(2048, {"model_type": "deberta-v2"}) == DEBERTA_MAX_DOCUMENT_SUBWORDS+ assert subword_budget(384, {"model_type": "deberta-v2"}) == SUBWORDS_PER_WORD * 384+ bert = {"model_type": "bert", "position_embedding_type": "absolute", "max_position_embeddings": 512}+ assert subword_budget(386, bert) == 508+ relative = {"model_type": "deberta-v2", "max_position_embeddings": 512}+ assert subword_budget(384, relative) == SUBWORDS_PER_WORD * 384+ # transformers 5 writes no position_embedding_type for BERT-style encoders.+ assert subword_budget(386, {"model_type": "bert", "max_position_embeddings": 512}) == 508+ assert subword_budget(386, {"model_type": "xlm-roberta", "max_position_embeddings": 514}) == 510+ bert_relative = {"model_type": "bert", "position_embedding_type": "relative_key", "max_position_embeddings": 512}+ assert subword_budget(386, bert_relative) == SUBWORDS_PER_WORD * 386+ rotary = {"model_type": "modernbert", "max_position_embeddings": 8192}+ assert subword_budget(2048, rotary) == MAX_DOCUMENT_SUBWORDS+++def test_a_batch_that_fits_runs_as_it_is() -> None:+ assert plan_forwards([600] * 12, rows_per_pass=12) is None+ assert plan_forwards([3000] * 12, rows_per_pass=1) is None+ assert plan_forwards([], rows_per_pass=8) is None++[email protected]("rows_per_pass", [8, 12])+def test_long_rows_run_in_passes_within_the_budget(rows_per_pass: int) -> None:+ rows = [3100, 40, 2000, 40, 1500, 3100, 40, 40, 900, 40, 40, 4096]++ groups = plan_forwards(rows, rows_per_pass=rows_per_pass)++ assert groups is not None+ assert sorted(index for group in groups for index in group) == list(range(len(rows)))+ for group in groups:+ longest = max(rows[index] for index in group)+ assert len(group) <= rows_per_pass+ assert len(group) == 1 or len(group) * longest**2 <= ATTENTION_BUDGET+ for group in groups:+ lengths = [rows[index] for index in group]+ assert max(lengths) <= 2 * min(lengths) # short rows are not padded to long ones+++def test_a_long_row_does_not_pad_the_short_rows_it_would_fit_with() -> None:+ rows = [2000] + [50] * 11++ groups = plan_forwards(rows, rows_per_pass=8)++ assert groups == [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11], [0]]