Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): encode GLiClass label groups separately by default (#364)

svonava71b395fee456
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 8e58cafae..c9f221559 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -87,8 +87,7 @@ document can push them out of the model's window; send
`options={"overflow_policy": "truncate_text"}` to shorten the document instead.
To answer several questions in one call, pass named `label_groups` instead of
-`labels`. Scores are normalized within each group, and `data` holds one answer
-per group:
+`labels`. `data` holds one answer per group:
```python
result = client.extract(
@@ -108,6 +107,27 @@ print(urgency["choice"], urgency["confidence"]) # e.g. medium 0.78
print(urgency["probabilities"]) # {"low": ..., "medium": ..., "high": ...}
```
+By default the model reads each group as its own row: the document with only
+that group's labels, plus the instruction and examples. A group then scores as
+a request whose `labels` are that group's labels would. The rows of a call
+share forward passes, so on a GPU, fp16 rounding can move a probability by a
+few thousandths against the one-group request. Batching several items into one
+call does the same. A call takes at most 64 groups, or 32 on models with a
+1,024-token window. Every group reads the part of the document that fits in
+the model's window again, so that part may span at most 64 characters per token
+of the window: 32,768 characters on a 512-token model, 65,536 on a 1,024-token
+one. With few groups the bound is 524,288 characters divided by the number of
+groups, when that is larger. Prose fills a 512-token window in about 2,300
+characters, and text laid out with long runs of spaces in about 20,000. Text
+written without spaces between words is read whole, so the bound applies to
+the whole document. A document over the bound comes back with an
+`INPUT_TOO_LONG` error, and the other items still succeed.
+
+`options={"group_encoding": "joint"}` reads all the groups in one row per item
+instead: the document next to every group's labels, written as `group.label`.
+That row costs less, but each group's scores then depend on the other groups'
+labels. Single-label scores are still normalized within each group.
+
Each group answers `{"type": "choice", "choice", "probabilities",
"confidence"}`, where `confidence` is `1 - entropy / log(number of labels)`.
With `"classification_type": "multi-label"` a group answers `{"labels",
@@ -115,15 +135,19 @@ With `"classification_type": "multi-label"` a group answers `{"labels",
at or above `options.threshold` (0.5 when no threshold is set).
`classifications` lists the same scores under `group.label` names. In a
grouped request, an example's labels may be written as `"urgency.high"` or as
-`{"urgency": "high"}`.
-
-Usage counts each item's document tokens plus the tokens of the instruction
-and example texts sent with it, since the model encodes them for every item.
-Label names are not counted. With an instruction or examples, each item's
-count is capped at the model window minus the label prompt, unless the
-document count alone is already higher. An item whose document pushes the
-labels out of the window comes back with an `INPUT_TOO_LONG` error in its
-`error` field, and the other items still succeed.
+`{"urgency": "high"}`. With separate rows, each row reads every example with
+only that group's labels.
+
+Usage counts the tokens of every row the model encodes: the document plus the
+instruction and example texts sent with it. Label names are not counted. A
+labels request or a joint call encodes one row per item. A call with separate
+groups encodes one row per item and group, so it counts the document once per
+group: three groups cost what three one-group requests cost. With an
+instruction or examples, each row's count is capped at the model window minus
+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 not
+billed. The other items still succeed.
## Generation prompts and guard verdicts
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
index 794b323d5..744d5bf5f 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
@@ -10,26 +10,54 @@ Performance note (Dec 2025):
like NLI cross-encoders), so the gliclass library pipeline has minimal overhead.
No separate "GLiClassFlashAdapter" is needed - the library is already efficient.
-Request surface (all optional; a request that sets none of them runs exactly the
-pipeline call used before these fields existed):
+Scoring runs the gliclass model directly with the library's own prompt assembly
+and tokenization, in the pipeline's sub-batches of eight rows, and applies the
+pipeline's softmax or sigmoid. The scores equal the pipeline's. The adapter skips
+the pipeline's progress bar and its per-label reads from the device, and it
+tokenizes each document once for its length checks and metering.
-- ``instruction``: task description passed to the pipeline as ``prompt``.
+Request surface (all optional; a request that sets none of them scores exactly
+like the pipeline call used before these fields existed):
+
+- ``instruction``: task description passed to the model as the pipeline's ``prompt``.
- ``options.examples``: few-shot examples, ``[{"text": ..., "labels": [...]}]``.
- ``options.classification_type``: ``"single-label"`` or ``"multi-label"`` for
this request, overriding the load-time default.
- ``options.label_groups``: named label groups, ``{"urgency": ["low", "high"],
- ...}``, used instead of ``labels``. Single-label scores are normalized within
- each group, and ``data`` holds one answer per group.
-
-Usage counts each item's document tokens plus the instruction and example
-texts encoded with it; label names are not counted.
+ ...}``, used instead of ``labels``. ``data`` holds one answer per group.
+- ``options.group_encoding``: how label groups are encoded. ``"separate"`` (the
+ default) encodes the document once per group, with only that group's labels.
+ Each group scores like a request whose ``labels`` are that group's labels.
+ The rows of a request share forward passes, and padding them together can
+ move fp16 probabilities by a few thousandths. ``"joint"`` encodes every
+ group's labels, as ``group.label``, next to one copy of the document, and
+ normalizes single-label scores within each group.
+
+Usage counts, for every encoded row, the document tokens plus the instruction
+and example texts encoded with it. Label names are not counted. A separate-group
+request encodes the document once per group, so it counts it once per group.
+
+A document is cut, before anything tokenizes it, to whole words whose tokens
+include every token the model reads (see ``_RequestTokens.visible``), so work
+does not grow with text the model never sees. This relies on what fast
+tokenizers guarantee: text is split into words at local boundaries, and each
+word is tokenized on its own. Scores and usage are unchanged. The ``error``
+overflow policy reports a lower bound on the length of a document it read
+only in part. A document without a word boundary early enough is read whole,
+tokenized once. In a separate-group request, the readable part may span at
+most ``_MAX_ROW_CHARS_PER_TOKEN`` characters per token of the window, or
+``_MAX_ITEM_ROW_CHARS`` divided by the number of groups when that is more; a
+document needing more fails alone with ``INPUT_TOO_LONG``.
"""
from __future__ import annotations
import math
import re
+from collections.abc import Iterator
+from contextlib import contextmanager
from dataclasses import dataclass
+from itertools import islice
from numbers import Real
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
@@ -48,7 +76,6 @@ from sie_server.types.overflow_policy import DEFAULT_OVERFLOW_POLICY, OverflowPo
from sie_server.types.responses import Classification, ErrorCode
if TYPE_CHECKING:
- from gliclass import ZeroShotClassificationPipeline # ty:ignore[unresolved-import]
from transformers import PreTrainedTokenizerBase # ty:ignore[unresolved-import]
from sie_server.types.inputs import Item
@@ -67,13 +94,19 @@ _ERR_INPUT_TOO_LONG = (
# never matches at all.
_INDEX_OOB_RE = re.compile(r"index (\d+) is out of bounds for dimension \d+ with size (\d+)")
ClassificationType = Literal["single-label", "multi-label"]
-_CLASSIFICATION_TYPES: tuple[ClassificationType, ...] = ("single-label", "multi-label")
+GroupEncoding = Literal["separate", "joint"]
+_DEFAULT_GROUP_ENCODING: GroupEncoding = "separate"
# gliclass joins a label group and its labels with this separator (the
# pipeline's default ``label_separator``); the model sees "urgency.high".
_LABEL_GROUP_SEPARATOR = "."
-# ``ZeroShotClassificationPipeline.__call__`` default. The grouped path runs the
-# model directly and mirrors the pipeline's sub-batching so padding matches.
+# ``ZeroShotClassificationPipeline.__call__`` default: rows per forward pass.
+# The flat path keeps it so that items share padding exactly as before.
_PIPELINE_BATCH_SIZE = 8
+# Separate group encoding runs one row of up to the model window per (item,
+# group). An item may occupy at most this many row tokens: 64 groups at a
+# 512-token window, 32 at 1024.
+_MAX_ITEM_ROW_TOKENS = 32_768
+_MAX_LABEL_GROUPS = 64
_MAX_EXAMPLES = 32
_EXAMPLE_KEYS = frozenset({"text", "labels"})
_DEFAULT_MULTI_LABEL_THRESHOLD = 0.5
@@ -92,10 +125,28 @@ _MAX_LABEL_CHARS_PER_TOKEN = 16
# on the fused encoding: tokenizing the document alone can differ by a token
# or two from tokenizing it next to the label prompt.
_FIT_MARGIN_TOKENS = 8
+# A document is cut to the part the model reads before anything else tokenizes
+# it. The first cut tries this many characters per token the model can read...
+_PREFIX_CHARS_PER_TOKEN = 8
+# ...and is kept when its whole words hold this many tokens past that part.
+_PREFIX_SLACK_TOKENS = 32
+# The search for a cut doubles up to this many characters per readable token.
+# Prose averages 4 to 5; text laid out with whitespace runs, which DeBERTa
+# tokenizers read as nothing, reaches about 40 (fixed-width logs, PDF layout).
+_MAX_ROW_CHARS_PER_TOKEN = 64
+# Separate group encoding tokenizes a document's readable part once per group.
+# A row may read up to ``_MAX_ROW_CHARS_PER_TOKEN`` characters per token of the
+# window, or this per-item budget shared by the groups when that is more.
+_MAX_ITEM_ROW_CHARS = _MAX_ITEM_ROW_TOKENS * _MAX_LABEL_CHARS_PER_TOKEN
_ERR_ITEM_LABELS_TRUNCATED = (
"The document pushes the labels out of the gliclass model's max sequence length. "
"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 "
+ "options.group_encoding='joint'."
+)
@dataclass(frozen=True)
@@ -105,7 +156,9 @@ class _RequestLayout:
``window`` is the number of non-special tokens the model keeps. The label
prompt (markers, label names, separator) is ``label_tokens`` long and its
last marker sits at ``last_marker``. ``context_tokens`` counts the
- billable instruction and example texts.
+ billable instruction and example texts. ``overhead_tokens`` is everything
+ a row encodes besides its document and special tokens: the label prompt,
+ the instruction and the formatted examples.
"""
prompt_first: bool
@@ -113,6 +166,7 @@ class _RequestLayout:
label_tokens: int
last_marker: int
context_tokens: int
+ overhead_tokens: int
def labels_fit(self, document_tokens: int) -> bool:
"""Whether every label marker survives truncation next to this document."""
@@ -121,6 +175,163 @@ class _RequestLayout:
return document_tokens + self.last_marker < self.window
+@dataclass
+class _Context:
+ """One (labels, instruction, examples) context of a request, tokenized once.
+
+ ``parts`` holds the token ids of the label prompt, the instruction, each
+ example text and the formatted examples; it stays empty for models
+ without in-sequence label markers. ``overflow_tokens`` is the length of
+ the pipeline input with an empty document. The layout is evaluated from
+ ``parts`` when a request first needs it, so errors keep their order.
+ """
+
+ parts: list[list[int]] | None = None
+ overflow_tokens: int | None = None
+ layout: _RequestLayout | None = None
+ has_layout: bool = False
+
+
+class _RequestTokens:
+ """What one adapter call tokenizes, each distinct text at most once.
+
+ ``visible`` cuts a document to the prefix the model can read, so nothing
+ downstream tokenizes more of it. ``full`` returns every token of a text
+ (the overflow policies need them all). ``cut`` returns ids truncated the
+ way the tokenizer truncates to a fixed length, sliced from what is already
+ tokenized. ``contexts`` holds the label contexts. The server can batch
+ requests with the same labels and options into one call, and they share
+ this; nothing carries over to the next call.
+ """
+
+ def __init__(self, tokenizer: Any, visible_tokens: int | None = None) -> None:
+ self._tokenizer = tokenizer
+ # Tokens the model can read of a document: its window plus the fit
+ # check's margin. None when unknown, and then documents are not cut.
+ self.visible_tokens = visible_tokens
+ self._full: dict[str, list[int]] = {}
+ self._cut: dict[str, tuple[list[int], int]] = {}
+ self._prefixes: dict[str, str | None] = {}
+ # Prefixes cut from longer documents.
+ self.shortened: set[str] = set()
+ self.contexts: dict[tuple[Any, ...], _Context] = {}
+ # Token ids of context strings: label prompts, instructions, examples.
+ self.context_ids: dict[str, list[int]] = {}
+
+ def visible(self, text: str, char_limit: int | None = None) -> str | None:
+ """``text`` cut to the prefix the model can read; None when that part exceeds ``char_limit`` characters.
+
+ The model reads at most ``visible_tokens`` tokens of a document, so
+ any prefix whose first ``visible_tokens`` tokens are the document's
+ own gives the model the same input. Fast tokenizers split text into
+ words (pre-tokens) at local boundaries and tokenize each word on its
+ own, so a prefix that ends where a word ends has the document's
+ tokens for every word in it. The cut drops the last, possibly
+ truncated, word of a stretch of the document and is kept when the
+ remaining whole words hold ``_PREFIX_SLACK_TOKENS`` more tokens than
+ the model reads, and their first tokens also match a stretch twice as
+ long. A single word can re-tokenize anywhere when it is cut: a
+ Unigram tokenizer segments a run of one repeated character by the
+ run's length. So a document with no word boundary early enough (text
+ written without spaces, a long run of one character) is not cut.
+
+ The search doubles the stretch up to ``char_limit`` characters, or
+ ``_MAX_ROW_CHARS_PER_TOKEN`` per readable token without one. A
+ document it cannot cut is then read whole: refused when it exceeds
+ ``char_limit``, and otherwise tokenized once, keeping only the tokens
+ anything reads.
+ """
+ if text not in self._prefixes:
+ self._prefixes[text] = self._find_prefix(text, char_limit)
+ return self._prefixes[text]
+
+ def _find_prefix(self, text: str, char_limit: int | None) -> str | None:
+ need = self.visible_tokens
+ if need is None or getattr(self._tokenizer, "truncation_side", "right") != "right":
+ return text if char_limit is None or len(text) <= char_limit else None
+ limit = char_limit if char_limit is not None else _MAX_ROW_CHARS_PER_TOKEN * need
+ size = need * _PREFIX_CHARS_PER_TOKEN
+ if size >= len(text):
+ return text if len(text) <= limit else None
+ while True:
+ size = min(size, limit, len(text))
+ words = self._whole_words(text[:size])
+ if words is not None and words[1] >= need + _PREFIX_SLACK_TOKENS:
+ prefix = words[0]
+ prefix_ids, longer = self._tokenizer([prefix, text[: 2 * size]], add_special_tokens=False)["input_ids"]
+ if prefix_ids[:need] == longer[:need]:
+ self._full[prefix] = prefix_ids
+ self.shortened.add(prefix)
+ return prefix
+ if size >= limit or size >= len(text):
+ break
+ size *= 2
+ if char_limit is not None and len(text) > char_limit:
+ return None
+ self._keep_readable(text)
+ return text
+
+ def _whole_words(self, head: str) -> tuple[str, int] | None:
+ """``head`` without its last word, and how many tokens that leaves; None when unknown."""
+ try:
+ encoded = self._tokenizer(
+ [head], add_special_tokens=False, return_offsets_mapping=True, return_attention_mask=False
+ )
+ words = encoded.word_ids(0)
+ offsets = encoded["offset_mapping"][0]
+ except Exception: # noqa: BLE001 -- a tokenizer without word alignment is simply not cut
+ return None
+ last = next((word for word in reversed(words) if word is not None), None)
+ if last is None:
+ return None
+ first_of_last = words.index(last)
+ return head[: offsets[first_of_last][0]], first_of_last
+
+ def _keep_readable(self, text: str) -> None:
+ """Tokenize a document that is read whole, once, keeping only the tokens anything reads."""
+ store = (self.visible_tokens or 0) + _PREFIX_SLACK_TOKENS
+ ids = self._tokenizer([text], add_special_tokens=False, truncation=True, max_length=store)["input_ids"][0]
+ self._full[text] = ids
+ if len(ids) >= store:
+ self.shortened.add(text)
+
+ def full(self, texts: list[str]) -> list[list[int]]:
+ missing = [text for text in dict.fromkeys(texts) if text not in self._full]
+ if missing:
+ encoded = self._tokenizer(missing, add_special_tokens=False)["input_ids"]
+ self._full.update(zip(missing, encoded, strict=True))
+ return [self._full[text] for text in texts]
+
+ def cut(self, texts: list[str], length: int) -> list[list[int]]:
+ # Truncate once to the longest length a call asks for, then slice.
+ store = max(length, self.visible_tokens or 0)
+ missing = [
+ text
+ for text in dict.fromkeys(texts)
+ if text not in self._full and (text not in self._cut or self._cut[text][1] < length)
+ ]
+ if missing:
+ encoded = self._tokenizer(missing, add_special_tokens=False, truncation=True, max_length=store)
+ for text, ids in zip(missing, encoded["input_ids"], strict=True):
+ self._cut[text] = (ids, store)
+ left = getattr(self._tokenizer, "truncation_side", "right") == "left"
+ cut_ids: list[list[int]] = []
+ for text in texts:
+ ids = self._full[text] if text in self._full else self._cut[text][0]
+ cut_ids.append(ids[len(ids) - length :] if left and len(ids) > length else ids[:length])
+ return cut_ids
+
+
+def _row_char_limit(group_count: int, window: int | None) -> int:
+ """Characters of a document's readable part one separate-group row may tokenize.
+
+ ``_MAX_ROW_CHARS_PER_TOKEN`` per token of the model window (32,768 at 512
+ tokens), or the per-item budget divided among the groups when that is more.
+ """
+ per_row = _MAX_ROW_CHARS_PER_TOKEN * window if window else 0
+ return max(1, per_row, _MAX_ITEM_ROW_CHARS // max(1, group_count))
+
+
def _choice_confidence(probabilities: list[float]) -> float:
"""``1 - H(p) / log(k)``: 1.0 for a certain answer, 0.0 for a uniform one."""
if len(probabilities) < 2:
@@ -133,7 +344,7 @@ def _pipeline_context(prompt: str | None, examples: list[dict[str, Any]] | None)
"""Pipeline keyword arguments for the fields a request actually set.
Leaving unset fields out keeps a request without them on exactly the
- pipeline call the adapter has always made.
+ pipeline input the adapter has always built.
"""
context: dict[str, Any] = {}
if prompt is not None:
@@ -158,6 +369,33 @@ def _string_list(value: Any) -> list[str] | None:
return None
+@contextmanager
+def _overflow_errors_as_input_too_long() -> Iterator[None]:
+ """Report the known gliclass overflow crash signatures as ``InputTooLongError``.
+
+ Inputs past the model's position capacity used to crash inside the
+ gliclass pipeline with empty intermediate tensors. The match is specific,
+ so unrelated errors keep propagating. Caught signatures:
+
+ - RuntimeError "argmax(): ... numel() == 0": argmax on an empty tensor.
+ - IndexError "index N is out of bounds for dimension D with size N"
+ (index == size: an exhausted dimension), both the empty-tensor case
+ (index 0 / size 0) and a label window that shrank under truncation
+ (e.g. index 79 / size 79). A generic out-of-range bug (index > size,
+ e.g. index 5 / size 3) is not this and propagates.
+ """
+ try:
+ yield
+ except (RuntimeError, IndexError) as exc:
+ msg = str(exc)
+ if isinstance(exc, RuntimeError) and "numel() == 0" in msg and "argmax" in msg:
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
+ oob = _INDEX_OOB_RE.search(msg)
+ if isinstance(exc, IndexError) and oob is not None and oob.group(1) == oob.group(2):
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
+ raise
+
+
def _restore_modernbert_rope_fields(encoder_config: Any) -> bool:
"""Carry a transformers-5 ModernBERT RoPE config over to transformers 4.
@@ -202,8 +440,8 @@ def _restore_modernbert_rope_fields(encoder_config: Any) -> bool:
class GLiClassAdapter(BaseAdapter):
"""Adapter for GLiClass zero-shot classification models.
- Uses the gliclass library's ZeroShotClassificationPipeline.
- Works with models like knowledgator/gliclass-base-v1.0.
+ Runs gliclass models with the library's input format. Works with models
+ like knowledgator/gliclass-base-v1.0.
GLiClass performs classification in a single forward pass (not NLI-based),
making it much faster than cross-encoder approaches.
@@ -212,7 +450,7 @@ class GLiClassAdapter(BaseAdapter):
spec: ClassVar[AdapterSpec] = AdapterSpec(
inputs=("text",),
outputs=("json",),
- unload_fields=("_pipeline", "_pipelines", "_tokenizer"),
+ unload_fields=("_pipe", "_tokenizer"),
)
def __init__(
@@ -238,8 +476,8 @@ class GLiClassAdapter(BaseAdapter):
to 0.0 so all requested labels are returned with their scores.
Callers can override per-request via ``options={"threshold": ...}``.
max_seq_length: Maximum input sequence length in tokens. Used to bound
- tokenization inside the gliclass pipeline so inputs cannot exceed
- the model's position-embedding capacity.
+ tokenization so inputs cannot exceed the model's
+ position-embedding capacity.
compute_precision: Precision for inference (float16, float32, bfloat16).
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading model artifacts.
@@ -252,10 +490,9 @@ class GLiClassAdapter(BaseAdapter):
self._compute_precision = compute_precision
self._revision = revision
- self._pipeline: ZeroShotClassificationPipeline | None = None
- # One pipeline per classification type, sharing the model and
- # tokenizer; ``_pipeline`` is the load-time type's entry.
- self._pipelines: dict[ClassificationType, ZeroShotClassificationPipeline] | None = None
+ # The gliclass pipe for the model's architecture: it assembles and
+ # tokenizes model inputs and holds the model.
+ self._pipe: Any | None = None
self._tokenizer: PreTrainedTokenizerBase | None = None
self._special_count: int = 0
self._max_token_chars: int = _DEFAULT_MAX_TOKEN_CHARS
@@ -295,36 +532,37 @@ class GLiClassAdapter(BaseAdapter):
else:
model = GLiClassModel.from_pretrained(self._model_name_or_path, **shared_kwargs)
model = model.to(device, dtype=torch_dtype)
- self._tokenizer = self._load_tokenizer(shared_kwargs)
+ tokenizer = self._load_tokenizer(shared_kwargs)
# Bound the tokenizer's max length so any internal tokenization in the
# gliclass library auto-truncates to the model's actual capacity.
if self._max_seq_length is not None:
- self._tokenizer.model_max_length = self._max_seq_length
+ tokenizer.model_max_length = self._max_seq_length
- # Create pipeline. Pass max_length explicitly so the pipeline's
+ # Pass max_length explicitly so the pipe's
# ``tokenizer(..., truncation=True, max_length=self.max_length)`` calls
# cap inputs at the model's position-embedding limit. Without this the
# library defaults to 1024, which exceeds the 512-token capacity of the
# current GLiClass models and causes argmax-on-empty-tensor crashes for
- # long inputs.
+ # long inputs. The classification type only matters to the pipeline's
+ # own ``__call__``, which the adapter does not use.
pipeline_kwargs: dict[str, Any] = {
"model": model,
- "tokenizer": self._tokenizer,
+ "tokenizer": tokenizer,
"device": device,
+ "classification_type": self._classification_type,
+ "progress_bar": False,
}
if self._max_seq_length is not None:
pipeline_kwargs["max_length"] = self._max_seq_length
+ self._attach(ZeroShotClassificationPipeline(**pipeline_kwargs).pipe, tokenizer)
- self._special_count = int(self._tokenizer.num_special_tokens_to_add(pair=False))
- self._max_token_chars = _longest_token_chars(self._tokenizer)
- self._pipelines = {
- classification_type: ZeroShotClassificationPipeline(
- **pipeline_kwargs, classification_type=classification_type
- )
- for classification_type in _CLASSIFICATION_TYPES
- }
- self._pipeline = self._pipelines[self._classification_type]
+ def _attach(self, pipe: Any, tokenizer: PreTrainedTokenizerBase) -> None:
+ """Use ``pipe`` (a gliclass pipe holding the model) and its tokenizer."""
+ self._pipe = pipe
+ self._tokenizer = tokenizer
+ self._special_count = int(tokenizer.num_special_tokens_to_add(pair=False))
+ self._max_token_chars = _longest_token_chars(tokenizer)
def _load_tokenizer(self, shared_kwargs: dict[str, Any]) -> PreTrainedTokenizerBase:
try:
@@ -337,6 +575,27 @@ class GLiClassAdapter(BaseAdapter):
raise
return PreTrainedTokenizerFast.from_pretrained(self._model_name_or_path, **shared_kwargs)
+ def _require_pipe(self) -> Any:
+ if self._pipe is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ return self._pipe
+
+ def _window(self) -> int | None:
+ """The model's max sequence length in tokens, special tokens included."""
+ window = self._max_seq_length or getattr(self._pipe, "max_length", None)
+ return window if isinstance(window, int) else None
+
+ def _visible_tokens(self) -> int | None:
+ """Most tokens of a document anything reads: the model window plus the fit check's margin.
+
+ None without a configured max sequence length: metering then counts
+ every token of a document, so documents are not cut.
+ """
+ max_length = getattr(self._pipe, "max_length", None)
+ if self._max_seq_length is None or not isinstance(max_length, int):
+ return None
+ return max(1, max_length - self._special_count + _FIT_MARGIN_TOKENS)
+
def _extract_text(self, item: Item) -> str:
if not item.text:
msg = "Item must have text for classification"
@@ -351,43 +610,40 @@ 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]:
"""Enforce overflow_policy by pre-tokenizing text and label_prompt separately.
- At inference the gliclass pipeline tokenizes the fused string with
- ``add_special_tokens=True``, so the model sees
- ``observed = text_tokens + label_prompt_tokens + special_count``, where
- ``special_count`` is the BERT-style ``[CLS]``/``[SEP]`` wrap (2 for all
- current gliclass models). We recover the same total without running the
- model by tokenizing each part with ``add_special_tokens=False``. The
- label prompt includes the task prompt and few-shot examples when the
- request sets them, so ``truncate_text`` shortens only the document.
+ The model sees ``observed = text_tokens + label_prompt_tokens +
+ special_count``, where ``special_count`` is the BERT-style
+ ``[CLS]``/``[SEP]`` wrap (2 for all current gliclass models). We
+ recover the same total without running the model by tokenizing each
+ part with ``add_special_tokens=False``. The label prompt includes the
+ task prompt and few-shot examples when the request sets them, so
+ ``truncate_text`` shortens only the document.
On overflow:
- ``default`` returns texts unchanged (upstream as-is — may crash inside
- the pipeline; the ``c0ce823c`` ``try/except`` in ``extract`` is the
- defense-in-depth backstop).
+ the model; ``_overflow_errors_as_input_too_long`` in ``extract`` is
+ the defense-in-depth backstop).
- ``error`` raises ``InputTooLongError`` (whole batch fails, no partial
responses).
- ``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.
+ the cap always raises. ``indices`` gives each text's item index for
+ error messages when ``texts`` is a subset of the items.
"""
if policy == "default":
return texts
- if self._pipeline is None:
- raise RuntimeError(ERR_NOT_LOADED)
- if self._tokenizer is None:
- raise RuntimeError(ERR_NOT_LOADED)
- if self._max_seq_length is None:
+ if self._pipe is None or self._tokenizer is None or self._max_seq_length is None:
raise RuntimeError(ERR_NOT_LOADED)
- context = _pipeline_context(prompt, examples)
- label_prompt = self._pipeline.pipe.prepare_input(text="", labels=labels, **context) # ty:ignore[unresolved-attribute]
- label_prompt_tokens = len(self._tokenizer(label_prompt, add_special_tokens=False)["input_ids"])
+ tokens = tokens or _RequestTokens(self._tokenizer)
+ label_prompt_tokens = self._overflow_label_tokens(labels, prompt, examples, tokens)
overhead = label_prompt_tokens + self._special_count
budget = self._max_seq_length - overhead
@@ -398,17 +654,24 @@ class GLiClassAdapter(BaseAdapter):
)
new_texts: list[str] = []
- for i, text in enumerate(texts):
- text_ids = self._tokenizer(text, add_special_tokens=False)["input_ids"]
+ for i, (text, text_ids) in enumerate(zip(texts, tokens.full(texts), strict=True)):
text_tokens = len(text_ids)
observed = text_tokens + overhead
if observed <= self._max_seq_length:
new_texts.append(text)
continue
if 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}"
+ else:
+ counts, text_count = f"observed_tokens={observed}", f"text={text_tokens}"
raise InputTooLongError(
- f"items[{i}] observed_tokens={observed} exceeds max_sequence_length ({self._max_seq_length}) "
- f"(text={text_tokens}, label_prompt={label_prompt_tokens}, special={self._special_count})"
+ f"items[{index}] {counts} exceeds max_sequence_length ({self._max_seq_length}) "
+ f"({text_count}, label_prompt={label_prompt_tokens}, special={self._special_count})"
)
new_texts.append(self._tokenizer.decode(text_ids[:budget], skip_special_tokens=True))
return new_texts
@@ -434,13 +697,14 @@ class GLiClassAdapter(BaseAdapter):
labels: Classification labels (e.g., ["positive", "negative", "neutral"]).
Required unless ``options["label_groups"]`` is set.
output_schema: Unused (included for interface compatibility).
- instruction: Optional task description, passed to the gliclass
- pipeline as its ``prompt``.
+ instruction: Optional task description, passed to the model as the
+ gliclass pipeline's ``prompt``.
options: Adapter options to override model config defaults.
Supported: ``threshold`` (float), ``classification_type``
("single-label" or "multi-label"), ``examples`` (few-shot
``[{"text": str, "labels": [str, ...]}]``), ``label_groups``
- (``{group: [label, ...]}``, used instead of ``labels``), and
+ (``{group: [label, ...]}``, used instead of ``labels``),
+ ``group_encoding`` ("separate" or "joint") and
``overflow_policy``.
Returns:
@@ -456,14 +720,13 @@ class GLiClassAdapter(BaseAdapter):
RuntimeError: If model not loaded.
InvalidInputError: If labels are missing or options are malformed.
InputTooLongError: If the labels do not fit in the model window.
- ValueError: If items lack text or the pipeline returns malformed
- scores.
+ ValueError: If items lack text or the model returns invalid scores.
"""
- if self._pipeline is None:
- raise RuntimeError(ERR_NOT_LOADED)
+ self._require_pipe()
opts = options or {}
label_groups = self._validate_label_groups(opts.get("label_groups"))
+ group_encoding = self._validate_group_encoding(opts, label_groups)
classification_type = self._validate_classification_type(
opts.get("classification_type", self._classification_type)
)
@@ -473,7 +736,12 @@ class GLiClassAdapter(BaseAdapter):
raise InvalidInputError("GLiClass accepts either labels or options.label_groups, not both")
else:
normalized_labels = self._flatten_label_groups(label_groups, classification_type)
- self._check_label_size(normalized_labels)
+ if label_groups is not None and group_encoding == "separate":
+ self._check_group_count(label_groups)
+ for _, group_labels in label_groups:
+ self._check_label_size(group_labels)
+ else:
+ self._check_label_size(normalized_labels)
prompt = self._validate_instruction(instruction)
examples = self._validate_examples(opts.get("examples"), normalized_labels, label_groups)
self._check_context_size(prompt, examples)
@@ -482,31 +750,52 @@ class GLiClassAdapter(BaseAdapter):
texts = [self._extract_text(item) for item in items]
# Get options with fallback to model defaults. The threshold is applied
- # server-side as a post-filter so we always get all label scores from the
- # underlying pipeline regardless of caller preferences.
+ # server-side as a post-filter so every label's score is computed
+ # regardless of caller preferences.
effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold))
overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
- texts = self._apply_overflow_policy(texts, normalized_labels, overflow_policy, prompt=prompt, examples=examples)
- layout = self._request_layout(normalized_labels, prompt, examples)
- fits = self._items_fit(texts, layout, normalized_labels, prompt, examples)
- input_token_counts = self._input_token_counts(texts, prompt, examples, layout, fits)
+ tokens = _RequestTokens(self._tokenizer, self._visible_tokens())
+
+ if label_groups is not None and group_encoding == "separate":
+ char_limit = _row_char_limit(len(label_groups), self._window())
+ return self._extract_separate(
+ [tokens.visible(text, char_limit) for text in texts],
+ label_groups,
+ classification_type=classification_type,
+ prompt=prompt,
+ examples=examples,
+ threshold=effective_threshold,
+ overflow_policy=overflow_policy,
+ tokens=tokens,
+ )
+
+ texts = [tokens.visible(text) or text for text in texts]
+ texts = self._apply_overflow_policy(
+ texts, normalized_labels, overflow_policy, prompt=prompt, examples=examples, tokens=tokens
+ )
+ layout = self._request_layout(normalized_labels, prompt, examples, tokens)
+ fits = self._items_fit(texts, layout, normalized_labels, prompt, examples, tokens=tokens)
+ input_token_counts = self._input_token_counts(texts, prompt, examples, layout, fits, tokens=tokens)
errors = self._item_errors(fits)
kept = [index for index, ok in enumerate(fits) if ok]
kept_texts = [texts[index] for index in kept]
if label_groups is not None:
- return self._extract_grouped(
- kept_texts,
+ rows = (
+ self._joint_scores(kept_texts, label_groups, normalized_labels, classification_type, prompt, examples)
+ if kept_texts
+ else []
+ )
+ return self._grouped_output(
+ rows,
label_groups,
- normalized_labels,
classification_type=classification_type,
- prompt=prompt,
- examples=examples,
threshold=effective_threshold,
- input_token_counts=input_token_counts,
kept=kept,
+ item_count=len(items),
errors=errors,
+ input_token_counts=input_token_counts,
)
if not kept_texts:
@@ -517,68 +806,21 @@ class GLiClassAdapter(BaseAdapter):
input_token_counts=input_token_counts,
)
- context = _pipeline_context(prompt, examples)
- pipeline = self._select_pipeline(classification_type)
-
- # Run batch classification.
- # - threshold=0.0: never let the gliclass library drop labels for us
- # (in single-label mode the lib returns only argmax anyway, so we
- # need return_hierarchical=True to recover all label scores).
- # - return_hierarchical=True with a flat ``labels`` list yields a list
- # of ``{label: score}`` dicts with every requested label present.
- try:
- with torch.inference_mode():
- batch_results = pipeline(
- kept_texts,
- normalized_labels,
- threshold=0.0,
- return_hierarchical=True,
- **context,
- )
- except (RuntimeError, IndexError) as exc:
- # The gliclass library crashes inside the pipeline when inputs exceed
- # the model's position-embedding capacity, producing empty intermediate
- # tensors that downstream ops then operate on. Surface the known crash
- # signatures as InputTooLongError (validation) instead of leaking as
- # 500 INFERENCE_ERROR. Match must be specific to avoid swallowing
- # unrelated errors. Catalog of caught signatures:
- # - RuntimeError "argmax(): ... numel() == 0"
- # torch.argmax on an empty tensor inside the classification head.
- # - IndexError "index N is out of bounds for dimension D with size N"
- # (index == size: off-by-one / exhausted dimension). Covers both the
- # empty-tensor case (#860, index 0 / size 0) and the label-window
- # overflow (#1434, e.g. index 79 / size 79): when too many labels
- # overflow the shared 512-token window only some survive truncation
- # and the single-label hierarchical decode then indexes exactly one
- # past the shrunk label window.
- msg = str(exc)
- if isinstance(exc, RuntimeError) and "numel() == 0" in msg and "argmax" in msg:
- raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
- oob = _INDEX_OOB_RE.search(msg)
- if isinstance(exc, IndexError) and oob is not None and oob.group(1) == oob.group(2):
- # Off-by-one: the gliclass single-label hierarchical decode indexes
- # exactly one past an exhausted dimension (index == size) when the
- # label/text window overflows max_sequence_length. Covers both the
- # empty-tensor case (#860, index 0 / size 0) and the label-window
- # overflow (#1434, e.g. index 79 / size 79). A generic out-of-range
- # bug (index > size, e.g. index 5 / size 3) is NOT this and must keep
- # propagating via the bare ``raise`` below.
- raise InputTooLongError(_ERR_INPUT_TOO_LONG) from exc
- raise
+ with _overflow_errors_as_input_too_long():
+ batch_scores = self._score_rows(
+ kept_texts,
+ normalized_labels,
+ classification_type=classification_type,
+ prompt=prompt,
+ examples=examples,
+ )
all_classifications: list[list[Classification]] = [[] for _ in items]
- for index, item_results in zip(kept, batch_results, strict=True):
- # With return_hierarchical=True and a flat label list the library
- # returns a dict {label: score}. Anything else (e.g. None for an
- # empty input) yields no classifications rather than crashing.
- if isinstance(item_results, dict):
- if set(item_results) != set(normalized_labels):
- raise ValueError("GLiClass returned classifications outside the requested label set")
- pairs = [(label, self._validate_score(item_results[label])) for label in normalized_labels]
- else:
- pairs = []
-
- classifications: list[Classification] = [Classification(label=label, score=score) for label, score in pairs]
+ for index, scores in zip(kept, batch_scores, strict=True):
+ classifications: list[Classification] = [
+ Classification(label=label, score=self._validate_score(score))
+ for label, score in zip(normalized_labels, scores, strict=True)
+ ]
# Server-side post-filter when the caller explicitly requested one.
if effective_threshold > 0.0:
@@ -596,49 +838,390 @@ class GLiClassAdapter(BaseAdapter):
input_token_counts=input_token_counts,
)
- def _select_pipeline(self, classification_type: ClassificationType) -> ZeroShotClassificationPipeline:
- if classification_type == self._classification_type:
- if self._pipeline is None:
- raise RuntimeError(ERR_NOT_LOADED)
- return self._pipeline
- if self._pipelines is None:
- raise RuntimeError(ERR_NOT_LOADED)
- return self._pipelines[classification_type]
+ 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 row it encodes.
+
+ Separate label groups encode each document once per group, next to
+ that group's labels and the request's instruction and examples, so
+ the default per-item character count would undercount such a request
+ by its group count. Other requests keep the default (None). This runs
+ before batching and before validation, so it walks at most
+ ``MAX_EXTRACT_LABELS`` labels and ``_MAX_EXAMPLES`` examples.
+ Best-effort: never raises; malformed requests fail in ``extract``.
+ """
+ _ = labels, output_schema
+ try:
+ opts = options or {}
+ groups = opts.get("label_groups")
+ if not isinstance(groups, dict) or not groups or len(groups) > _MAX_LABEL_GROUPS:
+ return None
+ if self._requested_group_encoding(opts) != "separate":
+ return None
+ group_labels = (label for values in groups.values() if isinstance(values, list) for label in values)
+ label_chars = sum(
+ len(label) for label in islice(group_labels, MAX_EXTRACT_LABELS) if isinstance(label, str)
+ )
+ context_chars = len(instruction) if isinstance(instruction, str) else 0
+ examples = opts.get("examples")
+ if isinstance(examples, list):
+ for example in islice(cast("list[Any]", examples), _MAX_EXAMPLES):
+ text = cast("dict[str, Any]", example).get("text") if isinstance(example, dict) else None
+ context_chars += len(text) if isinstance(text, str) else 0
+ return [len(groups) * (len(item.text or "") + context_chars) + label_chars for item in items]
+ except Exception: # noqa: BLE001 -- a cost estimate must never fail the request
+ return None
+
+ def _score_rows(
+ self,
+ texts: list[str],
+ labels: list[str] | list[list[str]],
+ *,
+ classification_type: ClassificationType,
+ prompt: str | None,
+ examples: list[dict[str, Any]] | list[list[dict[str, Any]]] | None,
+ batch_size: int = _PIPELINE_BATCH_SIZE,
+ ) -> list[list[float]]:
+ """Each row's label scores, computed as the gliclass pipeline computes them.
+
+ ``labels`` is one label list shared by every row, or one list per row
+ (then ``examples`` is also one list per row, or None). Rows run in
+ forward passes of at most ``batch_size``, by default the pipeline's
+ sub-batches. A single-label row gets a softmax over the label slots a
+ call with only its labels would have; a multi-label row a sigmoid per
+ label. Each forward's scores come back in one device-to-host copy.
+ """
+ pipe = self._require_pipe()
+ shared = isinstance(labels[0], str)
+ scores: list[list[float]] = []
+ with torch.inference_mode():
+ for start in range(0, len(texts), batch_size):
+ batch_texts = texts[start : start + batch_size]
+ end = start + len(batch_texts)
+ batch_labels = labels if shared else labels[start:end]
+ batch_examples = examples if shared or examples is None else examples[start:end]
+ inputs = pipe.prepare_inputs(
+ batch_texts, batch_labels, same_labels=shared, examples=batch_examples, prompt=prompt
+ )
+ logits = self._forward(pipe, inputs, batch_labels, same_labels=shared)
+ row_labels = cast("list[list[str]]", [batch_labels] * len(batch_texts) if shared else batch_labels)
+ probs = torch.sigmoid(logits) if classification_type == "multi-label" else None
+ rows: list[torch.Tensor] = []
+ for row, row_label_list in enumerate(row_labels):
+ count = len(row_label_list)
+ width = self._row_width(pipe, row_label_list, logits.shape[-1])
+ if width < count:
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG)
+ if probs is not None:
+ rows.append(probs[row, :count])
+ elif width == logits.shape[-1]:
+ rows.append(torch.softmax(logits[row], dim=-1)[:count])
+ else:
+ rows.append(torch.softmax(logits[row, :width], dim=-1)[:count])
+ values = torch.cat(rows).tolist()
+ position = 0
+ for row_label_list in row_labels:
+ scores.append(values[position : position + len(row_label_list)])
+ position += len(row_label_list)
+ return scores
+
+ @staticmethod
+ def _forward(pipe: Any, inputs: Any, labels: list[str] | list[list[str]], *, same_labels: bool) -> torch.Tensor:
+ """Run the model on tokenized rows, passing the class-slot count the pipeline passes."""
+ forward_kwargs: dict[str, Any] = {}
+ resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)
+ if resolve_max_num_classes is not None:
+ forward_kwargs["max_num_classes"] = resolve_max_num_classes(labels, same_labels)
+ return pipe.model(**inputs, **forward_kwargs).logits
+
+ @staticmethod
+ def _row_width(pipe: Any, labels: list[str], batch_width: int) -> int:
+ """Class slots a forward over only this row's labels would score.
- def _extract_grouped(
+ With the default dynamic allocation that is one slot per label, fewer
+ than a batch of rows with more labels gets. Fixed allocations give
+ every row the batch's width.
+ """
+ resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)
+ width = resolve_max_num_classes(labels, True) if resolve_max_num_classes is not None else None
+ return batch_width if width is None else min(int(width), batch_width)
+
+ def _joint_scores(
self,
texts: list[str],
label_groups: list[tuple[str, list[str]]],
flat_labels: list[str],
+ classification_type: ClassificationType,
+ prompt: str | None,
+ examples: list[dict[str, Any]] | None,
+ ) -> list[list[float]]:
+ """Score all groups' labels in one row per text and normalize per group.
+
+ All groups share one forward pass per text, as the gliclass pipeline
+ encodes a dict of labels ("group.label" after flattening). The
+ pipeline's own single-label mode applies one softmax across every
+ flattened label, which makes a group's scores depend on the other
+ groups. Here each group gets its own softmax over the raw logits
+ instead; multi-label scores are independent sigmoids either way.
+ """
+ pipe = self._require_pipe()
+ num_labels = len(flat_labels)
+
+ chunks: list[torch.Tensor] = []
+ with torch.inference_mode(), _overflow_errors_as_input_too_long():
+ for start in range(0, len(texts), _PIPELINE_BATCH_SIZE):
+ inputs = pipe.prepare_inputs(
+ texts[start : start + _PIPELINE_BATCH_SIZE],
+ flat_labels,
+ same_labels=True,
+ examples=examples,
+ prompt=prompt,
+ )
+ logits = self._forward(pipe, inputs, flat_labels, same_labels=True)
+ if logits.shape[-1] < num_labels:
+ raise InputTooLongError(_ERR_INPUT_TOO_LONG)
+ chunks.append(logits[:, :num_labels].float())
+
+ logits = torch.cat(chunks)
+ if classification_type == "multi-label":
+ scores = torch.sigmoid(logits)
+ else:
+ scores = torch.empty_like(logits)
+ start = 0
+ for _, group_labels in label_groups:
+ end = start + len(group_labels)
+ scores[:, start:end] = torch.softmax(logits[:, start:end], dim=-1)
+ start = end
+ return scores.cpu().tolist()
+
+ def _extract_separate(
+ self,
+ texts: list[str | None],
+ label_groups: list[tuple[str, list[str]]],
*,
classification_type: ClassificationType,
prompt: str | None,
examples: list[dict[str, Any]] | None,
threshold: float,
- input_token_counts: list[int] | None,
+ overflow_policy: OverflowPolicy,
+ tokens: _RequestTokens,
+ ) -> ExtractOutput:
+ """Encode the document once per group, with only that group's labels.
+
+ Each row is what a request with ``labels`` set to the group's labels
+ encodes: its overflow policy, window check and metering apply per
+ row. An item whose labels do not fit in one of its rows fails with
+ ``INPUT_TOO_LONG``, is billed nothing and is not checked against the
+ remaining groups; the other items still run. ``texts`` holds each
+ document's readable prefix, or None for one whose readable part
+ exceeds the per-group character bound.
+
+ The first group's context is tokenized and checked alone, so a
+ request whose instruction and examples cannot fit is refused before
+ the other groups' contexts are built.
+ """
+ group_examples = self._examples_by_group(examples, label_groups)
+ item_count = len(texts)
+ sparse = _ERR_ITEM_DOCUMENT_TOO_SPARSE.format(limit=_row_char_limit(len(label_groups), self._window()))
+ failures: list[str | None] = [None if text is not None else sparse for text in texts]
+ counts: list[int] | None = [0] * item_count
+ item_rows: list[list[str]] = [[] for _ in range(item_count)]
+ item_lengths: list[list[int]] | None = [[] for _ in range(item_count)]
+ for group, (_, group_labels) in enumerate(label_groups):
+ alive = [index for index, failure in enumerate(failures) if failure is None]
+ if not alive:
+ break
+ if group == 1:
+ self._contexts(
+ tokens,
+ [
+ (labels, prompt, group_examples[later] if group_examples is not None else None)
+ for later, (_, labels) in enumerate(label_groups[1:], start=1)
+ ],
+ overflow=overflow_policy != "default",
+ )
+ row_examples = group_examples[group] if group_examples is not None else None
+ row_texts = 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_fits = self._items_fit(row_texts, layout, group_labels, prompt, row_examples, tokens=tokens)
+ row_counts = self._input_token_counts(
+ row_texts, prompt, row_examples, layout, [True] * len(alive), tokens=tokens
+ )
+ row_lengths = None if layout is None else self._row_lengths(row_texts, layout, tokens)
+ if row_counts is None:
+ counts = None
+ if row_lengths is None:
+ item_lengths = None
+ for position, index in enumerate(alive):
+ if not row_fits[position]:
+ failures[index] = _ERR_ITEM_LABELS_TRUNCATED
+ continue
+ item_rows[index].append(row_texts[position])
+ if counts is not None and row_counts is not None:
+ counts[index] += row_counts[position]
+ if item_lengths is not None and row_lengths is not None:
+ item_lengths[index].append(row_lengths[position])
+ if counts is not None:
+ counts = [count if failure is None else 0 for count, failure in zip(counts, failures, strict=True)]
+ errors = (
+ None
+ if all(failure is None for failure in failures)
+ else [
+ None if failure is None else ExtractItemError(code=ErrorCode.INPUT_TOO_LONG.value, message=failure)
+ for failure in failures
+ ]
+ )
+ kept = [index for index, failure in enumerate(failures) if failure is None]
+ rows = self._separate_scores(
+ [item_rows[index] for index in kept],
+ label_groups,
+ classification_type=classification_type,
+ prompt=prompt,
+ group_examples=group_examples,
+ row_lengths=None if item_lengths is None else [item_lengths[index] for index in kept],
+ )
+ return self._grouped_output(
+ rows,
+ label_groups,
+ classification_type=classification_type,
+ threshold=threshold,
+ kept=kept,
+ item_count=item_count,
+ errors=errors,
+ input_token_counts=counts,
+ )
+
+ def _separate_scores(
+ self,
+ item_rows: list[list[str]],
+ label_groups: list[tuple[str, list[str]]],
+ *,
+ classification_type: ClassificationType,
+ prompt: str | None,
+ group_examples: list[list[dict[str, Any]]] | None,
+ row_lengths: list[list[int]] | None = None,
+ ) -> list[list[float]]:
+ """Scores of every (item, group) row, flattened per item in group order.
+
+ ``item_rows[i][g]`` is item ``i``'s document as group ``g`` encodes it,
+ and ``row_lengths[i][g]`` that row's estimated token length.
+ Uni-encoder rows of different groups share forward passes, packed by
+ ``_row_chunks``. Other architectures take one label set per forward,
+ so their rows run group by group.
+ """
+ if not item_rows:
+ return []
+ group_count = len(label_groups)
+ pipe = self._require_pipe()
+ config = getattr(getattr(pipe, "model", None), "config", None)
+ per_row: list[list[float]] = []
+ with _overflow_errors_as_input_too_long():
+ if getattr(config, "architecture_type", None) == "uni-encoder":
+ row_texts = [text for texts in item_rows for text in texts]
+ row_labels = [group_labels for _ in item_rows for _, group_labels in label_groups]
+ row_examples = (
+ [group_examples[group] for _ in item_rows for group in range(group_count)]
+ if group_examples is not None
+ else None
+ )
+ lengths = None if row_lengths is None else [length for item in row_lengths for length in item]
+ per_row = [[] for _ in row_texts]
+ for chunk in self._row_chunks(lengths, len(row_texts), pipe.max_length):
+ scored = self._score_rows(
+ [row_texts[row] for row in chunk],
+ [row_labels[row] for row in chunk],
+ classification_type=classification_type,
+ prompt=prompt,
+ examples=None if row_examples is None else [row_examples[row] for row in chunk],
+ batch_size=len(chunk),
+ )
+ for row, row_scores in zip(chunk, scored, strict=True):
+ per_row[row] = row_scores
+ else:
+ by_group = [
+ self._score_rows(
+ [texts[group] for texts in item_rows],
+ group_labels,
+ classification_type=classification_type,
+ prompt=prompt,
+ examples=group_examples[group] if group_examples is not None else None,
+ )
+ for group, (_, group_labels) in enumerate(label_groups)
+ ]
+ per_row = [by_group[group][item] for item in range(len(item_rows)) for group in range(group_count)]
+ return [
+ [score for row in per_row[item * group_count : (item + 1) * group_count] for score in row]
+ for item in range(len(item_rows))
+ ]
+
+ def _row_lengths(self, texts: list[str], layout: _RequestLayout, tokens: _RequestTokens) -> list[int]:
+ """Estimated token length of each row: its document, label prompt, context and special tokens.
+
+ The parts are tokenized apart, so a row can differ from its estimate
+ by a token or two where they meet.
+ """
+ pipe = self._require_pipe()
+ overhead = layout.overhead_tokens + self._special_count
+ return [min(pipe.max_length, len(ids) + overhead) for ids in tokens.cut(texts, layout.window)]
+
+ @staticmethod
+ def _row_chunks(lengths: list[int] | None, count: int, max_length: int) -> list[list[int]]:
+ """Group row indices into forward passes of at most ``_PIPELINE_BATCH_SIZE * max_length`` padded tokens.
+
+ That is the most a labels request's sub-batch of eight full-window
+ rows pads to. Rows are packed longest first, so rows of similar
+ length share padding and many short rows share one forward pass.
+ Without length estimates, rows run in order, eight per forward.
+ """
+ if lengths is None:
+ return [
+ list(range(start, min(start + _PIPELINE_BATCH_SIZE, count)))
+ for start in range(0, count, _PIPELINE_BATCH_SIZE)
+ ]
+ budget = _PIPELINE_BATCH_SIZE * max_length
+ order = sorted(range(count), key=lambda row: lengths[row], reverse=True)
+ chunks: list[list[int]] = []
+ start = 0
+ while start < count:
+ size = max(1, min(count - start, budget // max(1, lengths[order[start]])))
+ chunks.append(order[start : start + size])
+ start += size
+ return chunks
+
+ def _grouped_output(
+ self,
+ rows: list[list[float]],
+ label_groups: list[tuple[str, list[str]]],
+ *,
+ classification_type: ClassificationType,
+ threshold: float,
kept: list[int],
+ item_count: int,
errors: list[ExtractItemError | None] | None,
+ input_token_counts: list[int] | None,
) -> ExtractOutput:
- """Score grouped labels and return one answer per group.
-
- All groups share one forward pass per text, exactly as the gliclass
- pipeline encodes a dict of labels ("group.label" after flattening).
- The pipeline's own single-label mode applies one softmax across every
- flattened label, which makes a group's scores depend on the other
- groups. Here each group gets its own softmax over the raw logits
- instead; multi-label scores are independent sigmoids either way.
+ """One answer per group from each kept item's scores, in flattened group order.
A single-label group answers like a choice question:
``{"type": "choice", "choice", "probabilities", "confidence"}`` with
``confidence = 1 - H(p) / log(k)``. A multi-label group answers
``{"labels", "probabilities"}``.
"""
- rows = (
- self._grouped_scores(texts, label_groups, flat_labels, classification_type, prompt, examples)
- if texts
- else []
- )
- item_count = len(errors) if errors is not None else len(texts)
# Multi-label groups list the labels at or above the request threshold,
# or at or above 0.5 (an even sigmoid) when no threshold is set.
selection_threshold = threshold if threshold > 0.0 else _DEFAULT_MULTI_LABEL_THRESHOLD
@@ -682,52 +1265,32 @@ class GLiClassAdapter(BaseAdapter):
input_token_counts=input_token_counts,
)
- def _grouped_scores(
- self,
- texts: list[str],
- label_groups: list[tuple[str, list[str]]],
- flat_labels: list[str],
- classification_type: ClassificationType,
- prompt: str | None,
+ @staticmethod
+ def _examples_by_group(
examples: list[dict[str, Any]] | None,
- ) -> list[list[float]]:
- """Run the model on flattened group labels and normalize per group."""
- if self._pipeline is None:
- raise RuntimeError(ERR_NOT_LOADED)
- pipe = self._pipeline.pipe # ty:ignore[unresolved-attribute]
- model = pipe.model
- num_labels = len(flat_labels)
- forward_kwargs: dict[str, Any] = {}
- resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)
- if resolve_max_num_classes is not None:
- forward_kwargs["max_num_classes"] = resolve_max_num_classes(flat_labels, True)
-
- chunks: list[torch.Tensor] = []
- with torch.inference_mode():
- for start in range(0, len(texts), _PIPELINE_BATCH_SIZE):
- inputs = pipe.prepare_inputs(
- texts[start : start + _PIPELINE_BATCH_SIZE],
- flat_labels,
- same_labels=True,
- examples=examples,
- prompt=prompt,
- )
- logits = model(**inputs, **forward_kwargs).logits
- if logits.shape[-1] < num_labels:
- raise InputTooLongError(_ERR_INPUT_TOO_LONG)
- chunks.append(logits[:, :num_labels].float())
+ label_groups: list[tuple[str, list[str]]],
+ ) -> list[list[dict[str, Any]]] | None:
+ """Each group's view of the examples: every example, with only that group's labels.
- logits = torch.cat(chunks)
- if classification_type == "multi-label":
- scores = torch.sigmoid(logits)
- else:
- scores = torch.empty_like(logits)
- start = 0
- for _, group_labels in label_groups:
- end = start + len(group_labels)
- scores[:, start:end] = torch.softmax(logits[:, start:end], dim=-1)
- start = end
- return scores.cpu().tolist()
+ Example labels arrive flattened (``"group.label"``); the flattened
+ names are unique, so each maps back to one group.
+ """
+ if examples is None:
+ return None
+ owner = {
+ f"{group}{_LABEL_GROUP_SEPARATOR}{label}": (index, label)
+ for index, (group, group_labels) in enumerate(label_groups)
+ for label in group_labels
+ }
+ by_group: list[list[dict[str, Any]]] = [[] for _ in label_groups]
+ for example in examples:
+ chosen: list[list[str]] = [[] for _ in label_groups]
+ for flat in example["labels"]:
+ group, label = owner[flat]
+ chosen[group].append(label)
+ for group, group_labels in enumerate(chosen):
+ by_group[group].append({"text": example["text"], "labels": group_labels})
+ return by_group
@staticmethod
def _validate_classification_type(value: object) -> ClassificationType:
@@ -737,6 +1300,41 @@ class GLiClassAdapter(BaseAdapter):
return "multi-label"
raise InvalidInputError("GLiClass classification_type must be 'single-label' or 'multi-label'")
+ @staticmethod
+ def _requested_group_encoding(options: dict[str, Any]) -> GroupEncoding:
+ """The request's group encoding: the default when the option is absent.
+
+ The batching cost and ``extract`` both read it here, so a value one
+ of them rejects can never be costed as another encoding.
+ """
+ if "group_encoding" not in options:
+ return _DEFAULT_GROUP_ENCODING
+ value = options["group_encoding"]
+ if isinstance(value, str) and value in ("separate", "joint"):
+ return cast("GroupEncoding", value)
+ raise InvalidInputError("GLiClass group_encoding must be 'separate' or 'joint'")
+
+ @classmethod
+ def _validate_group_encoding(
+ cls, options: dict[str, Any], label_groups: list[tuple[str, list[str]]] | None
+ ) -> GroupEncoding:
+ encoding = cls._requested_group_encoding(options)
+ if "group_encoding" in options and label_groups is None:
+ raise InvalidInputError("GLiClass group_encoding applies only with options.label_groups")
+ return encoding
+
+ def _check_group_count(self, label_groups: list[tuple[str, list[str]]]) -> None:
+ """Bound the rows a separate-group request adds per item: one full row per group."""
+ window = self._max_seq_length or getattr(self._pipe, "max_length", None)
+ limit = _MAX_LABEL_GROUPS
+ if isinstance(window, int) and window > 0:
+ limit = max(1, min(limit, _MAX_ITEM_ROW_TOKENS // window))
+ if len(label_groups) > limit:
+ raise InvalidInputError(
+ f"GLiClass encodes the document once per label group and accepts at most {limit} groups "
+ f"per request (got {len(label_groups)}); send fewer groups, or options.group_encoding='joint'"
+ )
+
@staticmethod
def _validate_instruction(instruction: object) -> str | None:
if instruction is None:
@@ -887,13 +1485,118 @@ class GLiClassAdapter(BaseAdapter):
raise ValueError("GLiClass returned an invalid classification score")
return score
+ def _contexts(
+ self,
+ tokens: _RequestTokens,
+ contexts: list[tuple[list[str], str | None, list[dict[str, Any]] | None]],
+ *,
+ overflow: bool,
+ ) -> list[_Context]:
+ """Tokenize the (labels, instruction, examples) contexts a request encodes, in one call.
+
+ ``overflow`` also tokenizes each context's pipeline input with an
+ empty document, which the overflow policies measure. Contexts the
+ request already tokenized are reused.
+ """
+ entries: list[_Context] = []
+ pending: list[tuple[_Context, list[str] | None, str | None]] = []
+ for labels, prompt, examples in contexts:
+ key = (
+ tuple(labels),
+ prompt,
+ None if examples is None else tuple((e["text"], tuple(e["labels"])) for e in examples),
+ )
+ context = tokens.contexts.setdefault(key, _Context())
+ entries.append(context)
+ parts = self._layout_strings(labels, prompt, examples) if context.parts is None else None
+ empty = None
+ if overflow and context.overflow_tokens is None:
+ pipe = self._require_pipe()
+ empty = pipe.prepare_input(text="", labels=labels, **_pipeline_context(prompt, examples))
+ pending.append((context, parts, empty))
+ # Each distinct string is tokenized once per call: the instruction and
+ # example texts repeat in every group's context.
+ strings = list(
+ dict.fromkeys(
+ string
+ for _, parts, empty in pending
+ for string in [*(parts or []), *([empty] if empty is not None else [])]
+ if string not in tokens.context_ids
+ )
+ )
+ if strings:
+ if self._tokenizer is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ encoded = self._tokenizer(strings, add_special_tokens=False)["input_ids"]
+ tokens.context_ids.update(zip(strings, encoded, strict=True))
+ for context, parts, empty in pending:
+ if parts is not None:
+ context.parts = [tokens.context_ids[part] for part in parts]
+ if empty is not None:
+ context.overflow_tokens = len(tokens.context_ids[empty])
+ return entries
+
+ def _layout_strings(
+ self,
+ labels: list[str],
+ prompt: str | None,
+ examples: list[dict[str, Any]] | None,
+ ) -> list[str]:
+ """The parts of a context the label-fit check measures; none unless the model is a uni-encoder.
+
+ Only uni-encoder GLiClass models put label markers in their input.
+ """
+ pipe = self._pipe
+ config = getattr(getattr(pipe, "model", None), "config", None)
+ if (
+ pipe is None
+ or config is None
+ or self._tokenizer is None
+ or getattr(config, "architecture_type", None) != "uni-encoder"
+ ):
+ return []
+ label_prompt = "".join(f"{pipe.label_token}{label}" for label in labels) + pipe.sep_token
+ parts = [label_prompt, *([prompt] if prompt else []), *(example["text"] for example in examples or [])]
+ if examples:
+ parts.append(pipe._format_examples_for_input(examples))
+ return parts
+
def _request_layout(
self,
labels: list[str],
prompt: str | None,
examples: list[dict[str, Any]] | None,
+ tokens: _RequestTokens | None = None,
+ ) -> _RequestLayout | None:
+ """The token layout every item of a request shares (see ``_compute_layout``)."""
+ tokens = tokens or _RequestTokens(self._tokenizer)
+ (context,) = self._contexts(tokens, [(labels, prompt, examples)], overflow=False)
+ if not context.has_layout:
+ context.layout = self._compute_layout(context.parts or [], labels, prompt, examples)
+ context.has_layout = True
+ return context.layout
+
+ def _overflow_label_tokens(
+ self,
+ labels: list[str],
+ prompt: str | None,
+ examples: list[dict[str, Any]] | None,
+ tokens: _RequestTokens,
+ ) -> int:
+ """Tokens of the pipeline input with an empty document: labels, instruction and examples."""
+ (context,) = self._contexts(tokens, [(labels, prompt, examples)], overflow=True)
+ if context.overflow_tokens is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ return context.overflow_tokens
+
+ def _compute_layout(
+ self,
+ parts: list[list[int]],
+ labels: list[str],
+ prompt: str | None,
+ examples: list[dict[str, Any]] | None,
) -> _RequestLayout | None:
- """Tokenize the parts every item shares, once per request.
+ """The layout of a context from its tokenized parts (see ``_layout_strings``).
Returns None when the model does not put label markers in its input
(only uni-encoder GLiClass models do), so there is nothing to check.
@@ -903,43 +1606,34 @@ class GLiClassAdapter(BaseAdapter):
InvalidInputError: If the instruction and examples leave no room
for the document.
"""
- pipe = getattr(self._pipeline, "pipe", None)
+ pipe = self._pipe
config = getattr(getattr(pipe, "model", None), "config", None)
- tokenizer = self._tokenizer
- if (
- pipe is None
- or config is None
- or tokenizer is None
- or getattr(config, "architecture_type", None) != "uni-encoder"
- ):
+ if not parts or pipe is None or config is None:
return None
-
- def count(text: str) -> int:
- return len(tokenizer(text, add_special_tokens=False)["input_ids"])
-
- label_prompt = "".join(f"{pipe.label_token}{label}" for label in labels) + pipe.sep_token
- label_ids = tokenizer(label_prompt, add_special_tokens=False)["input_ids"]
+ label_ids = parts[0]
markers = [position for position, token in enumerate(label_ids) if token == config.class_token_index]
if len(markers) < len(labels):
return None
window = pipe.max_length - self._special_count
if markers[-1] >= window:
raise InputTooLongError(_ERR_INPUT_TOO_LONG)
- prompt_tokens = count(prompt) if prompt else 0
- example_text_tokens = sum(count(example["text"]) for example in examples or [])
- if prompt or examples:
- examples_tokens = count(pipe._format_examples_for_input(examples)) if examples else 0
- if len(label_ids) + prompt_tokens + examples_tokens >= window:
- raise InvalidInputError(
- "GLiClass instruction, examples and labels leave no room for the document in the "
- f"model's {window}-token window; shorten the instruction or send fewer examples"
- )
+ prompt_tokens = len(parts[1]) if prompt else 0
+ first_example = 2 if prompt else 1
+ example_count = len(examples or [])
+ example_text_tokens = sum(len(ids) for ids in parts[first_example : first_example + example_count])
+ examples_tokens = len(parts[-1]) if examples else 0
+ if (prompt or examples) and len(label_ids) + prompt_tokens + examples_tokens >= window:
+ raise InvalidInputError(
+ "GLiClass instruction, examples and labels leave no room for the document in the "
+ f"model's {window}-token window; shorten the instruction or send fewer examples"
+ )
return _RequestLayout(
prompt_first=bool(getattr(config, "prompt_first", False)),
window=window,
label_tokens=len(label_ids),
last_marker=markers[-1],
context_tokens=prompt_tokens + example_text_tokens,
+ overhead_tokens=len(label_ids) + prompt_tokens + examples_tokens,
)
def _items_fit(
@@ -949,26 +1643,30 @@ class GLiClassAdapter(BaseAdapter):
labels: list[str],
prompt: str | None,
examples: list[dict[str, Any]] | None,
+ *,
+ tokens: _RequestTokens | None = None,
) -> list[bool]:
"""Whether each item's label markers survive truncation.
Documents are tokenized once, on their own. Tokenizing a document next
to the label prompt can differ from that by a token or two (a trailing
space before a marker, for example), so items within a few tokens of
- the window edge are checked exactly on their fused encoding.
+ the window edge are checked exactly on their fused encoding. Counting
+ up to that margin past the window means a document that fills the
+ window by itself is refused without the exact check.
"""
if layout is None or layout.prompt_first or self._tokenizer is None:
return [True] * len(texts)
- encoded = self._tokenizer(texts, add_special_tokens=False, truncation=True, max_length=layout.window)
+ tokens = tokens or _RequestTokens(self._tokenizer)
fits: list[bool] = []
- for text, ids in zip(texts, encoded["input_ids"], strict=True):
+ for text, ids in zip(texts, tokens.cut(texts, layout.window + _FIT_MARGIN_TOKENS), strict=True):
estimate = len(ids) + layout.last_marker
if estimate < layout.window - _FIT_MARGIN_TOKENS:
fits.append(True)
elif estimate >= layout.window + _FIT_MARGIN_TOKENS:
fits.append(False)
else:
- fits.append(self._labels_survive(text, list(ids), labels, prompt, examples))
+ fits.append(self._labels_survive(text, list(ids[: layout.window]), labels, prompt, examples))
return fits
def _labels_survive(
@@ -980,7 +1678,7 @@ class GLiClassAdapter(BaseAdapter):
examples: list[dict[str, Any]] | None,
) -> bool:
"""Exact check: count the label markers left in the truncated fused input."""
- pipe = getattr(self._pipeline, "pipe", None)
+ pipe = self._pipe
tokenizer = self._tokenizer
if pipe is None or tokenizer is None:
return False
@@ -1011,19 +1709,21 @@ class GLiClassAdapter(BaseAdapter):
examples: list[dict[str, Any]] | None,
layout: _RequestLayout | None,
fits: list[bool],
+ *,
+ tokens: _RequestTokens | None = None,
) -> list[int] | None:
- """Billable input tokens per item.
+ """Billable input tokens per item, for one encoded row per item.
- Each item is billed for its document and for the free-form request
+ Each row is billed for its document and for the free-form request
text encoded with it: the instruction and the few-shot example texts.
Label names (including the labels attached to examples) and the
pipeline's marker tokens are not billed. With an instruction or
- examples, an item's total is capped at the model window minus the
+ examples, a row's total is capped at the model window minus the
label prompt, the most free-form text it can encode, unless the
document count alone is already higher. Items refused because their
labels would be cut off are billed nothing.
"""
- counts = self._doc_input_token_counts(texts)
+ counts = self._doc_input_token_counts(texts, tokens)
if counts is None:
return None
if prompt or examples:
@@ -1059,7 +1759,7 @@ class GLiClassAdapter(BaseAdapter):
holds, so it can never be scored correctly, and only tokenizing it
would take time proportional to its size.
"""
- window = self._max_seq_length or getattr(getattr(self._pipeline, "pipe", None), "max_length", None)
+ window = self._max_seq_length or getattr(self._pipe, "max_length", None)
if not isinstance(window, int):
return
limit = min(self._max_token_chars, _MAX_LABEL_CHARS_PER_TOKEN) * window
@@ -1081,24 +1781,33 @@ class GLiClassAdapter(BaseAdapter):
f"GLiClass instruction and examples must total at most {_MAX_CONTEXT_CHARS} characters"
)
- def _doc_input_token_counts(self, texts: list[str]) -> list[int] | None:
+ def _doc_input_token_counts(self, texts: list[str], tokens: _RequestTokens | None = None) -> list[int] | None:
"""Count document-only model-tokenizer input units for billing.
GLiClass fuses the request's label schema with every document. The
label prompt is reusable request schema rather than billed content, so
this mirrors the GLiNER family contract and counts each post-policy
document with the model tokenizer, including its normal special tokens.
+ The tokenizer truncates content to ``max_seq_length`` minus the
+ special tokens and then adds them, so the count is the document's
+ content tokens cut to that length, plus the special tokens.
"""
if self._tokenizer is None:
return None
+ special = self._special_count
try:
- encoded = self._tokenizer(
- texts,
- add_special_tokens=True,
- truncation=self._max_seq_length is not None,
- max_length=self._max_seq_length,
- )
- counts = [len(input_ids) for input_ids in encoded["input_ids"]]
+ if self._max_seq_length is None:
+ content = tokens.full(texts) if tokens is not None else None
+ if content is None:
+ encoded = self._tokenizer(texts, add_special_tokens=True)
+ return [len(input_ids) for input_ids in encoded["input_ids"]]
+ return [len(ids) + special for ids in content]
+ if tokens is None or self._max_seq_length <= special:
+ encoded = self._tokenizer(
+ texts, add_special_tokens=True, truncation=True, max_length=self._max_seq_length
+ )
+ counts = [len(input_ids) for input_ids in encoded["input_ids"]]
+ return counts if len(counts) == len(texts) else None
+ return [len(ids) + special for ids in tokens.cut(texts, self._max_seq_length - special)]
except Exception: # noqa: BLE001 -- metering must not fail classification
return None
- return counts if len(counts) == len(texts) else None
diff --git a/packages/sie_server/tests/adapters/test_gliclass_contracts.py b/packages/sie_server/tests/adapters/test_gliclass_contracts.py
index 2a3b91ff6..7dc53ab4f 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_contracts.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_contracts.py
@@ -1,43 +1,67 @@
-from unittest.mock import MagicMock
+import math
+from types import SimpleNamespace
+from typing import Any
import pytest
+import torch
+from sie_server.adapters.errors import InputTooLongError
from sie_server.adapters.gliclass import GLiClassAdapter
from sie_server.types.inputs import Item
class _CountingTokenizer:
+ """One token per word, plus CLS/SEP when special tokens are added."""
+
+ truncation_side = "right"
+
+ def num_special_tokens_to_add(self, pair: bool = False) -> int:
+ return 2
+
def __call__(
self,
texts: list[str],
*,
- add_special_tokens: bool,
- truncation: bool,
- max_length: int | None,
+ add_special_tokens: bool = True,
+ truncation: bool = False,
+ max_length: int | None = None,
) -> dict[str, list[list[int]]]:
- assert add_special_tokens is True
- counts = [len(text.split()) + 2 for text in texts]
+ extra = 2 if add_special_tokens else 0
+ counts = [len(text.split()) + extra for text in texts]
if truncation:
assert max_length is not None
counts = [min(count, max_length) for count in counts]
return {"input_ids": [list(range(count)) for count in counts]}
-def _adapter(results: object) -> GLiClassAdapter:
+class _Pipe:
+ """A gliclass pipe whose model returns fixed logits per text."""
+
+ max_length = 512
+
+ def __init__(self, logits: dict[str, list[float]]) -> None:
+ self.logits = logits
+ self.texts: list[str] = []
+ self.model = self._model
+
+ def prepare_inputs(self, texts: list[str], labels: list[str], same_labels: bool = False, **_: Any) -> dict:
+ self.texts = list(texts)
+ return {"input_ids": torch.ones(len(texts), 4, dtype=torch.long)}
+
+ def _resolve_max_num_classes(self, labels: list[str], same_labels: bool) -> int:
+ return len(labels)
+
+ def _model(self, **_: Any) -> SimpleNamespace:
+ return SimpleNamespace(logits=torch.tensor([self.logits[text] for text in self.texts]))
+
+
+def _adapter(logits: dict[str, list[float]]) -> GLiClassAdapter:
adapter = GLiClassAdapter("test-model", max_seq_length=512)
- pipeline = MagicMock()
- pipeline.return_value = results
- adapter._pipeline = pipeline
- adapter._tokenizer = _CountingTokenizer() # type: ignore[assignment]
+ adapter._attach(_Pipe(logits), _CountingTokenizer()) # ty:ignore[invalid-argument-type]
return adapter
def test_exact_document_token_counts_align_with_classification_batch() -> None:
- adapter = _adapter(
- [
- {"positive": 0.8, "negative": 0.2},
- {"positive": 0.1, "negative": 0.9},
- ]
- )
+ adapter = _adapter({"two words": [1.0, 0.0], "three whole words": [0.0, 1.0]})
output = adapter.extract(
[Item(text="two words"), Item(text="three whole words")],
@@ -46,12 +70,12 @@ def test_exact_document_token_counts_align_with_classification_batch() -> None:
assert output.input_token_counts == [4, 5]
assert output.classifications is not None
- assert len(output.classifications) == 2
+ assert [row[0]["label"] for row in output.classifications] == ["positive", "negative"]
@pytest.mark.parametrize("threshold", [True, "0.5", None, -0.1, 1.1, float("nan"), float("inf"), 10**1000])
def test_threshold_rejects_non_finite_and_non_numeric_values(threshold: object) -> None:
- adapter = _adapter([{"positive": 0.8, "negative": 0.2}])
+ adapter = _adapter({"hello": [1.0, 0.0]})
with pytest.raises(ValueError, match="finite number between 0 and 1"):
adapter.extract(
@@ -63,38 +87,38 @@ def test_threshold_rejects_non_finite_and_non_numeric_values(threshold: object)
@pytest.mark.parametrize("labels", [[""], ["positive", "positive"], [" "]])
def test_labels_must_be_non_empty_and_unique(labels: list[str]) -> None:
- adapter = _adapter([{}])
+ adapter = _adapter({"hello": [1.0, 0.0]})
with pytest.raises(ValueError, match="labels"):
adapter.extract([Item(text="hello")], labels=labels)
@pytest.mark.parametrize("score", [True, "0.8", -0.1, 1.1, float("nan"), float("inf"), 10**1000])
-def test_pipeline_scores_must_be_finite_probabilities(score: object) -> None:
- adapter = _adapter([{"positive": score, "negative": 0.2}])
+def test_scores_must_be_finite_probabilities(score: object) -> None:
+ with pytest.raises(ValueError, match="invalid classification score"):
+ GLiClassAdapter._validate_score(score)
+
+
[email protected]("classification_type", ["single-label", "multi-label"])
+def test_non_finite_model_logits_are_refused(classification_type: str) -> None:
+ adapter = _adapter({"hello": [math.nan, 0.0]})
with pytest.raises(ValueError, match="invalid classification score"):
adapter.extract(
[Item(text="hello")],
labels=["positive", "negative"],
+ options={"classification_type": classification_type},
)
- "result",
- [
- {"positive": 0.8},
- {"positive": 0.8, "negative": 0.1, "unexpected": 0.1},
- ],
-)
-def test_pipeline_label_set_must_match_requested_labels(result: dict[str, float]) -> None:
- adapter = _adapter([result])
+def test_fewer_class_slots_than_labels_is_an_overflow() -> None:
+ adapter = _adapter({"hello": [1.0]})
+ pipe = adapter._pipe
+ assert isinstance(pipe, _Pipe)
+ pipe._resolve_max_num_classes = lambda labels, same_labels: 1 # ty:ignore[invalid-assignment]
- with pytest.raises(ValueError, match="requested label set"):
- adapter.extract(
- [Item(text="hello")],
- labels=["positive", "negative"],
- )
+ with pytest.raises(InputTooLongError):
+ adapter.extract([Item(text="hello")], labels=["positive", "negative"])
class TestTokenizerLoading:
diff --git a/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py
index 281b96cce..6df836d1c 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_overflow_policy.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from types import SimpleNamespace
+from typing import Any
import pytest
from sie_server.adapters.errors import InputTooLongError
@@ -8,7 +9,9 @@ from sie_server.adapters.gliclass import GLiClassAdapter
class _FakeTokenizer:
- def __call__(self, text: str, add_special_tokens: bool = False) -> dict[str, list[str]]:
+ def __call__(self, text: str | list[str], add_special_tokens: bool = False) -> dict[str, Any]:
+ if isinstance(text, list):
+ return {"input_ids": [t.split() for t in text]}
return {"input_ids": text.split()}
def decode(self, ids: list[str], skip_special_tokens: bool = True) -> str:
@@ -21,10 +24,6 @@ class _FakePipe:
return f"{prefix} {text}".strip()
-class _FakePipeline:
- pipe = _FakePipe()
-
-
# With _FakeTokenizer + _FakePipe, N labels produce a 2N-token label_prompt.
# _LABELS → "<LABEL> x <SEP> y" = 4 tokens; with special_count=2 the overhead
# is 6, so for max_seq_length=10 the per-text budget is 4 tokens.
@@ -36,7 +35,7 @@ def _make_adapter(*, max_seq_length: int = 10, special_count: int = 2) -> GLiCla
adapter._max_seq_length = max_seq_length
adapter._special_count = special_count
adapter._tokenizer = _FakeTokenizer() # ty:ignore[invalid-assignment]
- adapter._pipeline = _FakePipeline() # ty:ignore[invalid-assignment]
+ adapter._pipe = _FakePipe()
return adapter
@@ -104,25 +103,25 @@ class TestApplyOverflowPolicy:
assert adapter._apply_overflow_policy(texts, _LABELS, "default") == texts
-class _RaisingPipeline:
- """Fake gliclass pipeline whose __call__ raises a chosen exception.
+class _RaisingPipe:
+ """Fake gliclass pipe whose model input preparation raises a chosen exception.
- Exercises the except-block crash-signature mapping in
- ``GLiClassAdapter.extract`` end-to-end (not just ``_apply_overflow_policy``).
- The default overflow policy returns texts without touching ``.pipe``, so the
- pipeline only needs to be callable.
+ Exercises the crash-signature mapping in ``GLiClassAdapter.extract``
+ end-to-end (not just ``_apply_overflow_policy``). The default overflow
+ policy returns texts without tokenizing, so the pipe only needs to fail
+ when the rows are prepared.
"""
def __init__(self, exc: BaseException) -> None:
self._exc = exc
- def __call__(self, *args: object, **kwargs: object) -> object:
+ def prepare_inputs(self, *args: object, **kwargs: object) -> object:
raise self._exc
def _make_raising_adapter(exc: BaseException) -> GLiClassAdapter:
adapter = GLiClassAdapter("test-model")
- adapter._pipeline = _RaisingPipeline(exc) # ty:ignore[invalid-assignment]
+ adapter._pipe = _RaisingPipe(exc)
return adapter
diff --git a/packages/sie_server/tests/adapters/test_gliclass_parity.py b/packages/sie_server/tests/adapters/test_gliclass_parity.py
new file mode 100644
index 000000000..66c8d4464
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliclass_parity.py
@@ -0,0 +1,354 @@
+"""GLiClass scores against the gliclass pipeline, on a tiny random model (no downloads).
+
+Before scoring moved into the adapter, a labels request ran exactly
+``ZeroShotClassificationPipeline(texts, labels, threshold=0.0,
+return_hierarchical=True, prompt=..., examples=...)``. The adapter must still
+return the scores that call returns, bit for bit. Separate label groups must
+score like one labels request per group.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+import pytest
+import torch
+from gliclass import GLiClassModel, GLiClassModelConfig, ZeroShotClassificationPipeline
+from sie_server.adapters.gliclass import GLiClassAdapter
+from sie_server.types.inputs import Item
+from tokenizers import Tokenizer, models, pre_tokenizers, processors
+from transformers import DebertaV2Config, PreTrainedTokenizerFast
+from transformers.tokenization_utils_base import PreTrainedTokenizerBase
+
+_MAX_LENGTH = 64
+_TEXTS = [f"the app crashes on startup {'when config file is missing ' * i}".strip() for i in range(11)]
+_LABELS = ["billing", "bug report", "feature request"]
+_GROUPS = {"topic": _LABELS, "urgency": ["low", "high"], "remote": ["yes", "no", "can exploit it over network"]}
+_EXAMPLE_TEXTS = ["charged twice for one order", "please add dark mode"]
+_INSTRUCTION = "classify the ticket"
+# Every word the tests send, so no word falls back to [UNK].
+_WORDS = sorted(
+ {
+ word
+ for text in [
+ *_TEXTS,
+ *_EXAMPLE_TEXTS,
+ _INSTRUCTION,
+ *(label for labels in _GROUPS.values() for label in labels),
+ ]
+ for word in text.split()
+ }
+)
+
+
+def _tokenizer() -> PreTrainedTokenizerFast:
+ specials = ["[PAD]", "[UNK]", "[CLS]", "[SEP]"]
+ vocab = {token: index for index, token in enumerate([*specials, *_WORDS, ".", ",", ":"])}
+ backend = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]")) # noqa: S106 -- a vocabulary entry, not a secret
+ backend.pre_tokenizer = pre_tokenizers.Whitespace()
+ backend.post_processor = processors.TemplateProcessing(
+ single="[CLS] $A [SEP]",
+ pair="[CLS] $A [SEP] $B [SEP]",
+ special_tokens=[("[CLS]", vocab["[CLS]"]), ("[SEP]", vocab["[SEP]"])],
+ )
+ tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=backend,
+ pad_token="[PAD]", # noqa: S106 -- vocabulary entries, not secrets
+ unk_token="[UNK]", # noqa: S106
+ cls_token="[CLS]", # noqa: S106
+ sep_token="[SEP]", # noqa: S106
+ )
+ tokenizer.add_tokens(["<<LABEL>>", "<<SEP>>", "<<EXAMPLE>>"], special_tokens=True)
+ tokenizer.model_max_length = _MAX_LENGTH
+ return tokenizer
+
+
+def _model(tokenizer: PreTrainedTokenizerFast, *, prompt_first: bool, scorer: str) -> GLiClassModel:
+ torch.manual_seed(0)
+ encoder = DebertaV2Config(
+ vocab_size=len(tokenizer),
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=64,
+ max_position_embeddings=128,
+ relative_attention=True,
+ position_buckets=16,
+ pos_att_type=["p2c", "c2p"],
+ position_biased_input=False,
+ pad_token_id=tokenizer.pad_token_id,
+ )
+ config = GLiClassModelConfig(
+ encoder_config=encoder,
+ encoder_model="tiny-gliclass-encoder-not-on-disk",
+ class_token_index=tokenizer.convert_tokens_to_ids("<<LABEL>>"),
+ text_token_index=tokenizer.convert_tokens_to_ids("<<SEP>>"),
+ example_token_index=tokenizer.convert_tokens_to_ids("<<EXAMPLE>>"),
+ vocab_size=len(tokenizer),
+ scorer_type=scorer,
+ scorer_mlp_hidden_size=32,
+ prompt_first=prompt_first,
+ dropout=0.0,
+ )
+ return GLiClassModel(config).eval()
+
+
+class _Rig:
+ """A tiny GLiClass model behind both the gliclass pipelines and the adapter."""
+
+ def __init__(self, *, prompt_first: bool, scorer: str) -> None:
+ tokenizer = _tokenizer()
+ model = _model(tokenizer, prompt_first=prompt_first, scorer=scorer)
+ self.pipelines = {
+ classification_type: ZeroShotClassificationPipeline(
+ model,
+ tokenizer,
+ max_length=_MAX_LENGTH,
+ classification_type=classification_type,
+ device="cpu",
+ progress_bar=False,
+ )
+ for classification_type in ("single-label", "multi-label")
+ }
+ self.adapter = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH)
+ self.adapter._attach(self.pipelines["single-label"].pipe, tokenizer)
+
+ def pipeline_scores(
+ self, texts: list[str], labels: list[str], classification_type: str, **context: Any
+ ) -> list[dict[str, float]]:
+ """The pre-change adapter's call, verbatim."""
+ with torch.inference_mode():
+ return self.pipelines[classification_type](
+ texts, labels, threshold=0.0, return_hierarchical=True, **context
+ )
+
+
[email protected](scope="module", params=[(False, "simple"), (True, "mlp")], ids=["text-first", "labels-first"])
+def rig(request: pytest.FixtureRequest) -> _Rig:
+ prompt_first, scorer = request.param
+ return _Rig(prompt_first=prompt_first, scorer=scorer)
+
+
+def _scores(output: Any) -> list[dict[str, float]]:
+ return [{c["label"]: c["score"] for c in row} for row in output.classifications]
+
+
[email protected]("classification_type", ["single-label", "multi-label"])
+ "context",
+ [
+ {},
+ {"prompt": _INSTRUCTION},
+ {"examples": [{"text": "charged twice for one order", "labels": ["billing"]}]},
+ ],
+ ids=["plain", "instruction", "examples"],
+)
+def test_labels_requests_score_bit_for_bit_like_the_pipeline(
+ rig: _Rig, classification_type: str, context: dict[str, Any]
+) -> None:
+ # Eleven texts of different lengths: two padded sub-batches of eight and three.
+ options: dict[str, Any] = {"classification_type": classification_type}
+ if "examples" in context:
+ options["examples"] = context["examples"]
+
+ output = rig.adapter.extract(
+ [Item(text=text) for text in _TEXTS], labels=_LABELS, instruction=context.get("prompt"), options=options
+ )
+
+ assert _scores(output) == rig.pipeline_scores(_TEXTS, _LABELS, classification_type, **context)
+
+
[email protected]("classification_type", ["single-label", "multi-label"])
+def test_separate_groups_score_like_one_labels_request_per_group(rig: _Rig, classification_type: str) -> None:
+ items = [Item(text=text) for text in _TEXTS[:4]]
+ options = {"classification_type": classification_type}
+
+ grouped = rig.adapter.extract(items, options={**options, "label_groups": _GROUPS})
+
+ assert grouped.data is not None
+ usage = [0] * len(items)
+ for group, labels in _GROUPS.items():
+ alone = rig.adapter.extract(items, labels=labels, options=options)
+ assert alone.input_token_counts is not None
+ for index, expected in enumerate(_scores(alone)):
+ got = grouped.data[index][group]["probabilities"]
+ assert got == pytest.approx(expected, abs=1e-6)
+ if classification_type == "single-label":
+ assert grouped.data[index][group]["choice"] == max(expected, key=expected.__getitem__)
+ usage[index] += alone.input_token_counts[index]
+ # Every group encodes the document again, and each row is metered.
+ assert grouped.input_token_counts == usage
+
+
+def test_separate_groups_with_examples_score_like_per_group_requests(rig: _Rig) -> None:
+ items = [Item(text=_TEXTS[2])]
+ examples = [
+ {"text": "charged twice for one order", "labels": {"topic": "billing", "urgency": "high"}},
+ {"text": "please add dark mode", "labels": ["topic.feature request"]},
+ ]
+
+ grouped = rig.adapter.extract(
+ items, instruction=_INSTRUCTION, options={"label_groups": _GROUPS, "examples": examples}
+ )
+
+ assert grouped.data is not None
+ per_group_examples = {
+ "topic": [
+ {"text": "charged twice for one order", "labels": ["billing"]},
+ {"text": "please add dark mode", "labels": ["feature request"]},
+ ],
+ "urgency": [
+ {"text": "charged twice for one order", "labels": ["high"]},
+ {"text": "please add dark mode", "labels": []},
+ ],
+ "remote": [
+ {"text": "charged twice for one order", "labels": []},
+ {"text": "please add dark mode", "labels": []},
+ ],
+ }
+ for group, labels in _GROUPS.items():
+ expected = rig.pipeline_scores(
+ [_TEXTS[2]], labels, "single-label", prompt=_INSTRUCTION, examples=per_group_examples[group]
+ )[0]
+ assert grouped.data[0][group]["probabilities"] == pytest.approx(expected, abs=1e-6)
+
+
+def test_joint_groups_are_unchanged_by_the_separate_default(rig: _Rig) -> None:
+ items = [Item(text=text) for text in _TEXTS[:3]]
+
+ joint = rig.adapter.extract(items, options={"label_groups": _GROUPS, "group_encoding": "joint"})
+ separate = rig.adapter.extract(items, options={"label_groups": _GROUPS})
+
+ assert joint.data is not None
+ assert separate.data is not None
+ for joint_answers, separate_answers in zip(joint.data, separate.data, strict=True):
+ assert list(joint_answers) == list(separate_answers) == list(_GROUPS)
+ for answer in joint_answers.values():
+ assert sum(answer["probabilities"].values()) == pytest.approx(1.0, abs=1e-5)
+ # The joint row encodes the document once.
+ assert joint.input_token_counts is not None
+ assert separate.input_token_counts is not None
+ assert [count * len(_GROUPS) for count in joint.input_token_counts] == separate.input_token_counts
+
+
+# Far longer than the model reads: its window holds about 60 of these words.
+_LONG_DOCUMENT = " ".join(f"the app crashes on startup when config file {index} is missing" for index in range(2_000))
+
+
+def _outputs(output: Any) -> dict[str, Any]:
+ errors = None if output.errors is None else [None if e is None else e.code for e in output.errors]
+ return {
+ "classifications": output.classifications,
+ "data": output.data,
+ "errors": errors,
+ "usage": output.input_token_counts,
+ }
+
+
[email protected]("policy", ["default", "truncate_text"])
+ "request_kwargs",
+ [
+ {"labels": _LABELS},
+ {"labels": _LABELS, "instruction": _INSTRUCTION, "options": {"classification_type": "multi-label"}},
+ {"options": {"label_groups": _GROUPS, "group_encoding": "joint"}},
+ {"options": {"label_groups": _GROUPS}},
+ ],
+ ids=["labels", "labels-context", "joint", "separate"],
+)
+def test_cutting_a_long_document_to_what_the_model_reads_changes_nothing(
+ rig: _Rig, policy: str, request_kwargs: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [Item(text=_LONG_DOCUMENT), Item(text=_TEXTS[3])]
+ kwargs = {**request_kwargs, "options": {**request_kwargs.get("options", {}), "overflow_policy": policy}}
+
+ cut = rig.adapter.extract(items, **kwargs)
+ monkeypatch.setattr(rig.adapter, "_visible_tokens", lambda: None)
+ whole = rig.adapter.extract(items, **kwargs)
+
+ assert _outputs(cut) == _outputs(whole)
+ if "labels" in request_kwargs and policy == "default" and rig.adapter._pipe.model.config.prompt_first:
+ # The pipeline reads the whole document.
+ expected = rig.pipeline_scores(
+ [item.text for item in items],
+ _LABELS,
+ request_kwargs.get("options", {}).get("classification_type", "single-label"),
+ **({"prompt": _INSTRUCTION} if "instruction" in request_kwargs else {}),
+ )
+ assert _scores(cut) == expected
+
+
+def _counting_tokenizer_chars(monkeypatch: pytest.MonkeyPatch) -> list[int]:
+ """Characters of every string handed to any tokenizer from now on."""
+ seen: list[int] = []
+ original = PreTrainedTokenizerBase.__call__
+
+ def counting(self: Any, text: Any = None, *args: Any, **kwargs: Any) -> Any:
+ texts = text if isinstance(text, list) else [text]
+ seen.append(sum(len(t) for t in texts if isinstance(t, str)))
+ return original(self, text, *args, **kwargs)
+
+ monkeypatch.setattr(PreTrainedTokenizerBase, "__call__", counting)
+ return seen
+
+
+_MANY_GROUPS = {f"q{index}": ["yes", "no"] for index in range(64)}
+
+
[email protected]("policy", ["default", "truncate_text"])
[email protected]("size", [10_000, 100_000, 1_000_000, 4_000_000])
+def test_characters_tokenized_do_not_grow_with_the_document(
+ rig: _Rig, size: int, policy: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ document = (_LONG_DOCUMENT * (size // len(_LONG_DOCUMENT) + 1))[:size]
+ seen = _counting_tokenizer_chars(monkeypatch)
+
+ output = rig.adapter.extract(
+ [Item(text=document)], options={"label_groups": _MANY_GROUPS, "overflow_policy": policy}
+ )
+
+ assert output.data is not None
+ # The model reads at most ``window`` document tokens. The document is cut
+ # to a prefix of about 8 characters per token it can read, tokenized with
+ # twice that once to check the cut, and then once per group.
+ window = _MAX_LENGTH - 2
+ bound = (len(_MANY_GROUPS) + 3) * (window + 8) * 8 * 2
+ assert sum(seen) < bound
+
+
+def test_a_multi_megabyte_document_with_64_groups_stays_fast(rig: _Rig) -> None:
+ document = (_LONG_DOCUMENT * 400)[: 4 * 1024 * 1024]
+
+ start = time.perf_counter()
+ output = rig.adapter.extract([Item(text=document)], options={"label_groups": _MANY_GROUPS})
+ elapsed = time.perf_counter() - start
+
+ assert output.data is not None
+ # Tokenizing the whole document once per group took minutes.
+ assert elapsed < 10.0
+
+
[email protected]("document", ["whitespace", "one-word"])
[email protected]("policy", ["default", "truncate_text"])
+def test_a_document_that_cannot_be_cut_costs_what_reading_it_whole_does(
+ rig: _Rig, document: str, policy: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Neither has a word boundary where the model's window ends: 1 MB of
+ # spaces (no tokens) before three words, and one 1 MB word.
+ text = " " * 1_000_000 + "the app crashes" if document == "whitespace" else "a" * 1_000_000
+ items = [Item(text=text)]
+ options = {"overflow_policy": policy}
+ seen = _counting_tokenizer_chars(monkeypatch)
+
+ searched = rig.adapter.extract(items, labels=_LABELS, options=options)
+ with_search = sum(seen)
+ seen.clear()
+ monkeypatch.setattr(rig.adapter, "_visible_tokens", lambda: None)
+ whole = rig.adapter.extract(items, labels=_LABELS, options=options)
+
+ assert _outputs(searched) == _outputs(whole)
+ # The search for a cut stops at 64 characters per readable token, and the
+ # document is then tokenized once for every check and for metering.
+ search_bound = 2 * 64 * (_MAX_LENGTH - 2 + 8)
+ assert with_search <= sum(seen) + search_bound
diff --git a/packages/sie_server/tests/adapters/test_gliclass_request_options.py b/packages/sie_server/tests/adapters/test_gliclass_request_options.py
index 3af62679a..1f2dd1b0b 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_request_options.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_request_options.py
@@ -1,12 +1,12 @@
-"""GLiClass request fields: instruction, examples, classification_type, label_groups."""
+"""GLiClass request fields: instruction, examples, classification_type, label_groups, group_encoding."""
from __future__ import annotations
import math
import re
+from collections.abc import Callable
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
import pytest
import torch
@@ -22,6 +22,14 @@ _TOKEN_RE = re.compile(r"<<LABEL>>|<<SEP>>|<<EXAMPLE>>|(?:(?!<<LABEL>>|<<SEP>>|<
class _MarkerAwareTokenizer:
"""One token per word or marker; CLS/SEP wrap adds two."""
+ truncation_side = "right"
+
+ def __init__(self) -> None:
+ self.calls: list[list[str]] = []
+
+ def num_special_tokens_to_add(self, pair: bool = False) -> int:
+ return 2
+
def __call__(
self,
texts: str | list[str],
@@ -31,6 +39,7 @@ class _MarkerAwareTokenizer:
**_: Any,
) -> dict[str, Any]:
batch = [texts] if isinstance(texts, str) else texts
+ self.calls.append(list(batch))
encoded = []
for text in batch:
ids = [_SPECIAL_IDS.get(token, 1) for token in _TOKEN_RE.findall(text)]
@@ -42,6 +51,9 @@ class _MarkerAwareTokenizer:
encoded.append(ids)
return {"input_ids": encoded[0] if isinstance(texts, str) else encoded}
+ def decode(self, ids: list[int], skip_special_tokens: bool = True) -> str:
+ return " ".join("w" for _ in ids)
+
class _StubPipe:
"""The attributes of a gliclass uni-encoder pipe that request checks read."""
@@ -51,7 +63,7 @@ class _StubPipe:
def __init__(self, *, prompt_first: bool, max_length: int = 512) -> None:
self.max_length = max_length
- self.model = SimpleNamespace(
+ self.model: Any = SimpleNamespace(
config=SimpleNamespace(
architecture_type="uni-encoder", class_token_index=_CLASS_TOKEN, prompt_first=prompt_first
)
@@ -80,95 +92,193 @@ class _SpaceBeforeMarkerTokenizer(_MarkerAwareTokenizer):
return super().__call__(marked[0] if isinstance(texts, str) else marked, **kwargs)
-def _pipeline(results: list[dict[str, float]]) -> MagicMock:
- pipeline = MagicMock()
- pipeline.return_value = results
- return pipeline
+Logit = Callable[[str, str], float]
+
+
+class _ScoringPipe(_StubPipe):
+ """A gliclass uni-encoder pipe whose model scores each (text, label) with ``logit``.
+
+ Class slots past a row's own labels (a batch of rows with different label
+ counts) get ``filler``, so a softmax that leaked across them would show.
+ """
+
+ def __init__(
+ self,
+ logit: Logit,
+ *,
+ prompt_first: bool = True,
+ max_length: int = 512,
+ filler: float = 50.0,
+ error: BaseException | None = None,
+ ) -> None:
+ super().__init__(prompt_first=prompt_first, max_length=max_length)
+ self.logit = logit
+ self.filler = filler
+ self.error = error
+ self.prepare_calls: list[dict[str, Any]] = []
+ self.model = _ScoringModel(self, prompt_first=prompt_first)
+
+ def prepare_inputs(
+ self,
+ texts: list[str],
+ labels: list[str] | list[list[str]],
+ same_labels: bool = False,
+ examples: Any = None,
+ prompt: str | None = None,
+ ) -> dict[str, torch.Tensor]:
+ if self.error is not None:
+ raise self.error
+ row_labels = [list(labels)] * len(texts) if same_labels else [list(row) for row in labels]
+ self.prepare_calls.append(
+ {
+ "texts": list(texts),
+ "labels": row_labels,
+ "same_labels": same_labels,
+ "examples": examples,
+ "prompt": prompt,
+ }
+ )
+ width = max(len(row) for row in row_labels) + 2
+ return {
+ "input_ids": torch.ones(len(texts), width, dtype=torch.long),
+ "attention_mask": torch.ones(len(texts), width, dtype=torch.long),
+ }
+
+ def _resolve_max_num_classes(self, labels: list[str] | list[list[str]], same_labels: bool) -> int:
+ return len(labels) if same_labels else max(len(row) for row in labels)
+
+
+class _ScoringModel:
+ def __init__(self, pipe: _ScoringPipe, *, prompt_first: bool) -> None:
+ self._pipe = pipe
+ self.config = SimpleNamespace(
+ class_token_index=_CLASS_TOKEN, architecture_type="uni-encoder", prompt_first=prompt_first
+ )
+ self.forward_kwargs: list[dict[str, Any]] = []
+
+ def __call__(self, *, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs: Any) -> SimpleNamespace:
+ self.forward_kwargs.append(kwargs)
+ call = self._pipe.prepare_calls[-1]
+ width = kwargs["max_num_classes"]
+ rows = [
+ [self._pipe.logit(text, label) for label in labels] + [self._pipe.filler] * (width - len(labels))
+ for text, labels in zip(call["texts"], call["labels"], strict=True)
+ ]
+ return SimpleNamespace(logits=torch.tensor(rows, dtype=torch.float32))
-def _flat_adapter(
- single: list[dict[str, float]],
- multi: list[dict[str, float]] | None = None,
+def _adapter(
+ logit: Logit,
*,
classification_type: str = "single-label",
-) -> GLiClassAdapter:
- adapter = GLiClassAdapter("test-model", max_seq_length=512, classification_type=classification_type) # ty:ignore[invalid-argument-type]
- pipelines = {"single-label": _pipeline(single), "multi-label": _pipeline(multi or single)}
- adapter._pipelines = pipelines # ty:ignore[invalid-assignment]
- adapter._pipeline = pipelines[classification_type] # ty:ignore[invalid-assignment]
- adapter._tokenizer = _MarkerAwareTokenizer() # ty:ignore[invalid-assignment]
- adapter._special_count = 2
- return adapter
+ prompt_first: bool = True,
+ max_length: int = 512,
+ tokenizer: Any = None,
+ error: BaseException | None = None,
+) -> tuple[GLiClassAdapter, _ScoringPipe]:
+ adapter = GLiClassAdapter("test-model", max_seq_length=max_length, classification_type=classification_type) # ty:ignore[invalid-argument-type]
+ pipe = _ScoringPipe(logit, prompt_first=prompt_first, max_length=max_length, error=error)
+ adapter._attach(pipe, tokenizer or _MarkerAwareTokenizer()) # ty:ignore[invalid-argument-type]
+ return adapter, pipe
_LABELS = ["billing", "bug report", "feature request"]
_SCORES = {"billing": 0.2, "bug report": 0.7, "feature request": 0.1}
+def _score_logit(text: str, label: str) -> float:
+ """Log-probabilities: a softmax over all three labels gives back ``_SCORES``."""
+ return math.log(_SCORES[label])
+
+
+def _flat_adapter(**kwargs: Any) -> tuple[GLiClassAdapter, _ScoringPipe]:
+ return _adapter(_score_logit, **kwargs)
+
+
+def _softmax(values: list[float]) -> list[float]:
+ exps = [math.exp(v) for v in values]
+ return [e / sum(exps) for e in exps]
+
+
+def _sigmoid(value: float) -> float:
+ return 1 / (1 + math.exp(-value))
+
+
class TestUnchangedRequests:
- """A request that sets none of the new fields runs the historical call."""
+ """A request that sets none of the newer fields builds the historical model input."""
- def test_pipeline_call_and_output_are_unchanged(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ def test_model_input_and_output_are_unchanged(self) -> None:
+ adapter, pipe = _flat_adapter()
output = adapter.extract([Item(text="The app crashes")], labels=list(_LABELS))
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- pipeline.assert_called_once_with(["The app crashes"], _LABELS, threshold=0.0, return_hierarchical=True)
- assert adapter._pipelines is not None
- other = adapter._pipelines["multi-label"]
- assert isinstance(other, MagicMock)
- other.assert_not_called()
- assert output.classifications == [
- [
- {"label": "bug report", "score": 0.7},
- {"label": "billing", "score": 0.2},
- {"label": "feature request", "score": 0.1},
- ]
+ assert pipe.prepare_calls == [
+ {"texts": ["The app crashes"], "labels": [_LABELS], "same_labels": True, "examples": None, "prompt": None}
]
+ assert pipe.model.forward_kwargs == [{"max_num_classes": 3}]
+ assert output.classifications is not None
+ assert [c["label"] for c in output.classifications[0]] == ["bug report", "billing", "feature request"]
+ assert [c["score"] for c in output.classifications[0]] == pytest.approx([0.7, 0.2, 0.1], abs=1e-6)
assert output.data is None
assert output.entities == [[]]
def test_threshold_filter_is_unchanged(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
output = adapter.extract([Item(text="x")], labels=list(_LABELS), options={"threshold": 0.15})
- assert output.classifications == [[{"label": "bug report", "score": 0.7}, {"label": "billing", "score": 0.2}]]
+ assert output.classifications is not None
+ assert [c["label"] for c in output.classifications[0]] == ["bug report", "billing"]
def test_blank_instruction_and_empty_examples_are_ignored(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, pipe = _flat_adapter()
adapter.extract([Item(text="x")], labels=list(_LABELS), instruction=" ", options={"examples": []})
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- pipeline.assert_called_once_with(["x"], _LABELS, threshold=0.0, return_hierarchical=True)
+ assert pipe.prepare_calls[0]["prompt"] is None
+ assert pipe.prepare_calls[0]["examples"] is None
+
+ def test_items_run_in_forward_passes_of_eight(self) -> None:
+ adapter, pipe = _flat_adapter()
+ texts = [f"text {i}" for i in range(10)]
+
+ output = adapter.extract([Item(text=t) for t in texts], labels=list(_LABELS))
+
+ assert [call["texts"] for call in pipe.prepare_calls] == [texts[:8], texts[8:]]
+ assert output.classifications is not None
+ assert len(output.classifications) == 10
- def test_default_classification_type_uses_the_load_time_pipeline(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ def test_a_request_tokenizes_each_document_and_its_labels_once(self) -> None:
+ tokenizer = _MarkerAwareTokenizer()
+ adapter, _ = _flat_adapter(prompt_first=False, tokenizer=tokenizer)
+ items = [Item(text="The app crashes"), Item(text="Charged twice")]
- adapter.extract([Item(text="x")], labels=list(_LABELS), options={"classification_type": "single-label"})
+ adapter.extract(items, labels=list(_LABELS), options={"overflow_policy": "truncate_text"})
+ first = list(tokenizer.calls)
+ tokenizer.calls.clear()
+ adapter.extract(items, labels=list(_LABELS), options={"overflow_policy": "truncate_text"})
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- assert pipeline.call_count == 1
+ # One call for the label prompt, which the fit check and the overflow
+ # policy both measure, and one for the documents; the model input
+ # itself is tokenized by the pipe. The overflow policy, fit check and
+ # metering share the document tokens.
+ label_prompt = "<<LABEL>>billing<<LABEL>>bug report<<LABEL>>feature request<<SEP>>"
+ assert first == [[label_prompt], ["The app crashes", "Charged twice"]]
+ # Nothing carries over from one request to the next.
+ assert tokenizer.calls == first
class TestInstructionAndExamples:
- def test_instruction_becomes_the_pipeline_prompt(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ def test_instruction_becomes_the_model_prompt(self) -> None:
+ adapter, pipe = _flat_adapter()
adapter.extract([Item(text="x")], labels=list(_LABELS), instruction="Classify the support ticket.")
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- assert pipeline.call_args.kwargs["prompt"] == "Classify the support ticket."
- assert "examples" not in pipeline.call_args.kwargs
+ assert pipe.prepare_calls[0]["prompt"] == "Classify the support ticket."
+ assert pipe.prepare_calls[0]["examples"] is None
def test_examples_are_normalized_and_forwarded(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, pipe = _flat_adapter()
examples = [
{"text": "I was charged twice", "labels": [" billing "]},
{"text": "Nothing applies here", "labels": []},
@@ -176,13 +286,11 @@ class TestInstructionAndExamples:
adapter.extract([Item(text="x")], labels=list(_LABELS), options={"examples": examples})
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- assert pipeline.call_args.kwargs["examples"] == [
+ assert pipe.prepare_calls[0]["examples"] == [
{"text": "I was charged twice", "labels": ["billing"]},
{"text": "Nothing applies here", "labels": []},
]
- assert "prompt" not in pipeline.call_args.kwargs
+ assert pipe.prepare_calls[0]["prompt"] is None
@pytest.mark.parametrize(
("examples", "match"),
@@ -202,13 +310,13 @@ class TestInstructionAndExamples:
],
)
def test_malformed_examples_are_rejected(self, examples: object, match: str) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
with pytest.raises(InvalidInputError, match=match):
adapter.extract([Item(text="x")], labels=list(_LABELS), options={"examples": examples})
def test_repeated_example_labels_are_sent_once(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, pipe = _flat_adapter()
adapter.extract(
[Item(text="x")],
@@ -216,12 +324,10 @@ class TestInstructionAndExamples:
options={"examples": [{"text": "charged twice", "labels": ["billing", " billing"]}]},
)
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- assert pipeline.call_args.kwargs["examples"] == [{"text": "charged twice", "labels": ["billing"]}]
+ assert pipe.prepare_calls[0]["examples"] == [{"text": "charged twice", "labels": ["billing"]}]
def test_label_text_that_cannot_fit_the_window_is_refused_before_tokenizing(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
calls: list[object] = []
tokenizer = adapter._tokenizer
@@ -234,13 +340,15 @@ class TestInstructionAndExamples:
adapter._max_seq_length = 8 # 4 x 8 = 32 characters, exactly the length of _LABELS
adapter.extract([Item(text="x")], labels=list(_LABELS))
+ accepted = len(calls)
with pytest.raises(InvalidInputError, match="at most 32 can fit"):
adapter.extract([Item(text="x")], labels=[*_LABELS[:2], "x" * 2_000_000])
- assert len(calls) == 1 # only the accepted request tokenized anything
+ assert accepted > 0
+ assert len(calls) == accepted # the refused request tokenized nothing
def test_label_limit_ignores_vocabularies_with_very_long_tokens(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
adapter._max_token_chars = 512 # e.g. a vocabulary holding a long whitespace run
adapter._max_seq_length = 8 # 16 characters per token x 8 = 128
@@ -248,19 +356,19 @@ class TestInstructionAndExamples:
adapter.extract([Item(text="x")], labels=[*_LABELS[:2], "x" * 200])
def test_overlong_instruction_is_rejected(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
with pytest.raises(InvalidInputError, match="at most 2048 characters"):
adapter.extract([Item(text="x")], labels=list(_LABELS), instruction="x" * 2049)
def test_item_without_text_is_invalid_input(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
with pytest.raises(InvalidInputError, match="must have text"):
adapter.extract([Item(text="")], labels=list(_LABELS))
def test_non_string_instruction_is_rejected(self) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
with pytest.raises(InvalidInputError, match="instruction must be a string"):
adapter.extract([Item(text="x")], labels=list(_LABELS), instruction=3) # ty:ignore[invalid-argument-type]
@@ -268,32 +376,29 @@ class TestInstructionAndExamples:
class TestClassificationType:
def test_request_can_switch_to_multi_label(self) -> None:
- multi = {"billing": 0.9, "bug report": 0.8, "feature request": 0.05}
- adapter = _flat_adapter([dict(_SCORES)], [multi])
+ adapter, _ = _flat_adapter()
output = adapter.extract([Item(text="x")], labels=list(_LABELS), options={"classification_type": "multi-label"})
- assert adapter._pipelines is not None
- single = adapter._pipelines["single-label"]
- assert isinstance(single, MagicMock)
- single.assert_not_called()
assert output.classifications is not None
- assert [c["label"] for c in output.classifications[0]] == ["billing", "bug report", "feature request"]
+ scores = {c["label"]: c["score"] for c in output.classifications[0]}
+ expected = {label: _sigmoid(math.log(p)) for label, p in _SCORES.items()}
+ assert scores == pytest.approx(expected, abs=1e-6)
def test_multi_label_model_can_switch_to_single_label(self) -> None:
- multi = {"billing": 0.9, "bug report": 0.8, "feature request": 0.05}
- adapter = _flat_adapter([dict(_SCORES)], [multi], classification_type="multi-label")
+ adapter, _ = _flat_adapter(classification_type="multi-label")
output = adapter.extract(
[Item(text="x")], labels=list(_LABELS), options={"classification_type": "single-label"}
)
assert output.classifications is not None
- assert output.classifications[0][0] == {"label": "bug report", "score": 0.7}
+ assert output.classifications[0][0]["label"] == "bug report"
+ assert output.classifications[0][0]["score"] == pytest.approx(0.7, abs=1e-6)
@pytest.mark.parametrize("value", ["multi_label", "binary", None, 1])
def test_unknown_classification_type_is_rejected(self, value: object) -> None:
- adapter = _flat_adapter([dict(_SCORES)])
+ adapter, _ = _flat_adapter()
with pytest.raises(InvalidInputError, match="classification_type"):
adapter.extract([Item(text="x")], labels=list(_LABELS), options={"classification_type": value})
@@ -303,118 +408,59 @@ class TestClassificationType:
GLiClassAdapter("test-model", classification_type="multilabel") # ty:ignore[invalid-argument-type]
-class _FakeGroupPipe(_StubPipe):
- """Stands in for the gliclass uni-encoder pipe used by the grouped path."""
-
- def __init__(
- self, logits_by_text: dict[str, list[float]], *, prompt_first: bool = True, max_length: int = 512
- ) -> None:
- super().__init__(prompt_first=prompt_first, max_length=max_length)
- self.logits_by_text = logits_by_text
- self.prepare_calls: list[dict[str, Any]] = []
- self.model = _FakeGroupModel(self, prompt_first=prompt_first)
-
- def prepare_inputs(
- self,
- texts: list[str],
- labels: list[str],
- same_labels: bool = False,
- examples: list[dict[str, Any]] | None = None,
- prompt: str | None = None,
- ) -> dict[str, torch.Tensor]:
- self.prepare_calls.append(
- {
- "texts": list(texts),
- "labels": list(labels),
- "same_labels": same_labels,
- "examples": examples,
- "prompt": prompt,
- }
- )
- row = [1] + [_CLASS_TOKEN] * len(labels) + [2, 3, 4]
- return {
- "input_ids": torch.tensor([row] * len(texts)),
- "attention_mask": torch.ones(len(texts), len(row), dtype=torch.long),
- }
+_GROUPS = {"urgency": ["low", "high"], "topic": ["billing", "bug", "feature"]}
+_LOGITS = {
+ "Charged twice, fix today": {"low": -1.0, "high": 2.0, "billing": 3.0, "bug": 0.5, "feature": -2.0},
+ "Dark mode someday?": {"low": 1.5, "high": -1.0, "billing": -3.0, "bug": -2.0, "feature": 4.0},
+}
- def _resolve_max_num_classes(self, labels: list[str], same_labels: bool) -> int:
- assert same_labels is True
- return len(labels)
+def _table_logit(text: str, label: str) -> float:
+ """Scores a plain label ("low") and its joint form ("urgency.low") alike."""
+ return _LOGITS[text][label.rsplit(".", 1)[-1]]
-class _FakeGroupModel:
- def __init__(self, pipe: _FakeGroupPipe, *, prompt_first: bool) -> None:
- self._pipe = pipe
- self.config = SimpleNamespace(
- class_token_index=_CLASS_TOKEN, architecture_type="uni-encoder", prompt_first=prompt_first
- )
- self.forward_kwargs: list[dict[str, Any]] = []
- def __call__(self, *, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs: Any) -> SimpleNamespace:
- self.forward_kwargs.append(kwargs)
- texts = self._pipe.prepare_calls[-1]["texts"]
- logits = torch.tensor([self._pipe.logits_by_text[text] for text in texts], dtype=torch.float16)
- return SimpleNamespace(logits=logits)
+def _group_adapter(**kwargs: Any) -> tuple[GLiClassAdapter, _ScoringPipe]:
+ return _adapter(_table_logit, **kwargs)
-_GROUPS = {"urgency": ["low", "high"], "topic": ["billing", "bug", "feature"]}
-# Flattened order: urgency.low, urgency.high, topic.billing, topic.bug, topic.feature
-_LOGITS = {
- "Charged twice, fix today": [-1.0, 2.0, 3.0, 0.5, -2.0],
- "Dark mode someday?": [1.5, -1.0, -3.0, -2.0, 4.0],
-}
-
-
-def _group_adapter(
- logits: dict[str, list[float]] | None = None, *, prompt_first: bool = True, max_length: int = 512
-) -> tuple[GLiClassAdapter, _FakeGroupPipe]:
- adapter = GLiClassAdapter("test-model", max_seq_length=max_length)
- pipe = _FakeGroupPipe(logits or _LOGITS, prompt_first=prompt_first, max_length=max_length)
- pipeline = MagicMock()
- pipeline.pipe = pipe
- adapter._pipeline = pipeline # ty:ignore[invalid-assignment]
- adapter._pipelines = {"single-label": pipeline, "multi-label": MagicMock()} # ty:ignore[invalid-assignment]
- adapter._tokenizer = _MarkerAwareTokenizer() # ty:ignore[invalid-assignment]
- adapter._special_count = 2
- return adapter, pipe
+def _group_options(**options: Any) -> dict[str, Any]:
+ return {"label_groups": _GROUPS, **options}
-def _softmax(values: list[float]) -> list[float]:
- exps = [math.exp(v) for v in values]
- return [e / sum(exps) for e in exps]
[email protected](params=["separate", "joint"])
+def group_encoding(request: pytest.FixtureRequest) -> str:
+ return request.param
class TestLabelGroups:
- def test_single_label_scores_are_normalized_per_group(self) -> None:
- adapter, pipe = _group_adapter()
+ """What both group encodings share: answer shape, normalization, validation."""
+
+ def test_single_label_scores_are_normalized_per_group(self, group_encoding: str) -> None:
+ adapter, _ = _group_adapter()
texts = list(_LOGITS)
- output = adapter.extract([Item(text=t) for t in texts], options={"label_groups": _GROUPS})
+ output = adapter.extract([Item(text=t) for t in texts], options=_group_options(group_encoding=group_encoding))
- assert pipe.prepare_calls[0]["labels"] == [
- "urgency.low",
- "urgency.high",
- "topic.billing",
- "topic.bug",
- "topic.feature",
- ]
assert output.data is not None
for text, data in zip(texts, output.data, strict=True):
- logits = [float(torch.tensor(v, dtype=torch.float16)) for v in _LOGITS[text]]
+ logits = _LOGITS[text]
assert list(data) == ["urgency", "topic"]
urgency, topic = data["urgency"]["probabilities"], data["topic"]["probabilities"]
assert list(urgency) == ["low", "high"]
- assert list(urgency.values()) == pytest.approx(_softmax(logits[:2]), abs=1e-6)
- assert list(topic.values()) == pytest.approx(_softmax(logits[2:]), abs=1e-6)
- assert sum(urgency.values()) == pytest.approx(1.0)
- assert sum(topic.values()) == pytest.approx(1.0)
+ assert list(urgency.values()) == pytest.approx(_softmax([logits["low"], logits["high"]]), abs=1e-6)
+ assert list(topic.values()) == pytest.approx(
+ _softmax([logits["billing"], logits["bug"], logits["feature"]]), abs=1e-6
+ )
assert output.data[0]["topic"]["choice"] == "billing"
assert output.data[1]["urgency"]["choice"] == "low"
- def test_single_label_groups_answer_like_choice_questions(self) -> None:
+ def test_single_label_groups_answer_like_choice_questions(self, group_encoding: str) -> None:
adapter, _ = _group_adapter()
- output = adapter.extract([Item(text="Charged twice, fix today")], options={"label_groups": _GROUPS})
+ output = adapter.extract(
+ [Item(text="Charged twice, fix today")], options=_group_options(group_encoding=group_encoding)
+ )
assert output.data is not None
answer = output.data[0]["topic"]
@@ -425,11 +471,12 @@ class TestLabelGroups:
assert answer["confidence"] == pytest.approx(1 - entropy / math.log(3))
assert 0.0 < answer["confidence"] < 1.0
- def test_classifications_use_group_dot_label_and_honor_threshold(self) -> None:
+ def test_classifications_use_group_dot_label_and_honor_threshold(self, group_encoding: str) -> None:
adapter, _ = _group_adapter()
output = adapter.extract(
- [Item(text="Charged twice, fix today")], options={"label_groups": _GROUPS, "threshold": 0.5}
+ [Item(text="Charged twice, fix today")],
+ options=_group_options(group_encoding=group_encoding, threshold=0.5),
)
assert output.classifications is not None
@@ -437,81 +484,50 @@ class TestLabelGroups:
assert output.data is not None
assert len(output.data[0]["topic"]["probabilities"]) == 3 # never threshold-filtered
- def test_multi_label_uses_independent_sigmoids(self) -> None:
+ def test_multi_label_uses_independent_sigmoids(self, group_encoding: str) -> None:
adapter, _ = _group_adapter()
output = adapter.extract(
[Item(text="Charged twice, fix today")],
- options={"label_groups": _GROUPS, "classification_type": "multi-label"},
+ options=_group_options(group_encoding=group_encoding, classification_type="multi-label"),
)
assert output.data is not None
- expected = [1 / (1 + math.exp(-v)) for v in _LOGITS["Charged twice, fix today"]]
+ expected = [_sigmoid(v) for v in _LOGITS["Charged twice, fix today"].values()]
urgency, topic = output.data[0]["urgency"], output.data[0]["topic"]
assert set(urgency) == {"labels", "probabilities"}
actual = [*urgency["probabilities"].values(), *topic["probabilities"].values()]
- assert actual == pytest.approx(expected, abs=1e-3)
+ assert actual == pytest.approx(expected, abs=1e-6)
# Without a request threshold, labels at or above 0.5 are selected.
assert urgency["labels"] == ["high"]
assert topic["labels"] == ["billing", "bug"]
- def test_multi_label_selection_follows_the_request_threshold(self) -> None:
+ def test_multi_label_selection_follows_the_request_threshold(self, group_encoding: str) -> None:
adapter, _ = _group_adapter()
output = adapter.extract(
[Item(text="Charged twice, fix today")],
- options={"label_groups": _GROUPS, "classification_type": "multi-label", "threshold": 0.9},
+ options=_group_options(group_encoding=group_encoding, classification_type="multi-label", threshold=0.9),
)
assert output.data is not None
assert output.data[0]["topic"]["labels"] == ["billing"]
assert output.data[0]["urgency"]["labels"] == []
- def test_prompt_examples_and_forward_kwargs_reach_the_model(self) -> None:
- adapter, pipe = _group_adapter()
-
- adapter.extract(
- [Item(text="Charged twice, fix today")],
- instruction="Triage the ticket.",
- options={
- "label_groups": _GROUPS,
- "examples": [
- {"text": "Refund please", "labels": {"topic": "billing", "urgency": ["low"]}},
- {"text": "App crashes", "labels": ["topic.bug"]},
- ],
- },
- )
-
- call = pipe.prepare_calls[0]
- assert call["prompt"] == "Triage the ticket."
- assert call["same_labels"] is True
- assert call["examples"] == [
- {"text": "Refund please", "labels": ["topic.billing", "urgency.low"]},
- {"text": "App crashes", "labels": ["topic.bug"]},
- ]
- assert pipe.model.forward_kwargs == [{"max_num_classes": 5}]
-
- def test_batches_follow_the_pipeline_sub_batch_size(self) -> None:
- texts = [f"text {i}" for i in range(10)]
- logits = {text: [0.0, 1.0, 0.0, 1.0, 2.0] for text in texts}
- adapter, pipe = _group_adapter(logits)
-
- output = adapter.extract([Item(text=t) for t in texts], options={"label_groups": _GROUPS})
-
- assert [len(call["texts"]) for call in pipe.prepare_calls] == [8, 2]
- assert output.data is not None
- assert len(output.data) == 10
-
- def test_a_document_that_pushes_labels_out_fails_only_its_own_item(self) -> None:
+ def test_a_document_that_pushes_labels_out_fails_only_its_own_item(self, group_encoding: str) -> None:
long_text = "attacker " * 600
- logits = {"Charged twice, fix today": _LOGITS["Charged twice, fix today"], long_text: [0.0] * 5}
- adapter, pipe = _group_adapter(logits, prompt_first=False)
+ logits = {
+ "Charged twice, fix today": _LOGITS["Charged twice, fix today"],
+ long_text: _LOGITS["Dark mode someday?"],
+ }
+ adapter, pipe = _adapter(lambda text, label: logits[text][label.rsplit(".", 1)[-1]], prompt_first=False)
output = adapter.extract(
- [Item(text="Charged twice, fix today"), Item(text=long_text)], options={"label_groups": _GROUPS}
+ [Item(text="Charged twice, fix today"), Item(text=long_text)],
+ options=_group_options(group_encoding=group_encoding),
)
- assert [call["texts"] for call in pipe.prepare_calls] == [["Charged twice, fix today"]]
+ assert {text for call in pipe.prepare_calls for text in call["texts"]} == {"Charged twice, fix today"}
assert output.errors is not None
assert output.errors[0] is None
assert output.errors[1] is not None
@@ -524,17 +540,21 @@ class TestLabelGroups:
assert output.input_token_counts is not None
assert output.input_token_counts[1] == 0
- def test_labels_that_alone_overflow_the_window_are_refused(self) -> None:
+ def test_labels_that_alone_overflow_the_window_are_refused(self, group_encoding: str) -> None:
adapter, _ = _group_adapter(max_length=6)
with pytest.raises(InputTooLongError):
- adapter.extract([Item(text="Charged twice, fix today")], options={"label_groups": _GROUPS})
+ adapter.extract(
+ [Item(text="Charged twice, fix today")], options=_group_options(group_encoding=group_encoding)
+ )
- def test_a_marker_inside_the_document_is_not_an_overflow(self) -> None:
+ def test_a_marker_inside_the_document_is_not_an_overflow(self, group_encoding: str) -> None:
text = "Charged twice, fix today"
- adapter, _ = _group_adapter({f"{text} <<LABEL>>": _LOGITS[text]})
+ adapter, _ = _adapter(lambda _text, label: _table_logit(text, label))
- output = adapter.extract([Item(text=f"{text} <<LABEL>>")], options={"label_groups": _GROUPS})
+ output = adapter.extract(
+ [Item(text=f"{text} <<LABEL>>")], options=_group_options(group_encoding=group_encoding)
+ )
assert output.errors is None
assert output.data is not None
@@ -574,24 +594,426 @@ class TestLabelGroups:
),
],
)
- def test_malformed_groups_are_rejected(self, options: dict[str, Any], labels: list[str] | None, match: str) -> None:
+ def test_malformed_groups_are_rejected(
+ self, group_encoding: str, options: dict[str, Any], labels: list[str] | None, match: str
+ ) -> None:
adapter, _ = _group_adapter()
with pytest.raises(InvalidInputError, match=match):
- adapter.extract([Item(text="x")], labels=labels, options=options)
+ adapter.extract([Item(text="x")], labels=labels, options={**options, "group_encoding": group_encoding})
- def test_single_label_group_of_one_is_allowed_in_multi_label_mode(self) -> None:
- logits = {"x": [0.3]}
- adapter, _ = _group_adapter(logits)
+ def test_single_label_group_of_one_is_allowed_in_multi_label_mode(self, group_encoding: str) -> None:
+ adapter, _ = _adapter(lambda text, label: 0.3)
output = adapter.extract(
- [Item(text="x")], options={"label_groups": {"spam": ["yes"]}, "classification_type": "multi-label"}
+ [Item(text="x")],
+ options={
+ "label_groups": {"spam": ["yes"]},
+ "classification_type": "multi-label",
+ "group_encoding": group_encoding,
+ },
)
assert output.data is not None
- assert output.data[0]["spam"]["probabilities"]["yes"] == pytest.approx(1 / (1 + math.exp(-0.3)), abs=1e-3)
+ assert output.data[0]["spam"]["probabilities"]["yes"] == pytest.approx(_sigmoid(0.3), abs=1e-6)
assert output.data[0]["spam"]["labels"] == ["yes"]
+ @pytest.mark.parametrize("value", ["Joint", "per-group", 1, True, None, ["separate"]])
+ def test_unknown_group_encoding_is_rejected(self, value: object) -> None:
+ adapter, _ = _group_adapter()
+
+ with pytest.raises(InvalidInputError, match="group_encoding must be 'separate' or 'joint'"):
+ adapter.extract([Item(text="x")], options=_group_options(group_encoding=value))
+
+ def test_group_encoding_without_label_groups_is_rejected(self) -> None:
+ adapter, _ = _flat_adapter()
+
+ with pytest.raises(InvalidInputError, match=r"only with options\.label_groups"):
+ adapter.extract([Item(text="x")], labels=list(_LABELS), options={"group_encoding": "separate"})
+
+
+class TestJointGroupEncoding:
+ def test_all_groups_share_one_row_per_item(self) -> None:
+ adapter, pipe = _group_adapter()
+ texts = list(_LOGITS)
+
+ adapter.extract([Item(text=t) for t in texts], options=_group_options(group_encoding="joint"))
+
+ assert len(pipe.prepare_calls) == 1
+ assert pipe.prepare_calls[0]["texts"] == texts
+ assert pipe.prepare_calls[0]["same_labels"] is True
+ assert pipe.prepare_calls[0]["labels"][0] == [
+ "urgency.low",
+ "urgency.high",
+ "topic.billing",
+ "topic.bug",
+ "topic.feature",
+ ]
+
+ def test_prompt_examples_and_forward_kwargs_reach_the_model(self) -> None:
+ adapter, pipe = _group_adapter()
+
+ adapter.extract(
+ [Item(text="Charged twice, fix today")],
+ instruction="Triage the ticket.",
+ options=_group_options(
+ group_encoding="joint",
+ examples=[
+ {"text": "Refund please", "labels": {"topic": "billing", "urgency": ["low"]}},
+ {"text": "App crashes", "labels": ["topic.bug"]},
+ ],
+ ),
+ )
+
+ call = pipe.prepare_calls[0]
+ assert call["prompt"] == "Triage the ticket."
+ assert call["examples"] == [
+ {"text": "Refund please", "labels": ["topic.billing", "urgency.low"]},
+ {"text": "App crashes", "labels": ["topic.bug"]},
+ ]
+ assert pipe.model.forward_kwargs == [{"max_num_classes": 5}]
+
+ def test_batches_follow_the_pipeline_sub_batch_size(self) -> None:
+ texts = [f"text {i}" for i in range(10)]
+ adapter, pipe = _adapter(lambda text, label: 0.5)
+
+ output = adapter.extract([Item(text=t) for t in texts], options=_group_options(group_encoding="joint"))
+
+ assert [len(call["texts"]) for call in pipe.prepare_calls] == [8, 2]
+ assert output.data is not None
+ assert len(output.data) == 10
+
+ def test_joint_groups_bill_the_document_once(self) -> None:
+ adapter, _ = _group_adapter()
+
+ output = adapter.extract(
+ [Item(text="Charged twice, fix today")], options=_group_options(group_encoding="joint")
+ )
+
+ assert output.input_token_counts == [4 + 2]
+
+
+class TestSeparateGroupEncoding:
+ def test_separate_is_the_default(self) -> None:
+ adapter, pipe = _group_adapter()
+
+ adapter.extract([Item(text="Charged twice, fix today")], options=_group_options())
+
+ assert pipe.prepare_calls[0]["same_labels"] is False
+ assert sorted(pipe.prepare_calls[0]["labels"]) == [["billing", "bug", "feature"], ["low", "high"]]
+
+ def test_rows_of_every_item_and_group_share_one_forward_pass(self) -> None:
+ adapter, pipe = _group_adapter()
+ texts = list(_LOGITS)
+
+ adapter.extract([Item(text=t) for t in texts], options=_group_options())
+
+ # One row per (item, group), the longest rows first.
+ assert len(pipe.prepare_calls) == 1
+ call = pipe.prepare_calls[0]
+ assert list(zip(call["texts"], call["labels"], strict=True)) == [
+ (texts[0], ["billing", "bug", "feature"]),
+ (texts[1], ["billing", "bug", "feature"]),
+ (texts[0], ["low", "high"]),
+ (texts[1], ["low", "high"]),
+ ]
+ assert pipe.model.forward_kwargs == [{"max_num_classes": 3}]
+
+ def test_many_short_rows_share_one_forward_pass(self) -> None:
+ texts = [f"text {i}" for i in range(20)]
+ adapter, pipe = _adapter(lambda text, label: 0.5)
+
+ output = adapter.extract([Item(text=t) for t in texts], options=_group_options())
+
+ assert [len(call["texts"]) for call in pipe.prepare_calls] == [40]
+ assert output.data is not None
+ assert len(output.data) == 20
+
+ def test_rows_are_packed_into_passes_of_eight_full_windows(self) -> None:
+ # Window 64, so a pass holds 8 x 64 = 512 padded tokens. Forty-word
+ # documents make 49-token topic rows and 47-token urgency rows:
+ # ten rows fit in the first pass.
+ texts = [" ".join(f"w{i}x{j}" for j in range(40)) for i in range(6)]
+ adapter, pipe = _adapter(lambda text, label: 0.5, max_length=64)
+
+ output = adapter.extract([Item(text=t) for t in texts], options=_group_options())
+
+ assert [len(call["texts"]) for call in pipe.prepare_calls] == [10, 2]
+ assert [len(labels) for labels in pipe.prepare_calls[0]["labels"]] == [3] * 6 + [2] * 4
+ assert output.data is not None
+ assert all(list(answers) == ["urgency", "topic"] for answers in output.data)
+
+ def test_each_group_scores_like_a_labels_request_with_its_labels(self) -> None:
+ # The filler logit (50.0) sits in the class slot a two-label row gets
+ # when it shares a forward pass with a three-label row. A softmax over
+ # it would push every urgency probability to zero.
+ adapter, _ = _group_adapter()
+ items = [Item(text=t) for t in _LOGITS]
+
+ grouped = adapter.extract(items, options=_group_options())
+
+ assert grouped.data is not None
+ for group, labels in _GROUPS.items():
+ alone = adapter.extract(items, labels=labels)
+ assert alone.classifications is not None
+ for index, row in enumerate(alone.classifications):
+ expected = {c["label"]: c["score"] for c in row}
+ assert grouped.data[index][group]["probabilities"] == expected
+
+ def test_each_row_gets_only_its_groups_example_labels(self) -> None:
+ adapter, pipe = _group_adapter()
+
+ adapter.extract(
+ [Item(text="Charged twice, fix today")],
+ instruction="Triage the ticket.",
+ options=_group_options(
+ examples=[
+ {"text": "Refund please", "labels": {"topic": "billing", "urgency": ["low"]}},
+ {"text": "App crashes", "labels": ["topic.bug"]},
+ ],
+ ),
+ )
+
+ call = pipe.prepare_calls[0]
+ assert call["prompt"] == "Triage the ticket."
+ examples_by_labels = {
+ tuple(labels): examples for labels, examples in zip(call["labels"], call["examples"], strict=True)
+ }
+ assert examples_by_labels == {
+ ("low", "high"): [{"text": "Refund please", "labels": ["low"]}, {"text": "App crashes", "labels": []}],
+ ("billing", "bug", "feature"): [
+ {"text": "Refund please", "labels": ["billing"]},
+ {"text": "App crashes", "labels": ["bug"]},
+ ],
+ }
+
+ def test_every_row_is_billed(self) -> None:
+ adapter, _ = _group_adapter()
+ items = [Item(text="Charged twice, fix today"), Item(text="Dark mode someday?")]
+
+ plain = adapter.extract(items, options=_group_options())
+ with_context = adapter.extract(
+ items,
+ instruction="Triage the ticket now",
+ options=_group_options(examples=[{"text": "Refund please", "labels": ["topic.billing"]}]),
+ )
+
+ # Documents of 4 and 3 words plus CLS/SEP, once per group.
+ assert plain.input_token_counts == [2 * (4 + 2), 2 * (3 + 2)]
+ # Each row also encodes the instruction (4) and the example text (2).
+ assert with_context.input_token_counts == [2 * (4 + 2 + 6), 2 * (3 + 2 + 6)]
+
+ def test_truncate_text_cuts_each_row_to_its_own_budget(self) -> None:
+ # max_length 14: the urgency label prompt is 5 tokens (two markers, two
+ # labels, the separator) and topic's is 7. With CLS/SEP the ten-word
+ # document keeps 7 tokens next to urgency and 5 next to topic.
+ text = "one two three four five six seven eight nine ten"
+ adapter, pipe = _adapter(lambda _text, label: 0.5, max_length=14)
+
+ output = adapter.extract([Item(text=text)], options=_group_options(overflow_policy="truncate_text"))
+
+ call = pipe.prepare_calls[0]
+ texts_by_labels = {tuple(labels): text for labels, text in zip(call["labels"], call["texts"], strict=True)}
+ assert texts_by_labels == {
+ ("low", "high"): " ".join(["w"] * 7),
+ ("billing", "bug", "feature"): " ".join(["w"] * 5),
+ }
+ assert output.input_token_counts == [(7 + 2) + (5 + 2)]
+
+ def test_an_item_whose_labels_miss_any_row_fails_alone(self) -> None:
+ # Text-first model keeping 10 content tokens: the six-word document leaves
+ # room for both urgency markers but pushes the third topic marker out.
+ adapter, pipe = _adapter(lambda _text, label: 0.5, prompt_first=False, max_length=12)
+ items = [Item(text="one two three four five six"), Item(text="short")]
+
+ output = adapter.extract(items, options=_group_options())
+
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+ assert output.errors[1] is None
+ assert {text for call in pipe.prepare_calls for text in call["texts"]} == {"short"}
+ assert output.input_token_counts is not None
+ assert output.input_token_counts[0] == 0
+ assert output.input_token_counts[1] == 2 * (1 + 2)
+
+ def test_the_group_count_is_capped_by_rows_per_item(self) -> None:
+ adapter, _ = _adapter(lambda _text, label: 0.5)
+ groups = {f"q{i}": ["yes", "no"] for i in range(65)}
+
+ with pytest.raises(InvalidInputError, match="at most 64 groups"):
+ adapter.extract([Item(text="x")], options={"label_groups": groups})
+ # A 1024-token window allows half as many rows per item.
+ adapter._max_seq_length = 1024
+ with pytest.raises(InvalidInputError, match="at most 32 groups"):
+ adapter.extract([Item(text="x")], options={"label_groups": dict(list(groups.items())[:33])})
+ # The joint encoding is one row per item and keeps its label cap only.
+ output = adapter.extract([Item(text="x")], options={"label_groups": groups, "group_encoding": "joint"})
+ assert output.data is not None
+ assert len(output.data[0]) == 65
+
+ def test_the_group_cap_is_checked_before_tokenizing(self) -> None:
+ tokenizer = _MarkerAwareTokenizer()
+ adapter, _ = _adapter(lambda _text, label: 0.5, tokenizer=tokenizer)
+
+ with pytest.raises(InvalidInputError, match="groups"):
+ adapter.extract([Item(text="x")], options={"label_groups": {f"q{i}": ["a", "b"] for i in range(65)}})
+
+ assert tokenizer.calls == []
+
+ def test_each_groups_label_text_is_checked_against_the_window(self) -> None:
+ adapter, _ = _adapter(lambda _text, label: 0.5)
+ adapter._max_seq_length = 8 # 16 characters per token x 8 = 128 per row
+
+ # Every group fits alone although together they exceed one row.
+ groups = {f"q{i}": ["x" * 60, "y" * 60] for i in range(3)}
+ output = adapter.extract([Item(text="x")], options={"label_groups": groups})
+ assert output.data is not None
+ with pytest.raises(InvalidInputError, match="at most 128 can fit"):
+ adapter.extract([Item(text="x")], options={"label_groups": {"q": ["x" * 70, "y" * 70]}})
+
+ def test_an_item_that_fails_one_group_is_not_checked_against_the_rest(self) -> None:
+ # Text-first model keeping 10 content tokens. Nine words land within the
+ # fit margin of the urgency row, whose exact check refuses them; the
+ # topic row is then skipped for that item.
+ adapter, pipe = _adapter(lambda _text, label: 0.5, prompt_first=False, max_length=12)
+ exact_checks: list[str] = []
+ original = adapter._labels_survive
+
+ def counting(text: str, *args: Any) -> bool:
+ exact_checks.append(text)
+ return original(text, *args)
+
+ adapter._labels_survive = counting # ty:ignore[invalid-assignment]
+ failing = " ".join(f"w{index}" for index in range(9))
+
+ output = adapter.extract([Item(text=failing), Item(text="short")], options=_group_options())
+
+ assert exact_checks.count(failing) == 1
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+ assert output.errors[1] is None
+ assert {text for call in pipe.prepare_calls for text in call["texts"]} == {"short"}
+
+ def test_text_laid_out_with_whitespace_runs_is_read_at_64_groups(self) -> None:
+ # Whitespace carries no tokens here, as with DeBERTa tokenizers, and
+ # columns padded with spaces average about 42 characters per token:
+ # the part the model reads spans about 23,000 characters.
+ adapter, _ = _adapter(lambda _text, label: 0.5)
+ layout = "".join(f"{f'item{index}':<20}{index:>22}\n" for index in range(700))
+ groups = {f"q{index}": ["yes", "no"] for index in range(64)}
+
+ output = adapter.extract([Item(text=layout)], options={"label_groups": groups})
+
+ assert output.errors is None
+ assert output.data is not None
+ assert len(output.data[0]) == 64
+
+ def test_a_document_the_groups_cannot_all_afford_fails_alone(self) -> None:
+ # The part of this document the model reads spans 40,000 characters,
+ # more than a row may tokenize (64 per window token: 32,768), though a
+ # labels request reads it whole.
+ adapter, _ = _adapter(lambda _text, label: 0.5)
+ sparse = "start" + " " * 40_000 + "end"
+ groups = {f"q{index}": ["yes", "no"] for index in range(64)}
+
+ output = adapter.extract([Item(text=sparse), Item(text="short")], options={"label_groups": groups})
+
+ assert output.errors is not None
+ assert output.errors[0] is not None
+ assert output.errors[0].code == "INPUT_TOO_LONG"
+ assert "32768 characters" in output.errors[0].message
+ assert output.errors[1] is None
+ assert output.input_token_counts is not None
+ assert output.input_token_counts[0] == 0
+ assert adapter.extract([Item(text=sparse)], labels=["yes", "no"]).errors is None
+
+ def test_few_groups_share_a_larger_per_item_budget(self) -> None:
+ adapter, _ = _adapter(lambda _text, label: 0.5)
+ sparse = "start" + " " * 40_000 + "end"
+
+ # 524,288 characters per item among 4 groups is 131,072 per row.
+ output = adapter.extract(
+ [Item(text=sparse)], options={"label_groups": {f"q{i}": ["yes", "no"] for i in range(4)}}
+ )
+
+ assert output.errors is None
+
+ def test_a_context_that_cannot_fit_is_refused_after_one_groups_worth_of_tokenizing(self) -> None:
+ tokenizer = _MarkerAwareTokenizer()
+ adapter, _ = _adapter(lambda _text, label: 0.5, max_length=64, tokenizer=tokenizer)
+ instruction = " ".join(["word"] * 60)
+ groups = {f"q{index}": ["yes", "no"] for index in range(64)}
+
+ with pytest.raises(InvalidInputError, match="no room for the document"):
+ adapter.extract([Item(text="short")], instruction=instruction, options={"label_groups": groups})
+
+ tokenized = [text for call in tokenizer.calls for text in call]
+ assert tokenized.count(instruction) == 1
+ assert sum(len(text) for text in tokenized) < 2 * len(instruction)
+
+ def test_each_groups_context_shares_one_tokenization_of_the_instruction_and_examples(self) -> None:
+ tokenizer = _MarkerAwareTokenizer()
+ adapter, _ = _adapter(lambda _text, label: 0.5, tokenizer=tokenizer)
+ examples = [{"text": "Refund please", "labels": {"topic": "billing"}}]
+
+ adapter.extract(
+ [Item(text="Charged twice")],
+ instruction="Triage the ticket.",
+ options=_group_options(examples=examples, overflow_policy="truncate_text"),
+ )
+
+ tokenized = [text for call in tokenizer.calls for text in call]
+ assert tokenized.count("Triage the ticket.") == 1
+ assert tokenized.count("Refund please") == 1
+
+
+class TestBatchingCost:
+ @pytest.mark.parametrize("value", [None, "Joint", 1])
+ def test_a_group_encoding_extract_refuses_is_never_costed_as_one_row(self, value: object) -> None:
+ # The cost hook and extract read group_encoding in one place: a value
+ # extract refuses gets no cost of its own, so it cannot be batched
+ # cheaply and then run as separate rows.
+ adapter, _ = _group_adapter()
+ options = {"label_groups": _GROUPS, "group_encoding": value}
+
+ assert adapter.extract_item_costs([Item(text="abcd")], options=options) is None
+ with pytest.raises(InvalidInputError, match="group_encoding"):
+ adapter.extract([Item(text="abcd")], options=options)
+
+ def test_separate_groups_cost_every_rows_characters(self) -> None:
+ adapter, _ = _group_adapter()
+ items = [Item(text="abcd"), Item(text="abcdefgh")]
+ label_chars = len("low" + "high" + "billing" + "bug" + "feature")
+
+ assert adapter.extract_item_costs(items, options={"label_groups": _GROUPS}) == [
+ 2 * 4 + label_chars,
+ 2 * 8 + label_chars,
+ ]
+ # Each row also encodes the instruction and the example texts.
+ costs = adapter.extract_item_costs(
+ items,
+ instruction="Triage",
+ options={"label_groups": _GROUPS, "examples": [{"text": "Refund", "labels": ["topic.billing"]}]},
+ )
+ assert costs == [2 * (4 + 12) + label_chars, 2 * (8 + 12) + label_chars]
+
+ @pytest.mark.parametrize(
+ "options",
+ [
+ None,
+ {},
+ {"label_groups": _GROUPS, "group_encoding": "joint"},
+ {"label_groups": "not a mapping"},
+ {"label_groups": {f"q{i}": ["a", "b"] for i in range(65)}},
+ ],
+ )
+ def test_other_requests_keep_the_default_cost(self, options: dict[str, Any] | None) -> None:
+ adapter, _ = _group_adapter()
+
+ assert adapter.extract_item_costs([Item(text="abcd")], labels=["a"], options=options) is None
+
class TestOverflowBudget:
def test_prompt_and_examples_count_against_the_text_budget(self) -> None:
@@ -600,7 +1022,9 @@ class TestOverflowBudget:
adapter._special_count = 2
class _Tokenizer:
- def __call__(self, text: str, add_special_tokens: bool = False) -> dict[str, list[str]]:
+ def __call__(self, text: str | list[str], add_special_tokens: bool = False) -> dict[str, Any]:
+ if isinstance(text, list):
+ return {"input_ids": [t.split() for t in text]}
return {"input_ids": text.split()}
def decode(self, ids: list[str], skip_special_tokens: bool = True) -> str:
@@ -623,7 +1047,7 @@ class TestOverflowBudget:
return " ".join(part for part in parts if part)
adapter._tokenizer = _Tokenizer() # ty:ignore[invalid-assignment]
- adapter._pipeline = SimpleNamespace(pipe=_Pipe()) # ty:ignore[invalid-assignment]
+ adapter._pipe = _Pipe()
text = " ".join(f"w{i}" for i in range(12))
plain = adapter._apply_overflow_policy([text], ["a"], "truncate_text")
@@ -644,6 +1068,9 @@ class TestOverflowBudget:
class _WordTokenizer:
"""One token per whitespace word; specials add two unless disabled."""
+ def num_special_tokens_to_add(self, pair: bool = False) -> int:
+ return 2
+
def __call__(self, texts: list[str], add_special_tokens: bool = True, **kwargs: Any) -> dict[str, list[list[int]]]:
extra = 2 if add_special_tokens else 0
counts = [len(text.split()) + extra for text in texts]
@@ -653,10 +1080,9 @@ class _WordTokenizer:
class TestMetering:
- def _adapter(self, max_seq_length: int = 512, items: int = 2) -> GLiClassAdapter:
- adapter = _flat_adapter([dict(_SCORES)] * items)
+ def _adapter(self, max_seq_length: int = 512) -> GLiClassAdapter:
+ adapter, _ = _flat_adapter(tokenizer=_WordTokenizer())
adapter._max_seq_length = max_seq_length
- adapter._tokenizer = _WordTokenizer() # ty:ignore[invalid-assignment]
return adapter
def test_requests_without_context_bill_the_document_only(self) -> None:
@@ -684,7 +1110,7 @@ class TestMetering:
assert output.input_token_counts == [4 + 11, 5 + 11]
def test_billing_is_capped_at_the_model_window(self) -> None:
- adapter = self._adapter(max_seq_length=12, items=1)
+ adapter = self._adapter(max_seq_length=12)
output = adapter.extract(
[Item(text="two words")], labels=list(_LABELS), instruction="one two three four five six seven eight nine"
@@ -692,29 +1118,27 @@ class TestMetering:
assert output.input_token_counts == [12]
+ def test_long_documents_bill_at_most_the_model_window(self) -> None:
+ adapter = self._adapter(max_seq_length=12)
+
+ output = adapter.extract([Item(text=" ".join(["word"] * 40))], labels=list(_LABELS))
+
+ assert output.input_token_counts == [12]
+
class TestFlatLabelOverflow:
- def _adapter(
- self, results: list[dict[str, float]], *, prompt_first: bool, max_length: int = 512
- ) -> GLiClassAdapter:
- adapter = _flat_adapter(results)
- adapter._max_seq_length = max_length
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- pipeline.pipe = _StubPipe(prompt_first=prompt_first, max_length=max_length)
- return adapter
+ def _adapter(self, *, prompt_first: bool, max_length: int = 512) -> tuple[GLiClassAdapter, _ScoringPipe]:
+ return _flat_adapter(prompt_first=prompt_first, max_length=max_length)
def test_one_oversized_document_does_not_fail_the_batch(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=False)
+ adapter, pipe = self._adapter(prompt_first=False)
attacker = "attacker " * 600
output = adapter.extract([Item(text="short victim text"), Item(text=attacker)], labels=list(_LABELS))
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- pipeline.assert_called_once_with(["short victim text"], _LABELS, threshold=0.0, return_hierarchical=True)
+ assert [call["texts"] for call in pipe.prepare_calls] == [["short victim text"]]
assert output.classifications is not None
- assert output.classifications[0][0] == {"label": "bug report", "score": 0.7}
+ assert output.classifications[0][0]["label"] == "bug report"
assert output.classifications[1] == []
assert output.errors is not None
assert output.errors[0] is None
@@ -723,38 +1147,36 @@ class TestFlatLabelOverflow:
assert output.input_token_counts == [5, 0]
def test_only_oversized_documents_skip_inference(self) -> None:
- adapter = self._adapter([], prompt_first=False)
+ adapter, pipe = self._adapter(prompt_first=False)
output = adapter.extract([Item(text="attacker " * 600)], labels=list(_LABELS))
- pipeline = adapter._pipeline
- assert isinstance(pipeline, MagicMock)
- pipeline.assert_not_called()
+ assert pipe.prepare_calls == []
assert output.errors is not None
assert output.errors[0] is not None
def test_labels_first_models_are_not_affected_by_document_length(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=True)
+ adapter, _ = self._adapter(prompt_first=True)
output = adapter.extract([Item(text="attacker " * 600)], labels=list(_LABELS))
assert output.errors is None
def test_labels_that_alone_overflow_the_window_are_refused(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=True, max_length=6)
+ adapter, _ = self._adapter(prompt_first=True, max_length=6)
with pytest.raises(InputTooLongError):
adapter.extract([Item(text="The app crashes")], labels=list(_LABELS))
def test_a_marker_inside_the_document_is_not_an_overflow(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=False)
+ adapter, _ = self._adapter(prompt_first=False)
output = adapter.extract([Item(text="quoted <<LABEL>> marker")], labels=list(_LABELS))
assert output.errors is None
def test_context_that_leaves_no_room_for_the_document_is_refused(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=True, max_length=24)
+ adapter, _ = self._adapter(prompt_first=True, max_length=24)
with pytest.raises(InvalidInputError, match="no room for the document"):
adapter.extract(
@@ -769,8 +1191,7 @@ class TestFlatLabelOverflow:
# label prompt. Twelve words look like they fit (12 + 5 < 18), but the
# trailing space becomes a token next to the first marker, so the last
# marker falls out of the window.
- adapter = self._adapter([dict(_SCORES)], prompt_first=False, max_length=20)
- adapter._tokenizer = _SpaceBeforeMarkerTokenizer() # ty:ignore[invalid-assignment]
+ adapter, _ = _flat_adapter(prompt_first=False, max_length=20, tokenizer=_SpaceBeforeMarkerTokenizer())
output = adapter.extract([Item(text="word " * words)], labels=list(_LABELS))
@@ -782,7 +1203,7 @@ class TestFlatLabelOverflow:
assert output.errors[0].code == "INPUT_TOO_LONG"
def test_billing_with_context_is_capped_at_window_minus_labels(self) -> None:
- adapter = self._adapter([dict(_SCORES)], prompt_first=True, max_length=40)
+ adapter, _ = self._adapter(prompt_first=True, max_length=40)
text = " ".join(["doc"] * 30)
output = adapter.extract([Item(text=text)], labels=list(_LABELS), instruction="one two three")
@@ -792,3 +1213,10 @@ class TestFlatLabelOverflow:
assert output.input_token_counts == [32]
short = adapter.extract([Item(text="doc doc")], labels=list(_LABELS), instruction="one two three")
assert short.input_token_counts == [4 + 3]
+
+ def test_a_model_with_fewer_class_slots_than_labels_is_an_overflow(self) -> None:
+ adapter, pipe = self._adapter(prompt_first=True)
+ pipe._resolve_max_num_classes = lambda labels, same_labels: 2 # ty:ignore[invalid-assignment]
+
+ with pytest.raises(InputTooLongError):
+ adapter.extract([Item(text="The app crashes")], labels=list(_LABELS))
diff --git a/packages/sie_server/tests/adapters/test_runtime_options.py b/packages/sie_server/tests/adapters/test_runtime_options.py
index b73f87cd9..6221377a3 100644
--- a/packages/sie_server/tests/adapters/test_runtime_options.py
+++ b/packages/sie_server/tests/adapters/test_runtime_options.py
@@ -1,15 +1,52 @@
from __future__ import annotations
-from typing import ClassVar
+import math
+from types import SimpleNamespace
+from typing import Any, ClassVar
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
+import torch
from sie_server.adapters._utils import extract_texts, resolve_embedding_options
+from sie_server.adapters.gliclass import GLiClassAdapter
from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
from sie_server.types.inputs import Item
+class _FixedLogitsPipe:
+ """A gliclass pipe whose model scores every text with the same logits."""
+
+ max_length = 512
+
+ def __init__(self, logits: list[float], error: BaseException | None) -> None:
+ self._logits = logits
+ self._error = error
+ self._rows = 0
+
+ def prepare_inputs(self, texts: list[str], labels: list[str], same_labels: bool = False, **_: Any) -> dict:
+ if self._error is not None:
+ raise self._error
+ self._rows = len(texts)
+ return {"input_ids": torch.ones(len(texts), 4, dtype=torch.long)}
+
+ def _resolve_max_num_classes(self, labels: list[str], same_labels: bool) -> int:
+ return len(labels)
+
+ def model(self, **_: Any) -> SimpleNamespace:
+ return SimpleNamespace(logits=torch.tensor([self._logits] * self._rows))
+
+
+def _gliclass_with_probabilities(
+ probabilities: list[float], error: BaseException | None = None, **kwargs: Any
+) -> GLiClassAdapter:
+ """A GLiClass adapter whose single-label softmax returns ``probabilities`` for every item."""
+ adapter = GLiClassAdapter("test-model", **kwargs)
+ adapter._pipe = _FixedLogitsPipe([math.log(p) for p in probabilities], error)
+ adapter._device = "cpu"
+ return adapter
+
+
class TestAdapterEncodeAcceptsOptions:
"""Verify all adapter encode() methods accept the 'options' keyword parameter.
@@ -822,21 +859,7 @@ class TestExtractRuntimeOptions:
def test_gliclass_populates_classifications_not_entities(self) -> None:
"""GLiClass adapter returns classifications in ExtractOutput, not entities."""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
-
- # Mock the pipeline to return known classification results.
- # The adapter calls the pipeline with return_hierarchical=True and a
- # flat label list, which yields a list of {label: score} dicts.
- mock_pipeline = MagicMock()
- mock_pipeline.return_value = [
- {"positive": 0.9, "negative": 0.1},
- ]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities([0.9, 0.1])
items = [Item(text="Great product!")]
output = adapter.extract(items, labels=["positive", "negative"])
@@ -845,9 +868,9 @@ class TestExtractRuntimeOptions:
assert output.classifications is not None
assert len(output.classifications) == 1
assert output.classifications[0][0]["label"] == "positive"
- assert output.classifications[0][0]["score"] == 0.9
+ assert output.classifications[0][0]["score"] == pytest.approx(0.9)
assert output.classifications[0][1]["label"] == "negative"
- assert output.classifications[0][1]["score"] == 0.1
+ assert output.classifications[0][1]["score"] == pytest.approx(0.1)
# Entities should be empty lists (one per item)
assert output.entities == [[]]
@@ -859,20 +882,7 @@ class TestExtractRuntimeOptions:
gliclass library, which dropped sub-threshold labels. The adapter must
now return every requested label with its score by default.
"""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
-
- mock_pipeline = MagicMock()
- # Hierarchical output: every requested label appears with its score,
- # including labels that would be below a 0.5 threshold.
- mock_pipeline.return_value = [
- {"company": 0.43, "person": 0.21, "location": 0.18, "technology": 0.18},
- ]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities([0.43, 0.21, 0.18, 0.18])
items = [Item(text="Apple was founded by Steve Jobs in California.")]
output = adapter.extract(
@@ -888,51 +898,28 @@ class TestExtractRuntimeOptions:
assert output.classifications[0][0]["label"] == "company"
assert output.classifications[0][0]["score"] == pytest.approx(0.43)
- def test_gliclass_calls_pipeline_with_zero_threshold_and_hierarchical(self) -> None:
- """Pipeline is invoked with threshold=0.0 and return_hierarchical=True.
+ def test_gliclass_threshold_does_not_change_the_scores(self) -> None:
+ """A request threshold filters labels after every label is scored.
- Even when callers request a non-zero ``options["threshold"]``, the
- adapter must NOT push that into the gliclass library (which would drop
- labels in single-label mode). Threshold filtering is applied
- server-side after the pipeline returns all label scores.
+ The single-label softmax still covers every requested label, so the
+ label that passes keeps the score it has without a threshold.
"""
- from unittest.mock import MagicMock
+ adapter = _gliclass_with_probabilities([0.9, 0.1])
- from sie_server.adapters.gliclass import GLiClassAdapter
+ output = adapter.extract([Item(text="hello")], labels=["a", "b"], options={"threshold": 0.7})
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.return_value = [{"a": 0.9, "b": 0.1}]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
-
- adapter.extract(
- [Item(text="hello")],
- labels=["a", "b"],
- options={"threshold": 0.7},
- )
-
- assert mock_pipeline.call_count == 1
- kwargs = mock_pipeline.call_args.kwargs
- assert kwargs.get("threshold") == 0.0
- assert kwargs.get("return_hierarchical") is True
+ assert output.classifications is not None
+ assert [c["label"] for c in output.classifications[0]] == ["a"]
+ assert output.classifications[0][0]["score"] == pytest.approx(0.9)
def test_gliclass_post_filters_threshold_server_side(self) -> None:
"""When caller explicitly passes a threshold, sub-threshold labels are dropped."""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.return_value = [{"a": 0.9, "b": 0.4, "c": 0.1}]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities([0.5, 0.4, 0.1])
output = adapter.extract(
[Item(text="hello")],
labels=["a", "b", "c"],
- options={"threshold": 0.5},
+ options={"threshold": 0.45},
)
assert output.classifications is not None
@@ -1000,23 +987,8 @@ class TestExtractRuntimeOptions:
assert fake_tokenizer.model_max_length == 512
assert captured.get("max_length") == 512
-
- def test_gliclass_handles_empty_pipeline_output(self) -> None:
- """Adapter does not crash when the pipeline returns an empty/None entry."""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.return_value = [None]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
-
- output = adapter.extract([Item(text="hello")], labels=["a", "b"])
-
- assert output.classifications == [[]]
- assert output.entities == [[]]
+ # The adapter never calls the pipeline itself, so it needs no progress bar.
+ assert captured.get("progress_bar") is False
def test_gliclass_translates_argmax_crash_to_validation_error(self) -> None:
"""The infamous ``argmax(): ... numel() == 0`` crash is surfaced as
@@ -1024,17 +996,9 @@ class TestExtractRuntimeOptions:
Regression for long-input handling.
"""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.side_effect = RuntimeError(
- "argmax(): Expected reduction dim to be specified for input.numel() == 0."
+ adapter = _gliclass_with_probabilities(
+ [1.0], error=RuntimeError("argmax(): Expected reduction dim to be specified for input.numel() == 0.")
)
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
with pytest.raises(ValueError, match="max sequence length"):
adapter.extract([Item(text="x" * 6000)], labels=["Electronics"])
@@ -1047,15 +1011,9 @@ class TestExtractRuntimeOptions:
Regression for #860 — observed on a ~2.5 KB repeated-sentence request to
``knowledgator/gliclass-large-v1.0`` under ``overflow_policy=default``.
"""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.side_effect = IndexError("index 0 is out of bounds for dimension 0 with size 0")
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities(
+ [1.0], error=IndexError("index 0 is out of bounds for dimension 0 with size 0")
+ )
with pytest.raises(ValueError, match="max sequence length"):
adapter.extract([Item(text="x" * 6000)], labels=["Electronics"])
@@ -1065,21 +1023,15 @@ class TestExtractRuntimeOptions:
must propagate untouched (so genuine bugs surface as 500s instead of
being silently rewritten to 4xx validation errors).
"""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model")
- mock_pipeline = MagicMock()
- mock_pipeline.side_effect = RuntimeError("CUDA out of memory")
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities([0.5, 0.5], error=RuntimeError("CUDA out of memory"))
+ pipe = adapter._pipe
+ assert isinstance(pipe, _FixedLogitsPipe)
with pytest.raises(RuntimeError, match="CUDA out of memory"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
# Also: a RuntimeError mentioning argmax but NOT numel must propagate.
- mock_pipeline.side_effect = RuntimeError("argmax() got an unexpected keyword argument")
+ pipe._error = RuntimeError("argmax() got an unexpected keyword argument")
with pytest.raises(RuntimeError, match="argmax"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
@@ -1088,34 +1040,34 @@ class TestExtractRuntimeOptions:
# and IS mapped to validation (InputTooLongError), not propagated, because
# too many labels overflowed the shared window and the single-label decode
# indexed exactly one past the shrunk label window.
- mock_pipeline.side_effect = IndexError("index 79 is out of bounds for dimension 0 with size 79")
+ pipe._error = IndexError("index 79 is out of bounds for dimension 0 with size 79")
with pytest.raises(ValueError, match="max sequence length"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
# Also: the empty-tensor case (index 0 / size 0, #860) is the same
# exhausted-dimension shape (index == size) and is mapped to validation.
- mock_pipeline.side_effect = IndexError("index 0 is out of bounds for dimension 0 with size 0")
+ pipe._error = IndexError("index 0 is out of bounds for dimension 0 with size 0")
with pytest.raises(ValueError, match="max sequence length"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
# Also: an IndexError with "out of bounds" but index > size (NOT the
# off-by-one shape) is a genuine out-of-range bug and must propagate —
# e.g. a real out-of-range index against a non-empty tensor.
- mock_pipeline.side_effect = IndexError("index 5 is out of bounds for dimension 0 with size 3")
+ pipe._error = IndexError("index 5 is out of bounds for dimension 0 with size 3")
with pytest.raises(IndexError, match="size 3"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
# Also: a genuinely-unrelated IndexError NOT matching the "out of bounds
# for dimension" shape (e.g. "list index out of range") must propagate —
# locks in that the guard stays anchored to the torch-tensor shape.
- mock_pipeline.side_effect = IndexError("list index out of range")
+ pipe._error = IndexError("list index out of range")
with pytest.raises(IndexError, match="list index out of range"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
# Also: an IndexError mentioning "size 0" but NOT the full "index N is out
# of bounds for dimension D with size M" shape must propagate — locks in
# that the guard is anchored to the torch-tensor index/size shape.
- mock_pipeline.side_effect = IndexError("some unrelated error with size 0 buried in the message")
+ pipe._error = IndexError("some unrelated error with size 0 buried in the message")
with pytest.raises(IndexError, match="unrelated"):
adapter.extract([Item(text="hello")], labels=["a", "b"])
@@ -1126,23 +1078,18 @@ class TestExtractRuntimeOptions:
Long-input regression: 54x repeated ``Lorem ipsum dolor sit amet,
consectetur adipiscing elit. `` with a single label ``Electronics``.
"""
- from unittest.mock import MagicMock
-
- from sie_server.adapters.gliclass import GLiClassAdapter
-
- adapter = GLiClassAdapter("test-model", max_seq_length=512)
- mock_pipeline = MagicMock()
- mock_pipeline.return_value = [{"Electronics": 0.27}]
- adapter._pipeline = mock_pipeline
- adapter._device = "cpu"
+ adapter = _gliclass_with_probabilities([0.27], max_seq_length=512)
long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " * 54
- output = adapter.extract([Item(text=long_text)], labels=["Electronics"])
+ output = adapter.extract(
+ [Item(text=long_text)], labels=["Electronics"], options={"classification_type": "multi-label"}
+ )
assert output.classifications is not None
assert len(output.classifications) == 1
assert output.classifications[0][0]["label"] == "Electronics"
- assert output.classifications[0][0]["score"] == pytest.approx(0.27)
+ # One label scored with a sigmoid: the logit log(0.27) gives 0.27 / 1.27.
+ assert output.classifications[0][0]["score"] == pytest.approx(0.27 / 1.27)
def test_nli_classification_flash_populates_classifications_not_entities(self) -> None:
"""NLI Classification Flash adapter returns classifications in ExtractOutput, not entities."""
diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.py
index d7794cd01..6969df5d4 100644
--- a/packages/sie_server/tests/test_all_models.py
+++ b/packages/sie_server/tests/test_all_models.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import io
+import json
import os
from pathlib import Path
from typing import Any
@@ -8,6 +9,7 @@ from typing import Any
import numpy as np
import pytest
from PIL import Image
+from sie_server.adapters.gliclass import _RequestTokens, _row_char_limit
from sie_server.core.loader import load_adapter, load_model_configs
from sie_server.types.inputs import ImageInput, Item
@@ -985,6 +987,10 @@ def test_knowledgator_gliclass_instruct_base_v1_0_extract() -> None:
assert _gliclass_top(adapter, _TICKET, _TICKET_LABELS, instruction="Classify the support ticket.") == "bug report"
+def test_knowledgator_gliclass_instruct_base_v1_0_long_documents() -> None:
+ _assert_long_documents_are_read(_get_adapter("knowledgator/gliclass-instruct-base-v1.0"), groups=64)
+
+
def test_knowledgator_gliclass_instruct_edge_v1_0_extract() -> None:
adapter = _get_adapter("knowledgator/gliclass-instruct-edge-v1.0")
assert _gliclass_top(adapter, _TICKET, _TICKET_LABELS) == "bug report"
@@ -1000,6 +1006,60 @@ def test_knowledgator_gliclass_instruct_large_v1_0_extract() -> None:
_assert_gliclass_groups(adapter, "bug report")
+_ITEMS = ["Widget", "Service fee", "Consulting hours", "Shipping", "Tax adjustment", "Support plan"]
+# Text laid out with runs of spaces, which DeBERTa tokenizers read as nothing:
+# 15 to 40 characters per token.
+_WHITESPACE_LAYOUTS = {
+ "pdf-invoice": "".join(f"{_ITEMS[i % 6]:<60}{i % 97 + 1:>10}{(i * 37 % 9999) / 100:>15.2f}\n" for i in range(3000)),
+ "json-indent-8": json.dumps(
+ {"rows": [{"a": {"b": {"c": [i, i + 1, i + 2, i + 3, i + 4]}}} for i in range(400)]}, indent=8
+ ),
+ "fixed-width-log": "".join(f"{i:>12}{'INFO':>40}{'ok':>60}\n" for i in range(3000)),
+}
+
+
+def _assert_long_documents_are_read(adapter: Any, groups: int) -> None:
+ """Whitespace layouts fit a separate-group row, and cut documents keep the tokens the model reads."""
+ tokenizer = adapter._tokenizer
+ need = adapter._visible_tokens()
+ limit = _row_char_limit(groups, adapter._window())
+ for name, text in _WHITESPACE_LAYOUTS.items():
+ prefix = _RequestTokens(tokenizer, need).visible(text, limit)
+ assert prefix is not None, name
+ # A Unigram tokenizer segments a run of one character by the run's length,
+ # so the run is read whole rather than cut.
+ for text in ("a" * 50_001, "a" * 100_003, *_WHITESPACE_LAYOUTS.values()):
+ prefix = _RequestTokens(tokenizer, need).visible(text)
+ assert prefix is not None
+ read = tokenizer([prefix, text], add_special_tokens=False)["input_ids"]
+ assert read[0][:need] == read[1][:need]
+
+
+def test_knowledgator_gliclass_large_v1_0_extract() -> None:
+ adapter = _get_adapter("knowledgator/gliclass-large-v1.0")
+ assert _gliclass_top(adapter, _TICKET, _TICKET_LABELS) == "bug report"
+
+ # Separate label groups (the default) score each group as a labels request
+ # with that group's labels, and meter the document once per group.
+ grouped = adapter.extract([Item(text=_TICKET)], options={"label_groups": _TICKET_GROUPS})
+ assert grouped.data is not None
+ assert grouped.input_token_counts is not None
+ usage = 0
+ for group, labels in _TICKET_GROUPS.items():
+ alone = adapter.extract([Item(text=_TICKET)], labels=labels)
+ assert alone.classifications is not None
+ assert alone.input_token_counts is not None
+ expected = {c["label"]: c["score"] for c in alone.classifications[0]}
+ assert grouped.data[0][group]["probabilities"] == pytest.approx(expected, abs=1e-5)
+ usage += alone.input_token_counts[0]
+ assert grouped.input_token_counts == [usage]
+ assert grouped.data[0]["topic"]["choice"] == "bug report"
+
+ joint = adapter.extract([Item(text=_TICKET)], options={"label_groups": _TICKET_GROUPS, "group_encoding": "joint"})
+ assert joint.data is not None
+ assert list(joint.data[0]) == list(_TICKET_GROUPS)
+
+
def test_knowledgator_gliclass_large_v3_0_extract() -> None:
# A request without instruction, examples, or label_groups keeps the scores
# the adapter has always returned for this model.
@@ -1012,6 +1072,10 @@ def test_knowledgator_gliclass_multilang_edge_extract() -> None:
assert _gliclass_top(_get_adapter("knowledgator/gliclass-multilang-edge"), _ACCOUNT_DE, labels) == "account access"
+def test_knowledgator_gliclass_multilang_mini_long_documents() -> None:
+ _assert_long_documents_are_read(_get_adapter("knowledgator/gliclass-multilang-mini"), groups=64)
+
+
def test_knowledgator_gliclass_multilang_mini_extract() -> None:
labels = ["billing", "account access", "feature request"]
assert _gliclass_top(_get_adapter("knowledgator/gliclass-multilang-mini"), _ACCOUNT_DE, labels) == "account access"
@@ -1148,6 +1212,10 @@ def test_knowledgator_opir_multitask_large_v1_0_extract() -> None:
assert scores["harassment and abuse"] < scores["instruction hierarchy attack"]
+def test_knowledgator_opir_multitask_large_v1_0_long_documents() -> None:
+ _assert_long_documents_are_read(_get_adapter("knowledgator/opir-multitask-large-v1.0"), groups=32)
+
+
def test_knowledgator_opir_multitask_multilang_v1_0_extract() -> None:
adapter = _get_adapter("knowledgator/opir-multitask-multilang-v1.0")
assert _gliclass_top(adapter, _INJECTION, ["safe", "unsafe"]) == "unsafe"