Module contents
Lesson 25 of 25Research 105 min

Visual foundation models II: promptable segmentation (SAM) and open-vocabulary recognition

Study promptable segmentation, SAM, video memory and open-vocabulary detection with measured end-to-end evaluations.

After this lesson you can

  • Explain geometric prompts, ambiguity and the SAM architecture.
  • Analyze segmentation data engines, stability and duplicate suppression.
  • Describe video memory and open-vocabulary detection pipelines.
  • Evaluate candidate masks and complete text-to-mask systems under declared protocols.

Before you start

Pointing is not naming

A person points to a spot on a shirt. Do you want the shirt, the person wearing it or the group they belong to? All three outlines can be consistent with the same point. Promptable segmentation asks for more than a class per pixel: output is conditioned on an indication such as a positive point, negative point, box or previous mask. Interpretation still depends on context and what the prompt leaves unspecified.

SAM, the original Segment Anything model, responds to geometric indications. A positive point marks a region to include; a negative point helps exclude another. A box supplies an approximate location, not an exact segmentation. The model does not directly interpret “the red mug” as a text prompt: going from words to regions requires a text-conditioned detector or another model with that capability.

For an ambiguous indication, SAM can produce three candidate masks and an estimated IoU for each. The estimate is a quality prediction that helps rank them; true IoU is known only by comparison with a reference. The regression head can return values outside [0, 1], so do not automatically treat them as calibrated probabilities. Adding points can reduce ambiguity, but multiple points do not guarantee one correct interpretation. The API also offers a single-output mode; choosing it is an interface decision, not proof of uniqueness. Nor does it necessarily select the best of the other mode’s three outputs: the original decoder uses a specific token for single output.

InteractiveIndicate a region to SAM

These are real precomputed outputs: clicks snap to the nearest available point and drawn boxes to one of three available boxes. A point cannot be both positive and negative. Use buttons to choose them by keyboard.

+

NASA photograph of Eileen Collins, a scikit-image example image. SAM ViT-B generates three masks for each combination in the lab. The score uses no reference and does not measure actual mask correctness.

Prompt
Point type
Positive point
Negative point
Candidate mask
SAM-estimated IoU0.849
Candidate1 of 3
Compare SAM ViT-B masks and scores for points and boxes already calculated on a real photograph.

The gallery contains twelve combinations calculated by the first cell: one positive point, that point with a different negative point, or one of three boxes. The Eileen Collins photograph is from NASA and comes from scikit-image’s sample images, where it is identified as public domain. Masks and scores are outputs of the cited checkpoint, not reference annotations.

Saving an image embedding is not enough to answer an arbitrary point: you also need to run a compatible decoder. A gallery with precomputed outputs can respond only to the combinations of indications it contains.

One image, many prompts

The SAM architecture separates three operations. An image ViT pretrained with MAE produces a feature map; an encoder represents points and boxes by position and type, or incorporates a mask as a dense indication; a lightweight decoder combines both inputs. Two bidirectional attention blocks update prompt tokens and image features. Output tokens feed mask prediction and the quality token produces IoU estimates. Connect this interaction to cross-attention and position to Fourier features.

This separation matters for interaction: encode the image once and reuse its representation for each new indication. If the image or its preprocessing changes, recalculate it. In the paper, the combined prompt encoder and decoder take approximately 50 ms on a browser CPU with the embedding already computed. That published figure excludes the encoder and does not promise that latency on your machine; resolution, load, transfer and compilation also matter.

To measure your implementation, synchronize CUDA before and after each stage, separate initial loading and warm-up runs, and compare the encoder with multiple prompts on the same embedding. Batching or using different images changes the calculation. Reducing resolution, using a smaller variant or offloading stages to CPU can reduce memory, but also changes cost and possibly masks: checkpoint file size does not establish that it fits in 8 GB.

Building data with the model in the loop

The segmentation data engine alternates model and annotation. In the first phase of SAM, section 4, people corrected model proposals: 4.3 million masks were collected on 120,000 images and average time per mask fell from 34 to 14 seconds during that phase. Model and procedure changed in several ways, so those endpoints alone do not identify one cause.

In the semi-automatic phase, the model proposed reliable masks and annotators added omitted objects. Another 5.9 million masks were obtained on 180,000 images. Average manual annotation time returned to 34 seconds per mask, excluding automatic ones: remaining cases were harder. Finally, the automatic phase produced proposals from a grid of points, filtered quality and stability, and removed duplicates. SA-1B contains approximately 1.1 billion masks (1.100 million in the source’s notation) in 11 million images. The 99.1% refers to the automatic share among masks produced by the engine; the published SA-1B dataset contains automatic masks.

In a sample of 500 images with about 50,000 masks, 94% of automatic-mask and professional-correction pairs exceeded 90% IoU. This is a comparison under that procedure, not a guarantee of completeness or performance on industrial parts or medical images. For your own dataset reserve independent examples, review difficult categories and capture conditions, and record both missed objects and false proposals.

InteractiveA hypothetical data engine

Hypothetical simulation, not a SAM measurement. Quality is an invented index for exploring model rules, not IoU or a validated metric. Automatic counts are expected values and can be fractional.

Quality index after each round

0.00.51.0123456
  • Assumed quality
  • Selected round

