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): preserve GLiNER word pieces across windows

svonavaacbd6792153b
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 954447b2f..c5f38f834 100644
--- a/packages/sie_server/src/sie_server/adapters/_word_window.py
+++ b/packages/sie_server/src/sie_server/adapters/_word_window.py
@@ -43,9 +43,9 @@ from __future__ import annotations
import json
from collections import Counter, OrderedDict
from collections.abc import Callable, Iterable, Iterator, Sequence
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from itertools import islice
-from typing import Any
+from typing import Any, Self
# A longer word is read in pieces of this many characters.
MAX_WORD_CHARS = 256
@@ -65,11 +65,6 @@ 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
@@ -204,7 +199,7 @@ class WindowedSplitter:
def window(self, text: str, *args: Any, **kwargs: Any) -> Window:
return read_window(
text,
- self.splitter(text, *args, **kwargs),
+ text.words if isinstance(text, _WindowText) else self.splitter(text, *args, **kwargs),
max_words=self.max_words,
max_subwords=self.max_subwords,
count_subwords=self.count_subwords,
@@ -221,6 +216,39 @@ class DocumentWindow:
read_end: int
# Words shared with the window before, or None for the first window.
overlap: int | None
+ # Canonical document pieces, with offsets relative to this window. The
+ # retained pieces do not change comparisons of window boundaries/overlap.
+ words: tuple[Word, ...] | None = field(default=None, repr=False, compare=False)
+
+
+class _WindowText(str):
+ """A GLiNER input string retaining its planned word pieces and local offsets.
+
+ GLiNER passes the original string to ``words_splitter`` for both metering
+ and inference. Re-splitting a slice would lose the document's piece grid
+ when it starts inside a word (notably on a hyphen). Keeping the pieces on
+ the input avoids mutable state on the shared model or splitter.
+ """
+
+ __slots__ = ("words",)
+
+ words: tuple[Word, ...]
+
+ def __new__(cls, text: str, words: tuple[Word, ...]) -> Self:
+ instance = super().__new__(cls, text)
+ instance.words = words
+ return instance
+
+
+def _counted_pieces(text: str, splitter: WindowedSplitter) -> Iterator[tuple[Word, int]]:
+ """Read the original word grid once, counting at most one block ahead."""
+ source = pieces(splitter.splitter(text), text)
+ while block := list(islice(source, _READ_BLOCK)):
+ counts = splitter.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, _), count in zip(block, counts, strict=True):
+ yield (word, start, end), count
def document_windows(
@@ -234,33 +262,39 @@ def document_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).
+ 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). Words are split once and retained on each
+ window: re-splitting a slice starting inside a long word need not give the
+ same pieces. Tokenization is bounded by one block beyond the words read,
+ even when a document exceeds ``max_windows``.
"""
windows: list[DocumentWindow] = []
+ source = _counted_pieces(text, splitter)
+ following = next(source, None)
+ kept: list[tuple[Word, int]] = []
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))
+ subwords = sum(count for _, count in kept)
+ while following is not None and len(kept) < splitter.max_words:
+ word, count = following
+ if kept and subwords + count > splitter.max_subwords:
+ break
+ kept.append((word, count))
+ subwords += count
+ following = next(source, None)
+ read_end = kept[-1][0][2] if kept else len(text)
+ words = tuple((word, begin - start, end - start) for (word, begin, end), _ in kept)
+ end = len(text) if following is None else read_end
+ windows.append(DocumentWindow(start, end, read_end, overlap, words))
+ if following is None or not kept:
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
+ shared = min(overlap_words, len(kept) // 2)
+ kept = kept[-shared:] if shared else []
+ start = kept[0][0][1] if kept else following[0][1]
overlap = shared
@@ -285,7 +319,8 @@ def window_rows(
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])
+ row = text[window.start : window.end]
+ rows.append(_WindowText(row, window.words) if window.words is not None else row)
owners.append(index)
overlaps.append(window.overlap)
return rows, owners, overlaps
@@ -301,44 +336,6 @@ def window_item_counts(row_counts: Sequence[int] | None, owners: Sequence[int],
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]]],
diff --git a/packages/sie_server/tests/adapters/test_gliner_windows.py b/packages/sie_server/tests/adapters/test_gliner_windows.py
index 93652c8a8..471ae2713 100644
--- a/packages/sie_server/tests/adapters/test_gliner_windows.py
+++ b/packages/sie_server/tests/adapters/test_gliner_windows.py
@@ -11,17 +11,26 @@ finds names in the words it reads.
from __future__ import annotations
import re
+from collections import Counter
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._word_window import (
+ MAX_DOCUMENT_WINDOWS,
+ MAX_WORD_CHARS,
+ WINDOW_OVERLAP_WORDS,
+ gliner_windows,
+ pieces,
+ subword_budget,
+ window_rows,
+)
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
+from .test_gliner_long_words import DEBERTA, MAX_LEN, FakeGLiNER, gliner_model, load, tokenizers
NAMES = ("Priya Raman", "Tomas Novak", "Ines Duarte")
@@ -56,6 +65,32 @@ class NameFinder(FakeGLiNER):
return sorted(found, key=lambda one: one["start"])
+class PreprocessingGLiNER(FakeGLiNER):
+ """Run gliner's real inference and collation up to the weightless encoder."""
+
+ inference = gliner_model.BaseEncoderGLiNER.inference
+ batch_predict_with_embeds = gliner_model.BaseBiEncoderGLiNER.batch_predict_with_embeds
+ _filter_valid_texts = gliner_model.BaseEncoderGLiNER._filter_valid_texts
+ _map_entities_to_original = gliner_model.BaseEncoderGLiNER._map_entities_to_original
+ _inference_packing_config = None
+
+ def __init__(self, *, bi_encoder: bool) -> None:
+ super().__init__(DEBERTA, bi_encoder=bi_encoder, max_len=384)
+ model_class = gliner_model.BiEncoderSpanGLiNER if bi_encoder else gliner_model.UniEncoderSpanGLiNER
+ self.data_collator_class = model_class.data_collator_class
+ self.inferred_words: list[list[str]] = []
+
+ def eval(self) -> PreprocessingGLiNER:
+ return self
+
+ def _process_batches(self, batches: Any, *args: Any, **kwargs: Any) -> list[list[Any]]:
+ result: list[list[Any]] = []
+ for batch in batches:
+ self.inferred_words.extend(batch["tokens"])
+ result.extend([] for _ in batch["tokens"])
+ return result
+
+
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}
@@ -170,6 +205,50 @@ def test_each_token_of_a_long_document_is_counted_once(adapter_and_model: tuple[
assert adapter._doc_input_token_counts([text, short], ["person"]) == output.input_token_counts
[email protected]("adapter_class", [GLiNERAdapter, GLiNERBiAdapter], ids=["gliner", "gliner-bi"])
[email protected]("repetitions", [1, 20, 120])
+def test_hyphen_start_windows_keep_canonical_pieces_and_count_each_token_once(
+ adapter_class: type[Any], repetitions: int
+) -> None:
+ model = PreprocessingGLiNER(bi_encoder=adapter_class is GLiNERBiAdapter)
+ tokenizer = model.data_processor.transformer_tokenizer
+ # Each x expands to four subwords; each word also gets a prefix subword.
+ # The latter makes a shifted piece grid observable even if no characters
+ # were counted twice. A character cutoff cannot recover these token counts.
+ tokenizer.backend_tokenizer.normalizer = tokenizers.normalizers.Sequence(
+ [tokenizers.normalizers.Replace("x", "abcd"), tokenizers.normalizers.Prepend("p")]
+ )
+ raw_splitter = model.data_processor.words_splitter
+ text = "x" * (2 * MAX_WORD_CHARS) + ("-" + "x" * MAX_WORD_CHARS) * repetitions
+ canonical = [(word, start, end) for word, start, end, _ in pieces(raw_splitter(text), text)]
+ expected = len(tokenizer([word for word, _, _ in canonical], is_split_into_words=True)["input_ids"])
+ adapter = load(adapter_class, model)
+
+ output = adapter.extract([Item(text=text), Item(text="Priya Raman")], labels=["person"])
+
+ assert output.errors is None
+ assert output.input_token_counts is not None
+ assert output.input_token_counts[0] == expected
+ assert adapter._doc_input_token_counts([text], ["person"]) == [expected]
+ windows = gliner_windows(model, [text])[0]
+ assert windows is not None
+ assert len(windows) > 1
+ assert text[windows[1].start] == "-"
+ rows, _, _ = window_rows([text], [windows])
+ seen = []
+ budget = subword_budget(384, DEBERTA)
+ for row, window in zip(rows, windows, strict=True):
+ planned = list(model.data_processor.words_splitter(row))
+ assert sum(model.data_processor.words_splitter.count_subwords([word for word, _, _ in planned])) <= budget
+ seen.extend(
+ (word, window.start + start, window.start + end) for word, start, end in planned[window.overlap or 0 :]
+ )
+ assert seen == canonical
+ expected_rows = [tuple(word for word, _, _ in model.data_processor.words_splitter(row)) for row in rows]
+ expected_rows.append(("Priya", "Raman"))
+ assert Counter(map(tuple, model.inferred_words)) == Counter(expected_rows)
+
+
def test_a_document_needing_too_many_windows_fails_rather_than_being_read_in_part(
adapter_and_model: tuple[Any, NameFinder],
) -> None:
diff --git a/packages/sie_server/tests/adapters/test_word_window.py b/packages/sie_server/tests/adapters/test_word_window.py
index 7075c374d..cb59c5887 100644
--- a/packages/sie_server/tests/adapters/test_word_window.py
+++ b/packages/sie_server/tests/adapters/test_word_window.py
@@ -23,6 +23,7 @@ from sie_server.adapters._word_window import (
read_window,
split_word_counter,
subword_budget,
+ window_rows,
)
_WORD = re.compile(r"\w+(?:[-_]\w+)*|\S")
@@ -281,12 +282,58 @@ def test_windows_of_a_document_longer_than_the_window_limit_are_none() -> 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:
[email protected]("budget", [1, 256, 512, 768])
+def test_windows_keep_long_word_pieces_when_a_window_starts_on_a_hyphen(budget: int) -> None:
+ text = "x" * MAX_WORD_CHARS + ("-" + "x" * (MAX_WORD_CHARS - 1)) * 7 + " tail"
+ reader = splitter(10, max_subwords=budget)
+ expected = [(word, start, end) for word, start, end, _ in pieces(words(text), text)]
+
+ windows = document_windows(text, reader)
+
+ assert windows is not None
+ rows, _, overlaps = window_rows([text], [windows])
+ seen = []
+ for row, window, overlap in zip(rows, windows, overlaps, strict=True):
+ read = list(reader(row))
+ seen.extend((word, window.start + start, window.start + end) for word, start, end in read[overlap or 0 :])
+ # The first word may exceed the budget, but subsequent words may not.
+ assert len(read) == 1 or sum(len(word) for word, _, _ in read) <= budget
+ assert seen == expected
+
+
+def test_identical_window_texts_keep_independent_document_word_boundaries() -> None:
+ suffix = "-" + "x" * (MAX_WORD_CHARS - 1)
+ texts = ["x" * MAX_WORD_CHARS + suffix, suffix]
+ reader = splitter(2, max_subwords=MAX_WORD_CHARS)
+ plans = [document_windows(text, reader) for text in texts]
+
+ rows, owners, _ = window_rows(texts, plans)
+
+ assert owners == [0, 0, 1]
+ assert rows[1] == rows[2] == suffix
+ assert [word for word, _, _ in reader(rows[1])] == [suffix]
+ assert [word for word, _, _ in reader(rows[2])] == ["-", suffix[1:]]
+ # Reading the other document does not alter an already-planned window.
+ assert [word for word, _, _ in reader(rows[1])] == [suffix]
+
+
+def test_windows_of_a_long_document_count_only_a_bounded_prefix() -> None:
text = " ".join(f"w{index}" for index in range(200_000))
+ batches: list[list[str]] = []
+
+ def count(batch: Sequence[str]) -> list[int]:
+ batches.append(list(batch))
+ return per_char(batch)
+
+ reader = WindowedSplitter(words, max_words=64, max_subwords=1000, count_subwords=count)
- windows = document_windows(text, splitter(64), max_windows=10)
+ windows = document_windows(text, reader, max_windows=10)
assert windows is None
+ assert all(len(batch) <= 64 for batch in batches)
+ # First window: 64 words, then 32 new words in each of 9 windows. At most
+ # one counting block may be prefetched; none of the huge remainder is tokenized.
+ assert sum(map(len, batches)) <= 64 + 9 * 32 + 64
def span(start: int, end: int, score: float, label: str = "person") -> dict[str, Any]: