Skip to content

armgit / sie

Public Imported from GitHub
0

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

perf(sam3): skip the unused mask decoder, encode images one at a time and cache label encodings (#643)

svonava06bc893a2567
diff --git a/packages/sie_server/src/sie_server/adapters/sam3/adapter.py b/packages/sie_server/src/sie_server/adapters/sam3/adapter.py
index ed05e8ee0..618d03d26 100644
--- a/packages/sie_server/src/sie_server/adapters/sam3/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/sam3/adapter.py
@@ -2,17 +2,20 @@
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.
+prompt. The adapter encodes each image once, encodes each label once (and
+keeps recent label encodings), then runs the detector for every
+(image, label) pair against those shared features, ``max_pairs_per_forward``
+pairs per forward pass.
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).
+return masks, so it does not compute them: the mask decoder is replaced by a
+stub at load. Boxes and scores come from the detector before the mask decoder,
+so they are unchanged. 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``).
@@ -31,7 +34,9 @@ from __future__ import annotations
import logging
import math
+from collections import OrderedDict
from pathlib import Path
+from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, ClassVar
import torch
@@ -58,9 +63,14 @@ DEFAULT_SCORE_THRESHOLD = 0.3
_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")
+# (image, label) pairs in one detector forward pass. One pair per pass is the
+# per-label forward of a single image exactly, so a request's boxes and scores are
+# bit-identical to running each label alone. More pairs per pass (the loadtime
+# option max_pairs_per_forward) run faster under concurrency, but bfloat16 GEMMs
+# over a different batch shape move scores slightly, as batching images does.
+_MAX_PAIRS_PER_FORWARD = 1
+# Label encodings kept between requests (each 32 x 256 values; labels repeat across images).
+_TEXT_CACHE_SIZE = 1024
_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"
@@ -104,13 +114,16 @@ def _image_side(image_processor: Any) -> int:
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
+class _NoMasks(torch.nn.Module):
+ """Stands in for ``Sam3Model.mask_decoder``: masks are not returned, so they are not computed.
+
+ ``Sam3Model.forward`` calls the mask decoder after the boxes, logits and
+ presence scores are final, so skipping it leaves those outputs unchanged.
+ """
+
+ def forward(self, *args: Any, **kwargs: Any) -> SimpleNamespace:
+ del args, kwargs
+ return SimpleNamespace(pred_masks=None, semantic_seg=None, attentions=None)
def _to_objects(result: dict[str, Any], label: str, size: tuple[int, int]) -> list[DetectedObject]:
@@ -155,6 +168,7 @@ class Sam3Adapter(BaseAdapter):
"_compute_precision",
"_device",
"_device_type",
+ "_max_pairs_per_forward",
"_model",
"_model_dtype",
"_model_name_or_path",
@@ -162,6 +176,7 @@ class Sam3Adapter(BaseAdapter):
"_processor",
"_revision",
"_score_threshold",
+ "_text_cache",
"_text_positions",
)
@@ -172,6 +187,7 @@ class Sam3Adapter(BaseAdapter):
compute_precision: ComputePrecision = "bfloat16",
revision: str | None = None,
score_threshold: float = DEFAULT_SCORE_THRESHOLD,
+ max_pairs_per_forward: int = _MAX_PAIRS_PER_FORWARD,
**kwargs: Any,
) -> None:
del kwargs
@@ -179,6 +195,14 @@ class Sam3Adapter(BaseAdapter):
self._compute_precision = compute_precision
self._revision = revision
self._score_threshold = _score_threshold(score_threshold)
+ if (
+ isinstance(max_pairs_per_forward, bool)
+ or not isinstance(max_pairs_per_forward, int)
+ or max_pairs_per_forward < 1
+ ):
+ msg = "max_pairs_per_forward must be a positive integer"
+ raise ValueError(msg)
+ self._max_pairs_per_forward = max_pairs_per_forward
self._model: Any = None
self._processor: Any = None
@@ -187,6 +211,8 @@ class Sam3Adapter(BaseAdapter):
self._device_type: str = "cpu"
self._model_dtype: torch.dtype = torch.float32
self._text_positions: int = _DEFAULT_TEXT_POSITIONS
+ # Prompt token ids -> the text encoder's output for that prompt ([1, 32, 256]).
+ self._text_cache: OrderedDict[tuple[int, ...], torch.Tensor] = OrderedDict()
def load(self, device: str) -> None:
import transformers
@@ -210,7 +236,9 @@ class Sam3Adapter(BaseAdapter):
self._model = model_class.from_pretrained(self._model_name_or_path, dtype=dtype, **shared_kwargs)
self._model.to(device)
self._model.eval()
+ self._model.mask_decoder = _NoMasks()
self._model_dtype = dtype
+ self._text_cache.clear()
text_config = getattr(self._model.config, "text_config", None)
positions = getattr(text_config, "max_position_embeddings", None)
@@ -342,7 +370,13 @@ class Sam3Adapter(BaseAdapter):
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.
+ """Detect each label in a batch of images, encoding each image once.
+
+ Every (image, label) pair goes through the detector, up to
+ ``max_pairs_per_forward`` pairs per pass, with the image's vision
+ features and the label's text features. Scores and boxes are computed
+ as ``Sam3Processor.post_process_object_detection`` computes them, in
+ float32, and copied to the host once.
Args:
pixel_values: Processed images ``[B, 3, H, W]``.
@@ -354,12 +388,12 @@ class Sam3Adapter(BaseAdapter):
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)]
+ pairs = [
+ (label_index, image_index) for label_index in range(len(text_inputs)) for image_index in range(batch_size)
+ ]
with (
torch.inference_mode(),
@@ -369,25 +403,80 @@ class Sam3Adapter(BaseAdapter):
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),
+ # Each image is encoded on its own. Images share nothing in the vision
+ # encoder, and a batch of one keeps every convolution at one input shape,
+ # so cuDNN's autotuning (enabled server-wide) runs once rather than again
+ # for every new batch size. The detector reads one FPN level, the last
+ # one Sam3Model.forward keeps (the others feed only the mask decoder).
+ features_parts: list[torch.Tensor] = []
+ positions_parts: list[torch.Tensor] = []
+ vision_outputs: list[type] = []
+ for index in range(batch_size):
+ vision = model.get_vision_features(
+ pixel_values=pixel_values[index : index + 1].to(device, dtype=self._model_dtype)
)
- results = processor.post_process_object_detection(
- _scored_in_float32(outputs),
- threshold=score_threshold,
- target_sizes=target_sizes,
+ features_parts.append(vision.fpn_hidden_states[:-1][-1])
+ positions_parts.append(vision.fpn_position_encoding[:-1][-1])
+ vision_outputs.append(type(vision))
+ # A pair's vision input: its image's features at that level. Sam3Model.forward drops the
+ # last entry of each tuple and reads the one before it, so (features, None) is that level.
+ vision_output = vision_outputs[0]
+ features = torch.cat(features_parts)
+ positions = torch.cat(positions_parts)
+ text_embeds = torch.cat([self._text_embedding(ids, mask) for _, ids, mask in text_inputs])
+ text_masks = torch.cat([mask for _, _, mask in text_inputs]).to(device)
+ # post_process_object_detection scales relative xyxy boxes by (width, height, width, height).
+ scale = torch.tensor(
+ [[width, height, width, height] for width, height in original_sizes], dtype=torch.float32, device=device
+ )
+ scores_parts: list[torch.Tensor] = []
+ boxes_parts: list[torch.Tensor] = []
+ for start in range(0, len(pairs), self._max_pairs_per_forward):
+ chunk = pairs[start : start + self._max_pairs_per_forward]
+ label_rows = torch.tensor([label_index for label_index, _ in chunk], device=device)
+ image_rows = torch.tensor([image_index for _, image_index in chunk], device=device)
+ outputs = model(
+ vision_embeds=vision_output(
+ fpn_hidden_states=(features[image_rows], None),
+ fpn_position_encoding=(positions[image_rows], None),
+ ),
+ text_embeds=SimpleNamespace(pooler_output=text_embeds[label_rows]),
+ attention_mask=text_masks[label_rows],
)
- for index, result in enumerate(results):
- detections[index].extend(_to_objects(result, label, original_sizes[index]))
+ scores = outputs.pred_logits.float().sigmoid()
+ if outputs.presence_logits is not None:
+ scores = scores * outputs.presence_logits.float().sigmoid()
+ scores_parts.append(scores)
+ boxes_parts.append(outputs.pred_boxes.float() * scale[image_rows].unsqueeze(1))
+ all_scores = torch.cat(scores_parts).cpu()
+ all_boxes = torch.cat(boxes_parts).cpu()
+
+ for row, (label_index, image_index) in enumerate(pairs):
+ keep = all_scores[row] > score_threshold
+ result = {"scores": all_scores[row][keep], "boxes": all_boxes[row][keep]}
+ detections[image_index].extend(
+ _to_objects(result, text_inputs[label_index][0], original_sizes[image_index])
+ )
for found in detections:
found.sort(key=lambda detected: detected["score"], reverse=True)
return detections
+ def _text_embedding(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ """The text encoder's output for one tokenized label (``[1, seq_len, hidden]``), cached by token ids."""
+ key = tuple(input_ids[0].tolist()) + tuple(attention_mask[0].tolist())
+ cached = self._text_cache.get(key)
+ if cached is not None:
+ self._text_cache.move_to_end(key)
+ return cached
+ encoded = self._model.get_text_features(
+ input_ids=input_ids.to(self._device), attention_mask=attention_mask.to(self._device), return_dict=True
+ ).pooler_output
+ self._text_cache[key] = encoded
+ if len(self._text_cache) > _TEXT_CACHE_SIZE:
+ self._text_cache.popitem(last=False)
+ return encoded
+
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.
diff --git a/packages/sie_server/tests/adapters/test_sam3.py b/packages/sie_server/tests/adapters/test_sam3.py
index 9d86b4590..408e41e5d 100644
--- a/packages/sie_server/tests/adapters/test_sam3.py
+++ b/packages/sie_server/tests/adapters/test_sam3.py
@@ -1,10 +1,10 @@
"""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)``.
+Pretrained loading and the model forward pass are mocked. The adapter scores
+detections as Transformers 5.19's
+``Sam3ImageProcessor.post_process_object_detection`` does: score =
+sigmoid(logit) x sigmoid(presence), kept when strictly above the threshold, and
+relative ``xyxy`` boxes scaled to the image's ``(width, height)``.
"""
from __future__ import annotations
@@ -18,7 +18,13 @@ 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.adapters.sam3.adapter import (
+ _MAX_PAIRS_PER_FORWARD,
+ DEFAULT_SCORE_THRESHOLD,
+ Sam3Adapter,
+ _NoMasks,
+ _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
@@ -36,7 +42,7 @@ def _score(logit: float) -> float:
class _FakeProcessor:
- """Sam3Processor's text tokenization and box post-processing, without assets."""
+ """Sam3Processor's text tokenization, without assets."""
START, END = 49406, 49407
@@ -44,7 +50,6 @@ class _FakeProcessor:
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] = {}
@@ -62,26 +67,6 @@ class _FakeProcessor:
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.
@@ -97,29 +82,51 @@ def _detections(rows: list[tuple[float, list[float]]]) -> tuple[list[float], lis
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.
+ The fake text encoder returns a label's token ids as its features and the
+ fake vision encoder returns each image's index as its features, so every
+ row of a detector forward pass can be traced back to its (image, label)
+ pair. ``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]
+ adapter.forwards = [] # type: ignore[attr-defined]
+
+ def vision(*, pixel_values):
+ # _prepared fills image i's pixels with i, so the features carry each image's index.
+ index = pixel_values[:, 0, 0, 0].float().view(-1, 1)
+ # Four FPN levels as Sam3VisionModel returns them; the detector reads the third.
+ levels = (torch.full_like(index, -1.0), torch.full_like(index, -2.0), index, torch.full_like(index, -4.0))
+ return SimpleNamespace(fpn_hidden_states=levels, fpn_position_encoding=levels)
+
+ def text(*, input_ids, attention_mask, return_dict):
+ assert return_dict is True
+ assert input_ids.shape[0] == attention_mask.shape[0] == 1
+ return SimpleNamespace(pooler_output=input_ids.float().unsqueeze(-1))
+
+ def forward(*, vision_embeds, text_embeds, attention_mask):
+ features, last = vision_embeds.fpn_hidden_states
+ assert last is None
+ images = [int(value) for value in features[:, 0].tolist()]
+ rows = []
+ for row, image in enumerate(images):
+ ids = text_embeds.pooler_output[row, :, 0].long()
+ tokens = ids[attention_mask[row].bool()].tolist()
+ prompt = processor.prompts[tuple(tokens)]
+ batch = per_label.get(prompt, [])
+ rows.append(_detections(batch[image] if image < len(batch) else []))
+ adapter.forwards.append(len(images)) # type: ignore[attr-defined]
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),
+ pred_masks=None,
)
+ model.get_vision_features.side_effect = vision
+ model.get_text_features.side_effect = text
model.side_effect = forward
adapter._model = model
adapter._processor = processor
@@ -201,6 +208,9 @@ def test_load_uses_sam3_classes_revision_and_dtype(monkeypatch, device, precisio
assert adapter.is_loaded()
assert adapter._model_dtype is dtype
assert adapter._text_positions == 32
+ # Masks are not returned, so the mask decoder is not run.
+ assert isinstance(model.mask_decoder, _NoMasks)
+ assert model.mask_decoder(decoder_queries=None).pred_masks is None
preprocessor = adapter.get_preprocessor()
assert isinstance(preprocessor, DetectionPreprocessor)
# Photos far larger than the 1008 px model input are shrunk on the CPU first.
@@ -232,7 +242,7 @@ def test_unload_clears_loaded_state() -> None:
# -- Detection ----------------------------------------------------------------
-def test_one_vision_encoding_and_one_prompt_per_label_over_the_batch() -> None:
+def test_one_encoding_per_image_and_label_and_one_pass_per_pair() -> None:
adapter = _loaded(
{
"cat": [
@@ -252,24 +262,18 @@ def test_one_vision_encoding_and_one_prompt_per_label_over_the_batch() -> None:
)
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)
+ # Each image is encoded once, on its own.
+ assert model.get_vision_features.call_count == 2
+ for call in model.get_vision_features.call_args_list:
+ assert call.kwargs["pixel_values"].shape == (1, 3, 4, 4)
+ assert call.kwargs["pixel_values"].dtype == torch.float32
+ # Each label is encoded once, and each (image, label) pair runs the detector once.
+ assert model.get_text_features.call_count == 2
+ assert adapter.forwards == [1, 1, 1, 1]
+ call = model.call_args
+ assert call.kwargs["attention_mask"].shape == (1, 32)
+ assert call.kwargs["text_embeds"].pooler_output.shape == (1, 32, 1)
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)
@@ -283,6 +287,34 @@ def test_one_vision_encoding_and_one_prompt_per_label_over_the_batch() -> None:
assert second == [{"label": "remote control", "score": pytest.approx(_score(3.0)), "bbox": [100, 100, 100, 100]}]
[email protected]("pairs_per_forward", [_MAX_PAIRS_PER_FORWARD, 32])
+def test_pairs_are_split_into_forward_passes_and_keep_their_detections(pairs_per_forward: int) -> None:
+ labels = [f"thing{index}" for index in range(9)]
+ images = 4
+ per_label = {label: [[(1.0 + image, [0.0, 0.0, 0.5, 0.5])] for image in range(images)] for label in labels}
+ adapter = _loaded(per_label)
+ adapter._max_pairs_per_forward = pairs_per_forward
+ output = adapter.extract(
+ [Item() for _ in range(images)], labels=labels, prepared_items=_prepared([(100, 100)] * images)
+ )
+
+ pairs = len(labels) * images
+ full, rest = divmod(pairs, pairs_per_forward)
+ assert adapter.forwards == [pairs_per_forward] * full + ([rest] if rest else [])
+ for image, found in enumerate(_objects(output)):
+ assert [item["label"] for item in found] == labels
+ assert [item["score"] for item in found] == pytest.approx([_score(1.0 + image)] * len(labels))
+
+
+def test_label_encodings_are_reused_across_requests() -> None:
+ adapter = _loaded({"cat": [[(2.0, [0.0, 0.0, 0.5, 0.5])]]})
+ first = adapter.extract([Item()], labels=["cat", "dog"], prepared_items=_prepared([(10, 10)]))
+ second = adapter.extract([Item()], labels=["dog", "cat"], prepared_items=_prepared([(10, 10)]))
+
+ assert adapter._model.get_text_features.call_count == 2
+ assert first.objects == second.objects
+
+
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])]]}
@@ -312,7 +344,8 @@ def test_labels_are_returned_verbatim_prompted_stripped_and_deduplicated() -> No
prepared_items=_prepared([(10, 20)]),
)
assert adapter._processor.texts == ["traffic light"]
- assert adapter._model.call_count == 1
+ assert adapter._model.get_text_features.call_count == 1
+ assert adapter.forwards == [1]
assert output.objects == [
[{"label": " traffic light ", "score": pytest.approx(_score(1.5)), "bbox": [0, 0, 10, 20]}]
]
@@ -327,7 +360,8 @@ def test_labels_that_tokenize_identically_are_prompted_once_under_the_first_labe
)
# 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 adapter._model.get_text_features.call_count == 2
+ assert adapter.forwards == [1, 1]
assert _objects(output) == [
[
{"label": "Cat", "score": pytest.approx(_score(2.0)), "bbox": [0, 0, 50, 50]},
@@ -369,7 +403,6 @@ def test_inline_images_use_the_image_processor_and_their_own_sizes() -> None:
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]}]]
@@ -448,6 +481,12 @@ def test_invalid_threshold_never_reaches_the_model(options) -> None:
adapter._model.get_vision_features.assert_not_called()
[email protected]("value", [0, -1, True, 2.0])
+def test_invalid_pairs_per_forward_is_rejected(value) -> None:
+ with pytest.raises(ValueError, match="max_pairs_per_forward must be a positive integer"):
+ Sam3Adapter(MODEL, max_pairs_per_forward=value)
+
+
@pytest.mark.parametrize("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"):