Rounds 1 and 2: manual work only. Rounds 3 to 6: manual work and automatic proposals. This simplified sequence does not reproduce the real SA-1B phases or rates.

RoundManualAcceptedAssumed usefulFinal quality
14000.00.00.509
24000.00.00.598
3400500.0449.70.737
4400500.0467.10.830
5400500.0478.70.890
6 · selected400500.0486.30.929

In round 6, quality moves from 0.890 to 0.929. After six rounds the allocated budget is 20 h; leftover seconds in each allocation are discarded. Every manual mask is assumed useful, and accepting proposals consumes no human time.

Rules, not empirical results. Hours are divided equally: M = floor(hours × 3600 / (6 × seconds)). From round 3, 1000 proposals per round are assumed with score s uniformly distributed in [0, 1]: A = 1000 × (1 − threshold). The probability of usefulness given s is assumed to be q + (1 − q) × s. Averaged over accepted proposals, assumed precision is P = q + (1 − q) × (1 + threshold) / 2 and the expected useful number is U = A × P. Before round 3, A = U = 0. The index updates as new q = q + (1 − q) × (1 − exp(−(M + U)/2000)), with initial q chosen above. The cumulative count adds M + A in each round, including non-useful proposals.

Uniform distribution, the relationship between score and precision, monotonic q increase and scale 2000 are assumptions chosen for this exercise. The model excludes training cost, review, human error, duplicates, correlation and degradation from incorrect labels. It does not predict real quality or identify an optimal threshold without independent data.

20
30
0.50
0.40
6
Manual masks per round400
Expected accepted automatic masks500.0
Of these, useful under the assumption486.3
Quality after this round0.929
Masks accumulated at the end4400.0
An explicit simulation explores budget and acceptance without attributing its results to SAM.

An annotation-budget simulation can count proposals and minutes with assumed rates. Its results depend on those rates: they do not imply learned quality grows along a particular curve or that a universal takeoff point exists.

Stability and duplicates

Let LL be mask logits, tt the threshold and δ≥0\delta\ge0 a perturbation. Define A={L>t+δ}A=\{L>t+\delta\} and B={L>t−δ}B=\{L>t-\delta\}. Since A⊆BA\subseteq B, their IoU is

S=IoU⁡(A,B)=∣A∣∣B∣si ∣B∣>0.S=\operatorname{IoU}(A,B)=\frac{|A|}{|B|}\quad\text{si }|B|>0.

The official function uses strict comparison. If both masks are empty, that division yields an undefined value; any other convention must be declared. A stable mask changes little when the threshold changes, but can confidently delineate the wrong object. Examine stability, estimated score and a sample with independent references without conflating them.

The official SAM automatic generator applies non-maximum suppression, NMS, to proposal boxes. In the lab you will implement an NMS variant over masks: two outlines with similar boxes need not have the same mask IoU. Fix score, tie-breaking order, threshold and treatment of empty masks; do not present that variant as an exact reproduction of the official generator.

From frame to memory

SAM 2 extends prompting to images and video. At each frame the visual encoder produces features; attention queries a video segmentation memory and conditions the current prediction. A memory encoder combines frame features with the mask to save reusable information. The system also incorporates object representations and a presence head, useful for handling occlusions. Memory does not make reidentification after occlusion infallible: an erroneous prediction can also propagate.

The protocol described in SAM 2 retains up to six recent memories alongside conditioning frames, depending on configuration. In a correction workflow, a marked frame can even be in the future relative to the one being processed; not all uses are strictly causal. SA-V contains 50,900 videos and 642,600 mask trajectories or masklets, and its manual and automatic parts total 35.5 million frame masks. A trajectory contains multiple masks; they are not interchangeable units.

The official repository reports 38.9 million parameters and 76.5 J&F on SA-V test for SAM 2.1 Hiera-Tiny. Its 91.2 frames per second are measured on A100 with PyTorch 2.5.1, CUDA 12.4 and compilation of all components. We do not transfer that speed to an RTX 4060 or conflate SAM 2 with the later SAM 2.1 checkpoint.

InteractiveAn illustrative temporal memory

Deterministic geometric simulation, without images or SAM 2 results. The square is the true object; the cross marks the position predicted by this rule. The obstacle blocks observation when it intersects the square, even partially.

  • True object
  • Position prediction
  • Obstacle

Frame 0: initial prompt. No active prediction.

Stored frames: t=0 (12.0, 32.0). Gray in the sequence marks frames whose observation is blocked. Buttons allow jumping to each one.

Exact rules: the true center is (12 + 5t, 32 + jump), with the jump applied from t=10. At t=0 a correct prompt is given. Without additional memory the last associated position is predicted. With memory, the last two associations are stored and their mean velocity extrapolated; with only one, velocity is zero. A visible observation is associated if its Euclidean distance to the prediction is at most the radius. If more frames have elapsed since the last association than the selected duration, the memory prediction expires and cannot recover without a new prompt, represented here by resetting.

This rule does not model SAM 2 attention, encoders or masks; tracking without memory also retains its last position. There are no distractors or noise, and observations, when associated, are perfect. Extrapolation can fail after a jump or long occlusion. The simulation illustrates assumptions and does not demonstrate real recovery.

