Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(server): add native ZeRank 2 scoring (#596)
svonavabe8a688374d6
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 8e76fb86b..81251c9c0 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -68,6 +68,24 @@ removes matched stop sequences consistently from returned text, completion-tokenusage, and logprobs. Long completions delay the first visible text; existingrequest timeouts still apply. Other adapters are unaffected.+### Native ZeRank 2 scoring++`zeroentropy/zerank-2-reranker` runs in the default bundle using its saved+SentenceTransformers CrossEncoder modules and publisher chat template: query+as SYSTEM, document as USER, followed by the plain assistant prefix. Scores are+raw logits for the publisher's positive token, 9454; higher values indicate+greater relevance. They can be negative or greater than one and are not+probabilities. Put retrieval conditions in the query; a separate `instruction`+parameter is unsupported.++The profile accepts complete encoded rows of at most 32,768 tokens, including+the query, document and template. An oversized row returns `INPUT_TOO_LONG`+before model execution. Runtime `max_seq_length` can lower this limit. The+adapter keeps the full source and never reports a score for a truncated prefix.+`usage.input_tokens` counts the complete native row for each pair, excluding+left padding and including template tokens. Native forward batches use at most+32,768 padded tokens regardless of the outer scheduling estimate.+### NLI zero-shot classification usageThe NLI zero-shot classifiers (`MoritzLaurer/deberta-v3-base-zeroshot-v2.0`,diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yamlindex 61d3b0aca..2e4591e71 100644--- a/packages/sie_server/bundles/default.yaml+++ b/packages/sie_server/bundles/default.yaml@@ -19,6 +19,7 @@ adapters:- sie_server.adapters.jina_flash_cross_encoder- sie_server.adapters.modernbert_flash- sie_server.adapters.modernbert_flash_cross_encoder+- sie_server.adapters.native_causal_cross_encoder.adapter- sie_server.adapters.nemo_colembed- sie_server.adapters.nomic_flash- sie_server.adapters.owlv2.adapter@@ -59,8 +60,8 @@ deps:huggingface-hub: '>=0.20'# colbert_rotary_flash, jina_flash_cross_encodereinops: '>=0.8'- # sentence_transformer- sentence-transformers: '>=5.0,<6'+ # sentence_transformer; native causal CrossEncoder module format requires 5.4.1+ sentence-transformers: '>=5.4.1,<6'# bge_m3_flagFlagEmbedding: '>=1.3'# grounding_dino. EXACT, not a range. `uv run --with-requirements` resolves thediff --git a/packages/sie_server/models/zeroentropy__zerank-2-reranker.yaml b/packages/sie_server/models/zeroentropy__zerank-2-reranker.yamlnew file mode 100644index 000000000..00ccc6cfc--- /dev/null+++ b/packages/sie_server/models/zeroentropy__zerank-2-reranker.yaml@@ -0,0 +1,22 @@+sie_id: zeroentropy/zerank-2-reranker+hf_id: zeroentropy/zerank-2-reranker+hf_revision: 5eae30d5ee3c6b2df2ef6d723bde45172d761c4c+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: {}+ extract: null+# Complete native causal row, including the publisher chat template.+max_sequence_length: 32768+profiles:+ default:+ max_batch_tokens: 32768+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.native_causal_cross_encoder.adapter:NativeCausalCrossEncoderAdapter+ adapter_options:+ loadtime: {}+ runtime: {}diff --git a/packages/sie_server/src/sie_server/adapters/native_causal_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/native_causal_cross_encoder/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/native_causal_cross_encoder/adapter.py b/packages/sie_server/src/sie_server/adapters/native_causal_cross_encoder/adapter.pynew file mode 100644index 000000000..77573b623--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/native_causal_cross_encoder/adapter.py@@ -0,0 +1,360 @@+"""Publisher-native causal CrossEncoder scoring with complete input admission."""++from __future__ import annotations++import copy+import json+from collections.abc import Mapping+from dataclasses import dataclass+from pathlib import Path+from typing import Any, ClassVar, cast++import numpy as np+import torch+from huggingface_hub import hf_hub_download++from sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ComputePrecision+from sie_server.adapters.errors import InputTooLongError+from sie_server.core.inference_output import ScoreOutput+from sie_server.types.inputs import InvalidInputError, Item++_CONTEXT_TOKENS = 32768+_FORWARD_PADDED_TOKENS = 32768+_TRUE_TOKEN_ID = 9454+_MODULE_TYPES = (+ "sentence_transformers.base.modules.transformer.Transformer",+ "sentence_transformers.cross_encoder.modules.logit_score.LogitScore",+)+_INTEGER_DTYPES = {torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64}+_ERR_NATIVE_FEATURES = "Native causal CrossEncoder returned invalid complete-row features"+_ERR_NATIVE_SCORES = "Native causal CrossEncoder returned invalid scores"+++class _NativeInputTooLongError(InputTooLongError, InvalidInputError):+ """Preserve INPUT_TOO_LONG while permitting fused-request isolation."""+++@dataclass(frozen=True, slots=True)+class _NativeRows:+ """One immutable admitted encoded row for every original text pair."""++ pairs: tuple[tuple[str, str], ...]+ ids: tuple[tuple[int, ...], ...]+ counts: tuple[int, ...]+ indices: tuple[int, ...]++ def __post_init__(self) -> None:+ size = len(self.pairs)+ if (+ not len(self.ids) == len(self.counts) == len(self.indices) == size+ or any(type(index) is not int for index in self.indices)+ or self.indices != tuple(range(size))+ or any(+ type(count) is not int or not row or len(row) != count+ for row, count in zip(self.ids, self.counts, strict=True)+ )+ ):+ raise RuntimeError("Native causal CrossEncoder admission rows are misaligned")+++class NativeCausalCrossEncoderAdapter(BaseAdapter):+ """Score ZeRank 2 pairs using its saved Transformer and LogitScore modules.++ The publisher's query/system and document/user chat template is preserved.+ Scores are raw positive-token logits, with the saved Identity activation.+ Complete native rows, including template tokens, must fit the configured+ context. Runtime ``max_seq_length`` can reduce that context. Token usage+ counts those exact rows without left padding. Forwards are bounded to+ 32768 padded tokens independently of the outer scheduler's cost estimate.+ """++ spec: ClassVar[AdapterSpec] = AdapterSpec(+ inputs=("text",), outputs=("score",), unload_fields=("_model", "_tokenizer", "_move_features")+ )++ def __init__(+ self,+ model_name_or_path: str | Path,+ *,+ revision: str | None = None,+ max_seq_length: int | None = None,+ compute_precision: ComputePrecision | None = None,+ ) -> None:+ self._model_name_or_path = str(model_name_or_path)+ self._revision = revision+ self._max_seq_length = self._validate_limit(+ _CONTEXT_TOKENS if max_seq_length is None else max_seq_length, _CONTEXT_TOKENS+ )+ if compute_precision is not None and compute_precision not in {"float16", "bfloat16", "float32"}:+ raise ValueError("Native causal CrossEncoder compute_precision must be float16, bfloat16 or float32")+ self._compute_precision = compute_precision+ self._forward_token_budget = _FORWARD_PADDED_TOKENS+ self._model: Any = None+ self._tokenizer: Any = None+ self._move_features: Any = None+ self._device: str | None = None++ def _require_saved_modules(self) -> None:+ root = Path(self._model_name_or_path)+ if root.is_dir():+ path = root / "modules.json"+ else:+ path = Path(hf_hub_download(self._model_name_or_path, "modules.json", revision=self._revision))+ try:+ modules = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise RuntimeError("Native causal CrossEncoder requires saved modules.json") from exc+ if (+ not isinstance(modules, list)+ or len(modules) != 2+ or any(+ not isinstance(module, dict)+ or cast("dict[str, Any]", module).get("idx") != index+ or cast("dict[str, Any]", module).get("type") != expected+ for index, (module, expected) in enumerate(zip(modules, _MODULE_TYPES, strict=True))+ )+ ):+ raise RuntimeError("Native causal CrossEncoder requires saved Transformer and LogitScore modules")++ def load(self, device: str) -> None:+ """Load and verify the native checkpoint without a fallback scorer."""+ from sentence_transformers import CrossEncoder+ from sentence_transformers.base.modules import Transformer+ from sentence_transformers.cross_encoder.modules import LogitScore+ from sentence_transformers.util import batch_to_device++ self._require_saved_modules()+ precision = self._compute_precision or ("bfloat16" if device.startswith("cuda") else "float32")+ dtype = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}[precision]+ model = CrossEncoder(+ self._model_name_or_path,+ revision=self._revision,+ device=device,+ max_length=self._max_seq_length,+ trust_remote_code=False,+ model_kwargs={"dtype": dtype, "attn_implementation": "sdpa"},+ )+ modules = list(model.children())+ if len(modules) != 2 or type(modules[0]) is not Transformer or type(modules[1]) is not LogitScore:+ raise RuntimeError("Native causal CrossEncoder loaded unexpected module classes")+ transformer, scorer = modules+ if (+ transformer.transformer_task != "text-generation"+ or transformer.module_output_name != "causal_logits"+ or transformer.can_flatten_inputs is not False+ or transformer.do_lower_case is not False+ or scorer.module_input_name != "causal_logits"+ or type(scorer.true_token_id) is not int+ or scorer.true_token_id != _TRUE_TOKEN_ID+ or scorer.false_token_id is not None+ or type(model.activation_fn) is not torch.nn.Identity+ ):+ raise RuntimeError("Native causal CrossEncoder checkpoint does not match the raw positive-token scorer")+ expected_modalities = {+ "text": {"method": "forward", "method_output_name": "logits"},+ "message": {"method": "forward", "method_output_name": "logits", "format": "flat"},+ }+ if transformer.modality_config != expected_modalities:+ raise RuntimeError("Native causal CrossEncoder checkpoint has an unexpected input formatter")+ tokenizer = transformer.tokenizer+ processor = transformer.processor+ if tokenizer is None or tokenizer.padding_side != "left" or processor.padding_side != "left":+ raise RuntimeError("Native causal CrossEncoder requires native left padding")+ self._verify_template(processor)+ processing = copy.deepcopy(transformer.processing_kwargs)+ if (+ not isinstance(processing, dict)+ or processing.get("chat_template") != {"add_generation_prompt": True}+ or not isinstance(processing.get("text", {}), dict)+ ):+ raise RuntimeError("Native causal CrossEncoder requires the saved generation-prefix processing")+ processing["text"] = {**processing.get("text", {}), "truncation": False}+ transformer.processing_kwargs = processing+ model.eval()+ self._model = model+ self._tokenizer = tokenizer+ self._move_features = batch_to_device+ self._device = device++ @staticmethod+ def _verify_template(tokenizer: Any) -> None:+ if not isinstance(tokenizer.chat_template, str) or not tokenizer.chat_template:+ raise RuntimeError("Native causal CrossEncoder requires the publisher chat template")+ query, document = "Query\n東京", "Document\nsource-tail-✓"+ expected = (+ f"<|im_start|>system\n{query}<|im_end|>\n<|im_start|>user\n{document}<|im_end|>\n<|im_start|>assistant\n"+ )+ rendered = tokenizer.apply_chat_template(+ [{"role": "query", "content": query}, {"role": "document", "content": document}],+ tokenize=False,+ add_generation_prompt=True,+ )+ if rendered != expected:+ raise RuntimeError("Native causal CrossEncoder chat template differs from the publisher format")++ def score(+ self, query: Item, items: list[Item], *, instruction: str | None = None, options: dict[str, Any] | None = None+ ) -> list[float]:+ """Score a query against documents through the same complete-row path."""+ return self.score_pairs([query] * len(items), items, instruction=instruction, options=options).scores.tolist()++ def score_pairs(+ self,+ queries: list[Item],+ docs: list[Item],+ *,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ ) -> ScoreOutput:+ """Admit every full row, score bounded native chunks, and restore pair order."""+ self._check_loaded()+ limit = self._runtime_limit(instruction, options)+ pairs = self._parse_pairs(queries, docs)+ if not pairs:+ return ScoreOutput(scores=np.empty(0, dtype=np.float32), input_token_counts=[])+ with self._tokenizer_guard():+ rows = self._admit(pairs, limit)+ scores = np.empty(len(pairs), dtype=np.float32)+ with torch.inference_mode():+ for indices in self._chunks(rows):+ features = self._preprocess([rows.pairs[index] for index in indices])+ ids = self._read_rows(features, len(indices), limit)+ if ids != tuple(rows.ids[index] for index in indices):+ raise RuntimeError("Native causal CrossEncoder encoded rows changed after admission")+ if features["input_ids"].numel() > self._forward_token_budget:+ raise RuntimeError(+ "Native causal CrossEncoder preprocessing exceeded the padded forward budget"+ )+ output = self._model.forward(self._move_features(features, self._device))+ if not isinstance(output, Mapping) or "scores" not in output:+ raise RuntimeError(_ERR_NATIVE_SCORES)+ native_scores = self._model.activation_fn(output["scores"])+ values = self._score_vector(native_scores, len(indices))+ for index, value in zip(indices, values, strict=True):+ scores[rows.indices[index]] = value+ return ScoreOutput(scores=scores, input_token_counts=list(rows.counts))++ def _runtime_limit(self, instruction: str | None, options: dict[str, Any] | None) -> int:+ if instruction is not None:+ raise InvalidInputError("Native causal CrossEncoder conditions belong in the query, not instruction")+ opts = options or {}+ if set(opts) - {"max_seq_length"}:+ raise InvalidInputError("Native causal CrossEncoder supports only the max_seq_length runtime option")+ return self._validate_limit(opts.get("max_seq_length", self._max_seq_length), self._max_seq_length)++ @staticmethod+ def _validate_limit(value: object, ceiling: int) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= ceiling:+ raise InvalidInputError(f"Native causal CrossEncoder max_seq_length must be an integer from 1 to {ceiling}")+ return value++ @staticmethod+ def _parse_pairs(queries: list[Item], docs: list[Item]) -> tuple[tuple[str, str], ...]:+ if len(queries) != len(docs):+ raise InvalidInputError("Native causal CrossEncoder requires equal numbers of queries and documents")+ pairs: list[tuple[str, str]] = []+ for query, document in zip(queries, docs, strict=True):+ pairs.append(+ (NativeCausalCrossEncoderAdapter._text(query), NativeCausalCrossEncoderAdapter._text(document))+ )+ return tuple(pairs)++ @staticmethod+ def _text(item: Item) -> str:+ if (+ not isinstance(item.text, str)+ or item.images is not None+ or item.audio is not None+ or item.video is not None+ or item.document is not None+ ):+ raise InvalidInputError("Native causal CrossEncoder accepts text-only query and document items")+ return item.text++ def _preprocess(self, pairs: list[tuple[str, str]]) -> dict[str, Any]:+ try:+ features = self._model.preprocess(pairs)+ except (ValueError, TypeError, KeyError):+ raise RuntimeError("Native causal CrossEncoder preprocessing failed") from None+ if not isinstance(features, Mapping):+ raise RuntimeError(_ERR_NATIVE_FEATURES)+ return dict(features)++ @staticmethod+ def _read_rows(features: dict[str, Any], size: int, limit: int) -> tuple[tuple[int, ...], ...]:+ ids, mask = features.get("input_ids"), features.get("attention_mask")+ if (+ not isinstance(ids, torch.Tensor)+ or not isinstance(mask, torch.Tensor)+ or ids.ndim != 2+ or ids.shape[0] != size+ or ids.shape[1] == 0+ or ids.dtype not in _INTEGER_DTYPES+ or mask.shape != ids.shape+ or mask.dtype not in _INTEGER_DTYPES | {torch.bool}+ or type(features.get("logits_to_keep")) is not int+ or features.get("logits_to_keep") != 1+ or not torch.all((mask == 0) | (mask == 1)).item()+ or not torch.all(mask[:, -1] == 1).item()+ or not torch.all(mask[:, 1:] >= mask[:, :-1]).item()+ or not torch.all(ids >= 0).item()+ ):+ raise RuntimeError(_ERR_NATIVE_FEATURES)+ counts = mask.sum(dim=1).tolist()+ if any(count > limit for count in counts):+ raise _NativeInputTooLongError(+ f"Native causal CrossEncoder complete input exceeds the {limit}-token context, including template tokens"+ )+ return tuple(tuple(row[attended.bool()].tolist()) for row, attended in zip(ids, mask, strict=True))++ def _admit(self, pairs: tuple[tuple[str, str], ...], limit: int) -> _NativeRows:+ ids = tuple(self._read_rows(self._preprocess([pair]), 1, limit)[0] for pair in pairs)+ return _NativeRows(pairs=pairs, ids=ids, counts=tuple(map(len, ids)), indices=tuple(range(len(pairs))))++ def _chunks(self, rows: _NativeRows) -> list[list[int]]:+ chunks: list[list[int]] = []+ current: list[int] = []+ for index in sorted(range(len(rows.pairs)), key=lambda index: rows.counts[index]):+ if rows.counts[index] > self._forward_token_budget:+ raise RuntimeError("Native causal CrossEncoder row exceeds the private forward budget")+ if current and (len(current) + 1) * rows.counts[index] > self._forward_token_budget:+ chunks.append(current)+ current = []+ current.append(index)+ if current:+ chunks.append(current)+ return chunks++ @staticmethod+ def _score_vector(scores: Any, size: int) -> np.ndarray:+ if not isinstance(scores, torch.Tensor) or not scores.is_floating_point():+ raise RuntimeError(_ERR_NATIVE_SCORES)+ if scores.ndim == 0 and size == 1:+ scores = scores.reshape(1)+ elif scores.ndim == 2 and scores.shape[1] == 1:+ scores = scores.squeeze(1)+ if scores.ndim != 1 or scores.shape[0] != size or not torch.isfinite(scores).all().item():+ raise RuntimeError(_ERR_NATIVE_SCORES)+ values = scores.detach().to(dtype=torch.float32).cpu().numpy()+ if not np.isfinite(values).all():+ raise RuntimeError(_ERR_NATIVE_SCORES)+ return values++ def count_pair_input_tokens(+ self, query: Item, docs: list[Item], *, instruction: str | None = None+ ) -> list[int] | None:+ """Count through the same complete native admission path, without a forward."""+ try:+ self._check_loaded()+ limit = self._runtime_limit(instruction, None)+ pairs = self._parse_pairs([query] * len(docs), docs)+ with self._tokenizer_guard():+ return list(self._admit(pairs, limit).counts)+ except (InvalidInputError, RuntimeError):+ return None++ def count_input_tokens(self, items: list[Item]) -> None:+ """Single text tokenization is not the native causal pair's accounting basis."""+ _ = itemsdiff --git a/packages/sie_server/tests/adapters/test_native_causal_cross_encoder.py b/packages/sie_server/tests/adapters/test_native_causal_cross_encoder.pynew file mode 100644index 000000000..57392c8f1--- /dev/null+++ b/packages/sie_server/tests/adapters/test_native_causal_cross_encoder.py@@ -0,0 +1,660 @@+"""Native causal scoring contracts with mocked loaders and tiny CPU tensors."""++from __future__ import annotations++import asyncio+import copy+import json+from collections.abc import Callable, Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any, cast+from unittest.mock import Mock++import numpy as np+import pytest+import sentence_transformers+import torch+from jinja2.sandbox import ImmutableSandboxedEnvironment+from sentence_transformers.base import modules as native_modules+from sentence_transformers.cross_encoder.modules import LogitScore+from sie_server.adapters.errors import InputTooLongError+from sie_server.adapters.native_causal_cross_encoder import adapter as adapter_module+from sie_server.adapters.native_causal_cross_encoder.adapter import (+ NativeCausalCrossEncoderAdapter,+ _NativeInputTooLongError,+ _NativeRows,+)+from sie_server.core.inference_output import ScoreOutput+from sie_server.core.oom import OomRecoveryConfig, OomRecoveryStats+from sie_server.core.worker.handlers.score import ScoreHandler+from sie_server.core.worker.oom_recovery import BatchExecutor, ConfigGroup+from sie_server.queue_executor import _inference_exception_outcome+from sie_server.types.inputs import AudioInput, InvalidInputError, Item++# The query/document branch of the pinned publisher's chat_template.jinja.+_PAIR_TEMPLATE = """{%- set query = messages | selectattr('role', 'eq', 'query') | map(attribute='content') | list -%}+{%- set document = messages | selectattr('role', 'eq', 'document') | map(attribute='content') | list -%}+{{- '<|im_start|>system\\n' + (query | first) + '<|im_end|>\\n' -}}+{{- '<|im_start|>user\\n' + (document | first) + '<|im_end|>\\n' -}}+{%- if add_generation_prompt -%}{{- '<|im_start|>assistant\\n' -}}{%- endif -%}+"""+++class ToyTokenizer:+ padding_side = "left"++ def __init__(self) -> None:+ self.chat_template: str | None = _PAIR_TEMPLATE++ def apply_chat_template(self, messages: list[dict[str, str]], **kwargs: Any) -> str:+ assert kwargs.get("tokenize") is False+ return (+ ImmutableSandboxedEnvironment()+ .from_string(self.chat_template or "")+ .render(messages=messages, add_generation_prompt=kwargs["add_generation_prompt"])+ )++ def row(self, query: str, document: str) -> list[int]:+ rendered = self.apply_chat_template(+ [{"role": "query", "content": query}, {"role": "document", "content": document}],+ tokenize=False,+ add_generation_prompt=True,+ )+ return [ord(character) + 1 for character in rendered]+++class ToyTransformer:+ def __init__(self) -> None:+ self.transformer_task = "text-generation"+ self.module_output_name = "causal_logits"+ self.can_flatten_inputs = False+ self.do_lower_case = False+ self.modality_config = {+ "text": {"method": "forward", "method_output_name": "logits"},+ "message": {"method": "forward", "method_output_name": "logits", "format": "flat"},+ }+ self.processing_kwargs = {"chat_template": {"add_generation_prompt": True}}+ self.tokenizer = ToyTokenizer()+ self.processor = self.tokenizer+++class ToyCrossEncoder:+ """Only nested processing_kwargs controls this fake native processor."""++ def __init__(self) -> None:+ self.transformer = ToyTransformer()+ self.scorer = LogitScore(true_token_id=9454, false_token_id=None)+ self.activation_fn: Any = torch.nn.Identity()+ self.extra_modules: list[Any] = []+ self.max_length = 32768+ self.preprocess_calls: list[tuple[list[tuple[str, str]], dict[str, Any]]] = []+ self.forward_calls: list[dict[str, Any]] = []+ self.values: dict[str, float] = {}+ self.output: Any = None+ self.mutate_batch: str | None = None+ self.malformed: Callable[[dict[str, Any]], dict[str, Any]] | None = None+ self.eval = Mock()++ def children(self) -> Iterator[Any]:+ yield self.transformer+ yield self.scorer+ yield from self.extra_modules++ def preprocess(self, pairs: list[tuple[str, str]], **kwargs: Any) -> dict[str, Any]:+ self.preprocess_calls.append((list(pairs), kwargs))+ truncate = self.transformer.processing_kwargs.get("text", {}).get("truncation", True)+ rows = [self.transformer.tokenizer.row(query, document) for query, document in pairs]+ if truncate:+ rows = [row[: self.max_length] for row in rows]+ width = max(map(len, rows))+ ids = [[0] * (width - len(row)) + row for row in rows]+ masks = [[0] * (width - len(row)) + [1] * len(row) for row in rows]+ features = {+ "input_ids": torch.tensor(ids, dtype=torch.long),+ "attention_mask": torch.tensor(masks, dtype=torch.long),+ "logits_to_keep": 1,+ "modality": "message",+ "_pairs": pairs,+ }+ if len(pairs) > 1 and self.mutate_batch == "ids":+ features["input_ids"][0, -1] += 1+ elif len(pairs) > 1 and self.mutate_batch == "counts":+ last_padding = (features["attention_mask"][0] == 0).nonzero()[-1, 0]+ features["attention_mask"][0, last_padding] = 1+ return self.malformed(features) if self.malformed is not None else features++ def forward(self, features: dict[str, Any]) -> dict[str, Any]:+ self.forward_calls.append(features)+ scores = self.output+ if scores is None:+ scores = torch.tensor([[self.values.get(document, 5.25)] for _, document in features["_pairs"]])+ return {"scores": scores}+++def native_loader(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> tuple[ToyCrossEncoder, Mock, Mock, Path]:+ model = ToyCrossEncoder()++ def construct(*args: Any, **kwargs: Any) -> ToyCrossEncoder:+ model.max_length = kwargs["max_length"]+ return model++ loader = Mock(side_effect=construct)+ monkeypatch.setattr(sentence_transformers, "CrossEncoder", loader)+ monkeypatch.setattr(native_modules, "Transformer", ToyTransformer)+ modules_file = tmp_path / "modules.json"+ modules_file.write_text(+ json.dumps(+ [+ {"idx": 0, "name": "0", "path": "", "type": adapter_module._MODULE_TYPES[0]},+ {"idx": 1, "name": "1", "path": "1_LogitScore", "type": adapter_module._MODULE_TYPES[1]},+ ]+ )+ )+ download = Mock(return_value=str(modules_file))+ monkeypatch.setattr(adapter_module, "hf_hub_download", download)+ return model, loader, download, modules_file+++def loaded(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path],+) -> tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder]:+ adapter = NativeCausalCrossEncoderAdapter("zeroentropy/zerank-2-reranker", revision="a" * 40)+ adapter.load("cpu")+ return adapter, native_loader[0]+++ ("device", "precision", "dtype"),+ [+ ("cpu", None, torch.float32),+ ("cuda:0", None, torch.bfloat16),+ ("cpu", "float16", torch.float16),+ ("cpu", "bfloat16", torch.bfloat16),+ ("cpu", "float32", torch.float32),+ ],+)+def test_native_constructor_and_saved_processing(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path], device: str, precision: Any, dtype: torch.dtype+) -> None:+ model, loader, download, _ = native_loader+ saved = copy.deepcopy(model.transformer.processing_kwargs)+ adapter = NativeCausalCrossEncoderAdapter(+ "zeroentropy/zerank-2-reranker", revision="b" * 40, compute_precision=precision, max_seq_length=32768+ )+ adapter.load(device)+ download.assert_called_once_with("zeroentropy/zerank-2-reranker", "modules.json", revision="b" * 40)+ loader.assert_called_once_with(+ "zeroentropy/zerank-2-reranker",+ revision="b" * 40,+ device=device,+ max_length=32768,+ trust_remote_code=False,+ model_kwargs={"dtype": dtype, "attn_implementation": "sdpa"},+ )+ assert model.transformer.processing_kwargs == {**saved, "text": {"truncation": False}}+ model.eval.assert_called_once()+++def test_local_native_modules_are_required_before_loading(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path], tmp_path: Path+) -> None:+ _, loader, download, modules_file = native_loader+ adapter = NativeCausalCrossEncoderAdapter(tmp_path, revision="b" * 40)+ modules_file.unlink()+ with pytest.raises(RuntimeError, match=r"requires saved modules\.json"):+ adapter.load("cpu")+ loader.assert_not_called()+ download.assert_not_called()+++ "metadata",+ [None, {}, [], [{"idx": 0, "type": "fallback"}], [{"idx": 0, "type": "fallback"}, {"idx": 1, "type": "fallback"}]],+)+def test_missing_or_altered_module_metadata_never_uses_fallback(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path], metadata: Any+) -> None:+ _, loader, _, modules_file = native_loader+ modules_file.write_text(json.dumps(metadata))+ with pytest.raises(RuntimeError, match="saved Transformer and LogitScore"):+ NativeCausalCrossEncoderAdapter("publisher/model").load("cpu")+ loader.assert_not_called()+++ ("target", "attribute", "value"),+ [+ ("transformer", "transformer_task", "sequence-classification"),+ ("transformer", "module_output_name", "scores"),+ ("transformer", "can_flatten_inputs", True),+ ("transformer", "do_lower_case", True),+ ("scorer", "true_token_id", 1),+ ("scorer", "true_token_id", True),+ ("scorer", "false_token_id", 442),+ ("scorer", "module_input_name", "logits"),+ ("model", "activation_fn", torch.nn.Sigmoid()),+ ],+)+def test_native_scorer_and_generation_identity_are_validated(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path], target: str, attribute: str, value: Any+) -> None:+ model = native_loader[0]+ owner = model if target == "model" else getattr(model, target)+ setattr(owner, attribute, value)+ with pytest.raises(RuntimeError, match="raw positive-token scorer"):+ NativeCausalCrossEncoderAdapter("publisher/model").load("cpu")+ assert not model.forward_calls+++def test_extra_native_modules_are_rejected(native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path]) -> None:+ native_loader[0].extra_modules.append(torch.nn.Identity())+ with pytest.raises(RuntimeError, match="module classes"):+ NativeCausalCrossEncoderAdapter("publisher/model").load("cpu")+++def test_wrong_native_module_class_is_rejected(native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path]) -> None:+ native_loader[0].scorer = torch.nn.Identity()+ with pytest.raises(RuntimeError, match="module classes"):+ NativeCausalCrossEncoderAdapter("publisher/model").load("cpu")++[email protected]("change", ["format", "padding", "template", "generation", "thinking"])+def test_native_format_padding_and_template_are_validated(+ native_loader: tuple[ToyCrossEncoder, Mock, Mock, Path], change: str+) -> None:+ model = native_loader[0]+ if change == "format":+ model.transformer.modality_config["message"]["format"] = "nested"+ elif change == "padding":+ model.transformer.tokenizer.padding_side = "right"+ elif change == "template":+ model.transformer.tokenizer.chat_template = None+ elif change == "generation":+ model.transformer.processing_kwargs = {"chat_template": {"add_generation_prompt": False}}+ else:+ model.transformer.tokenizer.chat_template += "<think>"+ with pytest.raises(RuntimeError, match=r"formatter|left padding|template|generation-prefix|publisher format"):+ NativeCausalCrossEncoderAdapter("publisher/model").load("cpu")+++def test_real_native_logit_score_preserves_raw_positive_logits() -> None:+ # Exercise the scoring module only; no causal model or checkpoint is loaded.+ logits = torch.zeros((2, 1, 9455))+ logits[:, 0, 0] = 1000+ logits[:, 0, 9454] = torch.tensor([5.25, -3.5])+ output = LogitScore(true_token_id=9454, false_token_id=None)({"causal_logits": logits})+ torch.testing.assert_close(output["scores"], torch.tensor([[5.25], [-3.5]]))+++def test_publisher_template_preserves_unicode_newlines_and_source_tail() -> None:+ query, document = "Question\n東京", "Élodie\nAnswer at source-tail-✓"+ rendered = ToyTokenizer().apply_chat_template(+ [{"role": "query", "content": query}, {"role": "document", "content": document}],+ tokenize=False,+ add_generation_prompt=True,+ )+ assert rendered == (+ f"<|im_start|>system\n{query}<|im_end|>\n<|im_start|>user\n{document}<|im_end|>\n<|im_start|>assistant\n"+ )+ assert "<think>" not in rendered+++def test_full_native_rows_raw_scores_and_exact_usage(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ query = "q\n東京"+ docs = ["short", "longer document ends at source-tail-✓"]+ model.values = {docs[0]: -3.5, docs[1]: 5.25}+ output = adapter.score_pairs([Item(text=query)] * 2, [Item(text=document) for document in docs])+ np.testing.assert_array_equal(output.scores, [-3.5, 5.25])+ assert output.scores.dtype == np.float32+ assert output.input_token_counts == [len(model.transformer.tokenizer.row(query, document)) for document in docs]+ assert output.content_token_counts is None+ assert all(kwargs == {} for _, kwargs in model.preprocess_calls)+ assert all(features["logits_to_keep"] == 1 for features in model.forward_calls)+ assert model.forward_calls[0]["attention_mask"][0, 0] == 0+ assert model.forward_calls[0]["_pairs"][1][1].endswith("source-tail-✓")+++def test_exact_limit_and_one_token_overflow(loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder]) -> None:+ adapter, model = loaded+ adapter._max_seq_length = len(model.transformer.tokenizer.row("q", "doc"))+ output = adapter.score_pairs([Item(text="q")], [Item(text="doc")])+ assert output.input_token_counts == [adapter._max_seq_length]+ model.forward_calls.clear()+ with pytest.raises(_NativeInputTooLongError, match="including template"):+ adapter.score_pairs([Item(text="q")], [Item(text="docx")])+ assert not model.forward_calls+++def test_large_query_and_small_doc_admit_complete_template_first(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ adapter._max_seq_length = 100+ with pytest.raises(_NativeInputTooLongError):+ adapter.score_pairs([Item(text="q" * 80)], [Item(text="d")])+ assert not model.forward_calls+ assert model.transformer.processing_kwargs["text"]["truncation"] is False+++def test_any_overlength_pair_prevents_all_forwards_in_its_request(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ adapter._max_seq_length = 100+ with pytest.raises(_NativeInputTooLongError):+ adapter.score_pairs([Item(text="q"), Item(text="q")], [Item(text="d"), Item(text="x" * 100)])+ assert not model.forward_calls++[email protected]("limit", [True, False, None, 0, -1, 1.5, "100", 32769])+def test_runtime_limit_only_reduces_context(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], limit: Any+) -> None:+ adapter, model = loaded+ with pytest.raises(InvalidInputError, match="max_seq_length"):+ adapter.score_pairs([Item(text="q")], [Item(text="d")], options={"max_seq_length": limit})+ assert not model.preprocess_calls+++def test_runtime_limit_does_not_mutate_native_processing(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ saved = copy.deepcopy(model.transformer.processing_kwargs)+ count = len(model.transformer.tokenizer.row("q", "d"))+ with pytest.raises(_NativeInputTooLongError):+ adapter.score_pairs([Item(text="q")], [Item(text="d")], options={"max_seq_length": count - 1})+ assert adapter.score_pairs([Item(text="q")], [Item(text="d")]).input_token_counts == [count]+ assert model.transformer.processing_kwargs == saved+ assert model.max_length == 32768+++ "option", [{"truncation": False}, {"prompt": "x"}, {"batch_size": 100}, {"activation_fn": "Identity"}]+)+def test_unknown_options_are_rejected(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], option: dict[str, Any]+) -> None:+ adapter, model = loaded+ with pytest.raises(InvalidInputError, match="only the max_seq_length"):+ adapter.score_pairs([Item(text="q")], [Item(text="d")], options=option)+ assert not model.preprocess_calls++[email protected]("instruction", ["condition", ""])+def test_separate_instruction_is_explicitly_unsupported(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], instruction: str+) -> None:+ adapter, model = loaded+ with pytest.raises(InvalidInputError, match="conditions belong in the query"):+ adapter.score_pairs([Item(text="q")], [Item(text="d")], instruction=instruction)+ assert not model.preprocess_calls+++ ("field", "value"),+ [+ ("images", []),+ ("images", [{"data": b"x"}]),+ ("audio", AudioInput(data=b"x")),+ ("video", {"data": b"x"}),+ ("document", {"data": b"x"}),+ ("text", None),+ ("text", 1),+ ],+)[email protected]("side", ["query", "document"])+def test_non_text_pairs_and_attached_media_are_rejected(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], field: str, value: Any, side: str+) -> None:+ adapter, model = loaded+ altered = Item(**{"text": "text", field: value})+ query, document = (altered, Item(text="d")) if side == "query" else (Item(text="q"), altered)+ with pytest.raises(InvalidInputError, match="text-only"):+ adapter.score_pairs([query], [document])+ assert not model.preprocess_calls+++def test_parallel_cardinality_and_empty_inputs(loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder]) -> None:+ adapter, model = loaded+ with pytest.raises(InvalidInputError, match="equal numbers"):+ adapter.score_pairs([Item(text="q")], [])+ output = adapter.score_pairs([], [])+ assert output.scores.shape == (0,)+ assert output.scores.dtype == np.float32+ assert output.input_token_counts == []+ assert not model.preprocess_calls+ assert not model.forward_calls+++ ("value", "size"),+ [+ (torch.tensor(5.25), 1),+ (torch.tensor([5.25]), 1),+ (torch.tensor([[5.25]]), 1),+ (torch.tensor([5.25, -3.5]), 2),+ (torch.tensor([[5.25], [-3.5]]), 2),+ ],+)+def test_native_singleton_and_batch_score_shapes(value: torch.Tensor, size: int) -> None:+ result = NativeCausalCrossEncoderAdapter._score_vector(value, size)+ assert result.shape == (size,)+ assert result.dtype == np.float32+ assert result[0] == 5.25+++ ("value", "size"),+ [+ (torch.tensor(1.0), 2),+ (torch.tensor([1.0]), 2),+ (torch.tensor([1.0, 2.0]), 1),+ (torch.ones(2, 2), 2),+ (torch.ones(2, 1, 1), 2),+ (torch.tensor([1]), 1),+ (torch.tensor([float("nan")]), 1),+ (torch.tensor([float("inf")]), 1),+ (torch.tensor([1e100], dtype=torch.float64), 1),+ (np.array([1.0]), 1),+ ],+)+def test_invalid_cardinality_dimensions_and_nonfinite_scores(value: Any, size: int) -> None:+ with pytest.raises(RuntimeError, match="invalid scores"):+ NativeCausalCrossEncoderAdapter._score_vector(value, size)+++def test_bad_native_output_is_internal_error(loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder]) -> None:+ adapter, model = loaded+ model.output = torch.ones(1, 2)+ with pytest.raises(RuntimeError, match="invalid scores") as error:+ adapter.score_pairs([Item(text="q")], [Item(text="d")])+ assert not isinstance(error.value, InvalidInputError)++[email protected]("mutation", ["ids", "counts"])+def test_admitted_ids_and_counts_must_match_chunk_preprocessing(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], mutation: str+) -> None:+ adapter, model = loaded+ model.mutate_batch = mutation+ with pytest.raises(RuntimeError, match="changed after admission"):+ adapter.score_pairs([Item(text="q")] * 2, [Item(text="d"), Item(text="longer document")])+ assert not model.forward_calls+++ "bad_features",+ [+ {},+ {"input_ids": torch.ones(1)},+ {"input_ids": torch.ones(1, 1), "attention_mask": torch.ones(1, 1)},+ {"input_ids": torch.zeros(1, 0, dtype=torch.long), "attention_mask": torch.zeros(1, 0, dtype=torch.long)},+ {"input_ids": torch.ones(1, 3, dtype=torch.long), "attention_mask": torch.tensor([[1, 0, 1]])},+ {"input_ids": torch.ones(1, 3, dtype=torch.long), "attention_mask": torch.tensor([[1, 1, 0]])},+ {"input_ids": torch.ones(1, 1, dtype=torch.long), "attention_mask": torch.tensor([[0]])},+ {"input_ids": torch.ones(1, 1, dtype=torch.long), "attention_mask": torch.tensor([[2]])},+ {"input_ids": torch.ones(1, 1, dtype=torch.long), "attention_mask": torch.tensor([[float("nan")]])},+ {"input_ids": torch.tensor([[-1]]), "attention_mask": torch.tensor([[1]])},+ {"logits_to_keep": 1.0},+ {"logits_to_keep": True},+ {"logits_to_keep": 2},+ ],+)+def test_malformed_native_rows_do_not_forward(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder], bad_features: dict[str, Any]+) -> None:+ adapter, model = loaded+ model.malformed = lambda features: {**features, **bad_features} if bad_features else {}+ with pytest.raises(RuntimeError, match="invalid complete-row features"):+ adapter.score_pairs([Item(text="q")], [Item(text="d")])+ assert not model.forward_calls+++def test_padded_budget_uses_rows_times_width_and_restores_original_order(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ docs = ["x" * 100, "d", "y" * 50, "dd"]+ model.values = dict(zip(docs, [1.0, -3.5, 8.0, 5.25], strict=True))+ adapter._forward_token_budget = 240+ output = adapter.score_pairs([Item(text="q")] * 4, [Item(text=document) for document in docs])+ np.testing.assert_array_equal(output.scores, [1.0, -3.5, 8.0, 5.25])+ assert output.input_token_counts == [len(model.transformer.tokenizer.row("q", document)) for document in docs]+ assert len(model.forward_calls) == 3+ for features in model.forward_calls:+ assert features["input_ids"].numel() <= adapter._forward_token_budget+ assert features["attention_mask"][:, -1].all()+ assert [document for features in model.forward_calls for _, document in features["_pairs"]] != docs+++def test_actual_native_padding_cannot_exceed_private_forward_budget(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ adapter._forward_token_budget = 240++ def extra_padding(features: dict[str, Any]) -> dict[str, Any]:+ for key in ("input_ids", "attention_mask"):+ features[key] = torch.nn.functional.pad(features[key], (300, 0))+ return features++ model.malformed = extra_padding+ with pytest.raises(RuntimeError, match="exceeded the padded forward budget"):+ adapter.score_pairs([Item(text="q")], [Item(text="d")])+ assert not model.forward_calls++[email protected]("change", ["count", "cardinality", "index", "empty_ids", "boolean_index"])+def test_native_rows_alignment_is_checked(change: str) -> None:+ values: dict[str, Any] = {"pairs": (("q", "d"),), "ids": ((1,),), "counts": (1,), "indices": (0,)}+ if change == "count":+ values["counts"] = (2,)+ elif change == "cardinality":+ values["counts"] = ()+ elif change == "index":+ values["indices"] = (1,)+ elif change == "empty_ids":+ values["ids"] = ((),)+ else:+ values["indices"] = (False,)+ with pytest.raises(RuntimeError, match="misaligned"):+ _NativeRows(**values)+++def test_score_and_count_hook_use_same_native_path(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ query = Item(text="q")+ docs = [Item(text="d"), Item(text="longer")]+ assert adapter.score(query, docs) == [5.25, 5.25]+ forwards = len(model.forward_calls)+ assert adapter.count_pair_input_tokens(query, docs) == [+ len(model.transformer.tokenizer.row("q", item.text)) for item in docs+ ]+ assert len(model.forward_calls) == forwards+ assert adapter.count_pair_input_tokens(query, docs, instruction="unsupported") is None+ adapter._max_seq_length = 1+ assert adapter.count_pair_input_tokens(query, docs) is None+ assert adapter.count_input_tokens([query]) is None+++def test_score_handler_preserves_exact_positional_counts() -> None:+ handler = ScoreHandler()+ output = ScoreOutput(scores=np.array([5.25, -3.5], dtype=np.float32), input_token_counts=[73, 100])+ parts = {1: handler.slice_output(output, 1), 0: handler.slice_output(output, 0)}+ restored = handler.assemble_output(parts, 2)+ np.testing.assert_array_equal(restored.scores, output.scores)+ assert restored.input_token_counts == [73, 100]+++async def test_overlength_native_pair_is_isolated_and_maps_to_input_too_long(+ loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder],+) -> None:+ adapter, model = loaded+ adapter._max_seq_length = 100+ loop = asyncio.get_running_loop()+ bad, good = [+ SimpleNamespace(+ future=loop.create_future(),+ _partial_results=None,+ items=[0],+ query=Item(text="q"),+ instruction=None,+ options=None,+ )+ for _ in range(2)+ ]+ group = cast("ConfigGroup", ([Item(text="x" * 100), Item(text="d")], [bad, good], [0, 0], [0, 1]))+ handler = ScoreHandler()+ executor = BatchExecutor(+ model_name="native", registry=None, config=OomRecoveryConfig(enabled=False), stats=OomRecoveryStats()+ )+ seen_sizes: list[int] = []++ async def dispatch(operation: Any, candidate: ConfigGroup) -> ScoreOutput:+ seen_sizes.append(len(candidate[0]))+ return operation.run_inference(adapter, candidate[0], (None, None), None, candidate[1])++ await executor.run(handler, group, dispatch)+ error = bad.future.exception()+ assert isinstance(error, _NativeInputTooLongError)+ assert isinstance(error, InvalidInputError)+ assert isinstance(error, InputTooLongError)+ assert seen_sizes == [2, 1, 1]+ assert good._partial_results[0].input_token_counts == [len(model.transformer.tokenizer.row("q", "d"))]+ assert not good.future.done()+ assert [pair for features in model.forward_calls for pair in features["_pairs"]] == [("q", "d")]+ batch_item = SimpleNamespace(work_item_id="w", request_id="r", item_index=0)+ outcome = _inference_exception_outcome(batch_item, error)+ assert outcome.error_code == "INPUT_TOO_LONG"+ assert outcome.units is None++[email protected]("value", [True, 0, -1, 32769, 1.5, "32768"])+def test_invalid_constructor_context_is_rejected(value: Any) -> None:+ with pytest.raises(InvalidInputError, match="max_seq_length"):+ NativeCausalCrossEncoderAdapter("publisher/model", max_seq_length=value)+++def test_constructor_rejects_imagined_options_and_precision() -> None:+ with pytest.raises(TypeError, match="unexpected keyword argument"):+ NativeCausalCrossEncoderAdapter("publisher/model", truncation=False) # type: ignore[call-arg]+ with pytest.raises(ValueError, match="compute_precision"):+ NativeCausalCrossEncoderAdapter("publisher/model", compute_precision="auto") # type: ignore[arg-type]+++def test_unload_clears_native_state(loaded: tuple[NativeCausalCrossEncoderAdapter, ToyCrossEncoder]) -> None:+ adapter, _ = loaded+ adapter.unload()+ assert all(getattr(adapter, field) is None for field in adapter.spec.unload_fields)+ with pytest.raises(RuntimeError, match="not loaded"):+ adapter.score_pairs([], [])diff --git a/packages/sie_server/tests/config/test_native_zerank_catalog.py b/packages/sie_server/tests/config/test_native_zerank_catalog.pynew file mode 100644index 000000000..e5e33ad64--- /dev/null+++ b/packages/sie_server/tests/config/test_native_zerank_catalog.py@@ -0,0 +1,59 @@+"""Public native ZeRank catalog identity and default bundle routing."""++from pathlib import Path+from unittest.mock import Mock++import pytest+import yaml+from sie_server.adapters.native_causal_cross_encoder.adapter import NativeCausalCrossEncoderAdapter+from sie_server.core.loader import load_adapter, load_model_configs++_SERVER = Path(__file__).resolve().parents[2]+_MODEL = "zeroentropy/zerank-2-reranker"+_REVISION = "5eae30d5ee3c6b2df2ef6d723bde45172d761c4c"+_ADAPTER = "sie_server.adapters.native_causal_cross_encoder.adapter"+++def test_native_catalog_pin_profile_and_bundle() -> None:+ config = yaml.safe_load((_SERVER / "models/zeroentropy__zerank-2-reranker.yaml").read_text())+ assert config["sie_id"] == config["hf_id"] == _MODEL+ assert config["hf_revision"] == _REVISION+ assert config["inputs"] == {"text": True, "image": False, "audio": False, "video": False}+ assert config["tasks"] == {"encode": None, "score": {}, "extract": None}+ assert config["max_sequence_length"] == 32768+ profile = config["profiles"]["default"]+ assert profile["compute_precision"] == "bfloat16"+ assert profile["max_batch_tokens"] == 32768+ assert profile["adapter_path"] == f"{_ADAPTER}:NativeCausalCrossEncoderAdapter"+ assert profile["adapter_options"] == {"loadtime": {}, "runtime": {}}+ bundle = yaml.safe_load((_SERVER / "bundles/default.yaml").read_text())+ assert _ADAPTER in bundle["adapters"]+ assert bundle["deps"]["sentence-transformers"] == ">=5.4.1,<6"+ assert bundle["deps"]["transformers"] == ">=4.57,<5"+ assert bundle["deps"]["gliner2"] == ">=1.3.1,<2"+++def test_loader_forwards_native_context_precision_and_revision(monkeypatch: pytest.MonkeyPatch) -> None:+ native_load = Mock()+ monkeypatch.setattr(NativeCausalCrossEncoderAdapter, "load", native_load)+ config = load_model_configs(_SERVER / "models")[_MODEL]+ adapter = load_adapter(config, _SERVER / "models", device="cpu")+ assert isinstance(adapter, NativeCausalCrossEncoderAdapter)+ assert adapter._max_seq_length == 32768+ assert adapter._model_name_or_path == _MODEL+ assert adapter._revision == _REVISION+ assert adapter._compute_precision == "bfloat16"+ native_load.assert_not_called()++[email protected]("name", ["0.6B", "4B"])+def test_existing_qwen_routes_keep_their_specialized_modes(name: str) -> None:+ config = yaml.safe_load((_SERVER / f"models/Qwen__Qwen3-Reranker-{name}.yaml").read_text())+ profile = config["profiles"]["default"]+ assert (+ profile["adapter_path"] == "sie_server.adapters.qwen2_flash_cross_encoder.adapter:Qwen2FlashCrossEncoderAdapter"+ )+ options = profile["adapter_options"]["loadtime"]+ assert options["input_format"] == "qwen3"+ assert options["score_mode"] == "log_softmax"+ assert (options["yes_token"], options["no_token"]) == ("yes", "no")