375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670 | class SegmentAnything3(RoboflowCoreModel):
"""SAM3 wrapper with a similar interface to SAM2 in this codebase."""
def __init__(
self,
*args,
model_id: str = "sam3/sam3_final",
**kwargs,
):
super().__init__(*args, model_id=model_id, **kwargs)
# Lazy import SAM3 to avoid hard dependency when disabled
from sam3 import build_sam3_image_model
checkpoint = self.cache_file("weights.pt")
bpe_path = self.cache_file("bpe_simple_vocab_16e6.txt.gz")
self.sam3_lock = threading.RLock()
self.model = build_sam3_image_model(
bpe_path=bpe_path,
checkpoint_path=checkpoint,
device="cuda" if torch.cuda.is_available() else "cpu",
load_from_HF=False,
compile=False,
)
# Preprocessing and postprocessing for PCS image path
self.transform = ComposeAPI(
transforms=[
RandomResizeAPI(
sizes=SAM3_IMAGE_SIZE,
max_size=SAM3_IMAGE_SIZE,
square=True,
consistent_transform=False,
),
ToTensorAPI(),
NormalizeAPI(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
)
self.image_size = SAM3_IMAGE_SIZE
self.task_type = "unsupervised-segmentation"
def _is_core_sam3_endpoint(self) -> bool:
return isinstance(self.endpoint, str) and self.endpoint.startswith("sam3/")
@property
def model_artifact_bucket(self):
# Use CORE bucket for base SAM3, standard INFER bucket for fine-tuned models
return CORE_MODEL_BUCKET if self._is_core_sam3_endpoint() else INFER_BUCKET
def download_weights(self) -> None:
infer_bucket_files = self.get_infer_bucket_file_list()
# Auth check aligned with chosen endpoint type
if MODELS_CACHE_AUTH_ENABLED:
endpoint_type = (
ModelEndpointType.CORE_MODEL
if self._is_core_sam3_endpoint()
else ModelEndpointType.ORT
)
if not _check_if_api_key_has_access_to_model(
api_key=self.api_key,
model_id=self.endpoint,
endpoint_type=endpoint_type,
):
raise RoboflowAPINotAuthorizedError(
f"API key {self.api_key} does not have access to model {self.endpoint}"
)
# Already cached
if are_all_files_cached(files=infer_bucket_files, model_id=self.endpoint):
return None
# S3 path works for both; keys are {endpoint}/<file>
if is_model_artefacts_bucket_available():
self.download_model_artefacts_from_s3()
return None
# API fallback
if self._is_core_sam3_endpoint():
# Base SAM3 from core_model endpoint; preserves filenames
return super().download_model_from_roboflow_api()
# Fine-tuned SAM3: use ORT endpoint to fetch weights map or model url
api_data = get_roboflow_model_data(
api_key=self.api_key,
model_id=self.endpoint,
endpoint_type=ModelEndpointType.ORT,
device_id=self.device_id,
)
ort = api_data.get("ort") if isinstance(api_data, dict) else None
if not isinstance(ort, dict):
raise ModelArtefactError("ORT response malformed for fine-tuned SAM3")
# Preferred: explicit weights map of filename -> URL
weights_map = ort.get("weights")
if isinstance(weights_map, dict) and len(weights_map) > 0:
for filename, url in weights_map.items():
resp = get_from_url(
url, json_response=False, verify_content_length=True
)
save_bytes_in_cache(
content=resp.content,
file=str(filename),
model_id=self.endpoint,
)
return None
raise ModelArtefactError(
"ORT response missing both 'weights' for fine-tuned SAM3"
)
def get_infer_bucket_file_list(self) -> List[str]:
# SAM3 weights managed by env; no core bucket artifacts
return [
"weights.pt",
"bpe_simple_vocab_16e6.txt.gz",
]
def preproc_image(self, image: InferenceRequestImage) -> np.ndarray:
np_image = load_image_rgb(image)
return np_image
@usage_collector("model")
def infer_from_request(self, request: Sam3InferenceRequest):
# with self.sam3_lock:
t1 = perf_counter()
if isinstance(request, Sam3SegmentationRequest):
# Pass strongly-typed fields to preserve Sam3Prompt objects
result = self.segment_image(
image=request.image,
image_id=request.image_id,
prompts=request.prompts,
output_prob_thresh=request.output_prob_thresh or 0.5,
format=request.format or "polygon",
nms_iou_threshold=request.nms_iou_threshold,
)
# segment_image now returns either bytes or a response model
return result
else:
raise ValueError(f"Invalid request type {type(request)}")
def segment_image(
self,
image: Optional[InferenceRequestImage],
image_id: Optional[str] = None,
prompts: Optional[List[Sam3Prompt]] = None,
output_prob_thresh: float = 0.5,
format: Optional[str] = "polygon",
nms_iou_threshold: Optional[float] = None,
**kwargs,
):
np_image = load_image_rgb(image)
h, w = np_image.shape[:2]
pil_image = Image.fromarray(np_image)
# Inference-only path; disable autograd throughout
with torch.inference_mode():
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
start_ts = perf_counter()
# TODO this can also take tensor directly instead of PIL image, so we want to avoid double conversion
# TODO: this also supports multiple images for multi batch inference
datapoint = Sam3Datapoint(
find_queries=[],
images=[Sam3ImageDP(data=pil_image, objects=[], size=(h, w))],
)
# Build prompts in order
prompts = prompts or []
# Map prompt_index -> prompt_id to retrieve results later
prompt_ids: List[int] = []
for idx, p in enumerate(prompts):
if getattr(p, "boxes", None):
q = _build_visual_query(
coco_id=idx,
h=h,
w=w,
boxes=p.boxes,
labels=p.box_labels or [],
text=p.text,
)
else:
q = _build_text_query(
coco_id=idx,
h=h,
w=w,
text=p.text,
)
datapoint.find_queries.append(q)
prompt_ids.append(idx)
# Transform and collate to BatchedDatapoint
datapoint = self.transform(datapoint)
batch = collate_fn_api(batch=[datapoint], dict_key="dummy")["dummy"]
batch = copy_data_to_device(
batch,
torch.device("cuda" if torch.cuda.is_available() else "cpu"),
non_blocking=True,
)
# Forward
output = self.model(batch)
# Calculate minimum threshold for initial filtering
# (we'll apply per-prompt thresholds later)
min_threshold = output_prob_thresh
for p in prompts:
prompt_thresh = getattr(p, "output_prob_thresh", None)
if prompt_thresh is not None:
min_threshold = min(min_threshold, prompt_thresh)
# Postprocess to original size and build per-prompt results
post = PostProcessImage(
max_dets_per_img=-1,
iou_type="segm",
use_original_sizes_box=True,
use_original_sizes_mask=True,
convert_mask_to_rle=False,
detection_threshold=float(
min_threshold if min_threshold is not None else 0.35
),
to_cpu=True,
)
processed = post.process_results(output, batch.find_metadatas)
needs_cross_prompt_nms = nms_iou_threshold is not None
prompt_results: List[Sam3PromptResult] = []
if needs_cross_prompt_nms and len(prompts) > 0:
all_masks = _collect_masks_with_per_prompt_threshold(
processed=processed,
prompt_ids=prompt_ids,
prompts=prompts,
default_threshold=output_prob_thresh,
)
if len(all_masks) > 0:
all_masks = _apply_nms_cross_prompt(all_masks, nms_iou_threshold)
regrouped = _regroup_masks_by_prompt(all_masks, len(prompts))
# Build prompt results from regrouped masks
for idx, coco_id in enumerate(prompt_ids):
has_visual = bool(getattr(prompts[idx], "boxes", None))
num_boxes = len(prompts[idx].boxes or []) if has_visual else 0
echo = Sam3PromptEcho(
prompt_index=idx,
type=("visual" if has_visual else "text"),
text=prompts[idx].text,
num_boxes=num_boxes,
)
# Convert regrouped masks to predictions
prompt_masks = regrouped.get(idx, [])
if prompt_masks:
masks_np = np.stack([m for m, _ in prompt_masks], axis=0)
scores = [s for _, s in prompt_masks]
else:
masks_np = np.zeros((0, 0, 0), dtype=np.uint8)
scores = []
preds = _masks_to_predictions(masks_np, scores, format)
prompt_results.append(
Sam3PromptResult(prompt_index=idx, echo=echo, predictions=preds)
)
else:
for idx, coco_id in enumerate(prompt_ids):
has_visual = bool(getattr(prompts[idx], "boxes", None))
num_boxes = len(prompts[idx].boxes or []) if has_visual else 0
echo = Sam3PromptEcho(
prompt_index=idx,
type=("visual" if has_visual else "text"),
text=prompts[idx].text,
num_boxes=num_boxes,
)
masks_np = _to_numpy_masks(processed[coco_id].get("masks"))
scores = list(processed[coco_id].get("scores", []))
prompt_thresh = getattr(prompts[idx], "output_prob_thresh", None)
if prompt_thresh is not None:
masks_np, scores = _filter_by_threshold(
masks_np, scores, prompt_thresh
)
preds = _masks_to_predictions(masks_np, scores, format)
prompt_results.append(
Sam3PromptResult(prompt_index=idx, echo=echo, predictions=preds)
)
return Sam3SegmentationResponse(
time=perf_counter() - start_ts, prompt_results=prompt_results
)
|