0
7
6
0
Frame0 / 15
StatusInitial prompt
Last observationt=0
Distance to predictionNot comparable
An explicit geometric model compares prediction and association without attributing its results to SAM 2.

An illustrative memory-bank representation is not a measurement of a model’s internal outputs. Seeing a trajectory drawn after an occlusion does not by itself demonstrate that SAM 2 would recover it in that sequence.

From text to boxes and boxes to masks

Open-vocabulary detection scores candidates using text descriptions instead of restricting the interface to a fixed list of training names. That does not mean recognizing any category without error. OWL-ViT starts from contrastive image-text pretraining and adapts the model to boxes and text-conditioned classification. In OWL-ViT, CLIP ViT-L/14 at 840 pixels reports 34.6 overall AP and 31.2 rare-category AP on LVIS v1.0 val, evaluating 1,203 categories with seven templates. It does not use rare-category boxes during detector training; that does not prove it never saw related concepts during pretraining.

Grounding DINO combines a DINO-family detector with visual and text encoders. Its name does not make it the self-supervised DINO studied in the previous lesson. The paper reports 52.5 COCO box AP for the Large variant under its data protocol without the COCO training set. This is not a mask measurement and does not correspond to the Tiny checkpoint. Absence of the COCO training split does not demonstrate prior absence of all its concepts either.

A practical pipeline receives image and text, obtains candidate boxes from a detector and uses each box as a geometric prompt for SAM. Keep boxes in original coordinates and apply image and coordinate resizing required by each processor. Also check rectangular images and edge boxes. Detector score, SAM estimated IoU and IoU against reference measure different things; multiplying the first two does not automatically create a calibrated probability.

To evaluate the complete system, count missed objects and false positives, not only IoU of detected boxes. State the matching rule, mean-IoU denominator, categories and object sizes; tune thresholds on validation and retain test for final evaluation. Excellent segmentation conditioned on a correct box can coexist with low system recall.

Concept prompts and limits

SAM 3 extends segmentation to concepts indicated by short noun phrases, visual examples or their combination. It introduces a concept-presence signal and combines it with proposal scores. It can locate multiple instances of a concept, but a high score does not guarantee all are found and a complex description is not always understood as intended. The repository presents SA-Co with 270,000 concepts and 75–80% of human performance under its metrics and protocols; that figure is not a universal percentage of correct masks. The paper’s human protocols also differ depending on how comparison annotations are chosen.

Terms of use differ across families. SAM and SAM 2 publish models under Apache-2.0; data may have separate terms. SAM 3 uses a different license and access to its weights is conditional: review and accept applicable terms before obtaining them. A reproducible cell should not depend on you already having that access. Pin checkpoint, revision, preprocessing and versions, and check the specific artifact’s license. Download size is not equivalent to VRAM use.

All these systems retain difficulties with thin edges, small objects, domain shift, ambiguity and missed categories. For a robot, a mask is an input to a decision, not proof that an object is graspable: three-dimensional position, occlusions and physical safety require additional sensors and validation. Models can be composed as tools and combined with dense retrieval, but composition retains component errors.

Labs

SAM as a building block on your GPU

This lab loads SAM ViT-B at a pinned revision, under Apache 2.0, and checks the weights’ SHA-256 before use. It takes a fixed image from the first test shard of Oxford-IIIT Pet, reduces its longest side to 512 pixels and encodes the image once. For each point it returns three candidates with estimated IoU and stability across two logit thresholds. If the lower-threshold mask is empty, this lab assigns zero stability and discards the candidate; this convention differs from undefined division. Selection and mask-IoU suppression form a teaching variant without crops or box suppression, not a reproduction of the original automatic generator. Timings, CUDA-synchronized after warm-up, are indicative and exclude pre- and post-processing.

You need CUDA and torch, transformers, huggingface_hub, pyarrow, pillow and numpy. The first run downloads weights and a dataset shard into the shared cache. ORYON_VERIFY_SHORT=1 uses a 3 × 3 grid to check the pipeline; normal mode uses 6 × 6. The JSON and masks are actual local outputs of your run. Publishing them requires checking attribution and photograph rights: the mirror used does not specify a license, although another Oxford-IIIT Pet mirror declares CC BY-SA 4.0.

The cell also downloads the gallery’s NASA photograph, verifies its hash and generates gallery.json with twelve prompts and three masks per prompt. Coordinates are fixed: the interface snaps clicks and boxes to those precomputed options and does not run SAM in the browser.

In the short test, nine Pet grid points produced 27 candidates; six remained after filters and mask NMS. The result depends on this image and fixed thresholds and does not measure how many actual objects were missed.

[ ]SAM: grid and reused embeddingsLocal GPU
"""SAM con codificación reutilizada y rejilla de puntos, sin entrenamiento.

Dependencias: torch, transformers, huggingface_hub, pyarrow, pillow, numpy.
Requiere CUDA; ORYON_VERIFY_SHORT=1 usa una rejilla de 3 por 3. La ejecución
normal usa 6 por 6. Descarga solo el shard indicado y los pesos oficiales.
El resultado es exploratorio; NMS de máscaras es una variante didáctica.
"""
import base64
import hashlib
import io
import json
import os
import time
import urllib.request
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import SamModel, SamProcessor

