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): size NLI zero-shot extract batches by the rows each item runs (#465)
svonava57a98562cba9
diff --git a/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.pyindex ff79bb400..54db6dbd3 100644--- a/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py@@ -23,6 +23,8 @@ logger = logging.getLogger(__name__)_ERR_REQUIRES_LABELS = "Zero-shot classification requires labels parameter."_ERR_TOO_MANY_LABELS = f"Zero-shot classification requests may carry at most {MAX_EXTRACT_LABELS} labels"+# Characters per token assumed when sizing a (text, hypothesis) row for batching.+_COST_CHARS_PER_TOKEN = 4class NLIClassificationFlashAdapter(FlashBaseAdapter):@@ -153,6 +155,37 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):raise ValueError(ERR_REQUIRES_TEXT.format(adapter_name="NLIClassificationFlashAdapter"))return item.text+ def extract_item_costs(+ self,+ items: list[Item],+ *,+ labels: list[str] | None = None,+ output_schema: dict[str, Any] | None = None,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ ) -> list[int] | None:+ """Batching cost per item: the characters of every (text, hypothesis) row it runs.++ The model reads an item's text once per label, next to that label's+ hypothesis, so the default per-item character count undercounts a+ request by its label count and lets the batcher pack many-label items+ into one oversized forward. Each row is capped at the characters the+ window holds. Runs before batching and validation; best-effort, never+ raises (malformed requests fail in extract()).+ """+ _ = output_schema, instruction+ try:+ if not labels or len(labels) > MAX_EXTRACT_LABELS:+ return None+ template = (options or {}).get("hypothesis_template", self._hypothesis_template)+ if not isinstance(template, str):+ template = self._hypothesis_template+ limit = self._max_length * _COST_CHARS_PER_TOKEN+ hypotheses = [len(template) + len(label) for label in labels if isinstance(label, str)]+ return [sum(min(len(item.text or "") + chars, limit) for chars in hypotheses) for item in items]+ except Exception: # noqa: BLE001 -- a cost estimate must never fail a request+ return None+def extract(self,items: list[Item],diff --git a/packages/sie_server/tests/adapters/test_nli_classification_flash_usage.py b/packages/sie_server/tests/adapters/test_nli_classification_flash_usage.pyindex 6b4766722..aa7e6c1a6 100644--- a/packages/sie_server/tests/adapters/test_nli_classification_flash_usage.py+++ b/packages/sie_server/tests/adapters/test_nli_classification_flash_usage.py@@ -8,17 +8,20 @@ same tokenizer called on one pair at a time, so they never see padding.from __future__ import annotations+from pathlib import Pathfrom types import SimpleNamespaceimport pytestimport torchfrom sie_server.adapters.nli_classification_flash import NLIClassificationFlashAdapter-from sie_server.core.extract_cost import MAX_EXTRACT_LABELS+from sie_server.core.extract_cost import MAX_EXTRACT_LABELS, adapter_extract_item_costs, build_extract_prepared_items+from sie_server.core.loader import load_model_configsfrom sie_server.types.inputs import InvalidInputError, Itemfrom tokenizers import Tokenizer, models, pre_tokenizers, processorsfrom transformers import PreTrainedTokenizerFast_MAX_LENGTH = 32+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"_TEMPLATE = "This text is about {}."_WORDS = ["this",@@ -158,3 +161,49 @@ def test_flash_adapter_refuses_more_labels_than_the_extract_limit() -> None:with pytest.raises(InvalidInputError, match=f"at most {MAX_EXTRACT_LABELS} labels"):adapter.extract([Item(text="i was charged twice")], labels=_labels(MAX_EXTRACT_LABELS + 1))+++def test_batch_cost_counts_every_row_an_item_runs() -> None:+ adapter = NLIClassificationFlashAdapter("test-model", hypothesis_template=_TEMPLATE, max_length=_MAX_LENGTH)+ texts = ["i was charged twice", "the app crashes on startup"]+ labels = ["bug", "billing", "feature request"]++ costs = adapter.extract_item_costs([Item(text=text) for text in texts], labels=labels)++ assert costs == [sum(len(text) + len(_TEMPLATE) + len(label) for label in labels) for text in texts]+ custom = adapter.extract_item_costs(+ [Item(text=texts[0])], labels=labels, options={"hypothesis_template": "It is {}"}+ )+ assert custom == [sum(len(texts[0]) + len("It is {}") + len(label) for label in labels)]+++def test_batch_cost_caps_each_row_at_the_window() -> None:+ adapter = NLIClassificationFlashAdapter("test-model", max_length=_MAX_LENGTH)+ long_text = "the app crashes on startup " * 200++ (cost,) = adapter.extract_item_costs([Item(text=long_text)], labels=["bug", "billing"]) or [0]++ assert cost == 2 * _MAX_LENGTH * 4+++def test_batch_cost_splits_many_label_items_the_character_count_would_pack() -> None:+ config = load_model_configs(_MODELS_DIR)["MoritzLaurer/deberta-v3-large-zeroshot-v2.0"]+ budget = config.profiles["default"].max_batch_tokens+ adapter = NLIClassificationFlashAdapter("test-model")+ items = [Item(text="I still have not received my new card, I ordered over a week ago.") for _ in range(16)]+ labels = [f"intent number {index}" for index in range(77)]++ default = build_extract_prepared_items(items)+ paired = build_extract_prepared_items(items, item_costs=adapter_extract_item_costs(adapter, items, labels=labels))++ assert sum(item.cost for item in default) <= budget+ assert sum(item.cost for item in paired) > budget+ assert paired[0].cost == 77 * default[0].cost + sum(len("This text is about {}.") + len(label) for label in labels)+++def test_batch_cost_defers_to_extract_for_requests_it_refuses() -> None:+ adapter = NLIClassificationFlashAdapter("test-model")+ items = [Item(text="i was charged twice")]++ assert adapter.extract_item_costs(items, labels=None) is None+ assert adapter.extract_item_costs(items, labels=_labels(MAX_EXTRACT_LABELS + 1)) is None