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 SAM 3 open-vocabulary detection (#614)
svonava7e7d0f5adee8
diff --git a/packages/sie_server/bundles/transformers5.yaml b/packages/sie_server/bundles/transformers5.yamlindex 47cd70a20..9cfc78588 100644--- a/packages/sie_server/bundles/transformers5.yaml+++ b/packages/sie_server/bundles/transformers5.yaml@@ -15,6 +15,8 @@ adapters:- sie_server.adapters.topk_embed.adapter# Parakeet-TDT speech-to-text (ParakeetForTDT).- sie_server.adapters.parakeet.adapter+# SAM 3 open-vocabulary detection (Sam3Model / Sam3Processor exist only in transformers 5.x).+- sie_server.adapters.sam3.adapterdeps:# Transformers 5.x for models requiring newer architecture support# (e.g., LightOnOCR-2-1B needs LightOnOcrForConditionalGeneration,diff --git a/packages/sie_server/models/facebook__sam3.yaml b/packages/sie_server/models/facebook__sam3.yamlnew file mode 100644index 000000000..3e8bf35c3--- /dev/null+++ b/packages/sie_server/models/facebook__sam3.yaml@@ -0,0 +1,50 @@+# SAM 3 (Meta): open-vocabulary detection with one concept prompt per caller+# label. Returns the standard objects list (label, score, [x, y, w, h] pixel+# box). SAM 3 also predicts an instance mask per detection; masks are not+# returned.+#+# LICENSE: SAM License (Meta, last updated 2025-11-19). This is not an OSI+# license. It allows use, reproduction, distribution and derivative works under+# its terms, and any redistribution of the materials must include a copy of the+# agreement. Read https://huggingface.co/facebook/sam3/blob/main/LICENSE before+# serving this model.+#+# GATED: facebook/sam3 is a gated Hugging Face repo, and Meta approves access+# requests manually. The server needs an HF_TOKEN from an approved account.+# Without one the registry records a terminal GATED failure and the API returns+# MODEL_LOAD_FAILED.+#+# Needs Sam3Model / Sam3Processor from Transformers 5, so the adapter is+# served from the transformers5 bundle only.+#+# score_threshold 0.3 is the default threshold of+# Sam3Processor.post_process_object_detection in Transformers 5.14 to 5.19.+# Scores are sigmoid(instance logit) x sigmoid(presence logit), and a detection+# is kept when its score is strictly above the threshold. The model card's+# examples pass threshold=0.5 explicitly, and Meta's reference sam3 package+# defaults to 0.5. Callers can pass score_threshold per request.+#+# compute_precision bfloat16 matches Meta's reference example notebook, which+# runs under bfloat16 autocast. Scores are computed in float32.+sie_id: facebook/sam3+hf_id: facebook/sam3+hf_revision: 3c879f39826c281e95690f02c7821c4de09afae7+inputs:+ text: false+ image: true+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sam3.adapter:Sam3Adapter+ adapter_options:+ loadtime:+ score_threshold: 0.3+ runtime:+ score_threshold: 0.3diff --git a/packages/sie_server/src/sie_server/adapters/sam3/__init__.py b/packages/sie_server/src/sie_server/adapters/sam3/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/sam3/adapter.py b/packages/sie_server/src/sie_server/adapters/sam3/adapter.pynew file mode 100644index 000000000..ed05e8ee0--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/sam3/adapter.py@@ -0,0 +1,410 @@+"""SAM 3 adapter for open-vocabulary object detection.++SAM 3 (Segment Anything Model 3, Meta) finds every instance of a concept given+as a short noun phrase ("yellow school bus"). Each caller label is one concept+prompt. The adapter encodes each image once and runs the detector once per+label against those shared vision features, the multi-prompt pattern the+Transformers documentation describes.++Scores come from ``Sam3Processor.post_process_object_detection``: the+per-instance probability multiplied by the per-prompt presence probability.+A detection is kept when its score is strictly above ``score_threshold``.++SAM 3 also predicts an instance mask for each detection. This adapter does not+return masks. It returns the standard ``objects`` list (label, score and an+``[x, y, w, h]`` box in integer pixels of the original image).++Target model: facebook/sam3 (SAM License, gated on the Hugging Face Hub).+It needs Transformers 5 (``Sam3Model`` and ``Sam3Processor``).++Usage:+ client.extract(+ "facebook/sam3",+ [Item(images=["photo.jpg"])],+ labels=["person", "yellow school bus"],+ )++See: https://huggingface.co/docs/transformers/model_doc/sam3+"""++from __future__ import annotations++import logging+import math+from pathlib import Path+from typing import TYPE_CHECKING, Any, ClassVar++import torch++from sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.core.inference_output import EncodeOutput, ExtractOutput+from sie_server.core.preprocessor import DetectionPreprocessor+from sie_server.core.preprocessor.vision import collect_detection_prepared_items+from sie_server.types.inputs import decode_image+from sie_server.types.responses import DetectedObject++if TYPE_CHECKING:+ from PIL.Image import Image++ from sie_server.types.inputs import Item++logger = logging.getLogger(__name__)++# Default of Sam3Processor.post_process_object_detection (Transformers 5.14 to 5.19).+DEFAULT_SCORE_THRESHOLD = 0.3+# Sam3ImageProcessor resizes every image to a 1008 x 1008 square.+_DEFAULT_IMAGE_SIDE = 1008+# Sam3Config's CLIP text encoder has 32 positions. Sam3Processor pads every prompt to 32 tokens.+_DEFAULT_TEXT_POSITIONS = 32+# Fields of a Sam3 output that post-processing reads. They are scored in float32 so that+# a bfloat16 forward pass does not quantise scores near the threshold.+_SCORED_OUTPUTS = ("pred_logits", "pred_boxes", "presence_logits")++_ERR_NO_LABELS = "Sam3Adapter requires labels: one short noun phrase per kind of object to detect"+_ERR_BAD_LABEL = "Sam3Adapter labels must be non-empty strings"+_ERR_THRESHOLD = "score_threshold must be a number between 0 and 1"+_ERR_ENCODE_NOT_SUPPORTED = "Sam3Adapter does not support encode(). Use extract() instead."+_ERR_TRANSFORMERS = (+ "SAM 3 needs Sam3Model and Sam3Processor from Transformers 5; serve it from the transformers5 bundle"+)+++def _score_threshold(value: Any) -> float:+ """``value`` as a threshold in [0, 1], or ``ValueError``."""+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(_ERR_THRESHOLD)+ if not 0 <= value <= 1:+ raise ValueError(_ERR_THRESHOLD)+ return float(value)+++def _label_prompts(labels: list[str] | None) -> list[tuple[str, str]]:+ """``(label, prompt)`` for each distinct caller label, in request order.++ The prompt is the label with surrounding whitespace removed; the label is+ returned to the caller unchanged. A repeated label is prompted once (see+ ``Sam3Adapter._tokenize`` for labels that tokenize identically).+ """+ if not labels:+ raise ValueError(_ERR_NO_LABELS)+ prompts: dict[str, str] = {}+ for label in labels:+ if not isinstance(label, str) or not label.strip():+ raise ValueError(_ERR_BAD_LABEL)+ prompts.setdefault(label, label.strip())+ return list(prompts.items())+++def _image_side(image_processor: Any) -> int:+ """The side of the square Sam3ImageProcessor resizes every image to."""+ size = getattr(image_processor, "size", None) or {}+ side = size.get("height") if isinstance(size, dict) else getattr(size, "height", None)+ return int(side) if side else _DEFAULT_IMAGE_SIDE+++def _scored_in_float32(outputs: Any) -> Any:+ """``outputs`` with the fields post-processing reads cast to float32."""+ for name in _SCORED_OUTPUTS:+ value = getattr(outputs, name, None)+ if isinstance(value, torch.Tensor):+ setattr(outputs, name, value.float())+ return outputs+++def _to_objects(result: dict[str, Any], label: str, size: tuple[int, int]) -> list[DetectedObject]:+ """Post-processed ``xyxy`` boxes as ``[x, y, w, h]`` integer boxes clipped to the image.++ ``size`` is the original ``(width, height)``. Coordinates are clipped to+ the image, then truncated to integers, the way the other detectors convert+ boxes, so ``x + w`` never exceeds the image width.+ """+ boxes = result["boxes"].detach().float().cpu().tolist()+ scores = result["scores"].detach().float().cpu().tolist()+ width, height = size+ objects: list[DetectedObject] = []+ for (x1, y1, x2, y2), score in zip(boxes, scores, strict=True):+ x1, x2 = min(max(x1, 0.0), width), min(max(x2, 0.0), width)+ y1, y2 = min(max(y1, 0.0), height), min(max(y2, 0.0), height)+ objects.append(+ DetectedObject(+ label=label,+ score=float(score),+ bbox=[int(x1), int(y1), int(x2 - x1), int(y2 - y1)],+ )+ )+ return objects+++class Sam3Adapter(BaseAdapter):+ """Adapter for SAM 3 text-prompted, open-vocabulary object detection.++ Given images and text labels, returns every instance of each label with a+ bounding box and a confidence score. Masks are not returned.+ """++ spec: ClassVar[AdapterSpec] = AdapterSpec(+ inputs=("image",),+ outputs=("json",),+ unload_fields=("_model", "_processor", "_preprocessor"),+ default_preprocessor="image",+ )++ __slots__ = (+ "_compute_precision",+ "_device",+ "_device_type",+ "_model",+ "_model_dtype",+ "_model_name_or_path",+ "_preprocessor",+ "_processor",+ "_revision",+ "_score_threshold",+ "_text_positions",+ )++ def __init__(+ self,+ model_name_or_path: str | Path,+ *,+ compute_precision: ComputePrecision = "bfloat16",+ revision: str | None = None,+ score_threshold: float = DEFAULT_SCORE_THRESHOLD,+ **kwargs: Any,+ ) -> None:+ del kwargs+ self._model_name_or_path = str(model_name_or_path)+ self._compute_precision = compute_precision+ self._revision = revision+ self._score_threshold = _score_threshold(score_threshold)++ self._model: Any = None+ self._processor: Any = None+ self._preprocessor: Any = None+ self._device: str | None = None+ self._device_type: str = "cpu"+ self._model_dtype: torch.dtype = torch.float32+ self._text_positions: int = _DEFAULT_TEXT_POSITIONS++ def load(self, device: str) -> None:+ import transformers++ model_class = getattr(transformers, "Sam3Model", None)+ processor_class = getattr(transformers, "Sam3Processor", None)+ if model_class is None or processor_class is None:+ raise RuntimeError(_ERR_TRANSFORMERS)++ self._device = device+ self._device_type = "cuda" if device.startswith("cuda") else "cpu"+ dtype = self._resolve_dtype()++ shared_kwargs: dict[str, Any] = {}+ if self._revision is not None:+ shared_kwargs["revision"] = self._revision++ logger.info("Loading SAM 3 model %s on device=%s with dtype=%s", self._model_name_or_path, device, dtype)++ self._processor = processor_class.from_pretrained(self._model_name_or_path, **shared_kwargs)+ self._model = model_class.from_pretrained(self._model_name_or_path, dtype=dtype, **shared_kwargs)+ self._model.to(device)+ self._model.eval()+ self._model_dtype = dtype++ text_config = getattr(self._model.config, "text_config", None)+ positions = getattr(text_config, "max_position_embeddings", None)+ self._text_positions = positions if isinstance(positions, int) and positions > 0 else _DEFAULT_TEXT_POSITIONS++ image_processor = self._processor.image_processor+ # Images larger than twice the model input are shrunk on the CPU first,+ # as for OWLv2. Boxes still map to the size the caller sent.+ self._preprocessor = DetectionPreprocessor(+ image_processor=image_processor,+ model_name=self._model_name_or_path,+ max_side=2 * _image_side(image_processor),+ )++ logger.info("SAM 3 model loaded successfully")++ def _resolve_dtype(self) -> torch.dtype:+ if not self._device or not str(self._device).startswith("cuda"):+ return torch.float32+ return {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}.get(+ self._compute_precision, torch.bfloat16+ )++ def is_loaded(self) -> bool:+ return self._model is not None++ def encode(+ self,+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ prepared_items: list[Any] | None = None,+ options: dict[str, Any] | None = None,+ ) -> EncodeOutput:+ raise NotImplementedError(_ERR_ENCODE_NOT_SUPPORTED)++ def extract(+ 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,+ prepared_items: list[Any] | None = None,+ ) -> ExtractOutput:+ """Detect every instance of each label in each item's first image.++ Every label and option is validated, and every label tokenized,+ before any image reaches the model.+ """+ del output_schema, instruction # Unused++ self._check_loaded()+ if self._processor is None:+ raise RuntimeError(ERR_NOT_LOADED)++ prompts = _label_prompts(labels)+ opts = options or {}+ score_threshold = _score_threshold(opts.get("score_threshold", opts.get("threshold", self._score_threshold)))+ text_inputs = self._tokenize(prompts)++ n_items = len(items)+ no_objects = ExtractOutput(entities=[[] for _ in range(n_items)], objects=[[] for _ in range(n_items)])++ if prepared_items:+ prepared_batch = collect_detection_prepared_items(prepared_items)+ if prepared_batch is None:+ return no_objects+ pixel_values, _pixel_mask, original_sizes, image_indices = prepared_batch+ else:+ images: list[Image] = []+ image_indices = []+ for idx, item in enumerate(items):+ img = self._extract_image(item, item_index=idx)+ if img is not None:+ images.append(img)+ image_indices.append(idx)+ if not images:+ return no_objects+ pixel_values = self._processor.image_processor(images=images, return_tensors="pt")["pixel_values"]+ original_sizes = [(img.width, img.height) for img in images]++ detections = self._detect(pixel_values, original_sizes, text_inputs, score_threshold)++ all_objects: list[list[DetectedObject]] = [[] for _ in range(n_items)]+ for result_idx, item_idx in enumerate(image_indices):+ all_objects[item_idx] = detections[result_idx]++ return ExtractOutput(entities=[[] for _ in range(n_items)], objects=all_objects)++ def _tokenize(self, prompts: list[tuple[str, str]]) -> list[tuple[str, torch.Tensor, torch.Tensor]]:+ """``(label, input_ids, attention_mask)`` per distinct prompt, each ``[1, seq_len]``.++ Uses the processor's own text path, which pads every prompt to the+ text encoder's 32 positions. A longer prompt is rejected, not+ truncated: SAM 3 is prompted with short noun phrases. The CLIP+ tokenizer lowercases, so labels that differ only in case ("Cat" and+ "cat") are the same model input. Such a prompt runs once, and its+ detections carry the first of those labels in request order.+ """+ tokenized: list[tuple[str, torch.Tensor, torch.Tensor]] = []+ seen: set[tuple[int, ...]] = set()+ with self._tokenizer_guard():+ for label, prompt in prompts:+ encoded = self._processor(text=prompt, return_tensors="pt")+ input_ids = encoded["input_ids"]+ attention_mask = encoded["attention_mask"]+ if input_ids.shape[-1] > self._text_positions:+ n_tokens = int(attention_mask.sum())+ msg = (+ f"SAM 3 label {label!r} is {n_tokens} tokens; the text encoder takes at most "+ f"{self._text_positions}. Use a short noun phrase."+ )+ raise ValueError(msg)+ key = tuple(input_ids[0][attention_mask[0].bool()].tolist())+ if key in seen:+ continue+ seen.add(key)+ tokenized.append((label, input_ids, attention_mask))+ return tokenized++ def _detect(+ self,+ pixel_values: torch.Tensor,+ original_sizes: list[tuple[int, int]],+ text_inputs: list[tuple[str, torch.Tensor, torch.Tensor]],+ score_threshold: float,+ ) -> list[list[DetectedObject]]:+ """Detect each label in a batch of images, encoding the images once.++ Args:+ pixel_values: Processed images ``[B, 3, H, W]``.+ original_sizes: ``(width, height)`` of each image as the caller sent it.+ text_inputs: Tokenized labels from ``_tokenize``.+ score_threshold: Keep detections scoring strictly above this.++ Returns:+ One list of detections per image, highest score first.+ """+ model = self._model+ processor = self._processor+ device = self._device+ batch_size = pixel_values.shape[0]+ # post_process_object_detection takes (height, width).+ target_sizes = [(height, width) for width, height in original_sizes]+ detections: list[list[DetectedObject]] = [[] for _ in range(batch_size)]++ with (+ torch.inference_mode(),+ torch.autocast(+ device_type=self._device_type,+ dtype=self._model_dtype,+ enabled=(self._device_type == "cuda"),+ ),+ ):+ vision_embeds = model.get_vision_features(pixel_values=pixel_values.to(device, dtype=self._model_dtype))+ for label, input_ids, attention_mask in text_inputs:+ outputs = model(+ vision_embeds=vision_embeds,+ input_ids=input_ids.to(device).repeat(batch_size, 1),+ attention_mask=attention_mask.to(device).repeat(batch_size, 1),+ )+ results = processor.post_process_object_detection(+ _scored_in_float32(outputs),+ threshold=score_threshold,+ target_sizes=target_sizes,+ )+ for index, result in enumerate(results):+ detections[index].extend(_to_objects(result, label, original_sizes[index]))++ for found in detections:+ found.sort(key=lambda detected: detected["score"], reverse=True)+ return detections++ def _extract_image(self, item: Item, *, item_index: int | None = None) -> Image | None:+ """The item's first image as RGB, or ``None`` when it has none.++ Expects the SDK wire format (an ImageInput dict with ``data`` bytes).+ """+ images = item.images+ if not images:+ return None++ img = images[0]+ if not isinstance(img, dict) or "data" not in img:+ return None++ # decode_image raises InvalidMediaError (-> 400 INVALID_INPUT) on+ # non-bytes or undecodable payloads, and converts to RGB.+ return decode_image(img, item_index=item_index, image_index=0)++ def get_preprocessor(self) -> Any | None:+ """The DetectionPreprocessor that decodes and resizes images on the CPU."""+ return self._preprocessordiff --git a/packages/sie_server/tests/adapters/test_sam3.py b/packages/sie_server/tests/adapters/test_sam3.pynew file mode 100644index 000000000..9d86b4590--- /dev/null+++ b/packages/sie_server/tests/adapters/test_sam3.py@@ -0,0 +1,470 @@+"""CPU contract tests for the SAM 3 detection adapter.++Pretrained loading and the model forward pass are mocked. The fake processor's+``post_process_object_detection`` reproduces Transformers 5.19's+``Sam3ImageProcessor.post_process_object_detection``: score = sigmoid(logit) x+sigmoid(presence), kept when strictly above the threshold, and relative+``xyxy`` boxes scaled to ``(height, width)``.+"""++from __future__ import annotations++import io+import sys+from types import SimpleNamespace+from typing import Any+from unittest.mock import MagicMock++import pytest+import torch+from PIL import Image+from sie_server.adapters.sam3.adapter import DEFAULT_SCORE_THRESHOLD, Sam3Adapter, _to_objects+from sie_server.core.inference_output import ExtractOutput+from sie_server.core.prepared import DetectionPayload, PreparedItem+from sie_server.core.preprocessor import DetectionPreprocessor+from sie_server.types.inputs import InvalidMediaError, Item+from sie_server.types.responses import DetectedObject++MODEL = "facebook/sam3"+REVISION = "3c879f39826c281e95690f02c7821c4de09afae7"+QUERIES = 4+++def _score(logit: float) -> float:+ """The score the post-processor gives a query with this logit and a certain presence."""+ return float(torch.sigmoid(torch.tensor(logit)))+++class _FakeProcessor:+ """Sam3Processor's text tokenization and box post-processing, without assets."""++ START, END = 49406, 49407++ def __init__(self) -> None:+ self.image_processor = MagicMock()+ self.image_processor.size = {"height": 1008, "width": 1008}+ self.texts: list[str] = []+ self.postprocess_calls: list[dict[str, Any]] = []+ self._vocab: dict[str, int] = {}+ self.prompts: dict[tuple[int, ...], str] = {}++ def __call__(self, *, text: str, return_tensors: str) -> dict[str, torch.Tensor]:+ """One id per lowercased word between start and end tokens, padded to 32, like the CLIP tokenizer."""+ assert return_tensors == "pt"+ self.texts.append(text)+ words = text.lower().split()+ ids = [self.START, *(self._vocab.setdefault(word, len(self._vocab) + 1) for word in words), self.END]+ self.prompts[tuple(ids)] = " ".join(words)+ width = max(32, len(ids))+ input_ids = torch.full((1, width), self.END, dtype=torch.long)+ input_ids[0, : len(ids)] = torch.tensor(ids)+ attention_mask = torch.zeros(1, width, dtype=torch.long)+ attention_mask[0, : len(ids)] = 1+ return {"input_ids": input_ids, "attention_mask": attention_mask}++ def post_process_object_detection(self, outputs, threshold=0.3, target_sizes=None):+ self.postprocess_calls.append(+ {+ "threshold": threshold,+ "target_sizes": target_sizes,+ "dtypes": {name: getattr(outputs, name).dtype for name in ("pred_logits", "pred_boxes")},+ }+ )+ scores = outputs.pred_logits.sigmoid() * outputs.presence_logits.sigmoid()+ boxes = outputs.pred_boxes+ if target_sizes is not None:+ heights = torch.tensor([size[0] for size in target_sizes], dtype=boxes.dtype)+ widths = torch.tensor([size[1] for size in target_sizes], dtype=boxes.dtype)+ boxes = boxes * torch.stack([widths, heights, widths, heights], dim=1).unsqueeze(1)+ results = []+ for image_scores, image_boxes in zip(scores, boxes, strict=True):+ keep = image_scores > threshold+ results.append({"scores": image_scores[keep], "boxes": image_boxes[keep]})+ return results+++def _detections(rows: list[tuple[float, list[float]]]) -> tuple[list[float], list[list[float]]]:+ """Pad ``(logit, relative xyxy box)`` rows to ``QUERIES`` with queries that score near zero.++ Logits and box coordinates are exact in bfloat16, so the expected boxes+ and scores do not depend on rounding.+ """+ logits = [logit for logit, _ in rows] + [-10.0] * (QUERIES - len(rows))+ boxes = [box for _, box in rows] + [[0.0, 0.0, 0.125, 0.125]] * (QUERIES - len(rows))+ return logits, boxes+++def _loaded(per_label: dict[str, list[list[tuple[float, list[float]]]]] | None = None) -> Sam3Adapter:+ """A loaded adapter whose model returns ``per_label[prompt][image]`` detections.++ The forward pass reads which prompt it was given back from its token ids,+ so ``per_label`` is keyed by the lowercased prompt the model sees.+ """+ per_label = per_label or {}+ adapter = Sam3Adapter(MODEL)+ processor = _FakeProcessor()+ model = MagicMock()+ model.get_vision_features.return_value = SimpleNamespace(name="vision-embeds")++ def forward(*, vision_embeds, input_ids, attention_mask):+ tokens = input_ids[0][attention_mask[0].bool()].tolist()+ assert all(row[attention_mask[0].bool()].tolist() == tokens for row in input_ids)+ prompt = processor.prompts[tuple(tokens)]+ batch = per_label.get(prompt, [[] for _ in range(input_ids.shape[0])])+ rows = [_detections(image_rows) for image_rows in batch]+ return SimpleNamespace(+ pred_logits=torch.tensor([logits for logits, _ in rows], dtype=torch.bfloat16),+ pred_boxes=torch.tensor([boxes for _, boxes in rows], dtype=torch.bfloat16),+ # A certain presence (sigmoid(30) is 1.0 in float32): the score is sigmoid(logit).+ presence_logits=torch.full((len(rows), 1), 30.0, dtype=torch.bfloat16),+ pred_masks=torch.zeros(len(rows), QUERIES, 2, 2),+ )++ model.side_effect = forward+ adapter._model = model+ adapter._processor = processor+ adapter._device = "cpu"+ adapter._device_type = "cpu"+ adapter._model_dtype = torch.float32+ return adapter+++def _prepared(sizes: list[tuple[int, int]]) -> list[PreparedItem[DetectionPayload]]:+ return [+ PreparedItem(+ payload=DetectionPayload(pixel_values=torch.full((3, 4, 4), float(index)), original_size=size),+ cost=1,+ original_index=index,+ )+ for index, size in enumerate(sizes)+ ]+++def _objects(output: ExtractOutput) -> list[list[DetectedObject]]:+ assert output.objects is not None+ return output.objects+++def _png(width: int, height: int) -> bytes:+ buffer = io.BytesIO()+ Image.new("RGB", (width, height), color=(120, 40, 200)).save(buffer, format="PNG")+ return buffer.getvalue()+++# -- Contract and lifecycle -------------------------------------------------+++def test_image_json_spec_and_unloaded_errors() -> None:+ adapter = Sam3Adapter(MODEL)+ assert adapter.capabilities.inputs == ["image"]+ assert adapter.capabilities.outputs == ["json"]+ assert adapter.dims.dense is None+ assert adapter._score_threshold == DEFAULT_SCORE_THRESHOLD == 0.3+ assert adapter._compute_precision == "bfloat16"+ assert not adapter.is_loaded()+ with pytest.raises(NotImplementedError, match=r"Use extract\(\)"):+ adapter.encode([Item()], ["dense"])+ with pytest.raises(RuntimeError, match="Model not loaded"):+ adapter.extract([Item()], labels=["cat"])+++ ("device", "precision", "dtype"),+ [+ ("cpu", "bfloat16", torch.float32),+ ("cuda:0", "bfloat16", torch.bfloat16),+ ("cuda:0", "float16", torch.float16),+ ("cuda:0", "float32", torch.float32),+ ],+)+def test_load_uses_sam3_classes_revision_and_dtype(monkeypatch, device, precision, dtype) -> None:+ processor = SimpleNamespace(image_processor=SimpleNamespace(size={"height": 1008, "width": 1008}))+ model = MagicMock()+ model.config.text_config.max_position_embeddings = 32+ processor_loader = MagicMock(return_value=processor)+ model_loader = MagicMock(return_value=model)+ monkeypatch.setitem(+ sys.modules,+ "transformers",+ SimpleNamespace(+ Sam3Processor=SimpleNamespace(from_pretrained=processor_loader),+ Sam3Model=SimpleNamespace(from_pretrained=model_loader),+ ),+ )+ adapter = Sam3Adapter(MODEL, revision=REVISION, compute_precision=precision)+ adapter.load(device)++ processor_loader.assert_called_once_with(MODEL, revision=REVISION)+ model_loader.assert_called_once_with(MODEL, dtype=dtype, revision=REVISION)+ model.to.assert_called_once_with(device)+ model.eval.assert_called_once_with()+ assert adapter.is_loaded()+ assert adapter._model_dtype is dtype+ assert adapter._text_positions == 32+ preprocessor = adapter.get_preprocessor()+ assert isinstance(preprocessor, DetectionPreprocessor)+ # Photos far larger than the 1008 px model input are shrunk on the CPU first.+ assert preprocessor._max_side == 2016+++def test_load_without_transformers5_sam3_fails_before_loading_assets(monkeypatch) -> None:+ processor_loader = MagicMock()+ monkeypatch.setitem(+ sys.modules,+ "transformers",+ SimpleNamespace(Sam3Processor=SimpleNamespace(from_pretrained=processor_loader)),+ )+ with pytest.raises(RuntimeError, match="transformers5 bundle"):+ Sam3Adapter(MODEL, revision=REVISION).load("cpu")+ processor_loader.assert_not_called()+++def test_unload_clears_loaded_state() -> None:+ adapter = _loaded()+ adapter.unload()+ assert adapter._model is None+ assert adapter._processor is None+ assert adapter._preprocessor is None+ assert adapter._device is None+ assert not adapter.is_loaded()+++# -- Detection ----------------------------------------------------------------+++def test_one_vision_encoding_and_one_prompt_per_label_over_the_batch() -> None:+ adapter = _loaded(+ {+ "cat": [+ [(2.0, [0.125, 0.25, 0.5, 0.625]), (-0.5, [0.5, 0.5, 0.75, 1.0])],+ [],+ ],+ "remote control": [+ [(0.5, [0.0, 0.0, 0.25, 0.25])],+ [(3.0, [0.5, 0.25, 1.0, 0.5])],+ ],+ }+ )+ output = adapter.extract(+ [Item(), Item()],+ labels=["cat", "remote control"],+ prepared_items=_prepared([(640, 480), (200, 400)]),+ )++ model = adapter._model+ model.get_vision_features.assert_called_once()+ pixel_values = model.get_vision_features.call_args.kwargs["pixel_values"]+ assert pixel_values.shape == (2, 3, 4, 4)+ assert pixel_values.dtype == torch.float32+ assert model.call_count == 2+ vision_embeds = model.get_vision_features.return_value+ for call in model.call_args_list:+ assert call.kwargs["vision_embeds"] is vision_embeds+ # The label's tokens are repeated for every image in the batch.+ assert call.kwargs["input_ids"].shape == (2, 32)+ assert torch.equal(call.kwargs["input_ids"][0], call.kwargs["input_ids"][1])+ assert call.kwargs["attention_mask"].shape == (2, 32)+ assert adapter._processor.texts == ["cat", "remote control"]+ for call in adapter._processor.postprocess_calls:+ assert call["threshold"] == 0.3+ assert call["target_sizes"] == [(480, 640), (400, 200)]+ # Scores are computed in float32 even when the forward pass ran in bfloat16.+ assert call["dtypes"] == {"pred_logits": torch.float32, "pred_boxes": torch.float32}++ assert output.entities == [[], []]+ first, second = _objects(output)+ # All labels' detections for an image, highest score first.+ assert [(found["label"], found["bbox"]) for found in first] == [+ ("cat", [80, 120, 240, 180]),+ ("remote control", [0, 0, 160, 120]),+ ("cat", [320, 240, 160, 240]),+ ]+ assert [found["score"] for found in first] == pytest.approx([_score(2.0), _score(0.5), _score(-0.5)])+ assert second == [{"label": "remote control", "score": pytest.approx(_score(3.0)), "bbox": [100, 100, 100, 100]}]+++def test_default_threshold_and_request_options_that_override_it() -> None:+ # sigmoid(-0.84375) is 0.3007 and sigmoid(-1) is 0.2689: either side of the 0.3 default.+ rows = {"dog": [[(-0.84375, [0.0, 0.0, 0.5, 0.5]), (-1.0, [0.5, 0.5, 1.0, 1.0])]]}++ default = _loaded(rows).extract([Item()], labels=["dog"], prepared_items=_prepared([(100, 100)]))+ assert [found["score"] for found in _objects(default)[0]] == pytest.approx([_score(-0.84375)])++ lower = _loaded(rows).extract(+ [Item()], labels=["dog"], options={"score_threshold": 0.2}, prepared_items=_prepared([(100, 100)])+ )+ assert [found["score"] for found in _objects(lower)[0]] == pytest.approx([_score(-0.84375), _score(-1.0)])++ alias = _loaded(rows).extract(+ [Item()], labels=["dog"], options={"threshold": 0.5}, prepared_items=_prepared([(100, 100)])+ )+ assert alias.objects == [[]]++ loadtime = Sam3Adapter(MODEL, score_threshold=0.0)+ assert loadtime._score_threshold == 0.0+++def test_labels_are_returned_verbatim_prompted_stripped_and_deduplicated() -> None:+ adapter = _loaded({"traffic light": [[(1.5, [0.0, 0.0, 1.0, 1.0])]]})+ output = adapter.extract(+ [Item()],+ labels=[" traffic light ", " traffic light "],+ prepared_items=_prepared([(10, 20)]),+ )+ assert adapter._processor.texts == ["traffic light"]+ assert adapter._model.call_count == 1+ assert output.objects == [+ [{"label": " traffic light ", "score": pytest.approx(_score(1.5)), "bbox": [0, 0, 10, 20]}]+ ]+++def test_labels_that_tokenize_identically_are_prompted_once_under_the_first_label() -> None:+ adapter = _loaded({"cat": [[(2.0, [0.0, 0.0, 0.5, 0.5])]], "remote control": [[(1.0, [0.5, 0.5, 1.0, 1.0])]]})+ output = adapter.extract(+ [Item()],+ labels=["Cat", "cat", "remote control", "CAT ", "Remote Control"],+ prepared_items=_prepared([(100, 100)]),+ )+ # Every label is tokenized (and checked for length); each distinct model input runs once.+ assert adapter._processor.texts == ["Cat", "cat", "remote control", "CAT", "Remote Control"]+ assert adapter._model.call_count == 2+ assert _objects(output) == [+ [+ {"label": "Cat", "score": pytest.approx(_score(2.0)), "bbox": [0, 0, 50, 50]},+ {"label": "remote control", "score": pytest.approx(_score(1.0)), "bbox": [50, 50, 50, 50]},+ ]+ ]+++def test_no_detections_and_missing_images_return_empty_objects() -> None:+ adapter = _loaded()+ output = adapter.extract([Item(), Item()], labels=["zebra"], prepared_items=_prepared([(64, 64), (32, 32)]))+ assert output.objects == [[], []]+ assert output.entities == [[], []]++ no_payloads = [SimpleNamespace(payload=None), SimpleNamespace(payload=None)]+ adapter = _loaded()+ output = adapter.extract([Item(), Item()], labels=["zebra"], prepared_items=no_payloads)+ assert output.objects == [[], []]+ adapter._model.get_vision_features.assert_not_called()++ adapter = _loaded()+ output = adapter.extract([Item(), Item(images=[])], labels=["zebra"])+ assert output.objects == [[], []]+ adapter._model.get_vision_features.assert_not_called()+++def test_prepared_items_without_payload_keep_their_positions() -> None:+ adapter = _loaded({"cup": [[(1.0, [0.0, 0.0, 0.5, 0.5])]]})+ prepared: list[Any] = [SimpleNamespace(payload=None), *_prepared([(50, 50)])]+ output = adapter.extract([Item(), Item()], labels=["cup"], prepared_items=prepared)+ assert output.objects == [[], [{"label": "cup", "score": pytest.approx(_score(1.0)), "bbox": [0, 0, 25, 25]}]]+++def test_inline_images_use_the_image_processor_and_their_own_sizes() -> None:+ adapter = _loaded({"square": [[(2.0, [0.25, 0.5, 0.75, 1.0])]]})+ adapter._processor.image_processor.return_value = {"pixel_values": torch.zeros(1, 3, 4, 4)}+ output = adapter.extract([Item(images=[{"data": _png(300, 120), "format": "png"}])], labels=["square"])++ image_call = adapter._processor.image_processor.call_args+ assert [image.size for image in image_call.kwargs["images"]] == [(300, 120)]+ assert image_call.kwargs["return_tensors"] == "pt"+ assert adapter._processor.postprocess_calls[0]["target_sizes"] == [(120, 300)]+ assert output.objects == [[{"label": "square", "score": pytest.approx(_score(2.0)), "bbox": [75, 60, 150, 60]}]]+++# -- Box conversion -----------------------------------------------------------+++def test_boxes_become_clipped_integer_xywh() -> None:+ result = {+ "boxes": torch.tensor(+ [+ [10.9, 20.1, 110.7, 220.8],+ [-3.5, -0.2, 40.2, 30.9],+ [600.0, 470.0, 655.0, 490.0],+ [700.0, 500.0, 720.0, 510.0],+ ]+ ),+ "scores": torch.tensor([0.9, 0.8, 0.7, 0.6]),+ }+ objects = _to_objects(result, "box", (640, 480))+ assert [found["bbox"] for found in objects] == [+ [10, 20, 99, 200],+ [0, 0, 40, 30],+ [600, 470, 40, 10],+ [640, 480, 0, 0],+ ]+ for found in objects:+ x, y, w, h = found["bbox"]+ assert all(isinstance(value, int) for value in found["bbox"])+ assert x >= 0+ assert x + w <= 640+ assert y >= 0+ assert y + h <= 480+ assert [found["score"] for found in objects] == pytest.approx([0.9, 0.8, 0.7, 0.6])+ assert all(found["label"] == "box" for found in objects)+++def test_empty_post_processed_result_has_no_objects() -> None:+ assert _to_objects({"boxes": torch.empty(0, 4), "scores": torch.empty(0)}, "box", (10, 10)) == []+++# -- Error paths ----------------------------------------------------------------+++ ("labels", "message"),+ [+ (None, "requires labels"),+ ([], "requires labels"),+ (["cat", " "], "non-empty strings"),+ (["cat", 7], "non-empty strings"),+ ],+)+def test_invalid_labels_never_reach_the_model(labels, message) -> None:+ adapter = _loaded()+ with pytest.raises(ValueError, match=message):+ adapter.extract([Item()], labels=labels, prepared_items=_prepared([(10, 10)]))+ adapter._model.get_vision_features.assert_not_called()+ adapter._model.assert_not_called()+++ "options",+ [+ {"score_threshold": True},+ {"score_threshold": "0.3"},+ {"score_threshold": float("nan")},+ {"score_threshold": -0.1},+ {"score_threshold": 1.5},+ {"threshold": None},+ ],+)+def test_invalid_threshold_never_reaches_the_model(options) -> None:+ adapter = _loaded()+ with pytest.raises(ValueError, match="score_threshold must be"):+ adapter.extract([Item()], labels=["cat"], options=options, prepared_items=_prepared([(10, 10)]))+ adapter._model.get_vision_features.assert_not_called()++[email protected]("value", [True, -1, 2.0, float("inf")])+def test_invalid_loadtime_threshold_is_rejected(value) -> None:+ with pytest.raises(ValueError, match="score_threshold must be"):+ Sam3Adapter(MODEL, score_threshold=value)+++def test_label_longer_than_the_text_encoder_is_rejected_before_any_image_work() -> None:+ adapter = _loaded()+ long_label = " ".join(["very"] * 40) + " long object"+ with pytest.raises(ValueError, match=r"is 44 tokens; the text encoder takes at most 32"):+ adapter.extract([Item()], labels=["cat", long_label], prepared_items=_prepared([(10, 10)]))+ adapter._model.get_vision_features.assert_not_called()+ adapter._model.assert_not_called()+++def test_undecodable_inline_image_names_the_item() -> None:+ adapter = _loaded()+ items = [Item(), Item(images=[{"data": b"not an image", "format": "png"}])]+ with pytest.raises(InvalidMediaError, match=r"at `\$\.items\[1\]\.images\[0\]\.data`"):+ adapter.extract(items, labels=["cat"])diff --git a/packages/sie_server/tests/config/test_sam3.py b/packages/sie_server/tests/config/test_sam3.pynew file mode 100644index 000000000..4c93a7c5c--- /dev/null+++ b/packages/sie_server/tests/config/test_sam3.py@@ -0,0 +1,48 @@+"""SAM 3 model identity, shipped detection threshold and Transformers5 bundle routing."""++from pathlib import Path++import yaml+from sie_sdk.bundle_utils import match_bundle_models+from sie_server.adapters.sam3.adapter import DEFAULT_SCORE_THRESHOLD+from sie_server.core.loader import load_model_configs, resolve_adapter_class++SERVER = Path(__file__).resolve().parents[2]+MODELS = SERVER / "models"+BUNDLES = SERVER / "bundles"+MODEL_ID = "facebook/sam3"+REVISION = "3c879f39826c281e95690f02c7821c4de09afae7"+++def test_sam3_descriptor_is_pinned_image_only_extract() -> None:+ config = load_model_configs(MODELS)[MODEL_ID]+ assert config.sie_id == config.hf_id == MODEL_ID+ assert config.hf_revision == REVISION+ assert config.inputs.image+ assert not config.inputs.text+ assert not config.inputs.audio+ assert not config.inputs.video+ assert config.tasks.extract is not None+ assert config.tasks.encode is None+ assert config.tasks.score is None+ profile = config.resolve_profile("default")+ assert profile.compute_precision == "bfloat16"+ assert profile.max_batch_tokens == 16384+ assert profile.adapter_path == "sie_server.adapters.sam3.adapter:Sam3Adapter"+ assert resolve_adapter_class(config, MODELS).__name__ == "Sam3Adapter"+++def test_sam3_ships_the_transformers_processor_default_threshold() -> None:+ profile = load_model_configs(MODELS)[MODEL_ID].resolve_profile("default")+ assert DEFAULT_SCORE_THRESHOLD == 0.3+ assert profile.loadtime == {"score_threshold": DEFAULT_SCORE_THRESHOLD}+ assert dict(profile.runtime) == {"score_threshold": DEFAULT_SCORE_THRESHOLD}+++def test_sam3_is_served_only_from_the_transformers5_bundle() -> None:+ bundle = yaml.safe_load((BUNDLES / "transformers5.yaml").read_text())+ assert "sie_server.adapters.sam3.adapter" in bundle["adapters"]+ assert MODEL_ID in match_bundle_models(BUNDLES / "transformers5.yaml", MODELS)+ default = yaml.safe_load((BUNDLES / "default.yaml").read_text())+ assert "sie_server.adapters.sam3.adapter" not in default["adapters"]+ assert MODEL_ID not in match_bundle_models(BUNDLES / "default.yaml", MODELS)