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): score NLI zero-shot labels like the transformers pipeline (#615)
Filip Makradulid134ab29815d
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 54db6dbd3..302253a14 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@@ -59,8 +59,13 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):model_name_or_path: HuggingFace model ID or local path.hypothesis_template: Template for converting labels to hypotheses.Must contain {} placeholder for the label.- multi_label: If True, use sigmoid for independent label scores.- If False, use softmax for mutually exclusive labels.+ multi_label: If True, score every label on its own: the probability+ of entailment against contradiction (or not_entailment) for+ that label's hypothesis. If False, labels are mutually+ exclusive: a softmax of the entailment logits across labels.+ A request with a single label is always scored on its own,+ since a softmax over one label is 1.0 whatever the text. Both+ rules are those of transformers' ZeroShotClassificationPipeline.max_length: Maximum sequence length for tokenization.compute_precision: Precision for inference (float16, bfloat16, float32).revision: Optional HuggingFace revision/branch/commit SHA to pin when@@ -119,9 +124,10 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):self._model.to(device)self._model.eval()- # Detect entailment index from model config- # MoritzLaurer models use: {0: 'entailment', 1: 'neutral', 2: 'contradiction'}- # Some models use: {0: 'contradiction', 1: 'neutral', 2: 'entailment'}+ # Detect entailment index from model config. The MoritzLaurer zeroshot-v2.0+ # models are binary, {0: 'entailment', 1: 'not_entailment'}; MNLI models+ # such as facebook/bart-large-mnli use {0: 'contradiction', 1: 'neutral',+ # 2: 'entailment'}.id2label = getattr(self._model.config, "id2label", {})for idx, label in id2label.items():if label.lower() == "entailment":@@ -266,18 +272,17 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):outputs = self._model(**encodings)logits = outputs.logits # [n_texts * n_labels, num_classes]- # Extract entailment scores- entailment_logits = logits[:, self._entailment_idx] # [n_texts * n_labels]-- # Reshape to [n_texts, n_labels]- entailment_logits = entailment_logits.view(n_texts, n_labels)-- # Normalize scores- if effective_multi_label:- # Independent scores per label- scores = torch.sigmoid(entailment_logits)+ if effective_multi_label or n_labels == 1:+ # Each label on its own: entailment against contradiction (the last+ # class when entailment is the first, else the first), the rule of+ # transformers' ZeroShotClassificationPipeline. For a binary+ # entailment/not_entailment head that is the not_entailment logit.+ contradiction_idx = logits.shape[-1] - 1 if self._entailment_idx == 0 else 0+ pair = logits[:, [contradiction_idx, self._entailment_idx]].float()+ scores = F.softmax(pair, dim=-1)[:, 1].view(n_texts, n_labels)else:- # Mutually exclusive labels+ # Mutually exclusive labels: a softmax of the entailment logits across labels+ entailment_logits = logits[:, self._entailment_idx].view(n_texts, n_labels)scores = F.softmax(entailment_logits, dim=-1)scores = scores.cpu().tolist()diff --git a/packages/sie_server/tests/adapters/test_nli_classification_flash_parity.py b/packages/sie_server/tests/adapters/test_nli_classification_flash_parity.pynew file mode 100644index 000000000..6d93d80f0--- /dev/null+++ b/packages/sie_server/tests/adapters/test_nli_classification_flash_parity.py@@ -0,0 +1,88 @@+"""NLI zero-shot classification parity with transformers' pipeline, on real weights.++Every shipped NLI config runs the flash adapter, which reimplements the+pipeline's scoring. This pins it to ``pipeline("zero-shot-classification")``+in the three modes users reach: one label, several mutually exclusive labels,+and ``multi_label``. Runs on CPU in float32.+"""++from __future__ import annotations++from pathlib import Path++import numpy as np+import pytest+from sie_server.core.loader import load_adapter, load_model_configs+from sie_server.types.inputs import Item++pytestmark = pytest.mark.model++MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+MODEL = "MoritzLaurer/deberta-v3-base-zeroshot-v2.0"+TEMPLATE = "This text is about {}."+TEXTS = [+ "The Lakers beat the Celtics 112-104 last night behind a late run from their bench.",+ "Preheat the oven to 180 degrees, knead the dough and bake the bread for forty minutes.",+ "The city council voted 7-2 to spend public money on a new stadium for the local football club.",+]++[email protected](scope="module")+def adapter():+ config = load_model_configs(MODELS_DIR)[MODEL]+ adapter = load_adapter(config, MODELS_DIR, device="cpu")+ adapter.load("cpu")+ return adapter++[email protected](scope="module")+def pipeline():+ from transformers import pipeline as hf_pipeline++ config = load_model_configs(MODELS_DIR)[MODEL]+ return hf_pipeline("zero-shot-classification", model=config.hf_id, revision=config.hf_revision, device=-1)+++def _sie(adapter, labels: list[str], multi_label: bool) -> np.ndarray:+ output = adapter.extract(+ [Item(text=text) for text in TEXTS],+ labels=labels,+ options={"hypothesis_template": TEMPLATE, "multi_label": multi_label},+ )+ return np.array(+ [[{c["label"]: c["score"] for c in row}[label] for label in labels] for row in output.classifications]+ )+++def _reference(pipeline, labels: list[str], multi_label: bool) -> np.ndarray:+ rows = []+ for text in TEXTS:+ result = pipeline(text, candidate_labels=labels, hypothesis_template=TEMPLATE, multi_label=multi_label)+ by_label = dict(zip(result["labels"], result["scores"], strict=True))+ rows.append([by_label[label] for label in labels])+ return np.array(rows)+++ ("labels", "multi_label"),+ [+ (["sports"], False),+ (["sports", "politics", "cooking"], False),+ (["sports", "politics", "cooking"], True),+ ],+ ids=["one-label", "exclusive", "multi-label"],+)+def test_scores_match_the_pipeline(adapter, pipeline, labels: list[str], multi_label: bool) -> None:+ # The adapter runs every (text, hypothesis) pair in one padded batch and the+ # pipeline does not, so float32 scores differ by up to about 3e-4. The scoring+ # bugs this guards against were off by 0.18 (multi_label) and 1.0 (one label).+ np.testing.assert_allclose(+ _sie(adapter, labels, multi_label), _reference(pipeline, labels, multi_label), rtol=0, atol=2e-3+ )+++def test_one_label_scores_follow_the_text(adapter) -> None:+ scores = _sie(adapter, ["sports"], multi_label=False)[:, 0]++ assert scores[0] > 0.99+ assert scores[1] < 0.01diff --git a/packages/sie_server/tests/adapters/test_nli_classification_flash_scores.py b/packages/sie_server/tests/adapters/test_nli_classification_flash_scores.pynew file mode 100644index 000000000..d211b7ac3--- /dev/null+++ b/packages/sie_server/tests/adapters/test_nli_classification_flash_scores.py@@ -0,0 +1,164 @@+"""Score normalisation of NLI zero-shot classification.++The flash adapter must score labels the way transformers'+ZeroShotClassificationPipeline does:++- one label, or ``multi_label``: every label on its own, a softmax over that+ label's [contradiction, entailment] logits;+- two or more labels otherwise: a softmax of the entailment logits across labels.++A softmax over one label's entailment logit is 1.0 whatever the text, and a+sigmoid of the entailment logit ignores the contradiction class, so both are+pinned here against the pipeline's formula on fixed logits.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any, cast++import numpy as np+import pytest+import torch+from sie_server.adapters.nli_classification_flash import NLIClassificationFlashAdapter+from sie_server.types.inputs import Item++# Heads of the shipped configs: MoritzLaurer zeroshot-v2.0 (binary),+# cross-encoder/nli-deberta-v3-base, and facebook/bart-large-mnli.+_BINARY = 0 # {0: entailment, 1: not_entailment}+_CROSS_ENCODER = 1 # {0: contradiction, 1: entailment, 2: neutral}+_MNLI = 2 # {0: contradiction, 1: neutral, 2: entailment}+++class _Tokenizer:+ """One row of inputs per (text, hypothesis) pair."""++ def __call__(self, texts: list[str], hypotheses: list[str], **_: Any) -> dict[str, torch.Tensor]:+ rows = len(texts)+ return {+ "input_ids": torch.zeros(rows, 4, dtype=torch.long),+ "attention_mask": torch.ones(rows, 4, dtype=torch.long),+ }+++class _Model:+ """Returns fixed logits, one row per (text, hypothesis) pair in request order."""++ def __init__(self, logits: list[list[float]]) -> None:+ self._logits = torch.tensor(logits, dtype=torch.float32)++ def __call__(self, **inputs: torch.Tensor) -> SimpleNamespace:+ assert inputs["input_ids"].shape[0] == self._logits.shape[0]+ return SimpleNamespace(logits=self._logits)+++def _adapter(+ logits: list[list[float]], entailment_idx: int, *, multi_label: bool = False+) -> NLIClassificationFlashAdapter:+ adapter = NLIClassificationFlashAdapter("test-model", multi_label=multi_label)+ adapter._tokenizer = cast("Any", _Tokenizer())+ adapter._model = _Model(logits)+ adapter._device = "cpu"+ adapter._entailment_idx = entailment_idx+ return adapter+++def _pipeline_scores(+ logits: list[list[float]], n_texts: int, n_labels: int, entailment_idx: int, *, multi_label: bool+) -> np.ndarray:+ """Transformers ZeroShotClassificationPipeline.postprocess, on raw logits."""+ reshaped = np.asarray(logits, dtype=np.float64).reshape(n_texts, n_labels, -1)+ if multi_label or n_labels == 1:+ contradiction_idx = -1 if entailment_idx == 0 else 0+ pair = np.exp(reshaped[..., [contradiction_idx, entailment_idx]])+ return (pair / pair.sum(-1, keepdims=True))[..., 1]+ entail = np.exp(reshaped[..., entailment_idx])+ return entail / entail.sum(-1, keepdims=True)+++def _scores(adapter: NLIClassificationFlashAdapter, texts: list[str], labels: list[str], **kwargs: Any) -> np.ndarray:+ output = adapter.extract([Item(text=text) for text in texts], labels=labels, **kwargs)+ assert output.classifications is not None+ return np.array(+ [[{c["label"]: c["score"] for c in row}[label] for label in labels] for row in output.classifications]+ )+++ ("entailment_idx", "says_yes", "says_no"),+ [+ # The "no" row is the real [entailment, not_entailment] pair of+ # MoritzLaurer/deberta-v3-base-zeroshot-v2.0 for "This text is about sports."+ # against a bread recipe.+ (_BINARY, [5.6, -6.1], [-4.854, 5.337]),+ (_CROSS_ENCODER, [-5.2, 6.0, -1.1], [6.647, -4.061, -2.0]),+ (_MNLI, [-3.0, -0.5, 4.2], [4.0, 0.2, -3.5]),+ ],+)+def test_one_label_is_scored_on_its_own(entailment_idx: int, says_yes: list[float], says_no: list[float]) -> None:+ logits = [says_yes, says_no]+ adapter = _adapter(logits, entailment_idx)++ scores = _scores(adapter, ["The Lakers beat the Celtics.", "Knead the dough and bake."], ["sports"])++ expected = _pipeline_scores(logits, 2, 1, entailment_idx, multi_label=False)+ np.testing.assert_allclose(scores, expected, rtol=0, atol=1e-6)+ # Before, a softmax over the single label made both scores 1.0.+ assert scores[0, 0] > 0.99+ assert scores[1, 0] < 0.01++[email protected]("entailment_idx", [_BINARY, _CROSS_ENCODER, _MNLI])+def test_multi_label_weighs_entailment_against_contradiction(entailment_idx: int) -> None:+ rng = np.random.default_rng(entailment_idx)+ width = 2 if entailment_idx == _BINARY else 3+ logits = rng.normal(0.0, 3.0, size=(2 * 3, width)).round(3).tolist()+ adapter = _adapter(logits, entailment_idx)++ scores = _scores(+ adapter, ["first text", "second text"], ["politics", "health", "economy"], options={"multi_label": True}+ )++ np.testing.assert_allclose(+ scores, _pipeline_scores(logits, 2, 3, entailment_idx, multi_label=True), rtol=0, atol=1e-6+ )+++def test_multi_label_reads_the_contradiction_logit() -> None:+ # cross-encoder/nli-deberta-v3-base on a stadium-funding text with "politics":+ # contradiction -4.341, entailment 0.095, neutral 3.643. The pipeline gives 0.988;+ # a sigmoid of the entailment logit alone gave 0.524.+ logits = [[-4.341, 0.095, 3.643]]+ adapter = _adapter(logits, _CROSS_ENCODER, multi_label=True)++ (score,) = _scores(adapter, ["The council voted to fund a stadium."], ["politics"])[0]++ assert score == pytest.approx(1.0 / (1.0 + np.exp(-4.341 - 0.095)), abs=1e-6)+ assert score > 0.98++[email protected]("entailment_idx", [_BINARY, _CROSS_ENCODER, _MNLI])+def test_two_or_more_labels_share_one_distribution(entailment_idx: int) -> None:+ rng = np.random.default_rng(10 + entailment_idx)+ width = 2 if entailment_idx == _BINARY else 3+ logits = rng.normal(0.0, 3.0, size=(2 * 3, width)).round(3).tolist()+ adapter = _adapter(logits, entailment_idx)++ scores = _scores(adapter, ["first text", "second text"], ["sports", "politics", "cooking"])++ np.testing.assert_allclose(+ scores, _pipeline_scores(logits, 2, 3, entailment_idx, multi_label=False), rtol=0, atol=1e-6+ )+ np.testing.assert_allclose(scores.sum(axis=1), 1.0, rtol=0, atol=1e-6)+++def test_request_option_overrides_the_profile_mode() -> None:+ logits = [[1.0, -1.0], [-2.0, 2.0]]+ single = _adapter(logits, _BINARY, multi_label=True)+ multi = _adapter(logits, _BINARY, multi_label=False)++ exclusive = _scores(single, ["text"], ["a", "b"], options={"multi_label": False})+ independent = _scores(multi, ["text"], ["a", "b"], options={"multi_label": True})++ np.testing.assert_allclose(exclusive, _pipeline_scores(logits, 1, 2, _BINARY, multi_label=False), atol=1e-6)+ np.testing.assert_allclose(independent, _pipeline_scores(logits, 1, 2, _BINARY, multi_label=True), atol=1e-6)