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): fail only the over-long GLiClass item under overflow_policy error (#429)
svonava0db8a34936f2
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex 9f22be40b..00cab38e1 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -150,9 +150,12 @@ that row's label prompt, unless the document count alone is already higher.An item whose document pushes the labels out of the window, in any of its rows,comes back with an `INPUT_TOO_LONG` error in its `error` field and is notbilled. The other items still succeed. Models that read the labels before-the document count only the part of the document they read, and a row whose-labels leave no room for the document fails its item the same way, instead of-being scored without the document.+the document count only the part of the document they read. Under the default+overflow policy, a row whose labels leave the document fewer than 8 tokens+fails its item the same way, instead of being scored with little or none of+the document; `truncate_text` and `error` accept a document cut to, or fitting+in, a smaller room. With `options={"overflow_policy": "error"}`, a document+that does not fit whole fails only its own item, the same way.On a CUDA server, the operator can load the DeBERTa-based GLiClass models withCUDA graphs, which cut the CPU time spent launching kernels. With `bucketed`diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 2353c9f21..39f10e9c5 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -75,12 +75,20 @@ The models that read the labels before the document (`prompt_first` in thecheckpoint's config: every shipped GLiClass model except `gliclass-small-v1.0`,`gliclass-base-v1.0` and `gliclass-large-v1.0`) cut the document to the roomthe label prompt and instruction leave, and count only the part of the document-they read, as `truncate_text` would. When the labels leave no room for any of-the document, each item returns a per-item `INPUT_TOO_LONG` error and counts-nothing, rather than being scored without its document. With `overflow_policy`-`truncate_text` or `error`, such a request is refused with `INPUT_TOO_LONG`, as+they read, as `truncate_text` would. When the labels leave fewer than 8 tokens+for the document (a margin for tokenization at the boundary), each item returns+a per-item `INPUT_TOO_LONG` error and counts nothing, rather than being scored+with little or none of its document. With `overflow_policy` `truncate_text` or+`error`, the document is cut to that room or checked against it instead, and a+request whose labels leave no room at all is refused with `INPUT_TOO_LONG`, asbefore.+With `options={"overflow_policy": "error"}`, an item whose document does not+fit whole next to the labels returns a per-item `INPUT_TOO_LONG` error and+counts nothing, while the other items succeed. Concurrent requests that share+labels and options are batched into one model call, so an over-long document+fails only its own item, never another request's.+The instruction and each example text may be at most 2,048 characters, andtogether with the example labels at most 8,192 characters. Up to 32 examplesare accepted, and they must leave room for the document in the model window.diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.pyindex bad634272..ff551f76e 100644--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py@@ -154,13 +154,21 @@ _ERR_ITEM_LABELS_TRUNCATED = ("Shorten the document, or send options.overflow_policy='truncate_text'.")# Models that read the labels first (``prompt_first``) cut the document to the-# room the label prompt and instruction leave. An item is refused unless its-# document keeps at least this many tokens, rather than scored without it.-_MIN_DOCUMENT_TOKENS = 1+# room the label prompt and instruction leave. Under the default overflow+# policy an item is refused unless that room holds at least this many tokens,+# rather than scored without its document. The room is counted on the parts+# tokenized apart; a token or two can merge where the instruction meets the+# document, so the floor is the fit check's margin rather than one token.+_MIN_DOCUMENT_TOKENS = _FIT_MARGIN_TOKENS_ERR_ITEM_NO_ROOM_FOR_DOCUMENT = ("The labels leave no room for the document in the gliclass model's max sequence length, ""so the model would not read it. Send fewer or shorter labels.")+_ERR_ITEM_DOCUMENT_TOO_LONG = (+ "The document does not fit whole in the gliclass model's max sequence length next to the labels "+ "({observed} tokens, at most {limit}), and options.overflow_policy is 'error'. Shorten the document, "+ "or send options.overflow_policy='truncate_text'."+)_ERR_ITEM_DOCUMENT_TOO_SPARSE = ("The part of the document the gliclass model reads spans more than {limit} characters, too many to ""encode once per label group. Shorten the document, send fewer groups, or send "@@ -673,8 +681,7 @@ class GLiClassAdapter(BaseAdapter):prompt: str | None = None,examples: list[dict[str, Any]] | None = None,tokens: _RequestTokens | None = None,- indices: list[int] | None = None,- ) -> list[str]:+ ) -> tuple[list[str], list[str | None]]:"""Enforce overflow_policy by pre-tokenizing text and label_prompt separately.The model sees ``observed = text_tokens + label_prompt_tokens +@@ -689,17 +696,22 @@ class GLiClassAdapter(BaseAdapter):- ``default`` returns texts unchanged (upstream as-is — may crash insidethe model; ``_overflow_errors_as_input_too_long`` in ``extract`` isthe defense-in-depth backstop).- - ``error`` raises ``InputTooLongError`` (whole batch fails, no partial- responses).+ - ``error`` fails each item whose document does not fit whole with an+ ``INPUT_TOO_LONG`` message; the other items run. One call can hold+ several callers' requests with the same labels and options, so one+ document never fails another caller's items, and no message names+ an item index.- ``truncate_text`` slices text to``budget = max_sequence_length - label_prompt_tokens - special_count``.Under ``truncate_text`` and ``error``, ``label_prompt`` alone exceeding- the cap always raises. ``indices`` gives each text's item index for- error messages when ``texts`` is a subset of the items.+ the cap always raises: every request in the call shares the labels.++ Returns the texts to encode and, per text, why it fails (or None)."""+ failures: list[str | None] = [None] * len(texts)if policy == "default":- return texts+ return texts, failuresif self._pipe is None or self._tokenizer is None or self._max_seq_length is None:raise RuntimeError(ERR_NOT_LOADED)@@ -723,20 +735,16 @@ class GLiClassAdapter(BaseAdapter):new_texts.append(text)continueif policy == "error":- index = i if indices is None else indices[i]if text in tokens.shortened and tokens.visible_tokens is not None:# Only a prefix of this document was tokenized.- text_tokens = tokens.visible_tokens- counts = f"observed_tokens>={text_tokens + overhead}"- text_count = f"text>={text_tokens}"+ observed_count = f"at least {tokens.visible_tokens + overhead}"else:- counts, text_count = f"observed_tokens={observed}", f"text={text_tokens}"- raise InputTooLongError(- f"items[{index}] {counts} exceeds max_sequence_length ({self._max_seq_length}) "- f"({text_count}, label_prompt={label_prompt_tokens}, special={self._special_count})"- )+ observed_count = str(observed)+ failures[i] = _ERR_ITEM_DOCUMENT_TOO_LONG.format(observed=observed_count, limit=self._max_seq_length)+ new_texts.append(text)+ continuenew_texts.append(self._tokenizer.decode(text_ids[:budget], skip_special_tokens=True))- return new_texts+ return new_texts, failuresdef extract(self,@@ -837,11 +845,14 @@ class GLiClassAdapter(BaseAdapter):)texts = [tokens.visible(text) or text for text in texts]- texts = self._apply_overflow_policy(+ texts, overflows = self._apply_overflow_policy(texts, normalized_labels, overflow_policy, prompt=prompt, examples=examples, tokens=tokens)layout = self._request_layout(normalized_labels, prompt, examples, tokens)- failures = self._item_failures(texts, layout, normalized_labels, prompt, examples, tokens=tokens)+ failures = self._item_failures(+ texts, layout, normalized_labels, prompt, examples, tokens=tokens, overflow_policy=overflow_policy+ )+ failures = [overflow or failure for overflow, failure in zip(overflows, failures, strict=True)]fits = [failure is None for failure in failures]input_token_counts = self._input_token_counts(texts, prompt, examples, layout, fits, tokens=tokens)errors = self._item_errors(failures)@@ -1234,17 +1245,19 @@ class GLiClassAdapter(BaseAdapter):overflow=overflow_policy != "default",)row_examples = group_examples[group] if group_examples is not None else None- row_texts = self._apply_overflow_policy(+ row_texts, row_overflows = self._apply_overflow_policy([cast("str", texts[index]) for index in alive],group_labels,overflow_policy,prompt=prompt,examples=row_examples,tokens=tokens,- indices=alive,)layout = self._request_layout(group_labels, prompt, row_examples, tokens)- row_failures = self._item_failures(row_texts, layout, group_labels, prompt, row_examples, tokens=tokens)+ row_failures = self._item_failures(+ row_texts, layout, group_labels, prompt, row_examples, tokens=tokens, overflow_policy=overflow_policy+ )+ row_failures = [overflow or failure for overflow, failure in zip(row_overflows, row_failures, strict=True)]row_counts = self._input_token_counts(row_texts, prompt, row_examples, layout, [True] * len(alive), tokens=tokens)@@ -1854,14 +1867,19 @@ class GLiClassAdapter(BaseAdapter):examples: list[dict[str, Any]] | None,*,tokens: _RequestTokens | None = None,+ overflow_policy: OverflowPolicy = DEFAULT_OVERFLOW_POLICY,) -> list[str | None]:"""Why each item cannot be scored as sent (an ``INPUT_TOO_LONG`` message), or None.A model that reads the labels first keeps every label and cuts thedocument to the room left after the label prompt and instruction.- When that room is under ``_MIN_DOCUMENT_TOKENS``, the model would read- none of the document, so every item is refused. Otherwise a longer- document is cut, as ``truncate_text`` would cut it.+ Under the default overflow policy, when that room is under+ ``_MIN_DOCUMENT_TOKENS`` the model might read none of the document,+ so every item is refused. Otherwise a longer document is cut, as+ ``truncate_text`` would cut it. ``truncate_text`` and ``error`` have+ already cut or checked each document against the room, and refused+ the request when the labels leave none (see+ ``_apply_overflow_policy``).A model that reads the document first keeps the document and losesthe labels past the window, so an item is refused when its document@@ -1876,8 +1894,8 @@ class GLiClassAdapter(BaseAdapter):if layout is None or self._tokenizer is None:return [None] * len(texts)if layout.prompt_first:- failure = None if layout.document_room >= _MIN_DOCUMENT_TOKENS else _ERR_ITEM_NO_ROOM_FOR_DOCUMENT- return [failure] * len(texts)+ no_room = overflow_policy == "default" and layout.document_room < _MIN_DOCUMENT_TOKENS+ return [_ERR_ITEM_NO_ROOM_FOR_DOCUMENT if no_room else None] * len(texts)tokens = tokens or _RequestTokens(self._tokenizer)failures: list[str | None] = []for text, ids in zip(texts, tokens.cut(texts, layout.window + _FIT_MARGIN_TOKENS), strict=True):diff --git a/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.pyindex 6df836d1c..f88d5fa60 100644--- a/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py+++ b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py@@ -44,45 +44,53 @@ class TestApplyOverflowPolicy:adapter = _make_adapter()texts = ["a b c d e f g h i j"] # 10 tokens, observed = 16 > 10- assert adapter._apply_overflow_policy(texts, _LABELS, "default") == texts+ assert adapter._apply_overflow_policy(texts, _LABELS, "default") == (texts, [None])def test_default_is_the_default_arg(self) -> None:adapter = _make_adapter()texts = ["a b c d e f g h i j"]- assert adapter._apply_overflow_policy(texts, _LABELS) == texts+ assert adapter._apply_overflow_policy(texts, _LABELS) == (texts, [None])def test_truncate_text_passes_fitting_text_through(self) -> None:adapter = _make_adapter()texts = ["a b c d"] # 4 tokens, observed = 10- assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b c d"]+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == (["a b c d"], [None])def test_truncate_text_slices_overflowing_text_to_budget(self) -> None:adapter = _make_adapter()texts = ["a b c d e f g"] # 7 tokens, budget = 4- assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b c d"]+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == (["a b c d"], [None])def test_truncate_text_mixed_batch(self) -> None:adapter = _make_adapter()texts = ["a b", "a b c d e f g"]- assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == ["a b", "a b c d"]+ assert adapter._apply_overflow_policy(texts, _LABELS, "truncate_text") == (["a b", "a b c d"], [None, None])- def test_error_raises_on_overflowing_text(self) -> None:+ def test_error_fails_only_the_overflowing_text(self) -> None:adapter = _make_adapter()- texts = ["a b c d e"] # 5 tokens, observed = 11 > 10+ texts = ["a b", "a b c d e"] # the second is 5 tokens, observed = 11 > 10- with pytest.raises(InputTooLongError, match=r"items\[0\] observed_tokens=11"):- adapter._apply_overflow_policy(texts, _LABELS, "error")+ out, failures = adapter._apply_overflow_policy(texts, _LABELS, "error")- def test_error_reports_first_overflowing_item_index(self) -> None:+ assert out == texts+ assert failures[0] is None+ assert failures[1] is not None+ assert "(11 tokens, at most 10)" in failures[1]+ assert "overflow_policy is 'error'" in failures[1]++ def test_error_messages_name_no_item_index(self) -> None:+ # One adapter call can hold several callers' requests, so an index+ # would point into another caller's items.adapter = _make_adapter()- texts = ["a b", "a b c d e f"]- with pytest.raises(InputTooLongError, match=r"items\[1\]"):- adapter._apply_overflow_policy(texts, _LABELS, "error")+ _, failures = adapter._apply_overflow_policy(["a b", "a b c d e f"], _LABELS, "error")++ assert failures[1] is not None+ assert "items[" not in failures[1]def test_label_prompt_overflow_raises_under_truncate_text(self) -> None:adapter = _make_adapter(max_seq_length=5) # overhead 6 > 5@@ -100,7 +108,7 @@ class TestApplyOverflowPolicy:adapter = _make_adapter(max_seq_length=5)texts = ["a b c"]- assert adapter._apply_overflow_policy(texts, _LABELS, "default") == texts+ assert adapter._apply_overflow_policy(texts, _LABELS, "default") == (texts, [None])class _RaisingPipe:diff --git a/packages/sie_server/tests/adapters/test_gliclass_request_options.py b/packages/sie_server/tests/adapters/test_gliclass_request_options.pyindex 81f153db2..a2dda9c9f 100644--- a/packages/sie_server/tests/adapters/test_gliclass_request_options.py+++ b/packages/sie_server/tests/adapters/test_gliclass_request_options.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport mathimport refrom collections.abc import Callable@@ -12,6 +13,9 @@ import pytestimport torchfrom sie_server.adapters.errors import InputTooLongErrorfrom sie_server.adapters.gliclass import GLiClassAdapter+from sie_server.core.inference_output import ExtractOutput+from sie_server.core.prepared import ExtractPreparedItem+from sie_server.core.worker import ModelWorker, WorkerConfigfrom sie_server.types.inputs import InvalidInputError, Item_CLASS_TOKEN = 7@@ -1069,8 +1073,8 @@ class TestOverflowBudget:adapter._pipe = _Pipe()text = " ".join(f"w{i}" for i in range(12))- plain = adapter._apply_overflow_policy([text], ["a"], "truncate_text")- with_context = adapter._apply_overflow_policy(+ plain, _ = adapter._apply_overflow_policy([text], ["a"], "truncate_text")+ with_context, _ = adapter._apply_overflow_policy([text],["a"],"truncate_text",@@ -1189,8 +1193,9 @@ class TestFlatLabelOverflow:# The label prompt is 9 tokens (3 markers, 5 label words and SEP) with its# last marker at index 5. At max_length 11 the window keeps 9 tokens: every- # marker fits, and nothing is left for the document.- @pytest.mark.parametrize(("max_length", "refused"), [(11, True), (12, False)])+ # marker fits, and nothing is left for the document. Room under the fit+ # margin (8 tokens, at max_length 18) is refused too; 8 tokens (19) is not.+ @pytest.mark.parametrize(("max_length", "refused"), [(11, True), (12, True), (18, True), (19, False)])def test_labels_first_items_are_refused_when_the_labels_leave_no_room_for_the_document(self, max_length: int, refused: bool) -> None:@@ -1202,8 +1207,7 @@ class TestFlatLabelOverflow:if not refused:assert output.errors is Noneassert [call["texts"] for call in pipe.prepare_calls] == [["The app crashes", "Charged twice"]]- # The model reads one token of each document: usage counts that token and CLS/SEP.- assert output.input_token_counts == [3, 3]+ assert output.input_token_counts == [5, 4]returnassert pipe.prepare_calls == []assert output.errors is not None@@ -1242,6 +1246,26 @@ class TestFlatLabelOverflow:[Item(text="The app crashes")], labels=list(_LABELS), options={"overflow_policy": "truncate_text"})+ def test_overflow_policy_error_fails_only_the_document_that_does_not_fit(self) -> None:+ # Window of 18 content tokens after CLS/SEP; the label prompt takes 9.+ adapter, pipe = self._adapter(prompt_first=True, max_length=20)+ short, long_text = "The app crashes", " ".join(["word"] * 12)++ output = adapter.extract(+ [Item(text=short), Item(text=long_text)], labels=list(_LABELS), options={"overflow_policy": "error"}+ )++ assert [call["texts"] for call in pipe.prepare_calls] == [[short]]+ assert output.errors is not None+ assert output.errors[0] is None+ assert output.errors[1] is not None+ assert output.errors[1].code == "INPUT_TOO_LONG"+ assert "overflow_policy is 'error'" in output.errors[1].message+ assert "items[" not in output.errors[1].message+ assert output.classifications is not None+ assert output.classifications[1] == []+ assert output.input_token_counts == [5, 0]+def test_truncate_text_cuts_the_document_to_the_room_the_labels_leave(self) -> None:adapter, pipe = self._adapter(prompt_first=True, max_length=12)@@ -1315,3 +1339,59 @@ class TestFlatLabelOverflow:with pytest.raises(InputTooLongError):adapter.extract([Item(text="The app crashes")], labels=list(_LABELS))+++class TestFusedRequestsUnderOverflowPolicyError:+ @pytest.mark.asyncio+ async def test_one_callers_long_document_fails_only_that_item(self) -> None:+ """Two callers with the same labels and options fuse into one adapter call.++ Under overflow_policy "error", the over-long document fails only its+ own item: the other caller's item and the same caller's other item+ are scored, and no message names an item index.+ """+ adapter, _ = _adapter(lambda _text, label: 1.0 if label == "bug report" else 0.0, max_length=20)+ calls: list[int] = []+ extract = adapter.extract++ def counting_extract(items: list[Item], **kwargs: Any) -> ExtractOutput:+ calls.append(len(items))+ return extract(items, **kwargs)++ adapter.extract = counting_extract # ty:ignore[invalid-assignment]+ worker = ModelWorker(+ adapter, WorkerConfig(max_batch_tokens=10_000, max_batch_requests=10, max_batch_wait_ms=50)+ )+ options = {"overflow_policy": "error"}+ await worker.start()+ try:+ first = await worker.submit_extract(+ [ExtractPreparedItem(cost=15, original_index=0)],+ [Item(text="The app crashes")],+ labels=list(_LABELS),+ options=options,+ )+ second = await worker.submit_extract(+ [ExtractPreparedItem(cost=13, original_index=0), ExtractPreparedItem(cost=60, original_index=1)],+ [Item(text="Charged twice"), Item(text=" ".join(["word"] * 12))],+ labels=list(_LABELS),+ options=options,+ )+ first_result = await asyncio.wait_for(first, timeout=5.0)+ second_result = await asyncio.wait_for(second, timeout=5.0)+ finally:+ await worker.stop()++ assert calls == [3]+ assert not any(first_result.output.errors or [])+ assert first_result.output.classifications is not None+ assert first_result.output.classifications[0][0]["label"] == "bug report"+ errors = second_result.output.errors+ assert errors is not None+ assert errors[0] is None+ assert second_result.output.classifications is not None+ assert second_result.output.classifications[0][0]["label"] == "bug report"+ assert errors[1] is not None+ assert errors[1].code == "INPUT_TOO_LONG"+ assert "items[" not in errors[1].message+ assert second_result.output.classifications[1] == []