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): read long documents whole in GLiNER extract (#451)

svonava2f97d022440f
diff --git a/examples/redact/README.md b/examples/redact/README.md
index 4f459f6d9..3bb08c44e 100644
--- a/examples/redact/README.md
+++ b/examples/redact/README.md
@@ -34,10 +34,13 @@ Two more figures it reproduces: 42 of the 49 masks land on a published gold
span, and 0 of the 29 currency amounts across the ten recorded documents are
masked.
-The second step is why the window matters. The model reads the first 384 words
-and punctuation marks and the reply gives no truncation signal, so a document
-longer than that has to be split by the caller, with each part's starting
-offset added back to the spans it returns.
+The second step is why the window matters. The model reads 384 words and
+punctuation marks at a time. The server this run was recorded against read
+only the first 384 and gave no truncation signal, so a longer document had to
+be split by the caller, with each part's starting offset added back to the
+spans it returns; the recorded inputs carry that split. Servers that include
+the fix for [#446](https://github.com/superlinked/sie/issues/446) read a longer
+document whole, in overlapping windows.
## Run it
diff --git a/packages/sie_mcp/src/sie_mcp/offload.py b/packages/sie_mcp/src/sie_mcp/offload.py
index d09437de6..f4ca60307 100644
--- a/packages/sie_mcp/src/sie_mcp/offload.py
+++ b/packages/sie_mcp/src/sie_mcp/offload.py
@@ -36,12 +36,13 @@ REQUEST_TIMEOUT_S = 600.0
# the server applies the model's default (0.5) and drops lower spans first.
MIN_PII_SCORE = 0.3
-# Bounded windowing for the GLiNER extract/redact path. GLiNER reads only the
-# first ``max_len`` words of each text (384 for the default models) and silently
-# ignores the rest, where a word is a match of ``_GLINER_WORD``, so every
-# punctuation mark counts as one. The label prompt does not count toward that
-# limit. A document is therefore split into overlapping windows of
-# EXTRACT_WINDOW_WORDS words, under the smallest ``max_len`` of the GLiNER models
+# Bounded windowing for the GLiNER extract/redact path. A GLiNER model reads
+# ``max_len`` words of a text at once (384 for the default models), where a word
+# is a match of ``_GLINER_WORD``, so every punctuation mark counts as one. The
+# label prompt does not count toward that limit. Older servers silently ignored
+# the rest of a longer text; current servers read it in windows of their own but
+# fail an item that needs too many. A document is therefore split here into
+# overlapping windows of EXTRACT_WINDOW_WORDS words, under the smallest ``max_len`` of the GLiNER models
# in the catalog (296) so that any configured model reads each window whole, and
# the entities are merged with offsets shifted back to the original text. The overlap is longer than the
# longest span the default models predict (12 words), so an entity that
diff --git a/packages/sie_server/src/sie_server/adapters/_word_window.py b/packages/sie_server/src/sie_server/adapters/_word_window.py
index cd1bd456f..add20de88 100644
--- a/packages/sie_server/src/sie_server/adapters/_word_window.py
+++ b/packages/sie_server/src/sie_server/adapters/_word_window.py
@@ -28,6 +28,11 @@ DeBERTa encoders, whose attention materializes score matrices of the square of
the row length), and within the position table of encoders with absolute
positions.
+``document_windows`` reads a document longer than one window as overlapping
+windows, each of which a model reads whole, and ``merge_window_spans`` maps
+the spans found in them back to the document and merges them (see those
+functions).
+
``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.
@@ -53,6 +58,17 @@ DEBERTA_MAX_DOCUMENT_SUBWORDS = 4096
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 a window shares with the one before it. GLiNER models find spans of at
+# most 12 words, so an entity cut by one window's edge is whole in its neighbour.
+WINDOW_OVERLAP_WORDS = 64
+# Most windows read of one document (about 40,000 words at 384 words a window).
+# A longer document fails with ``INPUT_TOO_LONG`` rather than being read in part.
+MAX_DOCUMENT_WINDOWS = 128
+# Characters of a document read to find one window, doubled until the window
+# ends this far inside them (or the document ends), so that a window of a long
+# document is found without copying the rest of the document each time.
+_WINDOW_SLICE_CHARS = 16384
+_WINDOW_SLICE_MARGIN = MAX_WORD_CHARS
# Words are counted in blocks, so reading stops at most one block past the window.
_READ_BLOCK = 64
_COUNT_CACHE_SIZE = 16384
@@ -194,6 +210,218 @@ class WindowedSplitter:
)
+@dataclass(frozen=True, slots=True)
+class DocumentWindow:
+ """One window of a document: ``text[start:end]`` is read whole."""
+
+ start: int
+ end: int
+ # The end of the last word read.
+ read_end: int
+ # Words shared with the window before, or None for the first window.
+ overlap: int | None
+
+
+def document_windows(
+ text: str,
+ splitter: WindowedSplitter,
+ *,
+ overlap_words: int = WINDOW_OVERLAP_WORDS,
+ max_windows: int = MAX_DOCUMENT_WINDOWS,
+) -> list[DocumentWindow] | None:
+ """The windows ``splitter`` reads ``text`` in, or None when it takes more than ``max_windows``.
+
+ A text read whole is one window of all of it, so a model is given exactly
+ the text it was given before. A longer text is read as successive windows,
+ each ending where ``splitter`` stops reading (``Window.cut``) and each
+ after the first starting at the start of the last ``overlap_words`` words
+ of the one before it (at most half of that window's words, so that every
+ window reads new words).
+ """
+ windows: list[DocumentWindow] = []
+ start = 0
+ overlap: int | None = None
+ while True:
+ window, rest, end = _window_from(text, start, splitter)
+ words = window.words
+ if window.cut is None or not words:
+ read_end = start + (words[-1][2] if words else len(rest))
+ windows.append(DocumentWindow(start, len(text), read_end, overlap))
+ return windows
+ windows.append(DocumentWindow(start, start + end, start + words[-1][2], overlap))
+ if len(windows) >= max_windows:
+ return None
+ shared = min(overlap_words, len(words) // 2)
+ if shared:
+ start += words[len(words) - shared][1]
+ else:
+ # One word read: the next window starts at the first piece not read.
+ following = _second_piece_start(splitter, rest) or _second_piece_start(splitter, text[start:])
+ if not following:
+ raise RuntimeError("a window stopped before the end of a document, but no word follows it")
+ start += following
+ overlap = shared
+
+
+def gliner_windows(model: Any, texts: Sequence[str]) -> list[list[DocumentWindow] | None]:
+ """The windows a loaded ``gliner`` model reads each text in; None for a text needing too many.
+
+ See ``document_windows``. A model without the bounded word splitter of
+ ``bound_gliner_words`` reads each text as one window.
+ """
+ splitter = getattr(getattr(model, "data_processor", None), "words_splitter", None)
+ if not isinstance(splitter, WindowedSplitter):
+ return [[DocumentWindow(0, len(text), len(text), None)] for text in texts]
+ return [document_windows(text, splitter) for text in texts]
+
+
+def window_rows(
+ texts: Sequence[str], plans: Sequence[list[DocumentWindow] | None]
+) -> tuple[list[str], list[int], list[int | None]]:
+ """The text of each window read, the item it belongs to, and its overlap with the window before."""
+ rows: list[str] = []
+ owners: list[int] = []
+ overlaps: list[int | None] = []
+ for index, (text, windows) in enumerate(zip(texts, plans, strict=True)):
+ for window in windows or []:
+ rows.append(text[window.start : window.end])
+ owners.append(index)
+ overlaps.append(window.overlap)
+ return rows, owners, overlaps
+
+
+def window_item_counts(row_counts: Sequence[int] | None, owners: Sequence[int], items: int) -> list[int] | None:
+ """Each item's input tokens: the sum over its windows (0 for an item not read)."""
+ if row_counts is None:
+ return None
+ counts = [0] * items
+ for owner, count in zip(owners, row_counts, strict=True):
+ counts[owner] += count
+ return counts
+
+
+def _second_piece_start(splitter: WindowedSplitter, text: str) -> int | None:
+ second = next(islice(pieces(splitter.splitter(text), text), 1, 2), None)
+ return None if second is None else second[1]
+
+
+def _window_from(text: str, start: int, splitter: WindowedSplitter) -> tuple[Window, str, int]:
+ """The window ``splitter`` reads of ``text[start:]``, the text it was read from, and where the window's text ends.
+
+ Reads a prefix of ``text[start:]`` that grows until the first piece the
+ window does not read ends at least ``_WINDOW_SLICE_MARGIN`` characters
+ before the prefix does: a word splitter matching words by pattern then
+ reads the same pieces up to it as in the whole text, and so the same
+ window. The window's text is ``rest[:cut]`` when that ends inside the
+ prefix, or else the prefix itself (a word too long for the prefix is read
+ in pieces of which the window reads only the first).
+ """
+ size = _WINDOW_SLICE_CHARS
+ while True:
+ rest = text[start : start + size]
+ window = splitter.window(rest)
+ if start + size >= len(text):
+ return window, rest, len(rest) if window.cut is None else window.cut
+ if window.cut is not None and window.words:
+ if window.cut + _WINDOW_SLICE_MARGIN <= len(rest):
+ return window, rest, window.cut
+ following = _piece_end_after(splitter, rest, window.words[-1][2])
+ if following is not None and following + _WINDOW_SLICE_MARGIN <= len(rest):
+ return window, rest, len(rest)
+ size *= 2
+
+
+def _piece_end_after(splitter: WindowedSplitter, text: str, offset: int) -> int | None:
+ """The end of the first piece of ``text`` after ``offset`` (the end of a piece), or None when there is none."""
+ tail = text[offset:]
+ first = next(pieces(splitter.splitter(tail), tail), None)
+ return None if first is None else offset + first[2]
+
+
+def merge_window_spans(
+ windows: Sequence[DocumentWindow],
+ spans: Sequence[Sequence[dict[str, Any]]],
+ text: str,
+ *,
+ flat_ner: bool,
+ multi_label: bool,
+) -> list[dict[str, Any]]:
+ """The spans of a document from the spans found in each of its windows.
+
+ ``spans[i]`` are the spans (``start``, ``end``, ``label``, ``score`` and
+ ``text``) found in ``windows[i]``, with offsets into that window's text.
+ One window's spans are returned as they are. Otherwise offsets are moved
+ to the document; a span reaching a window's edge that the window next to
+ it reads past is dropped when that window found an overlapping span of
+ the same label (the span may have been cut short at the edge, and the
+ other window reads it whole); the same span found twice keeps its highest
+ score; and overlapping spans are resolved as gliner resolves them in one
+ window: highest score first, keeping a span that overlaps none kept
+ (``flat_ner``) or that overlaps none kept without one holding the other,
+ where ``multi_label`` allows one span several labels. Spans are returned
+ in document order.
+ """
+ if len(windows) == 1:
+ return list(spans[0])
+ moved = [
+ [{**span, "start": span["start"] + window.start, "end": span["end"] + window.start} for span in found]
+ for window, found in zip(windows, spans, strict=True)
+ ]
+ best: dict[tuple[int, int, str], dict[str, Any]] = {}
+ for index, (window, found) in enumerate(zip(windows, moved, strict=True)):
+ for span in found:
+ if _cut_at_edge(span, index, window, windows, moved):
+ continue
+ key = (span["start"], span["end"], span["label"])
+ if key not in best or span["score"] > best[key]["score"]:
+ best[key] = {**span, "text": text[span["start"] : span["end"]]}
+ kept: list[dict[str, Any]] = []
+ for span in sorted(best.values(), key=lambda one: -one["score"]):
+ if not any(_conflict(span, other, flat_ner=flat_ner, multi_label=multi_label) for other in kept):
+ kept.append(span)
+ kept.sort(key=lambda one: (one["start"], one["end"]))
+ return kept
+
+
+def _cut_at_edge(
+ span: dict[str, Any],
+ index: int,
+ window: DocumentWindow,
+ windows: Sequence[DocumentWindow],
+ moved: Sequence[Sequence[dict[str, Any]]],
+) -> bool:
+ """Whether a neighbouring window reads ``span`` whole and found an overlapping span of its label there."""
+ neighbours = []
+ if index > 0 and span["start"] <= window.start:
+ neighbours.append(index - 1)
+ if index + 1 < len(windows) and span["end"] >= window.read_end:
+ neighbours.append(index + 1)
+ for other in neighbours:
+ reader = windows[other]
+ if not reader.start <= span["start"] < span["end"] <= reader.read_end:
+ continue
+ if any(
+ found["label"] == span["label"] and found["start"] < span["end"] and span["start"] < found["end"]
+ for found in moved[other]
+ ):
+ return True
+ return False
+
+
+def _conflict(span: dict[str, Any], other: dict[str, Any], *, flat_ner: bool, multi_label: bool) -> bool:
+ """Whether two spans conflict under gliner's overlap rule (``greedy_search``), on character offsets."""
+ if (span["start"], span["end"]) == (other["start"], other["end"]):
+ return not multi_label
+ if span["start"] >= other["end"] or other["start"] >= span["end"]:
+ return False
+ if flat_ner:
+ return True
+ nested = (span["start"] <= other["start"] and other["end"] <= span["end"]) or (
+ other["start"] <= span["start"] and span["end"] <= other["end"]
+ )
+ return not nested
+
+
class SubwordCounter:
"""Subword counts of words, from ``count`` (a list of words at a time), with the recent ones kept.
diff --git a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
index 84a410836..1280afd68 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
@@ -18,6 +18,13 @@ Joint entity-relation ("relex") models also extract relations between the
entities they find when a request names relation types in
``options["relation_labels"]``. Without it they return entities only.
+GLiNER reads at most ``max_len`` words of a text at once (384 for most
+checkpoints). A longer document is read whole, as overlapping windows of words
+(see ``_word_window.document_windows``); the spans found in them are mapped
+back to the document and merged, and its input tokens are counted once each.
+A document needing more than ``_word_window.MAX_DOCUMENT_WINDOWS`` windows
+returns a per-item ``INPUT_TOO_LONG`` error rather than being read in part.
+
A request's labels and relation types, which GLiNER encodes with every
document and does not bill, may have at most 128 characters each and take at
most ``max_prompt_tokens`` tokens together (default 1024); a longer prompt is
@@ -40,16 +47,28 @@ from sie_server.adapters._prompt_limit import (
)
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_REQUIRES_TEXT, ComputePrecision
-from sie_server.adapters._word_window import bound_gliner_words, plan_forwards
+from sie_server.adapters._word_window import (
+ MAX_DOCUMENT_WINDOWS,
+ bound_gliner_words,
+ gliner_windows,
+ merge_window_spans,
+ plan_forwards,
+ window_item_counts,
+ window_rows,
+)
from sie_server.core.extract_cost import MAX_EXTRACT_LABELS
-from sie_server.core.inference_output import ExtractOutput
+from sie_server.core.inference_output import ExtractItemError, ExtractOutput
from sie_server.types.inputs import InvalidInputError, Item
-from sie_server.types.responses import Entity, Relation
+from sie_server.types.responses import Entity, ErrorCode, Relation
# Error messages
_ERR_REQUIRES_LABELS = "GLiNER requires labels parameter for extraction"
_ERR_REQUIRES_NON_BLANK_TEXT = "GLiNER requires non-blank text for extraction"
_ERR_PROMPT_EXHAUSTS_DOCUMENT = "GLiNER label prompt leaves no document tokens for extraction"
+_ERR_TOO_MANY_WINDOWS = (
+ f"GLiNER reads a document in at most {MAX_DOCUMENT_WINDOWS} windows of words; "
+ "split this document into shorter items"
+)
# Joint entity-relation models score every ordered pair of entity candidates
# inside the forward pass, so memory grows with the square of the candidate
# count. Candidates are the spans above the entity threshold, which a caller
@@ -253,10 +272,16 @@ class GLiNERAdapter(BaseAdapter):
if any(not text.strip() for text in texts):
raise InvalidInputError(_ERR_REQUIRES_NON_BLANK_TEXT)
- # Meter the exact post-word-truncation document window before GPU work.
+ # A document longer than the model's word window is read as several
+ # overlapping windows, each a row of its own (see ``_word_window.gliner_windows``).
+ plans = gliner_windows(self._model, texts)
+ rows, owners, overlaps = window_rows(texts, plans)
+
+ # Meter the exact post-word-truncation windows before GPU work.
# Besides producing the authoritative terminal counts, this rejects a
# finite-tokenizer prompt that leaves no represented document subword.
- input_token_counts, row_tokens = self._meter(texts, labels, relation_labels)
+ row_counts, row_tokens = self._meter(rows, labels, relation_labels, overlaps) if rows else ([], [])
+ input_token_counts = window_item_counts(row_counts, owners, len(texts))
# Get options with fallback to model defaults
effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold), "threshold")
@@ -284,16 +309,41 @@ class GLiNERAdapter(BaseAdapter):
# Use batch prediction for efficiency (24x speedup vs single item loop)
with torch.inference_mode():
- 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,
+ row_entities, row_relations = (
+ self._inference(
+ rows,
+ labels,
+ row_tokens,
+ returns_relations=bool(relation_labels),
+ threshold=effective_threshold,
+ flat_ner=effective_flat_ner,
+ multi_label=effective_multi_label,
+ **relation_kwargs,
+ )
+ if rows
+ else ([], [] if relation_labels else None)
+ )
+
+ item_rows: list[list[int]] = [[] for _ in texts]
+ for position, owner in enumerate(owners):
+ item_rows[owner].append(position)
+ batch_entities: list[list[Any]] = []
+ batch_relations: list[list[Any]] | None = [] if row_relations is not None else None
+ for text, windows, positions in zip(texts, plans, item_rows, strict=True):
+ batch_entities.append(
+ []
+ if windows is None
+ else merge_window_spans(
+ windows,
+ [row_entities[position] for position in positions],
+ text,
+ flat_ner=bool(effective_flat_ner),
+ multi_label=bool(effective_multi_label),
+ )
)
+ if batch_relations is not None and row_relations is not None:
+ found = [relation for position in positions for relation in row_relations[position] or []]
+ batch_relations.append(_best_relations(found) if len(positions) > 1 else found)
# Convert to our format
all_entities = []
@@ -322,7 +372,17 @@ class GLiNERAdapter(BaseAdapter):
raise ValueError("GLiNER returned relations for a different number of items")
all_relations = [self._format_relations(relations) for relations in batch_relations]
- return ExtractOutput(entities=all_entities, relations=all_relations, input_token_counts=input_token_counts)
+ errors = None
+ if any(windows is None for windows in plans):
+ errors = [
+ None
+ if windows is not None
+ else ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message=_ERR_TOO_MANY_WINDOWS)
+ for windows in plans
+ ]
+ return ExtractOutput(
+ entities=all_entities, relations=all_relations, errors=errors, input_token_counts=input_token_counts
+ )
def _check_prompt(self, labels: list[str], relation_labels: list[str]) -> None:
"""Reject a request whose labels and relation types take more than ``max_prompt_tokens``.
@@ -441,14 +501,17 @@ class GLiNERAdapter(BaseAdapter):
labels: list[str],
relation_labels: list[str] | None = None,
) -> list[int] | None:
- """Count the document subwords represented by GLiNER's real processor (see ``_meter``)."""
- return self._meter(texts, labels, relation_labels)[0]
+ """Count the document subwords of each text GLiNER reads, over all its windows (see ``_meter``)."""
+ plans = gliner_windows(self._model, texts)
+ rows, owners, overlaps = window_rows(texts, plans)
+ return window_item_counts(self._meter(rows, labels, relation_labels, overlaps)[0], owners, len(texts))
def _meter(
self,
texts: list[str],
labels: list[str],
relation_labels: list[str] | None = None,
+ overlaps: list[int | None] | None = None,
) -> tuple[list[int] | None, list[int] | None]:
"""Count the document subwords represented by GLiNER's real processor, and each row's tokens.
@@ -470,6 +533,12 @@ class GLiNERAdapter(BaseAdapter):
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.
+
+ ``overlaps[i]`` is None for a row holding the start of a document, or
+ the number of words row ``i`` shares with the window before it (see
+ ``_word_window.document_windows``). Such a row counts neither its
+ special tokens nor the subwords of those words, so a document read in
+ several windows counts each of its tokens once, as if read in one row.
"""
processor = getattr(self._model, "data_processor", None)
prepare_inputs = getattr(self._model, "prepare_inputs", None)
@@ -504,6 +573,8 @@ class GLiNERAdapter(BaseAdapter):
entity_mappings = raw_batch["classes_to_id"]
encoded = processor.tokenize_inputs(retained_words, entity_mappings)
for batch_index in range(len(retained_words)):
+ overlap = overlaps[start + batch_index] if overlaps is not None else None
+ skip = overlap or 0
word_ids = encoded.word_ids(batch_index)
attention_mask = encoded["attention_mask"][batch_index].tolist()
words_mask = encoded["words_mask"][batch_index].tolist()
@@ -531,8 +602,12 @@ class GLiNERAdapter(BaseAdapter):
sum(
bool(attended)
and (
- word_id is None
- or (first_document_word_id is not None and word_id >= first_document_word_id)
+ (word_id is None and overlap is None)
+ or (
+ first_document_word_id is not None
+ and word_id is not None
+ and word_id >= first_document_word_id + skip
+ )
)
for attended, word_id in zip(attention_mask, word_ids)
)
@@ -610,6 +685,16 @@ class GLiNERAdapter(BaseAdapter):
return item.text
+def _best_relations(relations: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Relations found in several windows of a document, each (head, tail, relation) once at its highest score."""
+ best: dict[tuple[str, str, str], dict[str, Any]] = {}
+ for relation in relations:
+ key = (relation["head"]["text"], relation["tail"]["text"], relation["relation"])
+ if key not in best or relation["score"] > best[key]["score"]:
+ best[key] = relation
+ return list(best.values())
+
+
def _cap_relation_candidates(model: Any, limit: int) -> None:
"""Keep at most ``limit`` entity candidates per item for relation scoring.
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__.py
index f70959ff6..8af97000e 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,15 +11,27 @@ import torch
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._word_window import bound_gliner_words, plan_forwards
-from sie_server.core.inference_output import ExtractOutput
+from sie_server.adapters._word_window import (
+ MAX_DOCUMENT_WINDOWS,
+ bound_gliner_words,
+ gliner_windows,
+ merge_window_spans,
+ plan_forwards,
+ window_item_counts,
+ window_rows,
+)
+from sie_server.core.inference_output import ExtractItemError, ExtractOutput
from sie_server.types.inputs import InvalidInputError, Item
-from sie_server.types.responses import Entity
+from sie_server.types.responses import Entity, ErrorCode
logger = logging.getLogger(__name__)
_ERR_REQUIRES_LABELS = "GLiNER-bi requires labels parameter for extraction"
_ERR_NO_RELATIONS = "GLiNER bi-encoder models do not extract relations; options.relation_labels is not supported"
+_ERR_TOO_MANY_WINDOWS = (
+ f"GLiNER-bi reads a document in at most {MAX_DOCUMENT_WINDOWS} windows of words; "
+ "split this document into shorter items"
+)
# Maximum number of distinct label-set embeddings to cache.
_LABEL_CACHE_MAX_SIZE = 64
@@ -47,6 +59,10 @@ class GLiNERBiAdapter(BaseAdapter):
and cached via ``encode_labels()`` + ``batch_predict_with_embeds()``,
giving near-constant inference time regardless of label count.
+ A document longer than the model's word window is read whole, as
+ overlapping windows, as the GLiNER adapter reads it (see
+ ``_word_window.document_windows``).
+
Reference models:
- knowledgator/gliner-bi-base-v2.0 (Ettin text encoder)
- knowledgator/modern-gliner-bi-base-v1.0 (ModernBERT text encoder)
@@ -223,8 +239,16 @@ 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 document longer than the model's word window is read as several
+ # overlapping windows, each a row of its own.
+ plans = gliner_windows(self._model, texts)
+ rows, owners, overlaps = window_rows(texts, plans)
# 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)
+ row_counts = self._row_token_counts(rows, labels, overlaps)
+ row_tokens = (
+ self._row_token_counts(rows, labels) if any(overlap is not None for overlap in overlaps) else row_counts
+ )
+ input_token_counts = window_item_counts(row_counts, owners, len(texts))
def predict(batch: list[str]) -> list[Any]:
if use_precompute:
@@ -245,19 +269,37 @@ class GLiNERBiAdapter(BaseAdapter):
)
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)
+ if row_tokens is not None and self._quadratic_attention and rows:
+ groups = plan_forwards(row_tokens, rows_per_pass=_GLINER_BATCH_SIZE)
with torch.inference_mode():
- if groups is None:
- batch_entities = predict(texts)
+ if not rows:
+ row_entities: list[Any] = []
+ elif groups is None:
+ row_entities = predict(rows)
else:
- batch_entities: list[Any] = [[] for _ in texts]
+ row_entities = [[] for _ in rows]
for group in groups:
- group_entities = predict([texts[index] for index in group])
+ group_entities = predict([rows[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
+ row_entities[index] = entities
+
+ item_rows: list[list[int]] = [[] for _ in texts]
+ for position, owner in enumerate(owners):
+ item_rows[owner].append(position)
+ batch_entities = [
+ []
+ if windows is None
+ else merge_window_spans(
+ windows,
+ [row_entities[position] for position in positions],
+ text,
+ flat_ner=bool(effective_flat_ner),
+ multi_label=bool(effective_multi_label),
+ )
+ for text, windows, positions in zip(texts, plans, item_rows, strict=True)
+ ]
# Convert to SIE Entity format (same as GLiNERAdapter)
all_entities: list[list[Entity]] = []
@@ -275,10 +317,26 @@ class GLiNERBiAdapter(BaseAdapter):
)
all_entities.append(entity_results)
- return ExtractOutput(entities=all_entities, input_token_counts=input_token_counts)
+ errors = None
+ if any(windows is None for windows in plans):
+ errors = [
+ None
+ if windows is not None
+ else ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message=_ERR_TOO_MANY_WINDOWS)
+ for windows in plans
+ ]
+ return ExtractOutput(entities=all_entities, errors=errors, 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.
+ """Count the document tokens the bi-encoder encodes of each text, over all its windows."""
+ plans = gliner_windows(self._model, texts)
+ rows, owners, overlaps = window_rows(texts, plans)
+ return window_item_counts(self._row_token_counts(rows, labels, overlaps), owners, len(texts))
+
+ def _row_token_counts(
+ self, texts: list[str], labels: list[str], overlaps: list[int | None] | None = None
+ ) -> list[int] | None:
+ """Count the document tokens the bi-encoder actually encodes, per row.
A bi-encoder encodes labels separately, so its text input is the
document alone. Delegate word splitting (the bounded splitter installed
@@ -287,6 +345,11 @@ class GLiNERBiAdapter(BaseAdapter):
retained window, special tokens included, as the GLiNER adapter does.
Batches match GLiNER inference's default batch size. GLiNER skips
whitespace-only documents without encoding them, so they count zero.
+
+ ``overlaps[i]`` is None for a row holding the start of a document, or
+ the number of words row ``i`` shares with the window before it; such
+ a row counts neither its special tokens nor those words' subwords, so
+ a document read in several windows counts each of its tokens once.
"""
processor = getattr(self._model, "data_processor", None)
prepare_inputs = getattr(self._model, "prepare_inputs", None)
@@ -304,7 +367,19 @@ class GLiNERBiAdapter(BaseAdapter):
for start in range(0, len(raw_items), 8):
raw_batch = processor.collate_raw_batch(raw_items[start : start + 8], entity_types=labels)
encoded = processor.tokenize_inputs(raw_batch["tokens"])
- encoded_counts.extend(int(sum(mask)) for mask in encoded["attention_mask"].tolist())
+ for batch_index, mask in enumerate(encoded["attention_mask"].tolist()):
+ overlap = None if overlaps is None else overlaps[encoded_positions[start + batch_index]]
+ if overlap is None:
+ encoded_counts.append(int(sum(mask)))
+ continue
+ word_ids = encoded.word_ids(batch_index)
+ encoded_counts.append(
+ sum(
+ 1
+ for attended, word_id in zip(mask, word_ids, strict=True)
+ if attended and word_id is not None and word_id >= overlap
+ )
+ )
except Exception: # noqa: BLE001 -- metering must never fail an extraction
return None
if len(encoded_counts) != len(encoded_positions):
diff --git a/packages/sie_server/tests/adapters/test_gliner_long_words.py b/packages/sie_server/tests/adapters/test_gliner_long_words.py
index 11a01db86..d24b623f4 100644
--- a/packages/sie_server/tests/adapters/test_gliner_long_words.py
+++ b/packages/sie_server/tests/adapters/test_gliner_long_words.py
@@ -2,8 +2,10 @@
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
+The adapters now read words through ``_word_window``. A document longer than one
+window is read in several (``test_gliner_windows``), and one that needs more
+than ``MAX_DOCUMENT_WINDOWS`` fails with ``INPUT_TOO_LONG``. 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.
"""
@@ -20,6 +22,7 @@ from sie_server.adapters._word_window import (
ATTENTION_BUDGET,
MAX_WORD_CHARS,
WindowedSplitter,
+ gliner_windows,
subword_budget,
)
from sie_server.adapters.gliner import GLiNERAdapter
@@ -27,6 +30,7 @@ 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
+from sie_server.types.responses import ErrorCode
gliner_config = pytest.importorskip("gliner.config")
gliner_processor = pytest.importorskip("gliner.data_processing.processor")
@@ -118,6 +122,15 @@ def encoded(model: FakeGLiNER, texts: list[str], labels: list[str]) -> list[list
return encoding["input_ids"].tolist()
+def window_texts(model: FakeGLiNER, texts: list[str]) -> list[str]:
+ """The text of each window the adapters read ``texts`` in."""
+ return [
+ text[window.start : window.end]
+ for text, windows in zip(texts, gliner_windows(model, texts), strict=True)
+ for window in windows or []
+ ]
+
+
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)
@@ -146,15 +159,20 @@ 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]]
+ # Each window is encoded as gliner's own splitter encodes its text.
+ (rows,) = model.calls
+ for row in rows:
+ assert encoded(model, [row], ["person"]) == encoded(reference_model, [row], ["person"])
+ if len(rows) == 1:
+ assert rows == [text]
+ assert output.input_token_counts == reference_adapter._doc_input_token_counts([text], ["person"])
+ # Every character but whitespace is a subword, counted once, with [CLS] and [SEP].
+ assert output.input_token_counts == [sum(not char.isspace() for char in text) + 2]
@pytest.mark.parametrize("encoder_config", [DEBERTA, MODERNBERT], ids=["deberta", "modernbert"])
@@ -172,12 +190,37 @@ def test_gliner_reads_long_words_within_the_subword_budget(text: str, encoder_co
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
+ # The document needs more windows than one is read in: it fails whole
+ # rather than being read in part, and the other item is read as before.
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == ErrorCode.INPUT_TOO_LONG.value
+ assert output.errors[1] is None
+ assert output.entities[0] == []
+ assert output.input_token_counts == [0, 28]
+ assert model.calls == [["Priya Raman works at Novartis."]]
assert seconds < 2.0
[email protected]("encoder_config", [DEBERTA, MODERNBERT], ids=["deberta", "modernbert"])
+def test_gliner_reads_long_words_in_windows_within_the_subword_budget(encoder_config: dict[str, Any]) -> None:
+ model = FakeGLiNER(encoder_config)
+ adapter = load(GLiNERAdapter, model)
+ budget = subword_budget(MAX_LEN, encoder_config)
+ text = ("b" * 200 + " ") * 60
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ (rows,) = model.calls
+ assert len(rows) > 1
+ assert output.errors is None
+ for row in rows:
+ (split,), _, _ = model.prepare_inputs([row])
+ assert sum(len(word) for word in split) <= budget
+ assert output.input_token_counts == [200 * 60 + 2]
+
+
def test_gliner_plans_forward_passes_for_long_rows_on_deberta() -> None:
model = FakeGLiNER(DEBERTA, max_len=512)
adapter = load(GLiNERAdapter, model)
@@ -188,12 +231,16 @@ def test_gliner_plans_forward_passes_for_long_rows_on_deberta() -> None:
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 output.input_token_counts == [200 * 40 + 2] * 8 + [28] * 4
+ # Each long text is read as three windows of 20 words.
+ assert sorted(text for call in model.calls for text in call) == sorted(window_texts(model, texts))
+ assert len(window_texts(model, texts[:1])) == 3
assert len(model.calls) > 2
for call in model.calls:
- longest = max(rows[texts.index(text)] for text in call)
+ longest = max(encoded_rows(model, call, ["person"]))
assert len(call) <= 8
assert len(call) == 1 or len(call) * longest**2 <= ATTENTION_BUDGET
+ assert max(rows) <= max(encoded_rows(model, texts, ["person"]))
def test_gliner_keeps_one_call_for_long_rows_on_other_encoders() -> None:
@@ -203,7 +250,9 @@ def test_gliner_keeps_one_call_for_long_rows_on_other_encoders() -> None:
adapter.extract([Item(text=text) for text in texts], labels=["person"])
- assert model.calls == [texts]
+ # One call holding the three windows of each text.
+ assert len(model.calls) == 1
+ assert len(model.calls[0]) == 3 * len(texts)
def test_gliner_caps_an_absolute_position_encoder_at_its_position_table() -> None:
@@ -214,8 +263,9 @@ def test_gliner_caps_an_absolute_position_encoder_at_its_position_table() -> Non
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 output.input_token_counts == [len(text) - (MAX_LEN - 1) + 2]
+ (rows,) = model.calls
+ assert max(encoded_rows(model, rows, ["person"])) <= subword_budget(MAX_LEN, BERT) + 2 + 3
assert max(encoded_rows(model, [text] * 2, ["person"] * 200)) <= 512
@@ -241,7 +291,8 @@ def test_gliner_bi_encoder_plans_forward_passes_for_long_rows_on_deberta() -> No
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)
+ assert sorted(text for call in model.calls for text in call) == sorted(window_texts(model, texts))
+ assert output.input_token_counts == [200 * 40 + 2] * 8 + [28] * 4
def glirel_adapter(max_words: int = MAX_LEN) -> tuple[GLiRELAdapter, MagicMock]:
diff --git a/packages/sie_server/tests/adapters/test_gliner_metering.py b/packages/sie_server/tests/adapters/test_gliner_metering.py
index 966aabe34..799a8ddf7 100644
--- a/packages/sie_server/tests/adapters/test_gliner_metering.py
+++ b/packages/sie_server/tests/adapters/test_gliner_metering.py
@@ -179,7 +179,7 @@ def test_appending_words_beyond_processor_window_does_not_change_meter() -> None
("numind/NuNER_Zero", "c90187673f464518dca09f41689184ed6976242c"),
],
)
-def test_pinned_classic_processors_meter_only_the_executed_word_window(
+def test_pinned_classic_processors_meter_every_window_they_read(
model_id: str,
revision: str,
) -> None:
@@ -191,15 +191,21 @@ def test_pinned_classic_processors_meter_only_the_executed_word_window(
adapter.load("cuda:0")
labels = ["party", "date", "term", "law", "money", "obligation", "notice"]
prefix = " ".join(f"contractword{index}" for index in range(384))
- suffix = " ".join(f"discarded{index}" for index in range(120))
+ suffix = " ".join(f"readtail{index}" for index in range(120))
try:
prefix_count = adapter._doc_input_token_counts([prefix], labels)
+ suffix_count = adapter._doc_input_token_counts([suffix], labels)
extended_count = adapter._doc_input_token_counts([f"{prefix} {suffix}"], labels)
output = adapter.extract([Item(text=f"{prefix} {suffix}")], labels=labels)
finally:
adapter.unload()
assert prefix_count is not None
- assert extended_count == prefix_count
- assert output.input_token_counts == prefix_count
+ assert suffix_count is not None
+ assert extended_count is not None
assert prefix_count[0] > 384
+ # The words past the model window are read too, and each token is counted
+ # once: the special tokens of the one document, not of each window.
+ specials = 2
+ assert extended_count == [prefix_count[0] + suffix_count[0] - specials]
+ assert output.input_token_counts == extended_count
diff --git a/packages/sie_server/tests/adapters/test_gliner_windows.py b/packages/sie_server/tests/adapters/test_gliner_windows.py
new file mode 100644
index 000000000..93652c8a8
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner_windows.py
@@ -0,0 +1,216 @@
+"""GLiNER and GLiNER bi-encoder adapters read a long document whole, in overlapping windows.
+
+gliner reads at most ``max_len`` words of a text. A longer document is read as
+overlapping windows (``_word_window.document_windows``), and the spans found in
+each are mapped back to the document and merged. These tests use gliner's real
+processor and word splitter with the one-subword-per-character tokenizer of
+``test_gliner_long_words`` and a model window of 64 words; the stand-in model
+finds names in the words it reads.
+"""
+
+from __future__ import annotations
+
+import re
+from itertools import pairwise
+from typing import Any
+
+import pytest
+from sie_server.adapters._word_window import MAX_DOCUMENT_WINDOWS, WINDOW_OVERLAP_WORDS, gliner_windows
+from sie_server.adapters.gliner import GLiNERAdapter
+from sie_server.adapters.gliner_bi import GLiNERBiAdapter
+from sie_server.types.inputs import Item
+from sie_server.types.responses import ErrorCode
+
+from .test_gliner_long_words import DEBERTA, MAX_LEN, FakeGLiNER, load
+
+NAMES = ("Priya Raman", "Tomas Novak", "Ines Duarte")
+
+
+class NameFinder(FakeGLiNER):
+ """Finds each name of ``NAMES`` as a person in the words gliner reads of a text.
+
+ A name read whole scores 0.9 in the first half of the words read and 0.6
+ in the second. A name whose first word is the last word read is found cut
+ short, as a model may find it at a window's edge, with a score of 0.99.
+ """
+
+ def inference(self, texts: list[str], labels: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]:
+ self.calls.append(list(texts))
+ return [self._find(text) for text in texts]
+
+ def batch_predict_with_embeds(self, texts: list[str], *args: Any, **kwargs: Any) -> list[list[dict[str, Any]]]:
+ return self.inference(texts, [])
+
+ def _find(self, text: str) -> list[dict[str, Any]]:
+ words = list(self.data_processor.words_splitter(text))
+ read_end = words[-1][2]
+ found = []
+ for name in NAMES:
+ for match in re.finditer(re.escape(name), text):
+ if match.end() <= read_end:
+ score = 0.9 if match.start() < read_end / 2 else 0.6
+ found.append(span(text, match.start(), match.end(), score))
+ first = name.split()[0]
+ if text[words[-1][1] : read_end] == first and text[words[-1][1] :].startswith(name):
+ found.append(span(text, words[-1][1], read_end, 0.99))
+ return sorted(found, key=lambda one: one["start"])
+
+
+def span(text: str, start: int, end: int, score: float, label: str = "person") -> dict[str, Any]:
+ return {"text": text[start:end], "label": label, "score": score, "start": start, "end": end}
+
+
+def filler(count: int, first: int = 0) -> str:
+ return " ".join(f"w{index}" for index in range(first, first + count))
+
+
+def tokens(text: str) -> int:
+ """Tokens of a document read whole: one per character but whitespace, with [CLS] and [SEP]."""
+ return sum(not char.isspace() for char in text) + 2
+
+
+def found(output: Any, item: int = 0) -> list[tuple[str, int, int]]:
+ return [(entity["text"], entity["start"], entity["end"]) for entity in output.entities[item]]
+
+
[email protected](params=[GLiNERAdapter, GLiNERBiAdapter], ids=["gliner", "gliner-bi"])
+def adapter_and_model(request: pytest.FixtureRequest) -> tuple[Any, NameFinder]:
+ model = NameFinder(DEBERTA, bi_encoder=request.param is GLiNERBiAdapter)
+ return load(request.param, model), model
+
+
+def test_a_short_document_is_read_as_one_window_as_before(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ text = f"{filler(20)} Priya Raman {filler(20, 20)}"
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ assert model.calls == [[text]]
+ assert found(output) == [("Priya Raman", text.index("Priya"), text.index("Priya") + 11)]
+ assert output.errors is None
+
+
+def test_a_name_past_the_model_window_is_found_at_its_offsets(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ text = f"{filler(5 * MAX_LEN)} Priya Raman wrote in."
+ start = text.index("Priya")
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ assert len(model.calls[0]) > 1
+ assert found(output) == [("Priya Raman", start, start + len("Priya Raman"))]
+
+
+def test_names_at_the_start_middle_and_end_are_each_found_once(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, _ = adapter_and_model
+ text = f"Priya Raman {filler(200)} Tomas Novak {filler(200, 200)} Ines Duarte"
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ assert found(output) == [(name, text.index(name), text.index(name) + len(name)) for name in NAMES]
+ assert all(entity["text"] == text[entity["start"] : entity["end"]] for entity in output.entities[0])
+
+
+def test_a_name_straddling_a_window_edge_is_found_whole_once(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ # "Priya" is the last word of the first window and "Raman" the first word past it.
+ text = f"{filler(MAX_LEN - 1)} Priya Raman {filler(3 * MAX_LEN, MAX_LEN)}"
+ start = text.index("Priya")
+ windows = gliner_windows(model, [text])[0]
+ assert windows is not None
+ assert windows[0].read_end == start + len("Priya")
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ assert found(output) == [("Priya Raman", start, start + len("Priya Raman"))]
+
+
+def test_a_name_read_by_two_windows_keeps_its_highest_score(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ # In the second half of the first window and the first half of the second.
+ text = f"{filler(MAX_LEN - 10)} Priya Raman {filler(3 * MAX_LEN, MAX_LEN)}"
+ windows = gliner_windows(model, [text])[0]
+ assert windows is not None
+ assert windows[1].start < text.index("Priya") < windows[0].read_end
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ assert found(output) == [("Priya Raman", text.index("Priya"), text.index("Priya") + len("Priya Raman"))]
+ assert output.entities[0][0]["score"] == 0.9
+
+
+def test_windows_overlap_and_cover_the_whole_document(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ _, model = adapter_and_model
+ text = filler(10 * MAX_LEN)
+
+ windows = gliner_windows(model, [text])[0]
+
+ assert windows is not None
+ assert windows[0].start == 0
+ assert windows[0].overlap is None
+ assert windows[-1].read_end == len(text)
+ for before, after in pairwise(windows):
+ assert after.overlap == min(WINDOW_OVERLAP_WORDS, MAX_LEN // 2)
+ assert before.start < after.start < before.read_end < after.read_end
+ # The words shared are the last ``overlap`` words the window before reads.
+ shared = text[after.start : before.read_end].split()
+ assert len(shared) == after.overlap
+
+
+def test_each_token_of_a_long_document_is_counted_once(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ text = f"Priya Raman {filler(400)} Ines Duarte"
+ short = "Tomas Novak wrote in."
+
+ output = adapter.extract([Item(text=text), Item(text=short)], labels=["person"])
+
+ assert len(model.calls[0]) > 2
+ # One subword per character, with [CLS] and [SEP] once per document.
+ assert output.input_token_counts == [tokens(text), tokens(short)]
+ assert adapter._doc_input_token_counts([text, short], ["person"]) == output.input_token_counts
+
+
+def test_a_document_needing_too_many_windows_fails_rather_than_being_read_in_part(
+ adapter_and_model: tuple[Any, NameFinder],
+) -> None:
+ adapter, model = adapter_and_model
+ too_long = filler(MAX_LEN + MAX_DOCUMENT_WINDOWS * (MAX_LEN // 2))
+ short = "Tomas Novak wrote in."
+
+ output = adapter.extract([Item(text=too_long), Item(text=short)], labels=["person"])
+
+ assert gliner_windows(model, [too_long]) == [None]
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == ErrorCode.INPUT_TOO_LONG.value
+ assert str(MAX_DOCUMENT_WINDOWS) in output.errors[0].message
+ assert output.errors[1] is None
+ assert output.entities[0] == []
+ assert found(output, 1) == [("Tomas Novak", 0, 11)]
+ assert output.input_token_counts == [0, tokens(short)]
+ assert model.calls == [[short]]
+
+
+def test_a_document_just_within_the_window_limit_is_read_whole(adapter_and_model: tuple[Any, NameFinder]) -> None:
+ adapter, model = adapter_and_model
+ # The first window reads 64 words, and each after it 32 more.
+ text = f"{filler(MAX_LEN + (MAX_DOCUMENT_WINDOWS - 1) * (MAX_LEN // 2) - 2)} Priya Raman"
+
+ output = adapter.extract([Item(text=text)], labels=["person"])
+
+ windows = gliner_windows(model, [text])[0]
+ assert windows is not None
+ assert len(windows) == MAX_DOCUMENT_WINDOWS
+ assert output.errors is None
+ assert found(output) == [("Priya Raman", text.index("Priya"), len(text))]
+
+
+def test_adjacent_tokens_merge_across_a_window_edge() -> None:
+ model = NameFinder(DEBERTA)
+ adapter = load(GLiNERAdapter, model)
+ text = f"{filler(MAX_LEN - 1)} Priya Raman {filler(3 * MAX_LEN, MAX_LEN)}"
+
+ output = adapter.extract([Item(text=text)], labels=["person"], options={"merge_adjacent_entities": True})
+
+ start = text.index("Priya")
+ assert found(output) == [("Priya Raman", start, start + len("Priya Raman"))]
diff --git a/packages/sie_server/tests/adapters/test_word_window.py b/packages/sie_server/tests/adapters/test_word_window.py
index f411fa0ff..7075c374d 100644
--- a/packages/sie_server/tests/adapters/test_word_window.py
+++ b/packages/sie_server/tests/adapters/test_word_window.py
@@ -13,8 +13,11 @@ from sie_server.adapters._word_window import (
MAX_DOCUMENT_SUBWORDS,
MAX_WORD_CHARS,
SUBWORDS_PER_WORD,
+ DocumentWindow,
SubwordCounter,
WindowedSplitter,
+ document_windows,
+ merge_window_spans,
pieces,
plan_forwards,
read_window,
@@ -216,3 +219,133 @@ def test_a_long_row_does_not_pad_the_short_rows_it_would_fit_with() -> None:
groups = plan_forwards(rows, rows_per_pass=8)
assert groups == [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11], [0]]
+
+
+def splitter(max_words: int, max_subwords: int = 1000) -> WindowedSplitter:
+ return WindowedSplitter(words, max_words=max_words, max_subwords=max_subwords, count_subwords=per_char)
+
+
+def test_a_document_read_whole_is_one_window_of_all_of_it() -> None:
+ text = "Priya Raman works at Novartis. "
+
+ assert document_windows(text, splitter(10)) == [DocumentWindow(0, len(text), len(text) - 2, None)]
+
+
+def test_windows_share_words_and_read_every_word() -> None:
+ text = " ".join(f"w{index}" for index in range(100))
+
+ windows = document_windows(text, splitter(20), overlap_words=5)
+
+ assert windows is not None
+ read = [text[window.start : window.read_end].split() for window in windows]
+ assert read[0] == [f"w{index}" for index in range(20)]
+ assert read[1][:5] == read[0][-5:]
+ assert [window.overlap for window in windows] == [None] + [5] * (len(windows) - 1)
+ assert {word for words_read in read for word in words_read} == set(text.split())
+ assert windows[-1].end == len(text)
+
+
+def test_windows_advance_through_a_word_read_in_pieces() -> None:
+ text = "x" * (10 * MAX_WORD_CHARS) + " tail"
+
+ windows = document_windows(text, splitter(10, max_subwords=MAX_WORD_CHARS))
+
+ # One piece a window: nothing is shared, and every piece is read.
+ assert windows is not None
+ assert [window.start for window in windows] == [index * MAX_WORD_CHARS for index in range(10)] + [len(text) - 4]
+ assert [window.overlap for window in windows] == [None] + [0] * 10
+
+
+def test_windows_through_a_word_longer_than_a_slice_read_each_piece_once() -> None:
+ text = "x" * 50_000 + " tail"
+ reader = splitter(10, max_subwords=MAX_WORD_CHARS)
+
+ windows = document_windows(text, reader, max_windows=1000)
+
+ assert windows is not None
+ pieces_read = -(-50_000 // MAX_WORD_CHARS)
+ # The last window reads the last piece and "tail".
+ assert [window.start for window in windows] == [index * MAX_WORD_CHARS for index in range(pieces_read)]
+ assert windows[-1].read_end == len(text)
+ for window in windows[:-1]:
+ # Each window's text reads the piece the window reads, from a bounded prefix of the document.
+ assert window.end - window.start <= 20_000
+ (word,) = reader(text[window.start : window.end])
+ assert (word[1] + window.start, word[2] + window.start) == (window.start, window.read_end)
+
+
+def test_windows_of_a_document_longer_than_the_window_limit_are_none() -> None:
+ text = " ".join(f"w{index}" for index in range(100))
+
+ assert document_windows(text, splitter(20), overlap_words=10, max_windows=8) is None
+ assert document_windows(text, splitter(20), overlap_words=10, max_windows=9) is not None
+
+
+def test_windows_of_a_long_document_are_read_from_bounded_slices() -> None:
+ text = " ".join(f"w{index}" for index in range(200_000))
+
+ windows = document_windows(text, splitter(64), max_windows=10)
+
+ assert windows is None
+
+
+def span(start: int, end: int, score: float, label: str = "person") -> dict[str, Any]:
+ return {"text": "", "label": label, "score": score, "start": start, "end": end}
+
+
+TEXT = "0123456789" * 3
+# Windows reading characters 0-20 and 10-30 (the merge uses offsets only).
+TWO = [DocumentWindow(0, 20, 20, None), DocumentWindow(10, 30, 30, 2)]
+
+
+def merged(spans: list[list[dict[str, Any]]], *, flat_ner: bool = True, multi_label: bool = False) -> list[Any]:
+ result = merge_window_spans(TWO, spans, TEXT, flat_ner=flat_ner, multi_label=multi_label)
+ return [(one["start"], one["end"], one["label"], one["score"], one["text"]) for one in result]
+
+
+def test_one_window_spans_are_returned_as_they_are() -> None:
+ spans = [span(3, 1, 0.5, "odd")]
+
+ assert merge_window_spans([TWO[0]], [spans], TEXT, flat_ner=True, multi_label=False) == spans
+
+
+def test_merged_spans_move_to_document_offsets_and_keep_their_best_score() -> None:
+ result = merged([[span(12, 15, 0.6), span(2, 4, 0.7)], [span(2, 5, 0.9), span(12, 15, 0.8)]])
+
+ assert result == [(2, 4, "person", 0.7, "23"), (12, 15, "person", 0.9, "234"), (22, 25, "person", 0.8, "234")]
+
+
+def test_a_span_cut_at_an_edge_gives_way_to_the_neighbour_that_reads_it_whole() -> None:
+ # 18-20 ends at the first window's edge; the second window found 18-22.
+ result = merged([[span(18, 20, 0.99)], [span(8, 12, 0.7)]])
+
+ assert result == [(18, 22, "person", 0.7, "8901")]
+
+
+def test_a_span_at_an_edge_stays_when_the_neighbour_found_nothing_there() -> None:
+ assert merged([[span(18, 20, 0.99)], []]) == [(18, 20, "person", 0.99, "89")]
+ # A neighbour's span of another label does not replace it.
+ assert merged([[span(18, 20, 0.99)], [span(8, 12, 0.7, "place")]]) == [(18, 20, "person", 0.99, "89")]
+
+
+def test_a_span_at_the_start_of_a_window_gives_way_to_the_window_before() -> None:
+ result = merged([[span(8, 12, 0.5)], [span(0, 2, 0.99)]])
+
+ assert result == [(8, 12, "person", 0.5, "8901")]
+
+
+def test_overlapping_spans_from_two_windows_resolve_as_gliner_resolves_them() -> None:
+ first = [span(12, 16, 0.6, "person")]
+ second = [span(4, 8, 0.8, "place"), span(5, 6, 0.9, "thing")]
+
+ # flat_ner: highest score first, nothing overlapping what is kept.
+ assert merged([first, second]) == [(15, 16, "thing", 0.9, "5")]
+ # Nested: a span inside a kept one stays, a partly overlapping one does not.
+ assert merged([first, second], flat_ner=False) == [(14, 18, "place", 0.8, "4567"), (15, 16, "thing", 0.9, "5")]
+
+
+def test_multi_label_keeps_one_span_with_several_labels() -> None:
+ spans = [[span(12, 15, 0.6, "person")], [span(2, 5, 0.9, "place")]]
+
+ assert merged(spans) == [(12, 15, "place", 0.9, "234")]
+ assert merged(spans, multi_label=True) == [(12, 15, "place", 0.9, "234"), (12, 15, "person", 0.6, "234")]