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
feat(server): share label classification across decision adapters (#901)
svonava57b572e41710
diff --git a/packages/sie_gateway/src/handlers/systemone.rs b/packages/sie_gateway/src/handlers/systemone.rsindex b201d6cc9..d332e3529 100644--- a/packages/sie_gateway/src/handlers/systemone.rs+++ b/packages/sie_gateway/src/handlers/systemone.rs@@ -53,9 +53,15 @@ pub(crate) const MAX_RETRY_AFTER_S: u64 = 60;/// Adapter modules that answer typed questions: the modules of the single/// server's `DECISION_ADAPTERS` (`sie_server.api.systemone`), which names/// their classes.-const DECISION_ADAPTER_MODULES: [&str; 2] = [+const DECISION_ADAPTER_MODULES: [&str; 8] = ["sie_server.adapters.gliner2.decide",+ "sie_server.adapters.gliner2.decide_lora","sie_server.adapters.laya.adapter",+ "sie_server.adapters.laya.runtime_lora",+ "sie_server.adapters.pplx_decider.adapter",+ "sie_server.adapters.pplx_decider.runtime_lora",+ "sie_server.adapters.decision.qwen",+ "sie_server.adapters.sglang.decision",];/// Request fields for media the decision models cannot read.const MEDIA_FIELDS: [&str; 3] = ["images", "audio", "videos"];@@ -673,6 +679,21 @@ mod tests {.expect("systemone fixture")}+ #[test]+ fn decision_adapter_modules_match_the_python_contract() {+ let document = fixture();+ let mut expected: Vec<_> = document["decision_adapters"]+ .as_array()+ .unwrap()+ .iter()+ .map(|adapter| adapter.as_str().unwrap().split(':').next().unwrap())+ .collect();+ let mut actual = DECISION_ADAPTER_MODULES.to_vec();+ expected.sort_unstable();+ actual.sort_unstable();+ assert_eq!(actual, expected);+ }+#[test]fn lora_selectors_survive_systemone_translation() {let base = fixture()["requests"][0]["request"].clone();diff --git a/packages/sie_server/src/sie_server/adapters/decision/base.py b/packages/sie_server/src/sie_server/adapters/decision/base.pyindex 7fb463b06..2a44c06fb 100644--- a/packages/sie_server/src/sie_server/adapters/decision/base.py+++ b/packages/sie_server/src/sie_server/adapters/decision/base.py@@ -8,6 +8,7 @@ from typing import Anyimport torchfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters.decision.classification import classification_schema, classificationsfrom sie_server.adapters.decision.questions import Question, answer, describe, parse_questionsfrom sie_server.adapters.errors import InputTooLongErrorfrom sie_server.core.inference_output import ExtractItemError, ExtractOutput@@ -66,6 +67,31 @@ class DecisionBatchAdapter(BaseAdapter):def _answer(self, question: Question, probabilities: list[float]) -> dict[str, Any]:return answer(question, probabilities)+ def _extract_questions(+ self,+ labels: list[str] | None,+ output_schema: dict[str, Any] | None,+ instruction: str | None,+ options: dict[str, Any] | None,+ ) -> tuple[Question, ...]:+ if instruction is not None:+ raise InvalidInputError("Use classification labels or typed questions with their own instructions")+ if options is not None and not isinstance(options, dict):+ raise InvalidInputError("Decision options must be an object")+ opts = options or {}+ allowed = {"overflow_policy"}+ if labels is not None:+ allowed.update({"hypothesis_template", "multi_label"})+ if set(opts) - allowed or opts.get("overflow_policy", "error") != "error":+ raise InvalidInputError(+ "Unsupported decision options; overflow_policy must be 'error' and calibration is fixed"+ )+ if labels is not None:+ if output_schema is not None:+ raise InvalidInputError("Supply either classification labels or typed output_schema questions")+ output_schema = classification_schema(labels, opts)+ return self._parse_questions(output_schema)+def _raw_state(self, item: Item) -> Any:if item.images or item.audio is not None or item.video is not None or item.document is not None:raise InvalidInputError("Decisions currently accept text only")@@ -102,14 +128,7 @@ class DecisionBatchAdapter(BaseAdapter):) -> ExtractOutput:_ = prepared_itemsself._check_decision_loaded()- if labels is not None or instruction is not None:- raise InvalidInputError("Use typed output_schema questions with their own instructions and criteria")- if options is not None and not isinstance(options, dict):- raise InvalidInputError("Decision options must be an object")- opts = options or {}- if set(opts) - {"overflow_policy"} or opts.get("overflow_policy", "error") != "error":- raise InvalidInputError("Decisions accept only overflow_policy='error'; checkpoint calibration is fixed")- questions = self._parse_questions(output_schema)+ questions = self._extract_questions(labels, output_schema, instruction, options)rows: list[Row] = []errors: list[ExtractItemError | None] = [None] * len(items)counts = [0] * len(items)@@ -145,18 +164,27 @@ class DecisionBatchAdapter(BaseAdapter):counts[row.item] += row.lengthstart = enddata = [{question.id: item[question.id] for question in questions if question.id in item} for item in data]- return ExtractOutput(entities=[[] for _ in items], data=data, errors=errors, input_token_counts=counts)+ return ExtractOutput(+ entities=[[] for _ in items],+ classifications=classifications(data, labels, questions) if labels is not None else None,+ data=data if labels is None else None,+ errors=errors,+ input_token_counts=counts,+ )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,**kwargs: Any,) -> list[int] | None:_ = kwargstry:- questions = self._parse_questions(output_schema)+ questions = self._extract_questions(labels, output_schema, instruction, options)except (InvalidInputError, InputTooLongError):return Noneprompt_chars = sum(diff --git a/packages/sie_server/src/sie_server/adapters/decision/classification.py b/packages/sie_server/src/sie_server/adapters/decision/classification.pynew file mode 100644index 000000000..5f3f11210--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/decision/classification.py@@ -0,0 +1,71 @@+"""Translate the native label classification contract to typed decisions."""++from __future__ import annotations++from string import Formatter+from typing import Any++from sie_server.adapters.decision.questions import MAX_QUESTION_CHARS, MAX_QUESTIONS, Question+from sie_server.core.extract_cost import MAX_EXTRACT_LABELS+from sie_server.types.inputs import InvalidInputError+from sie_server.types.responses import Classification+++def classification_schema(labels: list[str], options: dict[str, Any]) -> dict[str, Any]:+ if (+ not isinstance(labels, list)+ or not 1 <= len(labels) <= MAX_EXTRACT_LABELS+ or any(not isinstance(label, str) or not label for label in labels)+ ):+ raise InvalidInputError(f"Classification requires 1 to {MAX_EXTRACT_LABELS} nonempty string labels")+ multi_label = options.get("multi_label", False)+ if not isinstance(multi_label, bool):+ raise InvalidInputError("multi_label must be a boolean")+ independent = multi_label or len(labels) == 1+ if independent and len(labels) > MAX_QUESTIONS:+ raise InvalidInputError(f"Independent classification supports at most {MAX_QUESTIONS} labels")+ template = options.get("hypothesis_template", "This text is about {}.")+ if not isinstance(template, str) or len(template) + sum(map(len, labels)) > MAX_QUESTION_CHARS:+ raise InvalidInputError("Classification labels and template exceed the character budget")+ try:+ fields = [field for field in Formatter().parse(template) if field[1] is not None]+ if not fields or any(name not in {"", "0"} or spec or conversion for _, name, spec, conversion in fields):+ raise ValueError+ if len(labels) * len(template) + len(fields) * sum(map(len, labels)) > MAX_QUESTION_CHARS:+ raise ValueError+ hypotheses = [template.format(label) for label in labels]+ except (ValueError, IndexError, KeyError) as exc:+ raise InvalidInputError(+ "hypothesis_template must use plain {} or {0} placeholders within the character budget"+ ) from exc+ if independent:+ return {str(index): {"type": "noul", "instructions": hypothesis} for index, hypothesis in enumerate(hypotheses)}+ return {+ "0": {+ "type": "choice",+ "instructions": "Choose the best matching classification for the text.",+ "criteria": {str(index): hypothesis for index, hypothesis in enumerate(hypotheses)},+ }+ }+++def classifications(+ data: list[dict[str, Any]], labels: list[str], questions: tuple[Question, ...]+) -> list[list[Classification]]:+ independent = questions[0].kind == "noul"+ result: list[list[Classification]] = []+ for item in data:+ row = (+ [+ Classification(+ label=label,+ score=item[str(index)]["noul"] if independent else item["0"]["probabilities"][str(index)],+ )+ for index, label in enumerate(labels)+ ]+ if item+ else []+ )+ row.sort(key=lambda classification: classification["score"], reverse=True)+ result.append(row)+ return resultdiff --git a/packages/sie_server/tests/adapters/test_decision_classification.py b/packages/sie_server/tests/adapters/test_decision_classification.pynew file mode 100644index 000000000..593d96f97--- /dev/null+++ b/packages/sie_server/tests/adapters/test_decision_classification.py@@ -0,0 +1,126 @@+"""The label contract is shared by NLI, Qwen and engine-backed decisions."""++from types import SimpleNamespace+from unittest.mock import Mock++import pytest+import torch+from sie_server.adapters.decision.base import Row+from sie_server.adapters.decision.qwen import QwenDecisionAdapter+from sie_server.adapters.nli_classification_flash import NLIClassificationFlashAdapter+from sie_server.adapters.sglang.decision import SGLangDecisionAdapter+from sie_server.types.inputs import InvalidInputError, Item++[email protected](params=["qev", "d3", "sglang"])+def decision(request):+ adapter = (+ SGLangDecisionAdapter("unused")+ if request.param == "sglang"+ else QwenDecisionAdapter("unused", decision_format=request.param)+ )+ adapter._check_decision_loaded = Mock()+ adapter._max_seq_length = adapter._max_forward_tokens = 64+ adapter._item_rows = Mock(+ side_effect=lambda index, item, questions: [+ Row(index, (question,), {"input_ids": torch.ones(len(item.text), dtype=torch.long)})+ for question in questions+ ]+ )+ adapter._forward = Mock(side_effect=lambda rows: [[0.25, 0.75] for row in rows for _ in row.questions])+ return adapter+++def test_same_boolean_request_and_response_contract_as_nli(decision):+ nli = NLIClassificationFlashAdapter("unused")+ nli._device = "cpu"+ nli._entailment_idx = 0+ nli._tokenizer = Mock(+ return_value={"input_ids": torch.ones(1, 7, dtype=torch.long), "attention_mask": torch.ones(1, 7)}+ )+ nli._model = Mock(return_value=SimpleNamespace(logits=torch.tensor([[1.0986123, 0.0]])))+ request = {"labels": ["Is this spam?"], "options": {"hypothesis_template": "{}", "multi_label": True}}+ for adapter in (nli, decision):+ output = adapter.extract([Item(text="message")], **request)+ assert output.classifications == [[{"label": "Is this spam?", "score": pytest.approx(0.75)}]]+ assert output.entities == [[]]+ assert output.data is None+ assert output.input_token_counts == [7]+ question = decision._item_rows.call_args.args[2][0]+ assert question.kind == "noul"+ assert question.instructions == "Is this spam?"+++def test_single_label_keeps_independent_probability_without_multi_label_option(decision):+ output = decision.extract([Item(text="hello")], labels=["spam"])+ assert output.classifications == [[{"label": "spam", "score": 0.75}]]+ assert decision._item_rows.call_args.args[2][0].instructions == "This text is about spam."+++def test_exclusive_labels_return_one_distribution_in_score_order(decision):+ output = decision.extract([Item(text="hello")], labels=["support", "billing"])+ assert output.classifications == [[{"label": "billing", "score": 0.75}, {"label": "support", "score": 0.25}]]+ assert output.input_token_counts == [5]+ question = decision._item_rows.call_args.args[2][0]+ assert question.kind == "choice"+ assert question.descriptions == ("0: This text is about support.", "1: This text is about billing.")+++def test_independent_labels_preserve_partial_errors_and_authoritative_meters(decision):+ output = decision.extract(+ [Item(text="one"), Item(text="x" * 65), Item(text="last")],+ labels=["positive", "helpful"],+ options={"multi_label": True, "hypothesis_template": "It is {0}"},+ )+ assert output.classifications == [+ [{"label": "positive", "score": 0.75}, {"label": "helpful", "score": 0.75}],+ [],+ [{"label": "positive", "score": 0.75}, {"label": "helpful", "score": 0.75}],+ ]+ assert output.errors[1].code == "INPUT_TOO_LONG"+ assert output.errors[0] is output.errors[2] is None+ assert output.input_token_counts == [6, 0, 8]+ assert [row.item for call in decision._forward.call_args_list for row in call.args[0]] == [2, 2, 0, 0]+++ "arguments",+ [+ {"labels": []},+ {"labels": [""]},+ {"labels": [1]},+ {"labels": "spam"},+ {"labels": ["spam"], "output_schema": {"q": {"type": "noul"}}},+ {"labels": ["spam"], "instruction": "extra"},+ {"labels": ["spam"], "options": {"multi_label": "false"}},+ {"labels": ["spam"], "options": {"hypothesis_template": "{0:1000000000}"}},+ {"labels": ["spam"], "options": {"hypothesis_template": "{0.__class__}"}},+ {"labels": ["spam"], "options": {"hypothesis_template": "{label}"}},+ {"labels": ["spam"], "options": {"hypothesis_template": "no placeholder"}},+ {"labels": ["spam"], "options": {"hypothesis_template": "{"}},+ {"labels": ["x" * 65536]},+ {"labels": ["x"] * 33, "options": {"multi_label": True}},+ {"labels": ["spam"], "options": {"overflow_policy": "truncate"}},+ {"labels": ["spam"], "options": {"temperature": 0.5}},+ {"output_schema": {"q": {"type": "noul"}}, "options": {"multi_label": True}},+ ],+)+def test_invalid_classification_fails_before_preparation_or_inference(decision, arguments):+ with pytest.raises(InvalidInputError):+ decision.extract([Item(text="hello")], **arguments)+ assert decision.extract_item_costs([Item(text="hello")], **arguments) is None+ decision._item_rows.assert_not_called()+ decision._forward.assert_not_called()+++def test_costs_account_for_all_independent_hypotheses(decision):+ items = [Item(text="a message")]+ one = decision.extract_item_costs(items, labels=["spam"], options={"multi_label": True})+ two = decision.extract_item_costs(items, labels=["spam", "spam"], options={"multi_label": True})+ assert two == [2 * one[0]]+++def test_typed_questions_keep_their_existing_output(decision):+ output = decision.extract([Item(text="hello")], output_schema={"spam": {"type": "noul"}})+ assert output.classifications is None+ assert output.data == [{"spam": {"type": "noul", "noul": 0.75, "answer": True, "confidence": 0.75}}]diff --git a/packages/sie_server/tests/api/test_systemone.py b/packages/sie_server/tests/api/test_systemone.pyindex fb30342e9..d64e112c4 100644--- a/packages/sie_server/tests/api/test_systemone.py+++ b/packages/sie_server/tests/api/test_systemone.py@@ -14,6 +14,7 @@ from sie_server.adapters.errors import InputTooLongErrorfrom sie_server.adapters.pplx_decider.questions import answer as pplx_answerfrom sie_server.adapters.pplx_decider.questions import parse_questions as pplx_questionsfrom sie_server.api.systemone import (+ DECISION_ADAPTERS,MAX_RETRY_AFTER_S,choice_confidence,error_response,@@ -424,6 +425,10 @@ FIXTURE = json.loads()+def test_decision_adapters_match_the_gateway_contract() -> None:+ assert frozenset(FIXTURE["decision_adapters"]) == DECISION_ADAPTERS++@pytest.mark.parametrize("case", FIXTURE["requests"], ids=lambda case: case["name"])def test_fixture_requests(client: TestClient, adapter: MagicMock, case: dict[str, Any]) -> None:assert client.post("/v1/systemone", json=case["request"]).status_code == 200diff --git a/packages/wire-fixtures/systemone.json b/packages/wire-fixtures/systemone.jsonindex 491b3d4cb..5ac95cc62 100644--- a/packages/wire-fixtures/systemone.json+++ b/packages/wire-fixtures/systemone.json@@ -18,6 +18,16 @@],"max_score_levels": 10,"max_retry_after_s": 60,+ "decision_adapters": [+ "sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter",+ "sie_server.adapters.gliner2.decide_lora:GLiNER2DecideLoraAdapter",+ "sie_server.adapters.laya.adapter:LayaAdapter",+ "sie_server.adapters.laya.runtime_lora:LayaLoraAdapter",+ "sie_server.adapters.pplx_decider.adapter:PerplexityDecisionAdapter",+ "sie_server.adapters.pplx_decider.runtime_lora:PerplexityDecisionLoraAdapter",+ "sie_server.adapters.decision.qwen:QwenDecisionAdapter",+ "sie_server.adapters.sglang.decision:SGLangDecisionAdapter"+ ],"requests": [{"name": "text state, all three question types",