SAM = 'facebook/sam-vit-base'
REV = '70c1a07f894ebb5b307fd9eaaee97b9dfc16068f'
SAM_SHA = '892c410e496344e527255ccdcb2cb7244a609acb5389c7c4fdba1288f861c579'
DATA = 'dpdl-benchmark/oxford_iiit_pet'
DATA_REV = '18515194612b584bf54692372ac035ef773a5b41'
SHARD = 'data/test-00000-of-00003.parquet'
SHARD_SHA = 'cc4a6ca162c95b297116a4462ff7accf8a7f8ae3ce123d9be56d4c91c00380fa'
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT', 'sam_grid_output'))
torch.set_num_threads(1)
if not torch.cuda.is_available():
    raise RuntimeError('Este laboratorio requiere CUDA.')
DEVICE = torch.device('cuda')


def checked_download(repo, revision, filename, digest, repo_type='model'):
    path = hf_hub_download(repo_id=repo, repo_type=repo_type, revision=revision, filename=filename)
    h = hashlib.sha256()
    with open(path, 'rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(chunk)
    if h.hexdigest() != digest:
        raise ValueError('SHA-256 inesperado: ' + filename)
    return path


def png64(image):
    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    return base64.b64encode(buffer.getvalue()).decode('ascii')


def image_and_id():
    path = checked_download(DATA, DATA_REV, SHARD, SHARD_SHA, 'dataset')
    table = pq.ParquetFile(path)
    # La primera fila se fija antes de ejecutar el modelo.
    batch = next(table.iter_batches(batch_size=1, columns=['image']))
    raw = batch.to_pylist()[0]['image']['bytes']
    with Image.open(io.BytesIO(raw)) as im:
        image = im.convert('RGB')
    image.thumbnail((512, 512), Image.Resampling.BILINEAR)
    return image, hashlib.sha256(raw).hexdigest()


def mask_iou(a, b):
    union = int(np.logical_or(a, b).sum())
    return float(np.logical_and(a, b).sum() / union) if union else 0.0


def synced_call(fn):
    torch.cuda.synchronize()
    start = time.perf_counter()
    result = fn()
    torch.cuda.synchronize()
    return result, time.perf_counter() - start


@torch.inference_mode()
def gallery(model, processor):
    # Fotografía de NASA distribuida como imagen de ejemplo por scikit-image.
    url = 'https://raw.githubusercontent.com/scikit-image/scikit-image/v0.24.0/skimage/data/astronaut.png'
    with urllib.request.urlopen(url, timeout=30) as response:
        raw = response.read(2_000_000)
    digest = hashlib.sha256(raw).hexdigest()
    if digest != '88431cd9653ccd539741b555fb0a46b61558b301d4110412b5bc28b5e3ea6cb5':
        raise ValueError('SHA-256 inesperado de la imagen NASA')
    with Image.open(io.BytesIO(raw)) as image:
        image = image.convert('RGB')
    base = processor(images=image, return_tensors='pt')
    embedding = model.get_image_embeddings(base['pixel_values'].to(DEVICE))
    points = [[220, 115], [150, 300], [400, 430]]
    boxes = [[155, 15, 300, 185], [20, 15, 360, 510], [280, 340, 510, 510]]
    prompts = []
    for positive in range(len(points)):
        for negative in [-1, *range(len(points))]:
            if negative == positive:
                continue
            coordinates = [points[positive]] + ([] if negative == -1 else [points[negative]])
            labels = [1] + ([] if negative == -1 else [0])
            prompts.append({'kind': 'points', 'positive': positive, 'negative': negative,
                            'coordinates': coordinates, 'labels': labels})
    for index, box in enumerate(boxes):
        prompts.append({'kind': 'box', 'box_index': index, 'box': box})
    for entry in prompts:
        if entry['kind'] == 'points':
            encoded = processor(images=image, input_points=[[entry['coordinates']]],
                                input_labels=[[entry['labels']]], return_tensors='pt')
            kwargs = {'input_points': encoded['input_points'].to(DEVICE),
                      'input_labels': encoded['input_labels'].to(DEVICE)}
        else:
            encoded = processor(images=image, input_boxes=[[entry['box']]], return_tensors='pt')
            kwargs = {'input_boxes': encoded['input_boxes'].to(DEVICE)}
        output = model(image_embeddings=embedding, multimask_output=True, **kwargs)
        logits = processor.image_processor.post_process_masks(output.pred_masks.cpu(), base['original_sizes'],
                    base['reshaped_input_sizes'], binarize=False)[0][0].numpy()
        scores = output.iou_scores[0, 0].float().cpu().numpy()
        if logits.shape != (3, image.height, image.width) or not np.isfinite(logits).all() or not np.isfinite(scores).all():
            raise ValueError('Salida inesperada de la galería')
        entry['candidates'] = [{'estimated_iou': float(scores[k]),
                                'mask_png_base64': png64(Image.fromarray((logits[k] > 0).astype(np.uint8) * 255))}
                               for k in range(3)]
    result = {'model': SAM, 'revision': REV, 'weights_sha256': SAM_SHA,
              'image_url': url, 'image_sha256': digest, 'image_png_base64': png64(image),
              'width': image.width, 'height': image.height, 'points': points, 'boxes': boxes, 'prompts': prompts}
    (OUT / 'gallery.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
    print('Galería NASA:', len(prompts), 'prompts, tres candidatas por prompt; salida:', OUT / 'gallery.json')
    del embedding


@torch.inference_mode()
def main():
    image, image_sha = image_and_id()
    checked_download(SAM, REV, 'model.safetensors', SAM_SHA)
    processor = SamProcessor.from_pretrained(SAM, revision=REV, trust_remote_code=False)
    model = SamModel.from_pretrained(SAM, revision=REV, use_safetensors=True, trust_remote_code=False).to(DEVICE).eval()
    base = processor(images=image, return_tensors='pt')
    pixels = base['pixel_values'].to(DEVICE)
    # Un calentamiento de encoder y decoder. No se incluye en los tiempos.
    embedding = model.get_image_embeddings(pixels)
    warm = processor(images=image, input_points=[[[[image.width / 2, image.height / 2]]]],
                     input_labels=[[[1]]], return_tensors='pt')
    model(image_embeddings=embedding, input_points=warm['input_points'].to(DEVICE),
          input_labels=warm['input_labels'].to(DEVICE), multimask_output=True)
    torch.cuda.synchronize()
    del embedding
    embedding, encoder_seconds = synced_call(lambda: model.get_image_embeddings(pixels))
    n = 3 if SHORT else 6
    candidates = []
    decoder_seconds = []
    for y in (np.arange(n) + .5) * image.height / n:
        for x in (np.arange(n) + .5) * image.width / n:
            prompt = processor(images=image, input_points=[[[[float(x), float(y)]]]],
                               input_labels=[[[1]]], return_tensors='pt')
            points = prompt['input_points'].to(DEVICE)
            labels = prompt['input_labels'].to(DEVICE)
            result, elapsed = synced_call(lambda: model(image_embeddings=embedding, input_points=points,
                                                       input_labels=labels, multimask_output=True))
            decoder_seconds.append(elapsed)
            logits = processor.image_processor.post_process_masks(result.pred_masks.cpu(), base['original_sizes'],
                       base['reshaped_input_sizes'], binarize=False)[0][0].numpy()
            scores = result.iou_scores[0, 0].float().cpu().numpy()
            if not np.isfinite(logits).all() or not np.isfinite(scores).all():
                raise ValueError('La inferencia ha producido valores no finitos.')
            for k in range(3):
                lo, hi = logits[k] > -1.0, logits[k] > 1.0
                area = int(lo.sum())
                mask = logits[k] > 0.0
                candidates.append({'point': [float(x), float(y)], 'candidate': k,
                    'estimated_iou': float(scores[k]), 'stability': float(hi.sum() / area) if area else 0.0,
                    'mask': mask, 'pixels': int(mask.sum())})
    # Selección por puntuaciones del modelo, nunca por una máscara de referencia.
    eligible = [c for c in candidates if c['pixels'] and c['estimated_iou'] >= .75 and c['stability'] >= .90]
    eligible.sort(key=lambda c: -c['estimated_iou'])
    kept = []
    for candidate in eligible:
        if all(mask_iou(candidate['mask'], previous['mask']) <= .8 for previous in kept):
            kept.append(candidate)
    for c in candidates:
        c['kept'] = any(c is k for k in kept)
        c['mask_png_base64'] = png64(Image.fromarray(c.pop('mask').astype(np.uint8) * 255))
    OUT.mkdir(parents=True, exist_ok=True)
    payload = {'model': SAM, 'revision': REV, 'weights_sha256': SAM_SHA,
        'image_source': DATA, 'dataset_revision': DATA_REV, 'shard': SHARD, 'row': 0,
        'image_sha256': image_sha, 'image_png_base64': png64(image), 'short': SHORT,
        'protocol': 'RGB reducido al lado máximo 512; 3 máscaras por punto; estabilidad logit ±1; '
                    'filtros IoU estimada >= 0.75 y estabilidad >= 0.90; estabilidad 0 si la máscara amplia es vacía; '
                    'NMS por IoU de máscaras <= 0.8, empates por orden de generación. '
                    'Variante sin recortes ni NMS de cajas; no reproduce AutomaticMaskGenerator.',
        'encoder_seconds': encoder_seconds, 'decoder_seconds': decoder_seconds,
        'gpu': torch.cuda.get_device_name(), 'torch': torch.__version__, 'cuda': torch.version.cuda,
        'candidates': candidates}
    (OUT / 'grid.json').write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Rejilla:', n, 'x', n, 'candidatas:', len(candidates), 'retenidas:', len(kept))
    print('Encoder sincronizado:', encoder_seconds, 's; mediana decoder:', float(np.median(decoder_seconds)), 's')
    print('Tiempos orientativos bajo carga compartida; no incluyen preprocesado ni posprocesado.')
    print('Salida:', OUT / 'grid.json')
    del embedding, pixels
    gallery(model, processor)
    del model
    torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

From a text description to an evaluated mask

This second cell applies OWL-ViT, licensed Apache 2.0, to the same two text queries in each image and passes retained boxes to SAM. Both models use pinned revisions and verified weights; they load sequentially to reduce GPU use. SAM chooses the mask by estimated IoU without consulting annotation. The code evaluates available annotations from the first Oxford-IIIT Pet test shard: one main instance per image. The reference box is derived from trimap foreground, ambiguous labels are excluded when measuring the mask, and matching requires correct species and box IoU at least 0.5.

Thresholds are fixed before evaluation and not tuned on test. Hits, omissions and false positives are counted by species and size, alongside conditional and end-to-end IoU. The latter averages one IoU per image, assigns zero to a miss and does not directly penalize false positives, which are counted separately. False positives are relative to the one annotated instance: another visible but unannotated animal can count as a false positive. This exploratory evaluation of one shard is not COCO mAP or representative of the whole dataset; overlap with pretraining data has not been ruled out. ORYON_VERIFY_SHORT=1 processes four images only to check the pipeline and normal mode examines up to 100 unique images. The cell saves results locally and requires the same dependencies as the previous one; images are not incorporated into the website here.

One short run obtained four hits, no false positives or omissions, and mean IoU 0.994 on evaluable pixels. This figure excludes ambiguous annotation boundaries and comes from only four images: it verifies the calculation, not general performance or absence of pretraining overlap.

[ ]From text to evaluated masksLocal GPU
"""OWL-ViT -> cajas -> SAM sobre un subconjunto test de Oxford-IIIT Pet.

Dependencias: torch, transformers, huggingface_hub, pyarrow, pillow, numpy.
Requiere CUDA. ORYON_VERIFY_SHORT=1 procesa cuatro imágenes; el modo normal,
las primeras 100 filas únicas del shard test fijado. No ajusta los umbrales.
Los falsos positivos se definen respecto de una sola instancia anotada y
pueden incluir animales visibles que el trimap no anota. No es COCO mAP.
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import OwlViTForObjectDetection, OwlViTProcessor, SamModel, SamProcessor

DATA = 'dpdl-benchmark/oxford_iiit_pet'
DATA_REV = '18515194612b584bf54692372ac035ef773a5b41'
SHARD = 'data/test-00000-of-00003.parquet'
SHARD_SHA = 'cc4a6ca162c95b297116a4462ff7accf8a7f8ae3ce123d9be56d4c91c00380fa'
OWL = 'google/owlvit-base-patch32'
OWL_REV = 'cbc355fb364588351c5d51c7f74465e8e7ec6f72'
OWL_SHA = '4dbe0399f0b7d7c8dddf1535a98769cc30743bebc877aea681998c8d984ce52b'
SAM = 'facebook/sam-vit-base'
SAM_REV = '70c1a07f894ebb5b307fd9eaaee97b9dfc16068f'
SAM_SHA = '892c410e496344e527255ccdcb2cb7244a609acb5389c7c4fdba1288f861c579'
NAMES = ('cat', 'dog')
TEXTS = ['a photo of a cat', 'a photo of a dog']
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT', 'owlvit_sam_output'))
torch.set_num_threads(1)
if not torch.cuda.is_available():
    raise RuntimeError('Este laboratorio requiere CUDA.')
DEVICE = torch.device('cuda')


def checked_download(repo, revision, filename, digest, repo_type='model'):
    path = hf_hub_download(repo_id=repo, repo_type=repo_type, revision=revision, filename=filename)
    h = hashlib.sha256()
    with open(path, 'rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(chunk)
    if h.hexdigest() != digest:
        raise ValueError('SHA-256 inesperado: ' + filename)
    return path


def png64(image):
    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    return base64.b64encode(buffer.getvalue()).decode('ascii')


def read_rows():
    path = checked_download(DATA, DATA_REV, SHARD, SHARD_SHA, 'dataset')
    rows, seen = [], set()
    limit = 4 if SHORT else 100
    offset = 0
    for batch in pq.ParquetFile(path).iter_batches(batch_size=8, columns=['image', 'segmentation_mask', 'species']):
        for j, row in enumerate(batch.to_pylist()):
            raw = row['image']['bytes']
            digest = hashlib.sha256(raw).hexdigest()
            if digest in seen:
                continue
            seen.add(digest)
            species = int(row['species'])
            if species not in (0, 1):
                raise ValueError('Etiqueta de especie inesperada.')
            with Image.open(io.BytesIO(raw)) as im:
                image = im.convert('RGB')
            with Image.open(io.BytesIO(row['segmentation_mask']['bytes'])) as im:
                trimap = im.copy()
            if image.size != trimap.size:
                raise ValueError('La imagen y la anotación no coinciden en tamaño.')
            image.thumbnail((512, 512), Image.Resampling.BILINEAR)
            trimap = trimap.resize(image.size, Image.Resampling.NEAREST)
            labels = np.asarray(trimap)
            if not set(np.unique(labels).tolist()).issubset({1, 2, 3, 255}):
                raise ValueError('Valores inesperados en el trimap.')
            foreground = labels == 1
            yy, xx = np.nonzero(foreground)
            if not len(xx):
                raise ValueError('Primer plano vacío tras el remuestreo.')
            box = [float(xx.min()), float(yy.min()), float(xx.max() + 1), float(yy.max() + 1)]
            rows.append({'id': offset + j, 'sha256': digest, 'image': image, 'labels': labels,
                         'species': species, 'gt_box': box, 'detections': []})
            if len(rows) == limit:
                return rows
        offset += len(batch)
    raise ValueError('El shard contiene menos filas únicas de las previstas.')


def box_iou(a, b):
    w = max(0., min(a[2], b[2]) - max(a[0], b[0]))
    h = max(0., min(a[3], b[3]) - max(a[1], b[1]))
    intersection = w * h
    aa = max(0., a[2] - a[0]) * max(0., a[3] - a[1])
    bb = max(0., b[2] - b[0]) * max(0., b[3] - b[1])
    union = aa + bb - intersection
    return intersection / union if union > 0 else 0.


def size_bin(box, image):
    ratio = max(0., box[2] - box[0]) * max(0., box[3] - box[1]) / (image.width * image.height)
    return 'pequeno' if ratio < .05 else ('mediano' if ratio < .20 else 'grande')


def mask_iou(pred, labels):
    valid = (labels == 1) | (labels == 2)
    truth = labels == 1
    inter = np.logical_and(pred, truth & valid).sum()
    union = np.logical_or(pred & valid, truth & valid).sum()
    return float(inter / union) if union else 0.


def box_nms(detections):
    # Desempate por orden de salida; NMS separada por consulta.
    retained = []
    for item in sorted(detections, key=lambda d: (-d['score'], d['index'])):
        if all(item['label'] != previous['label'] or box_iou(item['box'], previous['box']) <= .5
               for previous in retained):
            retained.append(item)
    return retained[:5 if SHORT else 20]


@torch.inference_mode()
def run_detector(rows):
    checked_download(OWL, OWL_REV, 'model.safetensors', OWL_SHA)
    processor = OwlViTProcessor.from_pretrained(OWL, revision=OWL_REV, trust_remote_code=False)
    model = OwlViTForObjectDetection.from_pretrained(OWL, revision=OWL_REV, use_safetensors=True,
                                                     trust_remote_code=False).to(DEVICE).eval()
    for row in rows:
        image = row['image']
        inputs = processor(text=[TEXTS], images=image, return_tensors='pt').to(DEVICE)
        output = model(**inputs)
        result = processor.image_processor.post_process_object_detection(outputs=output, threshold=.1,
                        target_sizes=torch.tensor([[image.height, image.width]], device=DEVICE))[0]
        scores = result['scores'].cpu().tolist()
        labels = result['labels'].cpu().tolist()
        boxes = result['boxes'].cpu().tolist()
        predictions = []
        for index, (score, label, box) in enumerate(zip(scores, labels, boxes)):
            if label not in (0, 1) or not np.isfinite([score, *box]).all():
                raise ValueError('Resultado del detector inesperado.')
            box = [max(0., min(float(v), float(image.width if i % 2 == 0 else image.height)))
                   for i, v in enumerate(box)]
            if box[2] > box[0] and box[3] > box[1]:
                predictions.append({'index': index, 'label': label, 'score': float(score), 'box': box})
        row['detections'] = box_nms(predictions)
    del model, processor, inputs, output, result
    torch.cuda.empty_cache()


@torch.inference_mode()
def run_sam(rows):
    checked_download(SAM, SAM_REV, 'model.safetensors', SAM_SHA)
    processor = SamProcessor.from_pretrained(SAM, revision=SAM_REV, trust_remote_code=False)
    model = SamModel.from_pretrained(SAM, revision=SAM_REV, use_safetensors=True,
                                     trust_remote_code=False).to(DEVICE).eval()
    for row in rows:
        if not row['detections']:
            continue
        image = row['image']
        base = processor(images=image, return_tensors='pt')
        embedding = model.get_image_embeddings(base['pixel_values'].to(DEVICE))
        for detection in row['detections']:
            prompt = processor(images=image, input_boxes=[[detection['box']]], return_tensors='pt')
            result = model(image_embeddings=embedding, input_boxes=prompt['input_boxes'].to(DEVICE),
                           multimask_output=True)
            scores = result.iou_scores[0, 0].float().cpu().numpy()
            if not np.isfinite(scores).all():
                raise ValueError('IoU estimada no finita.')
            best = int(np.argmax(scores))
            logits = processor.image_processor.post_process_masks(result.pred_masks.cpu(), base['original_sizes'],
                       base['reshaped_input_sizes'], binarize=False)[0][0, best].numpy()
            if not np.isfinite(logits).all():
                raise ValueError('Máscara no finita.')
            mask = logits > 0.
            detection['estimated_iou'] = float(scores[best])
            detection['mask_iou'] = mask_iou(mask, row['labels'])
            detection['mask_png_base64'] = png64(Image.fromarray(mask.astype(np.uint8) * 255))
        del embedding
    del model, processor
    torch.cuda.empty_cache()


def summarize(rows):
    # Con una instancia GT por imagen, el primer candidato correcto de mayor
    # puntuación con IoU de caja >= 0.5 es TP; los restantes son FP.
    totals = {'tp': 0, 'fp': 0, 'fn': 0}
    by_class = {name: {'tp': 0, 'fp': 0, 'fn': 0} for name in NAMES}
    by_size = {name: {'tp': 0, 'fp': 0, 'fn': 0} for name in ('pequeno', 'mediano', 'grande')}
    conditional = []
    records = []
    for row in rows:
        image, label, gt = row['image'], row['species'], row['gt_box']
        matched = None
        for detection in row['detections']:
            detection['box_iou'] = box_iou(detection['box'], gt)
            detection['matched'] = matched is None and detection['label'] == label and detection['box_iou'] >= .5
            if detection['matched']:
                matched = detection
                totals['tp'] += 1
                by_class[NAMES[label]]['tp'] += 1
                by_size[size_bin(gt, image)]['tp'] += 1
                conditional.append(detection['mask_iou'])
            else:
                totals['fp'] += 1
                by_class[NAMES[detection['label']]]['fp'] += 1
                by_size[size_bin(detection['box'], image)]['fp'] += 1
        if matched is None:
            totals['fn'] += 1
            by_class[NAMES[label]]['fn'] += 1
            by_size[size_bin(gt, image)]['fn'] += 1
        records.append({'row': row['id'], 'sha256': row['sha256'], 'species': NAMES[label],
                        'gt_box': gt, 'gt_size': size_bin(gt, image), 'image_png_base64': png64(image),
                        'trimap_png_base64': png64(Image.fromarray(row['labels'].astype(np.uint8))),
                        'detections': row['detections'], 'matched_mask_iou': matched['mask_iou'] if matched else 0.})
    for group in [totals, *by_class.values(), *by_size.values()]:
        tp, fp, fn = group['tp'], group['fp'], group['fn']
        group['precision'] = tp / (tp + fp) if tp + fp else None
        group['recall'] = tp / (tp + fn) if tp + fn else None
    return totals, by_class, by_size, conditional, records


def main():
    rows = read_rows()
    run_detector(rows)
    run_sam(rows)
    totals, by_class, by_size, conditional, records = summarize(rows)
    payload = {'short': SHORT, 'dataset': DATA, 'dataset_revision': DATA_REV, 'shard': SHARD,
      'shard_sha256': SHARD_SHA, 'detector': OWL, 'detector_revision': OWL_REV, 'detector_sha256': OWL_SHA,
      'segmenter': SAM, 'segmenter_revision': SAM_REV, 'segmenter_sha256': SAM_SHA, 'queries': TEXTS,
      'protocol': 'Test exploratorio, primeras filas únicas, umbral detector 0.1, NMS de cajas por clase 0.5, '
        'máximo 5/20 cajas en corto/completo, correspondencia por clase e IoU de caja >= 0.5. '
        'Se elige máscara por IoU estimada del modelo; 3 y 255 ignorados al medir máscara. '
        'GT es una sola instancia; animales visibles sin anotar pueden contarse como FP. '
        'Tamaños son fracciones de área de caja: <0.05, <0.20, resto; para FP se usa su propia caja. '
        'La IoU extremo a extremo promedia una por imagen y asigna 0 a omisiones; '
        'no penaliza directamente FP, que se cuentan aparte. '
        'No se han calibrado umbrales sobre test y la muestra no representa todo el conjunto.',
      'counts': totals, 'by_class': by_class, 'by_size': by_size,
      'mean_iou_conditional': float(np.mean(conditional)) if conditional else None,
      'mean_iou_end_to_end': float(sum(conditional) / len(rows)), 'images': len(rows), 'records': records,
      'gpu': torch.cuda.get_device_name(), 'torch': torch.__version__, 'cuda': torch.version.cuda}
    OUT.mkdir(parents=True, exist_ok=True)
    (OUT / 'evaluation.json').write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
    print('TP, FP, FN:', totals)
    print('Por clase:', by_class, '\nPor tamaño:', by_size)
    print('IoU media condicionada:', payload['mean_iou_conditional'],
          'IoU extremo a extremo:', payload['mean_iou_end_to_end'])
    print('Test exploratorio; falsos positivos relativos a la única instancia anotada.')
    print('Salida:', OUT / 'evaluation.json')


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

QuizOne point, several answers
A positive point falls on a person's sleeve. Which interpretation of SAM outputs is justified?
NumericReuse the embedding
Assume serial execution without extra costs: the encoder takes 400 ms per image and the decoder 10 ms per prompt. How many milliseconds do 50 prompts on the same image take if you reuse its embedding?
NumericChange image
With the same serial assumption of 400 ms per encoder and 10 ms per decoder, how many milliseconds does one prompt on each of 50 different images take?
CodeFilter by stability
Implement stability_score(logits, threshold, offset). For a nonempty finite two-dimensional matrix and finite nonnegative offset, return the IoU of masks logits > threshold + offset and logits > threshold - offset. If the union is empty return NaN. Reject invalid inputs with ValueError. Use strict comparisons and do not substitute the model's quality score for the result.
import numpy as np

def stability_score(logits, threshold, offset):
  pass
Shift+Enter to run
QuizTwenty hours of annotation
You have 20 hours for industrial-part masks. What data-engine design supports learning and evaluation without hiding failures?
QuizChoose a system for the robot
A robot must grasp objects of 30 known types. Representative annotated data exist, alongside latency and safety constraints. Which initial decision is best justified?
Key idea
A prompt turns a visual representation into a concrete proposal, but mask quality, detection of all instances and action safety are different questions requiring their own evaluations.