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(decision): token-accurate batch costs for decision adapters (#978)
Shai Shmuel91c778f4d502
diff --git a/packages/sie_server/src/sie_server/adapters/decision/base.py b/packages/sie_server/src/sie_server/adapters/decision/base.pyindex 2a44c06fb..28d430df5 100644--- a/packages/sie_server/src/sie_server/adapters/decision/base.py+++ b/packages/sie_server/src/sie_server/adapters/decision/base.py@@ -17,6 +17,9 @@ from sie_server.types.responses import ErrorCodeMAX_ITEM_TOKENS = 32_768MAX_FORWARD_ROWS = 8+# Character allowance per row for the system prompt, chat template and option framing that+# the unloaded fallback cost does not render (the d3 and qev system prompts are ~180 chars).+_ROW_CHARS = 384def check_token_budget(length: int, total: int, window: int) -> int:@@ -51,6 +54,8 @@ class DecisionBatchAdapter(BaseAdapter):_max_seq_length: int_max_forward_tokens: int+ # ``extract_item_costs`` tokenizes once loaded, so async callers run it off the event loop.+ extract_item_costs_tokenizes = Truedef _check_decision_loaded(self) -> None:raise NotImplementedError@@ -182,21 +187,46 @@ class DecisionBatchAdapter(BaseAdapter):options: dict[str, Any] | None = None,**kwargs: Any,) -> list[int] | None:+ """Per-item batching cost in model tokens, the unit of the profile's ``max_batch_tokens``.++ Once loaded, each item is rendered by ``_item_rows``, the same prompt template, question+ rendering and tokenizer ``extract`` runs, and the cost is the sum of its unpadded row+ lengths. Before load, or if rendering fails for a reason ``extract`` will report itself,+ the cost falls back to one token per rendered character plus a per-row template allowance.+ This only groups work: ``extract`` still enforces the exact row and item token limits.+ """_ = kwargstry:questions = self._extract_questions(labels, output_schema, instruction, options)except (InvalidInputError, InputTooLongError):return None- prompt_chars = sum(- len(question.instructions) + sum(map(len, question.descriptions)) + 8 * len(question.keys) + 512+ try:+ self._check_decision_loaded()+ loaded = True+ except Exception: # noqa: BLE001 - not loaded yet: use the character bound+ loaded = False+ question_chars = sum(+ len(question.instructions) + sum(map(len, question.descriptions)) + 8 * len(question.keys) + _ROW_CHARSfor question in questions)limit = MAX_ITEM_TOKENS * 4costs: list[int] = []for item in items:try:- state = describe(self._raw_state(item), self._max_seq_length * 64)- costs.append(min(limit, 2 * (len(questions) * len(state) + prompt_chars)))+ tokens = self._item_tokens(item, questions) if loaded else None+ if tokens is None:+ state = describe(self._raw_state(item), self._max_seq_length * 64)+ tokens = len(questions) * len(state) + question_chars+ costs.append(min(limit, tokens))except (InvalidInputError, InputTooLongError):costs.append(limit)return costs++ def _item_tokens(self, item: Item, questions: tuple[Question, ...]) -> int | None:+ """Unpadded tokens of the rows ``extract`` would run for ``item``; ``None`` if rendering failed."""+ try:+ return sum(row.length for row in self._item_rows(0, item, questions))+ except (InvalidInputError, InputTooLongError):+ raise+ except Exception: # noqa: BLE001 - a cost estimate must never fail the request+ return Nonediff --git a/packages/sie_server/src/sie_server/adapters/pplx_decider/adapter.py b/packages/sie_server/src/sie_server/adapters/pplx_decider/adapter.pyindex 8e4ff19d5..c2e07c9d4 100644--- a/packages/sie_server/src/sie_server/adapters/pplx_decider/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/pplx_decider/adapter.py@@ -62,6 +62,8 @@ class PerplexityDecisionAdapter(DecisionBatchAdapter):outputs=("json",),unload_fields=("_model", "_processor", "_tokenizer"),)+ # The override below prices items from character counts alone.+ extract_item_costs_tokenizes = Falsedef __init__(self,diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.pyindex c4a87252f..fa65f1473 100644--- a/packages/sie_server/src/sie_server/api/extract.py+++ b/packages/sie_server/src/sie_server/api/extract.py@@ -18,7 +18,7 @@ from sie_server.api.routing import remote_routing, route_requestfrom sie_server.api.serialization import MsgPackResponsefrom sie_server.api.validation import validate_machine_profile_headerfrom sie_server.core.extract_cost import (- adapter_extract_item_costs,+ adapter_extract_item_costs_off_loop,build_extract_prepared_items,dispatches_items_alone,)@@ -153,7 +153,7 @@ async def _extract_via_worker(adapter = registry.get(model)except (AttributeError, KeyError):adapter = None- item_costs = adapter_extract_item_costs(+ item_costs = await adapter_extract_item_costs_off_loop(adapter,items,labels=labels,diff --git a/packages/sie_server/src/sie_server/core/extract_cost.py b/packages/sie_server/src/sie_server/core/extract_cost.pyindex 287d15e19..bfdeda2ce 100644--- a/packages/sie_server/src/sie_server/core/extract_cost.py+++ b/packages/sie_server/src/sie_server/core/extract_cost.py@@ -32,6 +32,8 @@ adopt it without coordinating on a calibration table.from __future__ import annotations+import asyncio+import functoolsfrom typing import TYPE_CHECKING, Any, Finalfrom sie_server.core.prepared import ExtractPreparedItem@@ -173,6 +175,37 @@ def adapter_extract_item_costs(return _usable_item_costs(costs, len(items))+async def adapter_extract_item_costs_off_loop(+ adapter: object,+ 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:+ """``adapter_extract_item_costs`` for callers on the event loop.++ An adapter that sets ``extract_item_costs_tokenizes = True`` renders and+ tokenizes every item to price it, which takes milliseconds per item and+ would stall every other request if it ran on the loop. Its estimate runs+ on a worker thread; every other adapter's estimate is character+ arithmetic and stays inline.+ """+ estimate = functools.partial(+ adapter_extract_item_costs,+ adapter,+ items,+ labels=labels,+ output_schema=output_schema,+ instruction=instruction,+ options=options,+ )+ if getattr(adapter, "extract_item_costs_tokenizes", False) is True:+ return await asyncio.to_thread(estimate)+ return estimate()++def _usable_item_costs(costs: object, expected_len: int) -> list[int] | None:if not isinstance(costs, list) or len(costs) != expected_len:return Nonediff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 3d8e85870..276f0e52d 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -27,7 +27,7 @@ from sie_server.config.upstreams import validate_profile_upstreamsfrom sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_typesfrom sie_server.core.extract_cost import (MAX_EXTRACT_LABELS,- adapter_extract_item_costs,+ adapter_extract_item_costs_off_loop,build_extract_prepared_items,output_schema_shape_error,)@@ -1723,7 +1723,7 @@ class QueueExecutor:# Batching proxy only; authoritative text/page billing# comes from the adapter's ExtractOutput unit counts.# The sidecar sizes queue batches (cost 1 per extract item); this cost does not.- item_costs = adapter_extract_item_costs(+ item_costs = await adapter_extract_item_costs_off_loop(extract_adapter,[server_item],labels=bi.labels,diff --git a/packages/sie_server/tests/adapters/test_decision_classification.py b/packages/sie_server/tests/adapters/test_decision_classification.pyindex 593d96f97..f737b444e 100644--- a/packages/sie_server/tests/adapters/test_decision_classification.py+++ b/packages/sie_server/tests/adapters/test_decision_classification.py@@ -1,14 +1,20 @@"""The label contract is shared by NLI, Qwen and engine-backed decisions."""+import asyncio+import threadingfrom types import SimpleNamespacefrom unittest.mock import Mockimport pytestimport torch-from sie_server.adapters.decision.base import Row+from sie_server.adapters.decision import d3, qev+from sie_server.adapters.decision.base import MAX_ITEM_TOKENS, Rowfrom sie_server.adapters.decision.qwen import QwenDecisionAdapter+from sie_server.adapters.errors import InputTooLongErrorfrom sie_server.adapters.nli_classification_flash import NLIClassificationFlashAdapter+from sie_server.adapters.pplx_decider.adapter import PerplexityDecisionAdapterfrom sie_server.adapters.sglang.decision import SGLangDecisionAdapter+from sie_server.core.extract_cost import adapter_extract_item_costs_off_loopfrom sie_server.types.inputs import InvalidInputError, Item@@ -124,3 +130,105 @@ def test_typed_questions_keep_their_existing_output(decision):output = decision.extract([Item(text="hello")], output_schema={"spam": {"type": "noul"}})assert output.classifications is Noneassert output.data == [{"spam": {"type": "noul", "noul": 0.75, "answer": True, "confidence": 0.75}}]+++def test_loaded_costs_are_the_unpadded_tokens_of_the_rendered_rows(decision):+ items = [Item(text="a message"), Item(text="x" * 65)]+ costs = decision.extract_item_costs(items, labels=["spam", "ham"], options={"multi_label": True})+ assert costs == [18, 130]+ assert [call.args[1] for call in decision._item_rows.call_args_list] == items+++def test_unloaded_or_unrenderable_costs_use_a_bounded_character_estimate(decision):+ items = [Item(text="a message about an invoice")]+ exact = decision.extract_item_costs(items, labels=["spam"])+ decision._check_decision_loaded.side_effect = RuntimeError("not loaded")+ unloaded = decision.extract_item_costs(items, labels=["spam"])+ decision._check_decision_loaded.side_effect = None+ decision._item_rows.side_effect = ValueError("template")+ unrenderable = decision.extract_item_costs(items, labels=["spam"])+ question = decision._extract_questions(["spam"], None, None, None)[0]+ chars = len(items[0].text) + len(question.instructions) + sum(map(len, question.descriptions))+ assert exact == [len(items[0].text)]+ assert unloaded == unrenderable == [chars + 8 * len(question.keys) + 384]+ # Below the previous estimate, 2 * (characters + 512 per question).+ assert unloaded[0] < chars + 8 * len(question.keys) + 512+++def test_costs_of_items_extract_rejects_stay_at_the_limit(decision):+ decision._item_rows.side_effect = InputTooLongError("too long")+ assert decision.extract_item_costs([Item(text="hello")], labels=["spam"]) == [MAX_ITEM_TOKENS * 4]+ assert decision.extract_item_costs([Item(text="a", images=[{"data": b"x"}])], labels=["spam"]) == [+ MAX_ITEM_TOKENS * 4+ ]+++class _CharTokenizer:+ all_special_tokens = ("<|im_start|>", "<|im_end|>")+ pad_token_id = 0++ def apply_chat_template(self, messages, **kwargs):+ _ = kwargs+ return (+ "".join(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>" for m in messages) + "<|im_start|>assistant\n"+ )++ def encode(self, text, **kwargs):+ _ = kwargs+ return list(map(ord, text))++ def __call__(self, text, **kwargs):+ _ = kwargs+ return {"input_ids": self.encode(text), "offset_mapping": [(i, i + 1) for i in range(len(text))]}++[email protected]("decision_format", ["d3", "qev"])+def test_qwen_costs_match_the_prompts_extract_tokenizes(decision_format):+ adapter = QwenDecisionAdapter("unused", decision_format=decision_format)+ adapter._model, adapter._tokenizer, adapter._codes = Mock(), _CharTokenizer(), ("A", "B", "C")+ schema = {+ "topic": {"type": "choice", "instructions": "Topic?", "criteria": {"world": None, "sports": None}},+ "spam": {"type": "noul"},+ }+ state = "Stocks rallied after the earnings report."+ questions = adapter._parse_questions(schema)+ rendered = (+ d3.prompts(adapter._tokenizer, state, questions, adapter._codes)+ if decision_format == "d3"+ else qev.prompts(adapter._tokenizer, state, questions)+ )+ (cost,) = adapter.extract_item_costs([Item(text=state)], output_schema=schema)+ assert cost == sum(len(ids) for ids, _ in rendered)+++def _estimating_thread(adapter) -> tuple[list[int] | None, int]:+ seen: list[int] = []+ estimate = adapter.extract_item_costs++ def recording(*args, **kwargs):+ seen.append(threading.get_ident())+ return estimate(*args, **kwargs)++ adapter.extract_item_costs = recording+ costs = asyncio.run(adapter_extract_item_costs_off_loop(adapter, [Item(text="a message")], labels=["spam"]))+ return costs, seen[0]+++def test_tokenizing_costs_run_off_the_event_loop_thread(decision):+ costs, thread = _estimating_thread(decision)+ assert costs == [len("a message")]+ assert thread != threading.get_ident()+++def test_character_costs_stay_on_the_event_loop_thread(decision):+ decision.extract_item_costs_tokenizes = False+ costs, thread = _estimating_thread(decision)+ assert costs == [len("a message")]+ assert thread == threading.get_ident()+++def test_only_adapters_that_tokenize_costs_ask_for_a_thread():+ assert QwenDecisionAdapter.extract_item_costs_tokenizes is True+ assert SGLangDecisionAdapter.extract_item_costs_tokenizes is True+ assert PerplexityDecisionAdapter.extract_item_costs_tokenizes is False+ assert asyncio.run(adapter_extract_item_costs_off_loop(Mock(spec=[]), [Item(text="x")])) is None