SAM 3.1 Release (#503)

Summary:
SAM 3.1 multiplex video tracking for the OSS sam3 repository.

Features:
- Multiplex architecture: batch N objects into fixed-capacity buckets for efficient multi-object tracking (16 objects per bucket)
- Unified API: build_sam3_predictor(version="sam3.1") with auto-download from HuggingFace (facebook/sam3.1)
- Flash Attention 3, torch.compile support (~31 FPS compiled on H100)
- Text prompts, point prompts, box prompts, object removal, refinement
- Clean inheritance: Sam3MultiplexBase extends Sam3VideoBase
- Shared base predictor (Sam3BasePredictor) for both SAM3 and SAM3.1

Performance (H100, 5 objects, compiled):
- SAM 3.1: ~31 FPS
- Memory: ~17.7 GB

Usage:
  from sam3 import build_sam3_predictor predictor = build_sam3_predictor()  # auto-downloads SAM 3.1 from HF

Pull Request resolved: https://github.com/facebookresearch/sam3/pull/503

Reviewed By: josephgreer

Differential Revision: D98500763

Pulled By: arpitkalla

fbshipit-source-id: e2b74568f24bb4ecfb3144a4e8ec559aae6db5e8
This commit is contained in:
Arpit Kalla
2026-03-27 10:18:58 -07:00
committed by meta-codesync[bot]
parent 86ed770940
commit 9f22cb976f
79 changed files with 20772 additions and 792 deletions
+2 -2
View File
@@ -2,8 +2,8 @@
# pyre-unsafe
from .model_builder import build_sam3_image_model
from .model_builder import build_sam3_image_model, build_sam3_predictor
__version__ = "0.1.0"
__all__ = ["build_sam3_image_model"]
__all__ = ["build_sam3_image_model", "build_sam3_predictor"]
+3 -3
View File
@@ -296,9 +296,9 @@ def agent_inference(
assert LATEST_SAM3_TEXT_PROMPT != ""
# Make sure that the last message is a image
assert messages[-1]["content"][1]["type"] == "image", (
"Second content element should be an image"
)
assert (
messages[-1]["content"][1]["type"] == "image"
), "Second content element should be an image"
messages.pop() # Remove the last user message
# Add simplified replacement message
simplified_message = {
+10 -10
View File
@@ -84,9 +84,9 @@ class BoxMode(IntEnum):
], "Relative mode not yet supported!"
if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:
assert arr.shape[-1] == 5, (
"The last dimension of input shape must be 5 for XYWHA format"
)
assert (
arr.shape[-1] == 5
), "The last dimension of input shape must be 5 for XYWHA format"
original_dtype = arr.dtype
arr = arr.double()
@@ -244,9 +244,9 @@ class Boxes:
if isinstance(item, int):
return Boxes(self.tensor[item].view(1, -1))
b = self.tensor[item]
assert b.dim() == 2, (
"Indexing on Boxes with {} failed to return a matrix!".format(item)
)
assert (
b.dim() == 2
), "Indexing on Boxes with {} failed to return a matrix!".format(item)
return Boxes(b)
def __len__(self) -> int:
@@ -424,10 +424,10 @@ def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
Returns:
Tensor: iou, sized [N].
"""
assert len(boxes1) == len(boxes2), (
"boxlists should have the samenumber of entries, got {}, {}".format(
len(boxes1), len(boxes2)
)
assert len(boxes1) == len(
boxes2
), "boxlists should have the samenumber of entries, got {}, {}".format(
len(boxes1), len(boxes2)
)
area1 = boxes1.area() # [N]
area2 = boxes2.area() # [N]
+4 -4
View File
@@ -141,10 +141,10 @@ class BitMasks:
if isinstance(item, int):
return BitMasks(self.tensor[item].unsqueeze(0))
m = self.tensor[item]
assert m.dim() == 3, (
"Indexing on BitMasks with {} returns a tensor with shape {}!".format(
item, m.shape
)
assert (
m.dim() == 3
), "Indexing on BitMasks with {} returns a tensor with shape {}!".format(
item, m.shape
)
return BitMasks(m)
+3 -3
View File
@@ -363,9 +363,9 @@ class RotatedBoxes(Boxes):
if isinstance(item, int):
return RotatedBoxes(self.tensor[item].view(1, -1))
b = self.tensor[item]
assert b.dim() == 2, (
"Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
)
assert (
b.dim() == 2
), "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
return RotatedBoxes(b)
def __len__(self) -> int:
+3 -3
View File
@@ -221,9 +221,9 @@ class _PanopticPrediction:
empty_ids.append(id)
if len(empty_ids) == 0:
return np.zeros(self._seg.shape, dtype=np.uint8)
assert len(empty_ids) == 1, (
">1 ids corresponds to no labels. This is currently not supported"
)
assert (
len(empty_ids) == 1
), ">1 ids corresponds to no labels. This is currently not supported"
return (self._seg != empty_ids[0]).numpy().astype(np.bool)
def semantic_masks(self):
+18 -18
View File
@@ -126,9 +126,9 @@ class COCOCustom(COCO):
# MODIFICATION: faster and cached subset check
if not hasattr(self, "img_id_set"):
self.img_id_set = set(self.getImgIds())
assert set(annsImgIds).issubset(self.img_id_set), (
"Results do not correspond to current coco set"
)
assert set(annsImgIds).issubset(
self.img_id_set
), "Results do not correspond to current coco set"
# END MODIFICATION
if "caption" in anns[0]:
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
@@ -301,9 +301,9 @@ class CGF1Eval(COCOeval):
TP = (match_scores >= thresh).sum()
FP = len(dt) - TP
FN = len(gt) - TP
assert FP >= 0 and FN >= 0, (
f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
)
assert (
FP >= 0 and FN >= 0
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
TPs.append(TP)
FPs.append(FP)
FNs.append(FN)
@@ -599,9 +599,9 @@ class CGF1Evaluator:
"""
assert len(self.coco_gts) > 0, "No ground truth provided for evaluation."
assert len(self.coco_gts) == len(self.coco_evals), (
"Mismatch in number of ground truths and evaluators."
)
assert len(self.coco_gts) == len(
self.coco_evals
), "Mismatch in number of ground truths and evaluators."
if self.verbose:
print(f"Loading predictions from {pred_file}")
@@ -668,17 +668,17 @@ class CGF1Evaluator:
if len(scorings) == 1:
return scorings[0]
assert scorings[0].ndim == 3, (
f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
)
assert scorings[0].shape[0] == 1, (
f"Expecting a single category, got {scorings[0].shape[0]}"
)
assert (
scorings[0].ndim == 3
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
assert (
scorings[0].shape[0] == 1
), f"Expecting a single category, got {scorings[0].shape[0]}"
for scoring in scorings:
assert scoring.shape == scorings[0].shape, (
f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
)
assert (
scoring.shape == scorings[0].shape
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
selected_imgs = []
for img_id in range(scorings[0].shape[-1]):
+3 -3
View File
@@ -751,9 +751,9 @@ def loadRes(self, resFile):
anns = resFile
assert type(anns) == list, "results in not an array of objects"
annsImgIds = [ann["image_id"] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
"Results do not correspond to current coco set"
)
assert set(annsImgIds) == (
set(annsImgIds) & set(self.getImgIds())
), "Results do not correspond to current coco set"
if "caption" in anns[0]:
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
[ann["image_id"] for ann in anns]
+3 -3
View File
@@ -83,9 +83,9 @@ class PredictionDumper:
self.merge_predictions = merge_predictions
self.pred_file_evaluators = pred_file_evaluators
if self.pred_file_evaluators is not None:
assert merge_predictions, (
"merge_predictions must be True if pred_file_evaluators are provided"
)
assert (
merge_predictions
), "merge_predictions must be True if pred_file_evaluators are provided"
assert self.dump_dir is not None, "dump_dir must be provided"
if is_main_process():
+12 -12
View File
@@ -154,9 +154,9 @@ class DemoEval(COCOeval):
TP = (match_scores >= thresh).sum()
FP = len(dt) - TP
FN = len(gt) - TP
assert FP >= 0 and FN >= 0, (
f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
)
assert (
FP >= 0 and FN >= 0
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
TPs.append(TP)
FPs.append(FP)
FNs.append(FN)
@@ -526,17 +526,17 @@ class DemoEvaluator(CocoEvaluator):
if len(scorings) == 1:
return scorings[0]
assert scorings[0].ndim == 3, (
f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
)
assert scorings[0].shape[0] == 1, (
f"Expecting a single category, got {scorings[0].shape[0]}"
)
assert (
scorings[0].ndim == 3
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
assert (
scorings[0].shape[0] == 1
), f"Expecting a single category, got {scorings[0].shape[0]}"
for scoring in scorings:
assert scoring.shape == scorings[0].shape, (
f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
)
assert (
scoring.shape == scorings[0].shape
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
selected_imgs = []
for img_id in range(scorings[0].shape[-1]):
+7 -9
View File
@@ -83,9 +83,9 @@ class PostProcessImage(nn.Module):
ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
"""
if ret_tensordict:
assert consistent is True, (
"We don't support returning TensorDict if the outputs have different shapes"
) # NOTE: It's possible but we don't support it.
assert (
consistent is True
), "We don't support returning TensorDict if the outputs have different shapes" # NOTE: It's possible but we don't support it.
assert self.detection_threshold <= 0.0, "TODO: implement?"
try:
from tensordict import TensorDict
@@ -118,9 +118,7 @@ class PostProcessImage(nn.Module):
if boxes is None:
assert out_masks is not None
assert not ret_tensordict, (
"We don't support returning TensorDict if the output does not contain boxes"
)
assert not ret_tensordict, "We don't support returning TensorDict if the output does not contain boxes"
B = len(out_masks)
boxes = [None] * B
scores = [None] * B
@@ -420,9 +418,9 @@ class PostProcessAPIVideo(PostProcessImage):
if video_id == -1:
video_id = unique_vid_id.item()
else:
assert video_id == unique_vid_id.item(), (
"We can only postprocess one video per datapoint"
)
assert (
video_id == unique_vid_id.item()
), "We can only postprocess one video per datapoint"
# keeping track of which objects appear in the current frame
obj_ids_per_frame = frame_outs["pred_object_ids"]
assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2)
+3 -3
View File
@@ -95,9 +95,9 @@ class YTVIS(COCO):
anns = resFile
assert type(anns) == list, "results is not an array of objects"
annsImgIds = [ann["image_id"] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
"Results do not correspond to current coco set"
)
assert set(annsImgIds) == (
set(annsImgIds) & set(self.getImgIds())
), "Results do not correspond to current coco set"
if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
for id, ann in enumerate(anns):
+18 -16
View File
@@ -109,7 +109,9 @@ class YTVISevalMixin:
) # Num preds x Num GTS x Num frames
inter = inter.sum(-1)
union = union.sum(-1)
assert (union > 0).all(), (
assert (
union > 0
).all(), (
"There exists a tracklet with zero GTs across time. This is suspicious"
)
return inter / union
@@ -134,9 +136,9 @@ class YTVISevalMixin:
iou = inter / union
assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation"
else:
assert np.isclose(inter, 0) and np.isclose(union, 0), (
"Encountered an error in IoU computation"
)
assert np.isclose(inter, 0) and np.isclose(
union, 0
), "Encountered an error in IoU computation"
iou = 1
return iou
@@ -204,16 +206,16 @@ class YTVISResultsWriter:
if len(prediction) == 0:
continue
for k in ["boxes", "scores", "labels"]:
assert k in prediction, (
f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
)
assert (
k in prediction
), f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
if self.save_per_frame_scores:
assert "per_frame_scores" in prediction, (
f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
)
assert xor("masks" in prediction, "masks_rle" in prediction), (
f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
)
assert (
"per_frame_scores" in prediction
), f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
assert xor(
"masks" in prediction, "masks_rle" in prediction
), f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
boxes = prediction["boxes"]
boxes = convert_to_xywh(boxes).tolist()
@@ -221,9 +223,9 @@ class YTVISResultsWriter:
labels = prediction["labels"].tolist()
if "masks" in prediction:
masks = prediction["masks"].squeeze(2)
assert masks.ndim == 4, (
"Expected masks to be of shape(N_preds,T_frames,H,W)"
)
assert (
masks.ndim == 4
), "Expected masks to be of shape(N_preds,T_frames,H,W)"
areas = [mask.flatten(1).sum(1).tolist() for mask in masks]
rles = [rle_encode(masklet) for masklet in masks]
+3 -3
View File
@@ -42,9 +42,9 @@ def get_logger(name, level=logging.INFO):
"""A command line logger."""
if "LOG_LEVEL" in os.environ:
level = os.environ["LOG_LEVEL"].upper()
assert level in LOG_LEVELS, (
f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
)
assert (
level in LOG_LEVELS
), f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
level = LOG_LEVELS[level]
logger = logging.getLogger(name)
logger.setLevel(level)
+61 -3
View File
@@ -16,6 +16,53 @@ import torch
MyTensor = Union[torch.Tensor, List[Any]]
class NestedTensor:
def __init__(self, tensors, mask):
self.tensors = tensors
self.mask = mask
def to(self, *args, **kwargs):
cast_tensor = self.tensors.to(*args, **kwargs)
cast_mask = self.mask.to(*args, **kwargs) if self.mask is not None else None
return type(self)(cast_tensor, cast_mask)
def clone(self):
new_tensors = self.tensors.clone()
new_mask = None if self.mask is None else self.mask.clone()
return NestedTensor(new_tensors, new_mask)
def __getitem__(self, idx):
return self.tensors[idx]
def __len__(self):
return len(self.tensors)
@property
def device(self):
return self.tensors.device
@property
def shape(self):
return self.tensors.shape
# custom memory pinning method on custom type
def pin_memory(self, device=None):
self.tensors = self.tensors.pin_memory(device)
if self.mask is not None:
self.mask = self.mask.pin_memory(device)
# Register NestedTensor as a pytree node so tree_map_only can traverse into it
# (matches onevision/utils/misc.py registration)
from torch.utils import _pytree as pytree
pytree.register_pytree_node(
NestedTensor,
lambda x: ([x.tensors, x.mask], None),
lambda values, _: NestedTensor(values[0], values[1]),
)
def interpolate(
input, size=None, scale_factor=None, mode="nearest", align_corners=None
):
@@ -28,9 +75,9 @@ def interpolate(
input, size, scale_factor, mode, align_corners
)
assert input.shape[0] != 0 or input.shape[1] != 0, (
"At least one of the two first dimensions must be non zero"
)
assert (
input.shape[0] != 0 or input.shape[1] != 0
), "At least one of the two first dimensions must be non zero"
if input.shape[1] == 0:
# Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim
@@ -81,6 +128,15 @@ class FindStage:
# This is beneficial for tracking in videos without the need for pointers.
object_ids: Optional[List[List]] = None # List of objects per query
# Multiplex-specific fields (used by sam3_demo_multiplex)
img_ids_np: Optional[Any] = None
input_boxes_before_embed: Optional[MyTensor] = None
input_boxes_before_embed__type = torch.float
input_points_before_embed: Optional[MyTensor] = None
input_points_before_embed__type = torch.float
ptrs: Optional[Any] = None
ptrs_seg: Optional[Any] = None
@dataclass
class BatchedFindTarget:
@@ -165,6 +221,7 @@ class BatchedDatapoint:
find_targets: List[BatchedFindTarget]
find_metadatas: List[BatchedInferenceMetadata]
raw_images: Optional[List[Any]] = None
get_queries: Optional[Any] = None
def convert_my_tensors(obj):
@@ -188,6 +245,7 @@ def convert_my_tensors(obj):
):
stack_dim = 0
if field.name in [
"input_boxes_before_embed",
"input_boxes",
"input_boxes_label",
]:
+434 -13
View File
@@ -6,12 +6,17 @@ Transformer decoder.
Inspired from Pytorch's version, adds the pre-norm variant
"""
from typing import Any, Dict, List, Optional
import math
from functools import partial
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
import torch.nn.functional as torchF
from sam3.sam.rope import apply_rotary_enc, apply_rotary_enc_real, compute_axial_cis
from sam3.sam.transformer import RoPEAttention
from torch import nn, Tensor
from torch.nn.attention import sdpa_kernel, SDPBackend
from torchvision.ops.roi_align import RoIAlign
from .act_ckpt_utils import activation_ckpt_wrapper
@@ -439,9 +444,9 @@ class TransformerDecoder(nn.Module):
- valid_ratios/spatial_shapes: bs, nlevel, 2
"""
if memory_mask is not None:
assert self.boxRPB == "none", (
"inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
)
assert (
self.boxRPB == "none"
), "inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
apply_dac = apply_dac if apply_dac is not None else self.dac
if apply_dac:
@@ -511,18 +516,18 @@ class TransformerDecoder(nn.Module):
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
if self.boxRPB != "none" and reference_boxes is not None:
assert spatial_shapes.shape[0] == 1, (
"only single scale support implemented"
)
assert (
spatial_shapes.shape[0] == 1
), "only single scale support implemented"
memory_mask = self._get_rpb_matrix(
reference_boxes,
(spatial_shapes[0, 0], spatial_shapes[0, 1]),
)
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
if self.training:
assert self.use_act_checkpoint, (
"Activation checkpointing not enabled in the decoder"
)
assert (
self.use_act_checkpoint
), "Activation checkpointing not enabled in the decoder"
output, presence_out = activation_ckpt_wrapper(layer)(
tgt=output,
tgt_query_pos=query_pos,
@@ -671,9 +676,9 @@ class TransformerEncoderCrossAttention(nn.Module):
src_pos[0],
)
assert src.shape[1] == prompt.shape[1], (
"Batch size must be the same for src and prompt"
)
assert (
src.shape[1] == prompt.shape[1]
), "Batch size must be the same for src and prompt"
output = src
@@ -951,3 +956,419 @@ class TransformerDecoderLayerv2(TransformerDecoderLayerv1):
if self.pre_norm:
return self.forward_pre(*args, **kwds)
raise NotImplementedError
def functional_attention(
q: Tensor,
k: Tensor,
v: Tensor,
*,
dropout: float,
num_heads: int,
num_k_exclude_rope: int = 0,
freqs_cis: Optional[Tensor] = None,
freqs_cis_real: Optional[Tensor] = None,
freqs_cis_imag: Optional[Tensor] = None,
use_fa3: bool = False,
use_rope_real: bool = False,
rope_k_repeat: bool,
) -> Union[Tensor, tuple[Tensor, Tensor]]:
b, n, cq = q.shape
_, m, ck = k.shape
_, _, cv = v.shape
if b > 1:
assert k.shape[0] == v.shape[0] == b
else:
# broadcast-able
assert k.shape[0] == b == 1, f"{q.shape=} {k.shape=} {v.shape=}"
assert v.shape[1] == m
q = q.reshape(b, n, num_heads, cq // num_heads).transpose(1, 2)
k = k.reshape(b, m, num_heads, ck // num_heads).transpose(1, 2)
v = v.reshape(v.shape[0], m, num_heads, cv // num_heads).transpose(1, 2)
if freqs_cis is not None:
num_k_rope = k.size(-2) - num_k_exclude_rope
if use_rope_real:
q, k[:, :, :num_k_rope] = apply_rotary_enc_real(
q,
k[:, :, :num_k_rope],
freqs_cis_real=freqs_cis_real,
freqs_cis_imag=freqs_cis_imag,
repeat_freqs_k=rope_k_repeat,
)
else:
q, k[:, :, :num_k_rope] = apply_rotary_enc(
q,
k[:, :, :num_k_rope],
freqs_cis,
repeat_freqs_k=rope_k_repeat,
)
if use_fa3:
from sam3.perflib.fa3 import flash_attn_func
assert dropout == 0.0
out = flash_attn_func(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2))
else:
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
out = torchF.scaled_dot_product_attention(q, k, v, dropout_p=dropout)
out = out.transpose(1, 2) # B * n * n_heads * (cv // num_heads)
out = out.reshape(b, n, cv)
return out
class SimpleRoPEAttention(nn.Module):
"""
Attention with rotary position encoding.
This class is "simple" because it does not perform q/k/v/out projections.
"""
def __init__(
self,
d_model: int,
num_heads: int,
dropout_p: float,
rope_theta=10000.0,
# whether to repeat q rope to match k length
# this is needed for cross-attention to memories
rope_k_repeat=False,
feat_sizes=(64, 64), # [w, h] for stride 16 feats at 1024 resolution
use_fa3: bool = False,
use_rope_real: bool = False,
):
super().__init__()
self.num_heads = num_heads
self.dropout_p = dropout_p
self.compute_cis = partial(
compute_axial_cis, dim=d_model // num_heads, theta=rope_theta
)
device = torch.device("cuda") if torch.cuda.is_available() else None
self.freqs_cis = self.compute_cis(
end_x=feat_sizes[0], end_y=feat_sizes[1], device=device
)
self.use_fa3 = use_fa3
self.use_rope_real = use_rope_real
if self.use_rope_real:
self.freqs_cis_real = self.freqs_cis.real
self.freqs_cis_imag = self.freqs_cis.imag
self.rope_k_repeat = rope_k_repeat
def forward(
self,
q: Tensor,
k: Tensor,
v: Tensor,
num_k_exclude_rope: int = 0,
) -> Union[Tensor, tuple[Tensor, Tensor]]:
# Apply rotary position encoding
w = h = math.sqrt(q.shape[-2])
self.freqs_cis = self.freqs_cis.to(q.device)
if self.freqs_cis.shape[0] != q.shape[-2]:
self.freqs_cis = self.compute_cis(end_x=w, end_y=h, device=q.device)
if self.use_rope_real:
self.freqs_cis_real = self.freqs_cis.real
self.freqs_cis_imag = self.freqs_cis.imag
if q.shape[-2] != k.shape[-2]:
assert self.rope_k_repeat
dropout_p = self.dropout_p if self.training else 0.0
out = functional_attention(
q,
k,
v,
dropout=dropout_p,
num_heads=self.num_heads,
num_k_exclude_rope=num_k_exclude_rope,
freqs_cis=self.freqs_cis,
freqs_cis_real=self.freqs_cis_real if self.use_rope_real else None,
freqs_cis_imag=self.freqs_cis_imag if self.use_rope_real else None,
use_fa3=self.use_fa3,
use_rope_real=self.use_rope_real,
rope_k_repeat=self.rope_k_repeat,
)
return out
class DecoupledTransformerDecoderLayerv2(nn.Module):
def __init__(
self,
*,
activation: str,
d_model: int,
num_heads: int,
dim_feedforward: int,
dropout: float,
pos_enc_at_attn: bool,
pos_enc_at_cross_attn_keys: bool,
pos_enc_at_cross_attn_queries: bool,
pre_norm: bool,
cross_attention_first: bool = False,
self_attention_rope: SimpleRoPEAttention,
cross_attention_rope: SimpleRoPEAttention,
):
super().__init__()
self.d_model = d_model
self.num_heads = num_heads
self.dim_feedforward = dim_feedforward
self.dropout_value = dropout
self.self_attn_q_proj = nn.Linear(d_model, d_model)
self.self_attn_k_proj = nn.Linear(d_model, d_model)
self.self_attn_v_proj = nn.Linear(d_model, d_model)
self.self_attn_out_proj = nn.Linear(d_model, d_model)
self.cross_attn_q_proj = nn.Linear(d_model, d_model)
self.cross_attn_k_proj = nn.Linear(d_model, d_model)
self.cross_attn_v_proj = nn.Linear(d_model, d_model)
self.cross_attn_out_proj = nn.Linear(d_model, d_model)
self.image_cross_attn_q_proj = nn.Linear(d_model, d_model)
self.image_cross_attn_k_proj = nn.Linear(d_model, d_model)
self.self_attention_rope = self_attention_rope
self.cross_attention_rope = cross_attention_rope
# Implementation of Feedforward model
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.activation_str = activation
self.activation = get_activation_fn(activation)
self.pre_norm = pre_norm
self.pos_enc_at_attn = pos_enc_at_attn
self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
self.cross_attention_first = cross_attention_first
def _forward_sa(self, tgt, query_pos):
# Self-Attention
tgt2 = self.norm1(tgt)
q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
q = self.self_attn_q_proj(q)
k = self.self_attn_k_proj(k)
v = self.self_attn_v_proj(tgt2)
out = self.self_attention_rope(q, k, v)
tgt2 = self.self_attn_out_proj(out)
tgt = tgt + self.dropout1(tgt2)
return tgt
def _forward_ca(
self,
*,
image,
tgt,
memory_image,
memory,
query_pos,
memory_image_pos,
num_k_exclude_rope=0,
):
kwds = {}
if num_k_exclude_rope > 0:
assert isinstance(self.cross_attention_rope, SimpleRoPEAttention)
kwds = {"num_k_exclude_rope": num_k_exclude_rope}
# Cross-Attention
tgt2 = self.norm2(tgt)
q = self.image_cross_attn_q_proj(image) + self.cross_attn_q_proj(tgt2)
if self.pos_enc_at_cross_attn_queries:
q = q + query_pos
k = self.image_cross_attn_k_proj(memory_image) + self.cross_attn_k_proj(memory)
if self.pos_enc_at_cross_attn_keys:
k = k + memory_image_pos
v = self.cross_attn_v_proj(memory)
out = self.cross_attention_rope(q, k, v, **kwds)
tgt2 = self.cross_attn_out_proj(out)
tgt = tgt + self.dropout2(tgt2)
return tgt
def forward_pre(
self,
*,
image,
tgt,
memory_image,
memory,
image_pos: Optional[Tensor] = None,
query_pos: Optional[Tensor] = None,
memory_image_pos: Optional[Tensor] = None,
memory_pos: Optional[Tensor] = None,
num_k_exclude_rope: int = 0,
):
if self.cross_attention_first:
tgt = self._forward_ca(
image=image,
tgt=tgt,
memory_image=memory_image,
memory=memory,
query_pos=query_pos,
memory_image_pos=memory_image_pos,
num_k_exclude_rope=num_k_exclude_rope,
)
tgt = self._forward_sa(tgt, query_pos)
else:
tgt = self._forward_sa(tgt, query_pos)
tgt = self._forward_ca(
image=image,
tgt=tgt,
memory_image=memory_image,
memory=memory,
query_pos=query_pos,
memory_image_pos=memory_image_pos,
num_k_exclude_rope=num_k_exclude_rope,
)
# MLP
tgt2 = self.norm3(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
tgt = tgt + self.dropout3(tgt2)
return image, tgt
def forward(self, *args: Any, **kwds: Any) -> torch.Tensor:
if self.pre_norm:
return self.forward_pre(*args, **kwds)
raise NotImplementedError
class TransformerEncoderDecoupledCrossAttention(nn.Module):
def __init__(
self,
d_model: int,
frozen: bool,
pos_enc_at_input: bool,
layer,
num_layers: int,
use_act_checkpoint: bool = False,
batch_first: bool = False, # Do layers expect batch first input?
use_image_in_output: bool = True,
):
super().__init__()
self.d_model = d_model
self.layers = get_clones(layer, num_layers)
self.num_layers = num_layers
self.norm = nn.LayerNorm(d_model)
self.pos_enc_at_input = pos_enc_at_input
self.use_act_checkpoint = use_act_checkpoint
self.use_image_in_output = use_image_in_output
if frozen:
for p in self.parameters():
p.requires_grad_(False)
self.batch_first = batch_first
def forward(
self,
image: Tensor, # image features
src: Tensor, # self-attention inputs; object features
memory_image: Tensor, # cross-attention inputs; image features
memory: Tensor, # cross-attention inputs; object features
image_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
src_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
memory_image_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
):
assert (
src.shape[1] == memory.shape[1]
), "Batch size must be the same for src and memory"
assert (
image.shape[1] == memory_image.shape[1]
), "Batch size must be the same for image and memory_image"
output = src
if self.pos_enc_at_input and src_pos is not None:
output = output + 0.1 * src_pos
if self.batch_first:
# Convert to batch first
output = output.transpose(0, 1)
src_pos = src_pos.transpose(0, 1)
image = image.transpose(0, 1)
memory = memory.transpose(0, 1)
memory_pos = memory_pos.transpose(0, 1)
memory_image = memory_image.transpose(0, 1)
memory_image_pos = memory_image_pos.transpose(0, 1)
if memory_image.shape[1] != memory.shape[1]:
# Pad memory_image with zeros, to accodmate object pointers
assert (
(memory.shape[1] - memory_image.shape[1]) == num_obj_ptr_tokens
), f"{memory.shape[1]} - {memory_image.shape[1]} != {num_obj_ptr_tokens}"
memory_image = torch.cat(
[
memory_image,
torch.zeros(
(memory_image.shape[0], num_obj_ptr_tokens)
+ memory_image.shape[2:],
dtype=memory_image.dtype,
device=memory_image.device,
),
],
dim=1,
)
if memory_image_pos is not None:
assert (
(memory_pos.shape[1] - memory_image_pos.shape[1])
== num_obj_ptr_tokens
), f"{memory_pos.shape[1]} - {memory_image_pos.shape[1]} != {num_obj_ptr_tokens}"
# tpos is the same in the batch anyway; note that memory_image always has a batch size of 1
memory_image_pos = torch.cat(
[
memory_image_pos,
memory_pos[0:1, -num_obj_ptr_tokens:],
],
dim=1,
)
for layer in self.layers:
image, output = activation_ckpt_wrapper(layer)(
image=image,
tgt=output,
memory_image=memory_image,
memory=memory,
image_pos=image_pos,
query_pos=src_pos,
memory_image_pos=memory_image_pos,
memory_pos=memory_pos,
num_k_exclude_rope=num_obj_ptr_tokens,
act_ckpt_enable=self.training and self.use_act_checkpoint,
)
if self.use_image_in_output:
normed_output = self.norm(output + image)
else:
normed_output = self.norm(output)
if self.batch_first:
# Convert back to seq first
normed_output = normed_output.transpose(0, 1)
src_pos = src_pos.transpose(0, 1)
return {
"memory": normed_output,
"pos_embed": src_pos,
}
+9 -9
View File
@@ -322,9 +322,9 @@ class TransformerEncoder(nn.Module):
return reference_points
def _prepare_multilevel_features(self, srcs, masks, pos_embeds):
assert len(srcs) == self.num_feature_levels, (
"mismatch between expected and received # of feature levels"
)
assert (
len(srcs) == self.num_feature_levels
), "mismatch between expected and received # of feature levels"
src_flatten = []
mask_flatten = []
@@ -406,9 +406,9 @@ class TransformerEncoder(nn.Module):
- spatial_shapes: Spatial dimensions of each feature level
- valid_ratios: Valid ratios for each feature level
"""
assert len(src) == self.num_feature_levels, (
"must be equal to num_feature_levels"
)
assert (
len(src) == self.num_feature_levels
), "must be equal to num_feature_levels"
if src_key_padding_masks is not None:
assert len(src_key_padding_masks) == self.num_feature_levels
if pos is not None:
@@ -538,9 +538,9 @@ class TransformerEncoderFusion(TransformerEncoder):
else None
)
else:
assert all(x.dim == 4 for x in src), (
"expected list of (bs, c, h, w) tensors"
)
assert all(
x.dim == 4 for x in src
), "expected list of (bs, c, h, w) tensors"
if self.add_pooled_text_to_img_feat:
# Fusion: Add mean pooled text to image features
+112 -99
View File
@@ -147,42 +147,54 @@ class Prompt:
)
# Dimension checks
assert box_embeddings is not None and list(box_embeddings.shape[:2]) == [
box_seq_len,
bs,
], (
f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
)
assert box_mask is not None and list(box_mask.shape) == [
bs,
box_seq_len,
], (
f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
)
assert point_embeddings is not None and list(point_embeddings.shape[:2]) == [
point_seq_len,
bs,
], (
f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
)
assert point_mask is not None and list(point_mask.shape) == [
bs,
point_seq_len,
], (
f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
)
assert box_labels is not None and list(box_labels.shape) == [
box_seq_len,
bs,
], (
f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
)
assert point_labels is not None and list(point_labels.shape) == [
point_seq_len,
bs,
], (
f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_labels.shape}"
)
assert (
box_embeddings is not None
and list(box_embeddings.shape[:2])
== [
box_seq_len,
bs,
]
), f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
assert (
box_mask is not None
and list(box_mask.shape)
== [
bs,
box_seq_len,
]
), f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
assert (
point_embeddings is not None
and list(point_embeddings.shape[:2])
== [
point_seq_len,
bs,
]
), f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
assert (
point_mask is not None
and list(point_mask.shape)
== [
bs,
point_seq_len,
]
), f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
assert (
box_labels is not None
and list(box_labels.shape)
== [
box_seq_len,
bs,
]
), f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
assert (
point_labels is not None
and list(point_labels.shape)
== [
point_seq_len,
bs,
]
), f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_labels.shape}"
assert (
# Allowed to be None, we leave it to the encoder to check for validity before encoding.
mask_embeddings is None
@@ -191,41 +203,41 @@ class Prompt:
mask_seq_len,
bs,
]
), (
f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
)
assert mask_mask is None or list(mask_mask.shape) == [
bs,
mask_seq_len,
], (
f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
)
), f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
assert (
mask_mask is None
or list(mask_mask.shape)
== [
bs,
mask_seq_len,
]
), f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
# Device checks
assert box_embeddings is not None and box_embeddings.device == device, (
f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
)
assert box_mask is not None and box_mask.device == device, (
f"Expected box mask to be on device {device}, got {box_mask.device}"
)
assert box_labels is not None and box_labels.device == device, (
f"Expected box labels to be on device {device}, got {box_labels.device}"
)
assert point_embeddings is not None and point_embeddings.device == device, (
f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
)
assert point_mask is not None and point_mask.device == device, (
f"Expected point mask to be on device {device}, got {point_mask.device}"
)
assert point_labels is not None and point_labels.device == device, (
f"Expected point labels to be on device {device}, got {point_labels.device}"
)
assert mask_embeddings is None or mask_embeddings.device == device, (
f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
)
assert mask_mask is None or mask_mask.device == device, (
f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
)
assert (
box_embeddings is not None and box_embeddings.device == device
), f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
assert (
box_mask is not None and box_mask.device == device
), f"Expected box mask to be on device {device}, got {box_mask.device}"
assert (
box_labels is not None and box_labels.device == device
), f"Expected box labels to be on device {device}, got {box_labels.device}"
assert (
point_embeddings is not None and point_embeddings.device == device
), f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
assert (
point_mask is not None and point_mask.device == device
), f"Expected point mask to be on device {device}, got {point_mask.device}"
assert (
point_labels is not None and point_labels.device == device
), f"Expected point labels to be on device {device}, got {point_labels.device}"
assert (
mask_embeddings is None or mask_embeddings.device == device
), f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
assert (
mask_mask is None or mask_mask.device == device
), f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
self.box_embeddings = box_embeddings
self.point_embeddings = point_embeddings
@@ -251,30 +263,30 @@ class Prompt:
if point_embeddings is not None:
point_seq_len = point_embeddings.shape[0]
if bs is not None:
assert bs == point_embeddings.shape[1], (
f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
)
assert (
bs == point_embeddings.shape[1]
), f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
else:
bs = point_embeddings.shape[1]
if device is not None:
assert device == point_embeddings.device, (
"Device mismatch between box and point embeddings"
)
assert (
device == point_embeddings.device
), "Device mismatch between box and point embeddings"
else:
device = point_embeddings.device
if mask_embeddings is not None:
mask_seq_len = mask_embeddings.shape[0]
if bs is not None:
assert bs == mask_embeddings.shape[1], (
f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
)
assert (
bs == mask_embeddings.shape[1]
), f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
else:
bs = mask_embeddings.shape[1]
if device is not None:
assert device == mask_embeddings.device, (
"Device mismatch between box/point and mask embeddings."
)
assert (
device == mask_embeddings.device
), "Device mismatch between box/point and mask embeddings."
else:
device = mask_embeddings.device
@@ -526,9 +538,9 @@ class SequenceGeometryEncoder(nn.Module):
if add_cls:
self.cls_embed = torch.nn.Embedding(1, self.d_model)
assert points_direct_project or points_pos_enc or points_pool, (
"Error: need at least one way to encode points"
)
assert (
points_direct_project or points_pos_enc or points_pool
), "Error: need at least one way to encode points"
assert (
encode_boxes_as_points
or boxes_direct_project
@@ -570,16 +582,16 @@ class SequenceGeometryEncoder(nn.Module):
self.encode = None
if num_layers > 0:
assert add_cls, (
"It's currently highly recommended to add a CLS when using a transformer"
)
assert (
add_cls
), "It's currently highly recommended to add a CLS when using a transformer"
self.encode = get_clones(layer, num_layers)
self.encode_norm = nn.LayerNorm(self.d_model)
if mask_encoder is not None:
assert isinstance(mask_encoder, MaskEncoder), (
f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
)
assert isinstance(
mask_encoder, MaskEncoder
), f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
if add_mask_label:
self.mask_label_embed = torch.nn.Embedding(2, self.d_model)
self.add_mask_label = add_mask_label
@@ -688,15 +700,16 @@ class SequenceGeometryEncoder(nn.Module):
img_feats: torch.Tensor = None,
):
n_masks, bs = masks.shape[:2]
assert n_masks == 1, (
"We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
)
assert list(attn_mask.shape) == [
bs,
n_masks,
], (
f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
)
assert (
n_masks == 1
), "We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
assert (
list(attn_mask.shape)
== [
bs,
n_masks,
]
), f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
masks, pos = self.mask_encoder(
masks=masks.flatten(0, 1).float(),
pix_feat=img_feats,
+12 -2
View File
@@ -132,6 +132,13 @@ def load_video_frames(
match = re.match(r"<load-dummy-video-(\d+)>", video_path)
num_frames = int(match.group(1)) if match else 60
return load_dummy_video(image_size, offload_video_to_cpu, num_frames=num_frames)
elif video_path.startswith("<load-zero-video"):
# Check for pattern <load-zero-video-N> where N is an integer
match = re.match(r"<load-zero-video-(\d+)>", video_path)
num_frames = int(match.group(1)) if match else 60
return load_dummy_video(
image_size, offload_video_to_cpu, num_frames=num_frames, do_zeros=True
)
elif os.path.isdir(video_path):
return load_video_frames_from_image_folder(
image_folder=video_path,
@@ -322,12 +329,15 @@ def load_video_frames_from_video_file_using_cv2(
return video_tensor, original_height, original_width
def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60):
def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60, do_zeros=False):
"""
Load a dummy video with random frames for testing and compilation warmup purposes.
"""
video_height, video_width = 480, 640 # dummy original video sizes
images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
if not do_zeros:
images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
else:
images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float16)
if not offload_video_to_cpu:
images = images.cuda()
return images, video_height, video_width
+14 -6
View File
@@ -107,6 +107,12 @@ class SegmentationHead(nn.Module):
image_ids,
encoder_hidden_states,
) -> torch.Tensor:
# Unwrap NestedTensors to plain tensors if needed (multiplex path)
from sam3.model.data_misc import NestedTensor
def _unwrap(x):
return x.tensors if isinstance(x, NestedTensor) else x
feature_device = backbone_feats[0].device # features could be on CPU
model_device = self.device
image_ids_ = image_ids.to(feature_device)
@@ -116,10 +122,14 @@ class SegmentationHead(nn.Module):
backbone_visual_feats = []
for feat in backbone_feats:
# Copy the img features per query (pixel decoder won't share img feats)
backbone_visual_feats.append(feat[image_ids_, ...].to(model_device))
backbone_visual_feats.append(
_unwrap(feat)[image_ids_, ...].to(model_device)
)
else:
# Bs=1, we rely on broadcasting for query-based processing
backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats]
backbone_visual_feats = [
_unwrap(bb_feat).clone() for bb_feat in backbone_feats
]
# Extract visual embeddings
encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0)
spatial_dim = math.prod(backbone_feats[-1].shape[-2:])
@@ -135,7 +145,7 @@ class SegmentationHead(nn.Module):
else:
pixel_embed = self.pixel_decoder(backbone_visual_feats)
else:
backbone_feats = [x.to(model_device) for x in backbone_feats]
backbone_feats = [_unwrap(x).to(model_device) for x in backbone_feats]
pixel_embed = self.pixel_decoder(backbone_feats)
if pixel_embed.shape[0] == 1:
# For batch_size=1 training, we can avoid the indexing to save memory
@@ -248,9 +258,7 @@ class UniversalSegmentationHead(SegmentationHead):
self.d_model = hidden_dim
if dot_product_scorer is not None:
assert presence_head, (
"Specifying a dot product scorer without a presence head is likely a mistake"
)
assert presence_head, "Specifying a dot product scorer without a presence head is likely a mistake"
self.presence_head = None
if presence_head:
+11 -5
View File
@@ -38,14 +38,19 @@ class SimpleMaskDownSampler(nn.Module):
# Option to interpolate the input mask first before downsampling using convs. In that case, the total_stride is assumed to be after interpolation.
# If set to input resolution or None, we don't interpolate. We default to None to be safe (for older configs or if not explicitly set)
interpol_size=None,
# options for incorporating multiplex memory encoding
multiplex_count: int = 1,
starting_out_chan: int = 1,
input_channel_multiplier: int = 1,
):
super().__init__()
num_layers = int(math.log2(total_stride) // math.log2(stride))
multiplex_count = multiplex_count * input_channel_multiplier
assert stride**num_layers == total_stride
self.encoder = nn.Sequential()
mask_in_chans, mask_out_chans = 1, 1
mask_in_chans, mask_out_chans = multiplex_count, starting_out_chan
for _ in range(num_layers):
mask_out_chans = mask_in_chans * (stride**2)
mask_out_chans = mask_out_chans * (stride**2)
self.encoder.append(
nn.Conv2d(
mask_in_chans,
@@ -60,11 +65,12 @@ class SimpleMaskDownSampler(nn.Module):
mask_in_chans = mask_out_chans
self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
self.multiplex_count = multiplex_count
self.interpol_size = interpol_size
if self.interpol_size is not None:
assert isinstance(self.interpol_size, (list, tuple)), (
f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
)
assert isinstance(
self.interpol_size, (list, tuple)
), f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
self.interpol_size = list(interpol_size)
assert len(self.interpol_size) == 2
+688 -11
View File
@@ -6,18 +6,25 @@
import copy
import math
import warnings
import weakref
from collections.abc import Iterator
from contextlib import AbstractContextManager
from enum import auto, Enum
from typing import Dict, List, Optional, Union
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from torch.overrides import handle_torch_function, has_torch_function
from typing_extensions import override
try:
import xformers
except ImportError:
xformers = None
def inverse_sigmoid(x, eps=1e-3):
"""
@@ -30,10 +37,680 @@ def inverse_sigmoid(x, eps=1e-3):
return torch.log(x1 / x2)
class MultiheadAttentionWrapper(nn.MultiheadAttention):
def forward(self, *args, **kwargs):
kwargs["need_weights"] = False
return super().forward(*args, **kwargs)
def get_sdpa_settings():
if torch.cuda.is_available():
old_gpu = torch.cuda.get_device_properties(0).major < 7
# only use Flash Attention on Ampere (8.0) or newer GPUs
use_flash_attn = torch.cuda.get_device_properties(0).major >= 8
if not use_flash_attn:
warnings.warn(
"Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.",
category=UserWarning,
stacklevel=2,
)
# keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only
# available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases)
pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2])
if pytorch_version < (2, 2):
warnings.warn(
f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. "
"Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).",
category=UserWarning,
stacklevel=2,
)
math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn
else:
old_gpu = True
use_flash_attn = False
math_kernel_on = True
return old_gpu, use_flash_attn, math_kernel_on
OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
class AttentionType:
"""Type of attention"""
# Simple dot product attention
Vanilla = "Vanilla"
# Efficient attention from xformers
Xformer = "Xformer"
# Sparse attention
Sparse = "Sparse"
# Deformable attention (not compatible with text)
Deformable = "Deformable"
def multi_head_attention_forward(
query: Tensor,
key: Tensor,
value: Tensor,
embed_dim_to_check: int,
num_heads: int,
in_proj_weight: Optional[Tensor],
in_proj_bias: Optional[Tensor],
bias_k: Optional[Tensor],
bias_v: Optional[Tensor],
add_zero_attn: bool,
dropout_p: float,
out_proj_weight: Tensor,
out_proj_bias: Optional[Tensor],
training: bool = True,
key_padding_mask: Optional[Tensor] = None,
need_weights: bool = True,
attn_mask: Optional[Tensor] = None,
use_separate_proj_weight: bool = False,
q_proj_weight: Optional[Tensor] = None,
k_proj_weight: Optional[Tensor] = None,
v_proj_weight: Optional[Tensor] = None,
static_k: Optional[Tensor] = None,
static_v: Optional[Tensor] = None,
average_attn_weights: bool = True,
is_causal: bool = False,
attn_type: AttentionType = AttentionType.Vanilla,
attn_sparsity: float = 0.0,
attn_bias: Optional[Tensor] = None,
use_fa3: bool = False,
) -> Tuple[Tensor, Optional[Tensor]]:
tens_ops = (
query,
key,
value,
in_proj_weight,
in_proj_bias,
bias_k,
bias_v,
out_proj_weight,
out_proj_bias,
)
if has_torch_function(tens_ops):
return handle_torch_function(
multi_head_attention_forward,
tens_ops,
query,
key,
value,
embed_dim_to_check,
num_heads,
in_proj_weight,
in_proj_bias,
bias_k,
bias_v,
add_zero_attn,
dropout_p,
out_proj_weight,
out_proj_bias,
training=training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
is_causal=is_causal,
use_separate_proj_weight=use_separate_proj_weight,
q_proj_weight=q_proj_weight,
k_proj_weight=k_proj_weight,
v_proj_weight=v_proj_weight,
static_k=static_k,
static_v=static_v,
average_attn_weights=average_attn_weights,
use_fa3=use_fa3,
)
is_batched = True
if is_causal:
raise NotImplementedError("is_causal is not supported in this implem")
attn_mask = None
if not is_batched:
query = query.unsqueeze(1)
key = key.unsqueeze(1)
value = value.unsqueeze(1)
if key_padding_mask is not None:
key_padding_mask = key_padding_mask.unsqueeze(0)
# set up shape vars
tgt_len, bsz, embed_dim = query.shape
src_len, _, _ = key.shape
if key_padding_mask is not None:
_kpm_dtype = key_padding_mask.dtype
if _kpm_dtype != torch.bool and not torch.is_floating_point(key_padding_mask):
raise AssertionError(
"only bool and floating types of key_padding_mask are supported"
)
assert (
embed_dim == embed_dim_to_check
), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
if isinstance(embed_dim, torch.Tensor):
head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
else:
head_dim = embed_dim // num_heads
assert (
head_dim * num_heads == embed_dim
), f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
if use_separate_proj_weight:
assert (
key.shape[:2] == value.shape[:2]
), f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
else:
assert (
key.shape == value.shape
), f"key shape {key.shape} does not match value shape {value.shape}"
#
# compute in-projection
#
if not use_separate_proj_weight:
assert (
in_proj_weight is not None
), "use_separate_proj_weight is False but in_proj_weight is None"
q, k, v = F._in_projection_packed(
query, key, value, in_proj_weight, in_proj_bias
)
else:
assert (
q_proj_weight is not None
), "use_separate_proj_weight is True but q_proj_weight is None"
assert (
k_proj_weight is not None
), "use_separate_proj_weight is True but k_proj_weight is None"
assert (
v_proj_weight is not None
), "use_separate_proj_weight is True but v_proj_weight is None"
if in_proj_bias is None:
b_q = b_k = b_v = None
else:
b_q, b_k, b_v = in_proj_bias.chunk(3)
q, k, v = F._in_projection(
query,
key,
value,
q_proj_weight,
k_proj_weight,
v_proj_weight,
b_q,
b_k,
b_v,
)
# prep attention mask
if attn_mask is not None:
if attn_mask.dtype == torch.uint8:
warnings.warn(
"Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
)
attn_mask = attn_mask.to(torch.bool)
else:
assert (
attn_mask.is_floating_point() or attn_mask.dtype == torch.bool
), f"Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}"
# ensure attn_mask's dim is 3
if attn_mask.dim() == 2:
correct_2d_size = (tgt_len, src_len)
if attn_mask.shape != correct_2d_size:
raise RuntimeError(
f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
)
attn_mask = attn_mask.unsqueeze(0)
elif attn_mask.dim() == 3:
correct_3d_size = (bsz * num_heads, tgt_len, src_len)
if attn_mask.shape != correct_3d_size:
raise RuntimeError(
f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
)
else:
raise RuntimeError(
f"attn_mask's dimension {attn_mask.dim()} is not supported"
)
# add bias along batch dimension (currently second)
if bias_k is not None and bias_v is not None:
assert static_k is None, "bias cannot be added to static key."
assert static_v is None, "bias cannot be added to static value."
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
if attn_mask is not None:
attn_mask = F.pad(attn_mask, (0, 1))
if key_padding_mask is not None:
key_padding_mask = F.pad(key_padding_mask, (0, 1))
else:
assert bias_k is None
assert bias_v is None
#
# reshape q, k, v for multihead attention and make em batch first
#
q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
if static_k is None:
k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else:
assert (
static_k.size(0) == bsz * num_heads
), f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
assert (
static_k.size(2) == head_dim
), f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
k = static_k
if static_v is None:
v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else:
assert (
static_v.size(0) == bsz * num_heads
), f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
assert (
static_v.size(2) == head_dim
), f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
v = static_v
# add zero attention along batch dimension (now first)
if add_zero_attn:
zero_attn_shape = (bsz * num_heads, 1, head_dim)
k = torch.cat(
[k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1
)
v = torch.cat(
[v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1
)
if attn_mask is not None:
attn_mask = F.pad(attn_mask, (0, 1))
if key_padding_mask is not None:
key_padding_mask = F.pad(key_padding_mask, (0, 1))
# update source sequence length after adjustments
src_len = k.size(1)
# merge key padding and attention masks
if key_padding_mask is not None:
assert (
key_padding_mask.shape
== (
bsz,
src_len,
)
), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
key_padding_mask = (
key_padding_mask.view(bsz, 1, 1, src_len)
.expand(-1, num_heads, -1, -1)
.reshape(bsz * num_heads, 1, src_len)
)
if attn_mask is None:
attn_mask = key_padding_mask
elif attn_mask.dtype == torch.bool:
attn_mask = attn_mask.logical_or(key_padding_mask)
else:
attn_mask = attn_mask.masked_fill(key_padding_mask, float("-inf"))
# convert mask to float
if attn_mask is not None and attn_mask.dtype == torch.bool:
new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
new_attn_mask.masked_fill_(attn_mask, float("-inf"))
attn_mask = new_attn_mask
# adjust dropout probability
if not training:
dropout_p = 0.0
#
# (deep breath) calculate attention and out projection
#
if attn_mask is not None:
if attn_mask.size(0) == 1:
attn_mask = attn_mask.unsqueeze(0)
else:
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
if attn_bias is not None:
assert (
attn_bias.shape
== (
bsz,
num_heads,
tgt_len,
src_len,
)
), f"expecting attn_bias shape of {(bsz, num_heads, tgt_len, src_len)}, but got {attn_bias.shape}"
if attn_mask is None:
attn_mask = attn_bias
else:
attn_mask = attn_mask + attn_bias
q = q.view(bsz, num_heads, tgt_len, head_dim)
k = k.view(bsz, num_heads, src_len, head_dim)
v = v.view(bsz, num_heads, src_len, head_dim)
if attn_type == AttentionType.Vanilla:
if attn_mask is None and not is_causal and use_fa3:
from sam3.perflib.fa3 import flash_attn_func
assert dropout_p == 0.0
attn_output = flash_attn_func(
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
).transpose(1, 2)
else:
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_math_sdp(True)
torch.backends.cuda.enable_mem_efficient_sdp(True)
attn_output = F.scaled_dot_product_attention(
q, k, v, attn_mask, dropout_p, is_causal
)
attn_output = (
attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
)
elif attn_type == AttentionType.Xformer:
attn_output_weights = None
assert not need_weights, "need_weights is not supported in efficient mode"
attn_output = xformers.ops.memory_efficient_attention(
q.transpose(1, 2),
k.transpose(1, 2),
v.transpose(1, 2),
attn_bias=attn_mask,
p=dropout_p,
)
attn_output = attn_output.permute(1, 0, 2, 3).reshape(bsz * tgt_len, embed_dim)
elif attn_type == AttentionType.Sparse:
attn_output_weights = None
assert not need_weights, "need_weights is not supported in efficient mode"
# Need to collapse heads and batch dimensions
q = q.reshape(bsz * num_heads, tgt_len, head_dim).contiguous()
k = k.reshape(bsz * num_heads, src_len, head_dim).contiguous()
v = v.reshape(bsz * num_heads, src_len, head_dim).contiguous()
row_offsets, column_indices = xformers.ops.find_locations_new(
q, k, attn_sparsity, True
)
attn_output = xformers.ops.sparse_memory_efficient_attention(
q, k, v, row_offsets, column_indices, attn_bias=attn_mask
).reshape(bsz, num_heads, tgt_len, head_dim)
attn_output = attn_output.permute(2, 0, 1, 3).reshape(bsz * tgt_len, embed_dim)
else:
raise ValueError(f"Unsupported attention type {attn_type}")
attn_output = F.linear(attn_output, out_proj_weight, out_proj_bias)
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
if need_weights:
attn_output_weights = (q * head_dim**-0.5) @ k.transpose(-2, -1)
attn_output_weights = attn_output_weights.softmax(dim=-1)
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
if average_attn_weights:
attn_output_weights = attn_output_weights.sum(dim=1) / num_heads
if not is_batched:
attn_output = attn_output.squeeze(1)
attn_output_weights = attn_output_weights.squeeze(0)
return attn_output, attn_output_weights
else:
attn_output_weights = None
if not is_batched:
attn_output = attn_output.squeeze(1)
return attn_output, None
class MultiheadAttention(nn.Module):
__constants__ = ["batch_first"]
bias_k: Optional[torch.Tensor]
bias_v: Optional[torch.Tensor]
def __init__(
self,
embed_dim,
num_heads,
dropout=0.0,
bias=True,
add_bias_kv=False,
add_zero_attn=False,
kdim=None,
vdim=None,
batch_first=False,
device=None,
dtype=None,
attn_type: AttentionType = AttentionType.Vanilla,
sparsity: float = 0.0,
use_act_checkpoint: bool = False,
use_fa3: bool = False,
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if kdim is not None else embed_dim
self.vdim = vdim if vdim is not None else embed_dim
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.batch_first = batch_first
self.head_dim = embed_dim // num_heads
self.use_act_checkpoint = use_act_checkpoint
assert (
self.head_dim * num_heads == self.embed_dim
), "embed_dim must be divisible by num_heads"
assert (
attn_type == AttentionType.Sparse or sparsity == 0.0
), "sparsity is only supported for sparse attention"
if not self._qkv_same_embed_dim:
self.q_proj_weight = nn.Parameter(
torch.empty((embed_dim, embed_dim), **factory_kwargs)
)
self.k_proj_weight = nn.Parameter(
torch.empty((embed_dim, self.kdim), **factory_kwargs)
)
self.v_proj_weight = nn.Parameter(
torch.empty((embed_dim, self.vdim), **factory_kwargs)
)
self.register_parameter("in_proj_weight", None)
else:
self.in_proj_weight = nn.Parameter(
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
)
self.register_parameter("q_proj_weight", None)
self.register_parameter("k_proj_weight", None)
self.register_parameter("v_proj_weight", None)
if bias:
self.in_proj_bias = nn.Parameter(
torch.empty(3 * embed_dim, **factory_kwargs)
)
else:
self.register_parameter("in_proj_bias", None)
self.out_proj = nn.modules.linear.NonDynamicallyQuantizableLinear(
embed_dim, embed_dim, bias=bias, **factory_kwargs
)
if add_bias_kv:
self.bias_k = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
self.bias_v = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.attn_type = attn_type
self.sparsity = sparsity
self.use_fa3 = use_fa3
self._reset_parameters()
def _reset_parameters(self):
if self._qkv_same_embed_dim:
nn.init.xavier_uniform_(self.in_proj_weight)
else:
nn.init.xavier_uniform_(self.q_proj_weight)
nn.init.xavier_uniform_(self.k_proj_weight)
nn.init.xavier_uniform_(self.v_proj_weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
def __setstate__(self, state):
if "_qkv_same_embed_dim" not in state:
state["_qkv_same_embed_dim"] = True
super(MultiheadAttention, self).__setstate__(state)
def forward(
self,
query: Tensor,
key: Tensor,
value: Tensor,
key_padding_mask: Optional[Tensor] = None,
need_weights: bool = False,
attn_mask: Optional[Tensor] = None,
average_attn_weights: bool = True,
attn_bias: Optional[Tensor] = None,
) -> Tuple[Tensor, Optional[Tensor]]:
is_batched = query.dim() == 3
if key_padding_mask is not None:
_kpm_dtype = key_padding_mask.dtype
if _kpm_dtype != torch.bool and not torch.is_floating_point(
key_padding_mask
):
raise AssertionError(
"only bool and floating types of key_padding_mask are supported"
)
if self.batch_first and is_batched:
if key is value:
if query is key:
query = key = value = query.transpose(1, 0)
else:
query, key = [x.transpose(1, 0) for x in (query, key)]
value = key
else:
query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
if not self._qkv_same_embed_dim:
if self.use_act_checkpoint:
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward,
query,
key,
value,
self.embed_dim,
self.num_heads,
self.in_proj_weight,
self.in_proj_bias,
self.bias_k,
self.bias_v,
self.add_zero_attn,
self.dropout,
self.out_proj.weight,
self.out_proj.bias,
use_reentrant=False,
training=self.training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
use_separate_proj_weight=True,
q_proj_weight=self.q_proj_weight,
k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight,
average_attn_weights=average_attn_weights,
attn_type=self.attn_type,
attn_sparsity=self.sparsity,
attn_bias=attn_bias,
use_fa3=self.use_fa3,
)
else:
attn_output, attn_output_weights = multi_head_attention_forward(
query,
key,
value,
self.embed_dim,
self.num_heads,
self.in_proj_weight,
self.in_proj_bias,
self.bias_k,
self.bias_v,
self.add_zero_attn,
self.dropout,
self.out_proj.weight,
self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
use_separate_proj_weight=True,
q_proj_weight=self.q_proj_weight,
k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight,
average_attn_weights=average_attn_weights,
attn_type=self.attn_type,
attn_sparsity=self.sparsity,
attn_bias=attn_bias,
use_fa3=self.use_fa3,
)
else:
if self.use_act_checkpoint:
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward,
query,
key,
value,
self.embed_dim,
self.num_heads,
self.in_proj_weight,
self.in_proj_bias,
self.bias_k,
self.bias_v,
self.add_zero_attn,
self.dropout,
self.out_proj.weight,
self.out_proj.bias,
use_reentrant=False,
training=self.training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
average_attn_weights=average_attn_weights,
attn_type=self.attn_type,
attn_sparsity=self.sparsity,
attn_bias=attn_bias,
)
else:
attn_output, attn_output_weights = multi_head_attention_forward(
query,
key,
value,
self.embed_dim,
self.num_heads,
self.in_proj_weight,
self.in_proj_bias,
self.bias_k,
self.bias_v,
self.add_zero_attn,
self.dropout,
self.out_proj.weight,
self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
average_attn_weights=average_attn_weights,
attn_type=self.attn_type,
attn_sparsity=self.sparsity,
attn_bias=attn_bias,
)
if self.batch_first and is_batched:
return attn_output.transpose(1, 0), attn_output_weights
else:
return attn_output, attn_output_weights
# Keep backward compatibility alias
MultiheadAttentionWrapper = MultiheadAttention
class DotProductScoring(torch.nn.Module):
@@ -330,9 +1007,9 @@ class SAM3Output(list):
self.output = output
else:
self.output = []
assert isinstance(iter_mode, SAM3Output.IterMode), (
f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
)
assert isinstance(
iter_mode, SAM3Output.IterMode
), f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
self.iter_mode = iter_mode
# We create a weak reference to self to be used in the lambda functions.
@@ -411,9 +1088,9 @@ class SAM3Output(list):
return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode)
def append(self, item: list):
assert isinstance(item, list), (
f"Only list items are supported. Got {type(item)}"
)
assert isinstance(
item, list
), f"Only list items are supported. Got {type(item)}"
self.output.append(item)
def __repr__(self):
+470
View File
@@ -0,0 +1,470 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Type
import torch
from sam3.sam.common import LayerNorm2d
from torch import nn
from torch.nn import functional as F
class MultiplexMaskDecoder(nn.Module):
def __init__(
self,
*,
transformer_dim: int,
transformer: nn.Module,
multiplex_count: int,
num_multimask_outputs: int = 3,
activation: Type[nn.Module] = nn.GELU,
iou_head_depth: int = 3,
iou_head_hidden_dim: int = 256,
use_high_res_features: bool = False,
iou_prediction_use_sigmoid: bool = False,
dynamic_multimask_via_stability=False,
dynamic_multimask_stability_delta=0.05,
dynamic_multimask_stability_thresh=0.98,
pred_obj_scores: bool = False,
pred_obj_scores_mlp: bool = False,
use_multimask_token_for_obj_ptr: bool = False,
decode_mask_with_shared_tokens: bool = False,
decode_mask_attribute_with_shared_tokens: bool = False,
multimask_outputs_only: bool = False,
) -> None:
"""
Predicts masks given an image and prompt embeddings, using a
transformer architecture with multiplex capabilities.
Arguments:
multiplex_count: the number of masks multiplexed into a single feature map
num_multimask_outputs: the number of masks to predict per multiplex output
(the total number of masks is (num_multimask_outputs+1) * multiplex_count)
use_multimask_token_for_obj_ptr: whether to use multimask tokens for object pointers
decode_mask_with_shared_tokens: use the same mask token for multimasks with different projection layers
decode_mask_attribute_with_shared_tokens: use the mask tokens (instead of separate tokens)
to predict iou and object scores
multimask_outputs_only: predict num_multimask_outputs masks without the single
mask output token (i.e., without the +1)
"""
super().__init__()
self.transformer_dim = transformer_dim
self.transformer = transformer
self.multiplex_count = multiplex_count
self.num_multimask_outputs = num_multimask_outputs
self.multimask_outputs_only = multimask_outputs_only
self.decode_mask_with_shared_tokens = decode_mask_with_shared_tokens
self.decode_mask_attribute_with_shared_tokens = (
decode_mask_attribute_with_shared_tokens
)
if self.decode_mask_with_shared_tokens:
assert (
multimask_outputs_only
), "multimask_outputs_only must be True if decode_mask_with_shared_tokens"
if self.multimask_outputs_only:
self.num_mask_output_per_object = num_multimask_outputs
else:
self.num_mask_output_per_object = num_multimask_outputs + 1
if self.decode_mask_with_shared_tokens:
self.num_mask_tokens = multiplex_count
else:
self.num_mask_tokens = multiplex_count * self.num_mask_output_per_object
self.pred_obj_scores = pred_obj_scores
self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
if not self.decode_mask_attribute_with_shared_tokens:
self.iou_token = nn.Embedding(multiplex_count, transformer_dim)
if self.pred_obj_scores:
self.obj_score_token = nn.Embedding(multiplex_count, transformer_dim)
self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
self.output_upscaling = nn.Sequential(
nn.ConvTranspose2d(
transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
),
LayerNorm2d(transformer_dim // 4),
activation(),
nn.ConvTranspose2d(
transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
),
activation(),
)
self.use_high_res_features = use_high_res_features
if use_high_res_features:
self.conv_s0 = nn.Conv2d(
transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
)
self.conv_s1 = nn.Conv2d(
transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
)
if self.num_multimask_outputs == 0:
self.output_hypernetworks_mlp = MLP(
transformer_dim, transformer_dim, transformer_dim // 8, 3
)
else:
self.output_hypernetworks_mlps = nn.ModuleList(
[
MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
for _ in range(self.num_mask_output_per_object)
]
)
self.iou_prediction_head = MLP(
transformer_dim,
iou_head_hidden_dim,
(
1
if (
self.decode_mask_attribute_with_shared_tokens
and not self.decode_mask_with_shared_tokens
)
else self.num_mask_output_per_object
),
iou_head_depth,
sigmoid_output=iou_prediction_use_sigmoid,
)
if self.pred_obj_scores:
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
if pred_obj_scores_mlp:
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
# When outputting a single mask, optionally we can dynamically fall back to the best
# multimask output token if the single mask output token gives low stability scores.
self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
def forward(
self,
image_embeddings: torch.Tensor,
image_pe: torch.Tensor,
multimask_output: bool,
high_res_features: Optional[List[torch.Tensor]] = None,
extra_per_object_embeddings: Optional[torch.Tensor] = None,
) -> dict[str, torch.Tensor]:
"""
Predict masks given image and prompt embeddings.
Arguments:
image_embeddings (torch.Tensor): the embeddings from the image encoder
image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
extra_per_object_embeddings (torch.Tensor): a tensor with shape b * multiplex_count * C to be added to the mask tokens
Returns: a dict of Tensors indexed by strings
masks: batched predicted masks
iou_pred: batched predictions of mask quality
object_score_logits: batched predictions of object existence
"""
if self.num_multimask_outputs <= 0:
assert (
not multimask_output
), f"multimask_output must be False with {self.num_multimask_outputs=}"
if self.multimask_outputs_only:
assert (
multimask_output
), f"multimask_output must be True with {self.multimask_outputs_only=}"
out = self.predict_masks(
image_embeddings=image_embeddings,
image_pe=image_pe,
high_res_features=high_res_features,
extra_per_object_embeddings=extra_per_object_embeddings,
)
masks = out["masks"] # [B, M, (self.num_mask_token_per_object), H, W]
iou_pred = out["iou_pred"] # [B, M, (self.num_mask_token_per_object)]
mask_tokens_out = out[
"mask_tokens_out"
] # [B, M, (self.num_mask_token_per_object), C]
# Select the correct mask or masks for output
if multimask_output:
if not self.multimask_outputs_only:
masks = masks[:, :, 1:, :, :]
iou_pred = iou_pred[:, :, 1:]
elif self.dynamic_multimask_via_stability and not self.training:
masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
else:
masks = masks[:, :, 0:1, :, :]
iou_pred = iou_pred[:, :, 0:1]
if multimask_output and self.use_multimask_token_for_obj_ptr:
if self.multimask_outputs_only:
sam_tokens_out = mask_tokens_out
else:
sam_tokens_out = mask_tokens_out[
:, :, 1:
] # [B, M, num_multimask_outputs, C] shape
else:
# Take the mask output token. Here we *always* use the token for single mask output.
# At test time, even if we track after 1-click (and using multimask_output=True),
# we still take the single mask token here. The rationale is that we always track
# after multiple clicks during training, so the past tokens seen during training
# are always the single mask token (and we'll let it be the object-memory token).
sam_tokens_out = mask_tokens_out[:, :, 0:1] # [B, M, 1, C] shape
del out["mask_tokens_out"]
out["masks"] = masks
out["iou_pred"] = iou_pred
out["sam_tokens_out"] = sam_tokens_out
if multimask_output:
assert (
masks.shape[2] == self.num_mask_output_per_object
), f"{masks.shape=}, {self.num_mask_output_per_object=}"
assert (
iou_pred.shape[2] == self.num_mask_output_per_object
), f"{iou_pred.shape=}, {self.num_mask_output_per_object=}"
if self.use_multimask_token_for_obj_ptr:
if self.decode_mask_with_shared_tokens:
assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}"
else:
assert (
sam_tokens_out.shape[2] == self.num_mask_output_per_object
), f"{sam_tokens_out.shape=}, {self.num_mask_output_per_object=}"
else:
assert masks.shape[2] == 1, f"{masks.shape=}"
assert iou_pred.shape[2] == 1, f"{iou_pred.shape=}"
assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}"
return out
def predict_masks(
self,
image_embeddings: torch.Tensor,
image_pe: torch.Tensor,
high_res_features: Optional[List[torch.Tensor]] = None,
extra_per_object_embeddings: Optional[
torch.Tensor
] = None, # num_buckets, multiplex_count, C
) -> dict[str, torch.Tensor]:
"""Predicts masks. See 'forward' for more details."""
# Concatenate output tokens
B = image_embeddings.shape[0]
token_list = []
if self.pred_obj_scores and not self.decode_mask_attribute_with_shared_tokens:
token_list.append(self.obj_score_token.weight)
if not self.decode_mask_attribute_with_shared_tokens:
token_list.append(self.iou_token.weight)
tokens = torch.cat(token_list, dim=0)
tokens = tokens.unsqueeze(0).expand(B, -1, -1)
if extra_per_object_embeddings is not None:
mask_tokens = self.mask_tokens.weight.view(
1, self.multiplex_count, self.num_mask_output_per_object, -1
).expand(B, -1, -1, -1)
mask_tokens = mask_tokens + extra_per_object_embeddings.unsqueeze(2)
mask_tokens = mask_tokens.flatten(1, 2)
else:
mask_tokens = self.mask_tokens.weight.unsqueeze(0).expand(B, -1, -1)
tokens = torch.cat([tokens, mask_tokens], dim=1)
src = image_embeddings
assert (
image_pe.size(0) == 1
), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
b, c, h, w = src.shape
# Run the transformer
hs, src = self.transformer(src, pos_src, tokens)
# Parse transformer outputs based on token sharing configuration
if self.decode_mask_attribute_with_shared_tokens:
assert (
hs.shape[1] == self.num_mask_tokens
), f"{hs.shape=}, {self.num_mask_tokens=}"
iou_token_out = mask_tokens_out = hs[:, 0 : self.num_mask_tokens]
if self.pred_obj_scores:
obj_score_token_out = mask_tokens_out
else:
# Separate tokens for each prediction type
s = 0
if self.pred_obj_scores:
obj_score_token_out = hs[:, s : s + self.multiplex_count, :]
s += self.multiplex_count
iou_token_out = hs[:, s : s + self.multiplex_count, :]
s += self.multiplex_count
mask_tokens_out = hs[:, s : s + self.num_mask_tokens, :]
assert (
hs.shape[1] == s + self.num_mask_tokens
), f"{hs.shape=}, {s=}, {self.num_mask_tokens=}"
# Upscale mask embeddings and predict masks using the mask tokens
src = src.transpose(1, 2).view(b, c, h, w)
if not self.use_high_res_features:
upscaled_embedding = self.output_upscaling(src)
else:
dc1, ln1, act1, dc2, act2 = self.output_upscaling
feat_s0, feat_s1 = high_res_features
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
if self.decode_mask_with_shared_tokens:
mask_tokens_out = mask_tokens_out.view(B, self.multiplex_count, 1, -1)
else:
mask_tokens_out = mask_tokens_out.view(
B, self.multiplex_count, self.num_mask_output_per_object, -1
)
if self.num_multimask_outputs == 0:
hyper_in = self.output_hypernetworks_mlp(
mask_tokens_out[:, :, 0, :]
).unsqueeze(2) # [B, M, 1, C]
else:
hyper_in_list: List[torch.Tensor] = []
for i in range(self.num_mask_output_per_object):
if self.decode_mask_with_shared_tokens:
hyper_in_list.append(
self.output_hypernetworks_mlps[i](mask_tokens_out[:, :, 0, :])
)
else:
hyper_in_list.append(
self.output_hypernetworks_mlps[i](mask_tokens_out[:, :, i, :])
)
# hyper_in: [B, M, num_multimask_outputs+1, C]
hyper_in = torch.stack(hyper_in_list, dim=2)
# generate the masks
b, c, h, w = upscaled_embedding.shape
masks = torch.bmm(
hyper_in.flatten(1, 2), upscaled_embedding.view(b, c, h * w)
).view(b, self.multiplex_count, self.num_mask_output_per_object, h, w)
# Generate mask quality predictions, with shape b * multiplex_count * (num_multimask_outputs+1)
iou_pred = self.iou_prediction_head(iou_token_out).view(
b, self.multiplex_count, self.num_mask_output_per_object
)
if self.pred_obj_scores:
# Generate mask quality predictions, with shape b * (num_multimask_outputs+1)
if (
self.decode_mask_attribute_with_shared_tokens
and not self.decode_mask_with_shared_tokens
):
object_score_logits = (
self.pred_obj_score_head(obj_score_token_out)
.view(b, self.multiplex_count, self.num_mask_output_per_object)
.sum(-1, keepdim=True)
)
else:
object_score_logits = self.pred_obj_score_head(obj_score_token_out)
else:
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
object_score_logits = 10.0 * iou_pred.new_ones(
iou_pred.shape[0], iou_pred.shape[1]
)
outputs = {
"masks": masks,
"iou_pred": iou_pred,
"mask_tokens_out": mask_tokens_out,
"object_score_logits": object_score_logits,
}
return outputs
def _get_stability_scores(self, mask_logits):
"""
Compute stability scores of the mask logits based on the IoU between upper and
lower thresholds.
"""
mask_logits = mask_logits.flatten(-2)
stability_delta = self.dynamic_multimask_stability_delta
area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
return stability_scores
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
"""
When outputting a single mask, if the stability score from the current single-mask
output (based on output token 0) falls below a threshold, we instead select from
multi-mask outputs (based on output token 1~3) the mask with the highest predicted
IoU score. This is intended to ensure a valid mask for both clicking and tracking.
"""
# first, flatten the batch and the multiplex dimensions
B, M = all_mask_logits.shape[:2]
all_mask_logits = all_mask_logits.flatten(0, 1)
all_iou_scores = all_iou_scores.flatten(0, 1)
# The best mask from multimask output tokens (1~3)
multimask_logits = all_mask_logits[:, 1:, :, :]
multimask_iou_scores = all_iou_scores[:, 1:]
best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
batch_inds = torch.arange(
multimask_iou_scores.size(0), device=all_iou_scores.device
)
best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
best_multimask_logits = best_multimask_logits.unsqueeze(1)
best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
# The mask from singlemask output token 0 and its stability score
singlemask_logits = all_mask_logits[:, 0:1, :, :]
singlemask_iou_scores = all_iou_scores[:, 0:1]
stability_scores = self._get_stability_scores(singlemask_logits)
is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
# Dynamically fall back to best multimask output upon low stability scores.
mask_logits_out = torch.where(
is_stable[..., None, None].expand_as(singlemask_logits),
singlemask_logits,
best_multimask_logits,
)
iou_scores_out = torch.where(
is_stable.expand_as(singlemask_iou_scores),
singlemask_iou_scores,
best_multimask_iou_scores,
)
# restore the batch and multiplex dimensions
mask_logits_out = mask_logits_out.unflatten(0, (B, M))
iou_scores_out = iou_scores_out.unflatten(0, (B, M))
return mask_logits_out, iou_scores_out
# Lightly adapted from
# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
class MLP(nn.Module):
def __init__(
self,
input_dim: int,
hidden_dim: int,
output_dim: int,
num_layers: int,
sigmoid_output: bool = False,
) -> None:
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(
nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
)
self.sigmoid_output = sigmoid_output
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
if self.sigmoid_output:
x = F.sigmoid(x)
return x
+538
View File
@@ -0,0 +1,538 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
# pyre-unsafe
import logging
import math
from typing import Optional
import torch
from torch import nn
# Special values for object tracking
_PADDING_NUM = -1 # Marks empty slots in buckets
_REMOVED_NUM = -1116 # Marks objects that have been removed
logger = logging.getLogger(__name__)
class MultiplexState:
"""
MultiplexState records the state of multiplexing, for one or more buckets.
At a high level, we deal with the conversion of tensors between the data space (batch_size, num_channels, ...)
and the multiplex space (num_buckets, multiplex_count, num_channels, ...).
The multiplex state stores the assignments of each batch element to a slot in a bucket.
Each bucket has a fixed number of slots (multiplex_count), and not all slots need to be filled.
The batch size should equate to total_valid_entries, which is the sum of the number of valid entries in each bucket.
There are two main operations that this class supports:
mux: convert tensors in the data space to the multiplex space.
The mental model is that we start from a tensor of zeros that has the shape of the output,
then we go through the valid entries and place them into the corresponding slots, indicated by the assignments.
demux: convert tensors in the multiplex space to the data space.
This is the reverse operation of mux. Note that zeros were used in mux for the padding slots,
and that those slots are ignored in demux.
There are also two utility functions for object mangement:
add_objects: add new objects to the state by filling in empty slots
remove_objects: remove objects from the state by marking them as removed (not the same as empty!)
"""
def __init__(
self,
assignments: list[list[int]],
device: torch.device,
dtype: torch.dtype,
allowed_bucket_capacity: int,
*,
object_ids: Optional[list[int]] = None,
):
"""
assignments: a list of lists of object indices
Each top-level list represents a bucket
Each inner list represents the object indices that are in the bucket
The object indices must ranges from 0 to num_valid_entries - 1, except for the following special values (all negatives):
_PADDING_NUM, which denotes padding entries
_REMOVED_NUM, which denotes an pre-existing object that got removed (currently not used during init)
If you wish to save the "true" object IDs, i.e., during inference, you can bookkeep them here
"""
self.device = device
self.dtype = dtype
# Initialize bucket assignments and precompute matrices
self.allowed_bucket_capacity = allowed_bucket_capacity
self._initialize_assignments(assignments, object_ids=object_ids)
def _initialize_assignments(
self, assignments: list[list[int]], *, object_ids: Optional[list[int]] = None
):
self.assignments = assignments
self.num_buckets = len(self.assignments)
if self.num_buckets == 0:
logger.error("No buckets found in the state")
raise ValueError("No buckets found in the state")
self.multiplex_count = len(self.assignments[0])
assert all(
len(self.assignments[i]) == self.multiplex_count
for i in range(self.num_buckets)
)
# number of non-negative elements in the state
self.total_valid_entries = sum(
sum(1 for x in bucket if x >= 0) for bucket in self.assignments
)
self.total_non_padding_entries = sum(
sum(1 for x in bucket if x != _PADDING_NUM) for bucket in self.assignments
)
# check the validity of the object IDs
self.object_ids = object_ids
if self.object_ids is not None:
assert (
len(self.object_ids) == self.total_valid_entries
), "object_ids should map 1:1 to the valid entries"
# check the validity of the assignments
all_object_idxs = set()
for bucket in self.assignments:
valid_entries_in_bucket = sum(1 for x in bucket if x != _PADDING_NUM)
assert (
valid_entries_in_bucket <= self.allowed_bucket_capacity
), f"{valid_entries_in_bucket=} > {self.allowed_bucket_capacity=}"
for obj_idx in bucket:
if obj_idx >= 0:
assert (
obj_idx < self.total_non_padding_entries
), f"object ID {obj_idx} >= {self.total_non_padding_entries}"
assert obj_idx not in all_object_idxs, "object IDs must be unique"
all_object_idxs.add(obj_idx)
# Precompute and cache the actual selection matrices
self._precompute_transition_matrices(self.device, self.dtype)
@property
def available_slots(self) -> int:
# returns the number of available slots in the state
return (
self.num_buckets * self.allowed_bucket_capacity
- self.total_non_padding_entries
)
def find_next_batch_of_available_indices(
self,
num_objects: int,
*,
allow_new_buckets: bool = False,
prefer_new_buckets: bool = False,
) -> list[int]:
# produce a list of consecutive indices that are available in the state
# Note: prefer_new_buckets parameter is accepted for API compatibility but not used here
# as the actual bucket allocation logic is in add_objects()
assert num_objects > 0, f"{num_objects=} must be positive"
if not allow_new_buckets:
assert (
self.available_slots >= num_objects
), f"not enough available slots {self.available_slots} < {num_objects}"
return list(
range(
self.total_valid_entries,
self.total_valid_entries + num_objects,
)
)
def add_objects(
self,
object_indices: list[int],
*,
object_ids: Optional[list[int]] = None,
allow_new_buckets: bool = False,
prefer_new_buckets: bool = False,
):
"""
Add new objects to the state by filling in empty slots and
creating new buckets if necessary.
object_indices must be sorted and follow existing object indices.
If prefer_new_buckets is True, we skip filling existing slots and place
the objects into freshly created buckets (requires allow_new_buckets=True).
"""
if len(object_indices) == 0:
return
# we will modify this in-place
object_indices = object_indices.copy()
assert (object_ids is None) == (
self.object_ids is None
), "object_ids must either be always given or always omitted"
if object_ids is not None:
assert len(object_ids) == len(
object_indices
), "object_ids must have the same length as object_indices"
object_ids = object_ids.copy()
num_new_objects = len(object_indices)
assert object_indices == sorted(object_indices), "object_indices must be sorted"
object_indices.reverse() # reverse so we can pop from the end
if object_ids is not None:
object_ids.reverse()
if prefer_new_buckets:
assert allow_new_buckets, "prefer_new_buckets requires allow_new_buckets"
slots_filled = 0
buckets_created = 0
def _pop_next():
idx = object_indices.pop()
if object_ids is not None and self.object_ids is not None:
self.object_ids.append(object_ids.pop())
return idx
if not prefer_new_buckets:
# Fill empty slots in existing buckets first
for bucket in self.assignments:
for i in range(self.allowed_bucket_capacity):
if bucket[i] == _PADDING_NUM:
bucket[i] = _pop_next()
slots_filled += 1
if len(object_indices) == 0:
break
if len(object_indices) == 0:
break
if len(object_indices) > 0 and not allow_new_buckets:
raise ValueError(
f"Cannot place objects {list(reversed(object_indices))} without creating new buckets"
)
# Create new buckets for remaining objects (or all objects if prefer_new_buckets)
while len(object_indices) > 0:
new_bucket = [_PADDING_NUM] * self.multiplex_count
for i in range(self.allowed_bucket_capacity):
if len(object_indices) == 0:
break
new_bucket[i] = _pop_next()
self.assignments.append(new_bucket)
buckets_created += 1
# reinitialize all the settings
original_num_entries = self.total_valid_entries
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
assert (
self.total_valid_entries == original_num_entries + num_new_objects
), f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}"
logger.info(
f"Filled {slots_filled} slots and created {buckets_created} new buckets"
)
logger.info(
f"{self.num_buckets=}, {self.total_valid_entries=}, {self.total_non_padding_entries=}"
)
def remove_objects(self, object_indices: list[int], strict: bool = True):
"""
Remove objects from the state by marking them as removed.
Remove a bucket if all objects in the bucket are removed.
Args:
object_indices: List of object indices to remove
strict: If True, will raise an error if any object indices are not found in the state
Returns:
List of bucket indices that we are going to keep
"""
object_indices = object_indices.copy()
# Mark objects as removed in assignments
for bucket_idx, bucket in enumerate(self.assignments):
for slot_idx, obj_id in enumerate(bucket):
if obj_id in object_indices:
self.assignments[bucket_idx][slot_idx] = _REMOVED_NUM
object_indices.remove(obj_id)
if strict:
assert (
len(object_indices) == 0
), f"Failed to remove objects: {object_indices}"
# Check which buckets should be completely removed (all objects removed/paddings)
# and which buckets we will keep
buckets_to_remove = []
buckets_to_keep = []
for bucket_idx, bucket in enumerate(self.assignments):
# Check if all objects in this bucket are removed or are paddings
all_removed = all(
obj_id in [_PADDING_NUM, _REMOVED_NUM] for obj_id in bucket
)
if all_removed:
buckets_to_remove.append(bucket_idx)
logger.info(
f"Bucket {bucket_idx} marked for removal - all objects removed/paddings"
)
else:
buckets_to_keep.append(bucket_idx)
# Remove buckets in reverse order to maintain correct indices
for bucket_idx in reversed(buckets_to_remove):
del self.assignments[bucket_idx]
if len(buckets_to_keep) == 0:
logger.info(f"Removing all buckets: {buckets_to_remove}; state invalidated")
self.assignments = None
if self.object_ids is not None:
self.object_ids = []
return buckets_to_keep
# After removal, remap object IDs to be sequential
# Collect all unique positive object IDs and create a mapping to sequential IDs
all_positive_ids = set()
for bucket in self.assignments:
for obj_id in bucket:
if obj_id >= 0:
all_positive_ids.add(obj_id)
# Create mapping from old IDs to new sequential IDs
sorted_ids = sorted(all_positive_ids)
id_mapping = {old_id: new_id for new_id, old_id in enumerate(sorted_ids)}
# Apply the mapping to assignments to make IDs sequential
for bucket in self.assignments:
for i, obj_id in enumerate(bucket):
if obj_id >= 0:
bucket[i] = id_mapping[obj_id]
# Update object_ids if they exist
if self.object_ids is not None:
# Create new object_ids array based on the remapped indices
# We need to preserve the original object_ids for the objects that weren't removed
new_object_ids = [None] * len(sorted_ids)
# Map the original object_ids to their new positions
for old_idx, new_idx in id_mapping.items():
new_object_ids[new_idx] = self.object_ids[old_idx]
assert not any(obj_id is None for obj_id in new_object_ids)
self.object_ids = new_object_ids
# Reinitialize the state to update all internal structures
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
logger.info(f"Removed these buckets: {buckets_to_remove}")
logger.info(f"Kept these buckets: {buckets_to_keep}")
logger.info(
f"Remaining buckets: {self.num_buckets}, total valid entries: {self.total_valid_entries}"
)
return buckets_to_keep
def _precompute_transition_matrices(self, device: torch.device, dtype: torch.dtype):
"""
Precompute the transition matrices for maximum efficiency.
Note that these should be partial permutation matrices.
"""
# Create a transition matrix for muxing
self.mux_matrix = torch.zeros(
self.num_buckets * self.multiplex_count,
self.total_valid_entries,
device=device,
dtype=dtype,
)
# Create a transition matrix for demuxing
self.demux_matrix = torch.zeros(
self.total_valid_entries,
self.num_buckets * self.multiplex_count,
device=device,
dtype=dtype,
)
# Fill both matrices based on assignments
for i in range(self.num_buckets):
for j in range(self.multiplex_count):
bucket_idx = i * self.multiplex_count + j
object_idx = self.assignments[i][j]
if object_idx >= 0:
self.mux_matrix[bucket_idx, object_idx] = 1.0
self.demux_matrix[object_idx, bucket_idx] = 1.0
def mux(self, x: torch.Tensor) -> torch.Tensor:
"""
Multiplexing operation
x: self.total_valid_entries * ...
return num_buckets * multiplex_count * ...
with padding entries filled with 0
"""
num_valid_entries = x.shape[0]
assert (
num_valid_entries == self.total_valid_entries
), f"{num_valid_entries=} != {self.total_valid_entries=}"
output_shape = (
self.num_buckets,
self.multiplex_count,
) + x.shape[1:]
x_flat = x.reshape(num_valid_entries, -1)
# Apply mux matrix: (num_buckets * multiplex_count, batch_size) @ (batch_size, features)
# Result: (num_buckets * multiplex_count, features)
result_flat = self.mux_matrix @ x_flat
result = result_flat.view(output_shape)
return result
def demux(self, x: torch.Tensor) -> torch.Tensor:
"""
Inverse operation of mux
x: num_buckets, multiplex_count * ...
Returns: total_valid_entries * ...
"""
num_buckets, multiplex_count = x.shape[:2]
assert num_buckets == self.num_buckets, f"{num_buckets=} != {self.num_buckets=}"
assert (
multiplex_count == self.multiplex_count
), f"{multiplex_count=} != {self.multiplex_count=}"
output_shape = (self.total_valid_entries,) + x.shape[2:]
x_flat = x.reshape(num_buckets * multiplex_count, -1)
# Apply demux matrix: (total_valid_entries, num_buckets*multiplex_count) @ (num_buckets*multiplex_count, features)
# Result: (total_valid_entries, features)
result_flat = self.demux_matrix @ x_flat
result = result_flat.view(output_shape)
return result
def get_valid_object_mask(self) -> torch.Tensor:
"""
Returns a (num_buckets, multiplex_count) tensor with 1 for valid entries and 0 for padding entries
"""
valid_mask = self.mux_matrix.sum(dim=1) > 0
valid_mask = valid_mask.reshape(self.num_buckets, self.multiplex_count)
return valid_mask
def get_all_valid_object_idx(self) -> set[int]:
"""
Returns a set of all valid object idx in the state
Note that this returns the internal object idx representations,
not the arbitrary object IDs that are passed in during initialization
"""
all_valid_objects = {
obj_idx for bucket in self.assignments for obj_idx in bucket if obj_idx >= 0
}
return all_valid_objects
class MultiplexController(nn.Module):
def __init__(
self,
multiplex_count: int,
full_shuffle: bool = False,
eval_multiplex_count: int = -1,
):
super().__init__()
self.multiplex_count = multiplex_count
self.full_shuffle = full_shuffle
if eval_multiplex_count < 0:
self.eval_multiplex_count = multiplex_count
else:
self.eval_multiplex_count = eval_multiplex_count
assert self.multiplex_count >= 1
@property
def allowed_bucket_capacity(self) -> int:
if self.training:
return self.multiplex_count
else:
return self.eval_multiplex_count
def get_state(
self,
num_valid_entries: int,
device: torch.device,
dtype: torch.dtype,
random: bool = True,
*,
object_ids: Optional[
list[int]
] = None, # object_ids is an auxiliary field that we pass to the state unmodified
) -> MultiplexState:
# returns a state that maps elements in the batch to buckets of size self.multiplex_count
allowed_bucket_capacity = self.allowed_bucket_capacity
# the size of the bucket during training
true_bucket_capacity = self.multiplex_count
num_buckets = math.ceil(num_valid_entries / allowed_bucket_capacity)
# each bucket contains at most self.multiplex_count elements
# padding elements are marked with _PADDING_NUM (only the last bucket should contain _PADDING_NUM)
if self.full_shuffle:
# Shuffle all IDs, including the paddings
ids = torch.cat(
[
torch.arange(num_valid_entries, dtype=torch.long),
torch.tensor(
[_PADDING_NUM]
* (num_buckets * true_bucket_capacity - num_valid_entries),
dtype=torch.long,
),
],
dim=0,
)
if random:
indices = torch.randperm(ids.shape[0], dtype=torch.long)
ids = ids[indices]
# convert to a list of list
assignments = []
for i in range(num_buckets):
assignments.append(
ids[
i * true_bucket_capacity : (i + 1) * true_bucket_capacity
].tolist()
)
else:
# Only shuffle the the IDs within the first #batch_size slots, leave all paddings at the end
if random:
# randomly assign ids to buckets
ids = torch.randperm(num_valid_entries, dtype=torch.int64)
else:
ids = torch.arange(num_valid_entries)
# append with _PADDING_NUM to make a multiple of bucket_capacity
total_elements = num_buckets * allowed_bucket_capacity
if ids.shape[0] < total_elements:
ids = torch.cat(
[
ids,
torch.tensor([_PADDING_NUM] * (total_elements - ids.shape[0])),
]
)
# convert to a list of list
assignments = []
for i in range(num_buckets):
assignments.append(
ids[
i * allowed_bucket_capacity : (i + 1) * allowed_bucket_capacity
].tolist()
+ [_PADDING_NUM] * (true_bucket_capacity - allowed_bucket_capacity)
)
return MultiplexState(
assignments,
device,
dtype,
allowed_bucket_capacity=allowed_bucket_capacity,
object_ids=object_ids,
)
+143
View File
@@ -9,6 +9,7 @@ from typing import List, Optional, Tuple
import torch
import torch.nn as nn
from sam3.model.data_misc import NestedTensor
class Sam3DualViTDetNeck(nn.Module):
@@ -124,3 +125,145 @@ class Sam3DualViTDetNeck(nn.Module):
sam2_out.append(sam2_x_out)
sam2_pos.append(sam2_pos_out)
return sam3_out, sam3_pos, sam2_out, sam2_pos
class Sam3TriViTDetNeck(nn.Module):
def __init__(
self,
trunk: nn.Module,
position_encoding: nn.Module,
d_model: int,
neck_norm=None,
scale_factors=(4.0, 2.0, 1.0),
):
"""
SimpleFPN neck with three heads (sam3, interactive, propagation).
"""
super().__init__()
self.trunk = trunk
self.position_encoding = position_encoding
self.convs = nn.ModuleList()
self.scale_factors = scale_factors
use_bias = neck_norm is None
dim = self.trunk.channel_list[-1]
for _, scale in enumerate(scale_factors):
current = nn.Sequential()
if scale == 4.0:
current.add_module(
"dconv_2x2_0",
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
)
current.add_module(
"gelu",
nn.GELU(),
)
current.add_module(
"dconv_2x2_1",
nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
)
out_dim = dim // 4
elif scale == 2.0:
current.add_module(
"dconv_2x2",
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
)
out_dim = dim // 2
elif scale == 1.0:
out_dim = dim
elif scale == 0.5:
current.add_module(
"maxpool_2x2",
nn.MaxPool2d(kernel_size=2, stride=2),
)
out_dim = dim
else:
raise NotImplementedError(f"scale_factor={scale} is not supported yet.")
current.add_module(
"conv_1x1",
nn.Conv2d(
in_channels=out_dim,
out_channels=d_model,
kernel_size=1,
bias=use_bias,
),
)
current.add_module(
"conv_3x3",
nn.Conv2d(
in_channels=d_model,
out_channels=d_model,
kernel_size=3,
padding=1,
bias=use_bias,
),
)
self.convs.append(current)
# Assumes the new necks are just clones of the original neck
self.interactive_convs = deepcopy(self.convs)
self.propagation_convs = deepcopy(self.convs)
def forward(
self,
tensor_list,
*,
need_sam3_out: bool = True,
need_interactive_out: bool = True,
need_propagation_out: bool = True,
):
xs = self.trunk(tensor_list)
sam3_out = []
interactive_out = []
propagation_out = []
sam3_pos = []
interactive_pos = []
propagation_pos = []
x = xs[-1] # simpleFPN
# OSS trunk returns plain tensors; onevision trunk returns NestedTensors.
# Use getattr to handle both in a torch.compile-friendly way.
x_data = getattr(x, "tensors", x)
x_mask = getattr(x, "mask", None)
for _, (conv, interactive_conv, propagation_conv) in enumerate(
zip(self.convs, self.interactive_convs, self.propagation_convs)
):
if need_sam3_out:
sam3_conv_out = conv(x_data)
sam3_x_out = NestedTensor(sam3_conv_out, x_mask)
sam3_out.append(sam3_x_out)
sam3_pos.append(
self.position_encoding(sam3_conv_out).to(sam3_conv_out.dtype)
)
if need_interactive_out:
interactive_conv_out_t = interactive_conv(x_data)
interactive_conv_out = NestedTensor(interactive_conv_out_t, x_mask)
interactive_out.append(interactive_conv_out)
interactive_pos.append(
self.position_encoding(interactive_conv_out_t).to(
interactive_conv_out_t.dtype
)
)
if need_propagation_out:
propagation_conv_out = propagation_conv(x_data)
propagation_x_out = NestedTensor(propagation_conv_out, x_mask)
propagation_out.append(propagation_x_out)
propagation_pos.append(
self.position_encoding(propagation_conv_out).to(
propagation_conv_out.dtype
)
)
return (
sam3_out,
sam3_pos,
interactive_out,
interactive_pos,
propagation_out,
propagation_pos,
)
+7 -1
View File
@@ -38,11 +38,17 @@ class PositionEmbeddingSine(nn.Module):
# Precompute positional encodings under `precompute_resolution` to fill the cache
# and avoid symbolic shape tracing errors in torch.compile in PyTorch 2.4 nightly.
if precompute_resolution is not None:
# We precompute pos enc for stride 4, 8, 16 and 32 to fill `self.cache`.
# We precompute pos enc for all strides used by both DualViTDetNeck and
# TriViTDetNeck (scale_factors 4.0, 2.0, 1.0, 0.5 applied to backbone
# output at stride 14 from 1008px input → 72x72).
precompute_sizes = [
(int(precompute_resolution // 3.5), int(precompute_resolution // 3.5)),
(precompute_resolution // 4, precompute_resolution // 4),
(int(precompute_resolution // 7), int(precompute_resolution // 7)),
(precompute_resolution // 8, precompute_resolution // 8),
(int(precompute_resolution // 14), int(precompute_resolution // 14)),
(precompute_resolution // 16, precompute_resolution // 16),
(int(precompute_resolution // 28), int(precompute_resolution // 28)),
(precompute_resolution // 32, precompute_resolution // 32),
]
for size in precompute_sizes:
+15 -15
View File
@@ -94,9 +94,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
input_image = self._transforms(image)
input_image = input_image[None, ...].to(self.device)
assert len(input_image.shape) == 4 and input_image.shape[1] == 3, (
f"input_image must be of size 1x3xHxW, got {input_image.shape}"
)
assert (
len(input_image.shape) == 4 and input_image.shape[1] == 3
), f"input_image must be of size 1x3xHxW, got {input_image.shape}"
logging.info("Computing image embeddings for the provided image...")
backbone_out = self.model.forward_image(input_image)
(
@@ -133,17 +133,17 @@ class SAM3InteractiveImagePredictor(nn.Module):
assert isinstance(image_list, list)
self._orig_hw = []
for image in image_list:
assert isinstance(image, np.ndarray), (
"Images are expected to be an np.ndarray in RGB format, and of shape HWC"
)
assert isinstance(
image, np.ndarray
), "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
self._orig_hw.append(image.shape[:2])
# Transform the image to the form expected by the model
img_batch = self._transforms.forward_batch(image_list)
img_batch = img_batch.to(self.device)
batch_size = img_batch.shape[0]
assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, (
f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
)
assert (
len(img_batch.shape) == 4 and img_batch.shape[1] == 3
), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
logging.info("Computing image embeddings for the provided images...")
backbone_out = self.model.forward_image(img_batch)
(
@@ -299,9 +299,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
):
unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
if point_coords is not None:
assert point_labels is not None, (
"point_labels must be supplied if point_coords is supplied."
)
assert (
point_labels is not None
), "point_labels must be supplied if point_coords is supplied."
point_coords = torch.as_tensor(
point_coords, dtype=torch.float, device=self.device
)
@@ -438,9 +438,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
raise RuntimeError(
"An image must be set with .set_image(...) to generate an embedding."
)
assert self._features is not None, (
"Features must exist if an image has been set."
)
assert (
self._features is not None
), "Features must exist if an image has been set."
return self._features["image_embed"]
@property
+322
View File
@@ -0,0 +1,322 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
# pyre-unsafe
"""
Base predictor class shared by SAM3 and SAM3.1 (multiplex) video predictors.
Provides the common handle_request/handle_stream_request API and session management.
Subclasses only need to override methods where their behavior differs.
"""
import gc
import time
import uuid
from typing import Dict, List, Optional
import torch
from sam3.logger import get_logger
logger = get_logger(__name__)
class Sam3BasePredictor:
"""
Base class for SAM3 video predictors. Provides:
- Session management (start, reset, close)
- Request dispatch (handle_request / handle_stream_request)
- Common add_prompt / propagate_in_video / remove_object / reset_session / close_session
Subclasses must set `self.model` and `self._all_inference_states` before use.
"""
def __init__(self):
# Subclasses must populate these
self.model = None
self._all_inference_states: Dict[str, dict] = {}
# ── Request dispatch ──────────────────────────────────────────────
@torch.inference_mode()
def handle_request(self, request):
"""Dispatch a request based on its type."""
request_type = request["type"]
if request_type == "start_session":
return self.start_session(
resource_path=request["resource_path"],
session_id=request.get("session_id", None),
offload_video_to_cpu=request.get("offload_video_to_cpu", False),
)
elif request_type == "add_prompt":
return self.add_prompt(
session_id=request["session_id"],
frame_idx=request["frame_index"],
text=request.get("text", None),
points=request.get("points", None),
point_labels=request.get("point_labels", None),
clear_old_points=request.get("clear_old_points", True),
bounding_boxes=request.get("bounding_boxes", None),
bounding_box_labels=request.get("bounding_box_labels", None),
clear_old_boxes=request.get("clear_old_boxes", True),
output_prob_thresh=request.get(
"output_prob_thresh",
getattr(self, "default_output_prob_thresh", 0.5),
),
obj_id=request.get("obj_id", None),
)
elif request_type == "remove_object":
return self.remove_object(
session_id=request["session_id"],
frame_idx=request.get("frame_index", 0),
obj_id=request["obj_id"],
)
elif request_type == "reset_session":
return self.reset_session(session_id=request["session_id"])
elif request_type == "cancel_propagation":
return self.cancel_propagation(session_id=request["session_id"])
elif request_type == "close_session":
return self.close_session(
session_id=request["session_id"],
run_gc_collect=request.get("run_gc_collect", True),
)
else:
raise RuntimeError(f"invalid request type: {request_type}")
@torch.inference_mode()
def handle_stream_request(self, request):
"""Dispatch a stream request based on its type."""
request_type = request["type"]
if request_type == "propagate_in_video":
yield from self.propagate_in_video(
session_id=request["session_id"],
propagation_direction=request.get("propagation_direction", "both"),
start_frame_idx=request.get("start_frame_index", None),
max_frame_num_to_track=request.get("max_frame_num_to_track", None),
output_prob_thresh=request.get(
"output_prob_thresh",
getattr(self, "default_output_prob_thresh", 0.5),
),
)
else:
raise RuntimeError(f"invalid request type: {request_type}")
# ── Session management ────────────────────────────────────────────
def start_session(
self,
resource_path,
session_id=None,
offload_video_to_cpu=False,
):
"""Start a new inference session on a video directory or path."""
init_kwargs = dict(
resource_path=resource_path,
offload_video_to_cpu=offload_video_to_cpu,
)
if hasattr(self, "async_loading_frames"):
init_kwargs["async_loading_frames"] = self.async_loading_frames
if hasattr(self, "video_loader_type"):
init_kwargs["video_loader_type"] = self.video_loader_type
inference_state = self.model.init_state(**init_kwargs)
if not session_id:
session_id = str(uuid.uuid4())
self._all_inference_states[session_id] = {
"state": inference_state,
"session_id": session_id,
"start_time": time.time(),
"last_use_time": time.time(),
}
logger.info(f"started new session {session_id}")
return {"session_id": session_id}
def add_prompt(
self,
session_id: str,
frame_idx: int,
text: Optional[str] = None,
points=None,
point_labels=None,
clear_old_points: bool = True,
bounding_boxes=None,
bounding_box_labels=None,
clear_old_boxes: bool = True,
output_prob_thresh: float = 0.5,
obj_id: Optional[int] = None,
):
"""Add text, box and/or point prompt on a specific video frame."""
session = self._get_session(session_id)
inference_state = session["state"]
self._extend_expiration_time(session)
# Convert lists to tensors if needed
if points is not None and not isinstance(points, torch.Tensor):
points = torch.tensor(points, dtype=torch.float32)
if point_labels is not None and not isinstance(point_labels, torch.Tensor):
point_labels = torch.tensor(point_labels, dtype=torch.int32)
if bounding_boxes is not None and not isinstance(bounding_boxes, torch.Tensor):
bounding_boxes = torch.tensor(bounding_boxes, dtype=torch.float32)
if bounding_box_labels is not None and not isinstance(
bounding_box_labels, torch.Tensor
):
bounding_box_labels = torch.tensor(bounding_box_labels, dtype=torch.int32)
kwargs = dict(
inference_state=inference_state,
frame_idx=frame_idx,
text_str=text,
points=points,
point_labels=point_labels,
clear_old_points=clear_old_points,
boxes_xywh=bounding_boxes,
box_labels=bounding_box_labels,
clear_old_boxes=clear_old_boxes,
output_prob_thresh=output_prob_thresh,
)
if obj_id is not None:
kwargs["obj_id"] = obj_id
# Filter kwargs to only pass what the model accepts
# (SAM3 has a simpler add_prompt than SAM3.1)
import inspect
sig = inspect.signature(self.model.add_prompt)
valid_params = set(sig.parameters.keys())
filtered_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
frame_idx, outputs = self.model.add_prompt(**filtered_kwargs)
return {"frame_index": frame_idx, "outputs": outputs}
def remove_object(
self,
session_id: str,
frame_idx: int = 0,
obj_id: int = 0,
is_user_action: bool = True,
):
"""Remove an object from tracking."""
session = self._get_session(session_id)
inference_state = session["state"]
self._extend_expiration_time(session)
result = self.model.remove_object(
inference_state, obj_id, frame_idx=frame_idx, is_user_action=is_user_action
)
# Handle both return conventions
if result is None or (isinstance(result, tuple) and result[1] is None):
import numpy as np
out_obj_ids = torch.zeros(0, dtype=torch.int64)
out_binary_masks = torch.zeros(
0,
inference_state["orig_height"],
inference_state["orig_width"],
dtype=torch.bool,
)
out_boxes_xywh = torch.zeros(0, 4, dtype=torch.float32)
outputs = {
"out_obj_ids": out_obj_ids.cpu().numpy(),
"out_boxes_xywh": out_boxes_xywh.cpu().numpy(),
"out_binary_masks": out_binary_masks.cpu().numpy(),
}
elif isinstance(result, tuple):
_, outputs = result
else:
outputs = result
return {"frame_index": frame_idx, "outputs": outputs}
def cancel_propagation(self, session_id):
"""Cancel any ongoing propagation. No-op if not supported by the model."""
session = self._get_session(session_id)
inference_state = session["state"]
self._extend_expiration_time(session)
if hasattr(self.model, "cancel_propagation"):
self.model.cancel_propagation(inference_state)
return {"is_success": True}
def propagate_in_video(
self,
session_id,
propagation_direction="both",
start_frame_idx=None,
max_frame_num_to_track=None,
output_prob_thresh=0.5,
**kwargs,
):
"""Propagate the added prompts to get results on all video frames."""
try:
session = self._get_session(session_id)
inference_state = session["state"]
self._extend_expiration_time(session)
if propagation_direction not in ["both", "forward", "backward"]:
raise ValueError(
f"invalid propagation direction: {propagation_direction}"
)
propagate_kwargs = dict(
inference_state=inference_state,
start_frame_idx=start_frame_idx,
max_frame_num_to_track=max_frame_num_to_track,
)
# Only pass output_prob_thresh / extra kwargs if the model supports them
import inspect
sig = inspect.signature(self.model.propagate_in_video)
if "output_prob_thresh" in sig.parameters:
propagate_kwargs["output_prob_thresh"] = output_prob_thresh
for k, v in kwargs.items():
if k in sig.parameters:
propagate_kwargs[k] = v
# Forward propagation
if propagation_direction in ["both", "forward"]:
for frame_idx, outputs in self.model.propagate_in_video(
**propagate_kwargs,
reverse=False,
):
yield {"frame_index": frame_idx, "outputs": outputs}
# Backward propagation
if propagation_direction in ["both", "backward"]:
for frame_idx, outputs in self.model.propagate_in_video(
**propagate_kwargs,
reverse=True,
):
yield {"frame_index": frame_idx, "outputs": outputs}
finally:
logger.info(f"propagation ended in session {session_id}")
def reset_session(self, session_id):
"""Reset the session to its initial state."""
session = self._get_session(session_id)
inference_state = session["state"]
self._extend_expiration_time(session)
self.model.reset_state(inference_state)
return {"is_success": True}
def close_session(self, session_id, run_gc_collect=True):
"""Close a session. Idempotent."""
session = self._all_inference_states.pop(session_id, None)
if session is None:
logger.warning(f"cannot close session {session_id} as it does not exist")
else:
del session
if run_gc_collect:
gc.collect()
logger.info(f"removed session {session_id}")
return {"is_success": True}
def _get_session(self, session_id):
session = self._all_inference_states.get(session_id, None)
if session is None:
raise RuntimeError(
f"Cannot find session {session_id}; it might have expired"
)
return session
def _extend_expiration_time(self, session):
"""Update last-use time for session expiration tracking."""
session["last_use_time"] = time.time()
def shutdown(self):
"""Shutdown the predictor and clear all sessions."""
self._all_inference_states.clear()
+32 -4
View File
@@ -16,6 +16,7 @@ from sam3.train.data.collator import BatchedDatapoint
from .act_ckpt_utils import activation_ckpt_wrapper
from .box_ops import box_cxcywh_to_xyxy
from .data_misc import FindStage
from .geometry_encoders import Prompt
from .model_misc import inverse_sigmoid
@@ -442,6 +443,7 @@ class Sam3Image(torch.nn.Module):
find_input,
find_target,
geometric_prompt: Prompt,
**kwargs,
):
with torch.profiler.record_function("SAM3Image._encode_prompt"):
prompt, prompt_mask, backbone_out = self._encode_prompt(
@@ -474,10 +476,14 @@ class Sam3Image(torch.nn.Module):
# Run segmentation heads
with torch.profiler.record_function("SAM3Image._run_segmentation_heads"):
# Apply id_mapping to img_ids if backbone features were recomputed
seg_img_ids = find_input.img_ids
if "id_mapping" in backbone_out and backbone_out["id_mapping"] is not None:
seg_img_ids = backbone_out["id_mapping"][seg_img_ids]
self._run_segmentation_heads(
out=out,
backbone_out=backbone_out,
img_ids=find_input.img_ids,
img_ids=seg_img_ids,
vis_feat_sizes=encoder_out["vis_feat_sizes"],
encoder_hidden_states=out["encoder_hidden_states"],
prompt=prompt,
@@ -516,6 +522,28 @@ class Sam3Image(torch.nn.Module):
return out
def _get_geo_prompt_from_find_input(self, find_input: FindStage):
"""Construct an initial geometric prompt from the find input."""
point_embeddings, point_mask, point_labels = None, None, None
if find_input.input_points_before_embed is not None:
# Point embeddings are batch first, switch to seq first
point_embeddings = find_input.input_points_before_embed.transpose(0, 1)
# they are stored as (x,y,label), so we unpack
point_labels = point_embeddings[..., -1]
point_embeddings = point_embeddings[..., :-1]
point_mask = find_input.input_points_mask
geometric_prompt = Prompt(
box_embeddings=find_input.input_boxes_before_embed,
box_mask=find_input.input_boxes_mask,
box_labels=find_input.input_boxes_label,
point_embeddings=point_embeddings,
point_mask=point_mask,
point_labels=point_labels,
)
return geometric_prompt
def _get_dummy_prompt(self, num_prompts=1):
device = self.device
geometric_prompt = Prompt(
@@ -656,9 +684,9 @@ class Sam3Image(torch.nn.Module):
inference_state["original_heights"],
inference_state["original_widths"],
)
assert batch_size == len(orig_heights) == len(orig_widths), (
f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
)
assert (
batch_size == len(orig_heights) == len(orig_widths)
), f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
feats = [
feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
for feat, feat_size in zip(
+3 -3
View File
@@ -81,9 +81,9 @@ class Sam3Processor:
if not isinstance(images, list):
raise ValueError("Images must be a list of PIL images or tensors")
assert len(images) > 0, "Images list must not be empty"
assert isinstance(images[0], PIL.Image.Image), (
"Images must be a list of PIL images"
)
assert isinstance(
images[0], PIL.Image.Image
), "Images must be a list of PIL images"
state["original_heights"] = [image.height for image in images]
state["original_widths"] = [image.width for image in images]
File diff suppressed because it is too large Load Diff
+943
View File
@@ -0,0 +1,943 @@
import os
import torch
from sam3.model.vl_combiner import SAM3VLBackbone
try:
from sam3.model.vl_combiner import SAM3VLBackboneTri
except ImportError:
SAM3VLBackboneTri = None
from typing import Dict, List, Optional
import numpy as np
from sam3.model.data_misc import BatchedDatapoint, FindStage
from sam3.model.geometry_encoders import Prompt
from sam3.model.model_misc import SAM3Output
from sam3.model.sam3_image import Sam3Image
from sam3.model.sam3_multiplex_detector_utils import nms_masks
class Sam3MultiplexImageBase(Sam3Image):
"""A wrapper class to run Sam3Image on videos for per-frame detection (no tracking)."""
def __init__(
self,
*args,
tracking_score_thresh: float = 0.0,
offload_outputs_to_cpu_for_eval: bool = False,
**kwargs,
):
super().__init__(*args, **kwargs)
self.tracking_score_thresh = tracking_score_thresh
self.offload_outputs_to_cpu_for_eval = offload_outputs_to_cpu_for_eval
self.trim_outputs_for_eval = True # dummy option -- it doesn't do anything
def forward(
self,
input: BatchedDatapoint,
is_inference=False, # (a dummy parameter not used anymore)
):
assert (
not self.training
), "Sam3MultiplexImageBase should only be used in eval mode."
device = self.device
backbone_out = {"img_batch_all_stages": input.img_batch}
text_outputs = self.backbone.forward_text(input.find_text_batch, device=device)
backbone_out.update(text_outputs)
num_frames = len(input.find_inputs)
previous_stages_out = SAM3Output(
iter_mode=SAM3Output.IterMode.LAST_STEP_PER_STAGE
)
for frame_idx in range(num_frames):
find_input = input.find_inputs[frame_idx]
find_target = input.find_targets[frame_idx]
geometric_prompt = self._get_geo_prompt_from_find_input(find_input)
cur_out, _ = self.forward_video_grounding(
backbone_out=backbone_out,
find_input=find_input,
find_target=find_target,
geometric_prompt=geometric_prompt,
)
# offload model outputs to CPU (to save GPU memory) for evaluation
if self.offload_outputs_to_cpu_for_eval:
cur_out = {k: v.cpu() for k, v in cur_out.items()}
previous_stages_out.append([cur_out])
get_queries = None
return previous_stages_out, get_queries
def forward_video_grounding(
self,
backbone_out,
find_input,
find_target,
geometric_prompt: Prompt,
**kwargs,
):
# route this to the image grounding forward method
out = self.forward_grounding(
backbone_out=backbone_out,
find_input=find_input,
find_target=find_target,
geometric_prompt=geometric_prompt,
)
# trim the output to only include the necessary keys
out = {
"pred_logits": out["pred_logits"],
"pred_boxes": out["pred_boxes"],
"pred_boxes_xyxy": out["pred_boxes_xyxy"],
"pred_masks": out["pred_masks"],
"pred_object_ids": self._get_dummy_object_ids(out["pred_logits"]),
}
return out, backbone_out
def _get_dummy_object_ids(self, pred_logits):
"""Generate dummy object IDs for the detected objects, based on their detection query indices."""
# Assuming pred_logits has shape [batch_size, num_queries, num_classes]
B, Q, _ = pred_logits.shape
is_above_thresh = pred_logits.squeeze(2) > self.tracking_score_thresh
dummy_obj_ids = torch.arange(Q, device=self.device).expand(B, -1)
dummy_obj_ids = torch.where(is_above_thresh, dummy_obj_ids, -1)
return dummy_obj_ids
def _trim_outputs(self, *args, **kwargs):
pass # not needed for image-on-video
def _batch_find_inputs(
self,
find_inputs: List[FindStage],
chunk_start: int,
chunk_end: int,
) -> FindStage:
"""
Batch multiple FindStage objects into a single batched FindStage.
For each frame in the chunk, creates img_ids that point to the correct
frame index. When processing streaming video, the img_ids are the actual
frame indices (e.g., [0, 1, 2, ..., 15] for chunk 0-16), and the modulo
for circular buffer access is applied later in _get_img_feats.
Args:
find_inputs: List of FindStage objects for all frames.
chunk_start: Start index of the chunk.
chunk_end: End index of the chunk (exclusive).
Returns:
A single FindStage with batched tensors.
"""
chunk_find_inputs = [
find_inputs[i % len(find_inputs)] for i in range(chunk_start, chunk_end)
]
# Generate img_ids based on chunk frame indices
# Each frame in the chunk gets its corresponding frame index
# The modulo for circular buffer access is handled in _get_img_feats
device = chunk_find_inputs[0].img_ids.device
dtype = chunk_find_inputs[0].img_ids.dtype
img_ids_list = [
torch.tensor([i], device=device, dtype=dtype)
for i in range(chunk_start, chunk_end)
]
batched_img_ids = torch.cat(img_ids_list, dim=0)
# Generate img_ids_np to match
img_ids_np_list = [np.array([i]) for i in range(chunk_start, chunk_end)]
batched_img_ids_np = np.concatenate(img_ids_np_list, axis=0)
# Concatenate text_ids
text_ids_list = [fi.text_ids for fi in chunk_find_inputs]
batched_text_ids = torch.cat(text_ids_list, dim=0)
# Concatenate input_boxes
input_boxes_list = [fi.input_boxes for fi in chunk_find_inputs]
batched_input_boxes = (
torch.cat(input_boxes_list, dim=0)
if input_boxes_list[0] is not None
else None
)
# Concatenate input_boxes_mask
input_boxes_mask_list = [fi.input_boxes_mask for fi in chunk_find_inputs]
batched_input_boxes_mask = (
torch.cat(input_boxes_mask_list, dim=0)
if input_boxes_mask_list[0] is not None
else None
)
# Concatenate input_boxes_label
input_boxes_label_list = [fi.input_boxes_label for fi in chunk_find_inputs]
batched_input_boxes_label = (
torch.cat(input_boxes_label_list, dim=0)
if input_boxes_label_list[0] is not None
else None
)
# Concatenate input_points
input_points_list = [fi.input_points for fi in chunk_find_inputs]
batched_input_points = (
torch.cat(input_points_list, dim=0)
if input_points_list[0] is not None
else None
)
# Concatenate input_points_mask
input_points_mask_list = [fi.input_points_mask for fi in chunk_find_inputs]
batched_input_points_mask = (
torch.cat(input_points_mask_list, dim=0)
if input_points_mask_list[0] is not None
else None
)
# Handle optional fields
input_boxes_before_embed_list = [
fi.input_boxes_before_embed for fi in chunk_find_inputs
]
batched_input_boxes_before_embed = (
torch.cat(input_boxes_before_embed_list, dim=0)
if input_boxes_before_embed_list[0] is not None
else None
)
input_points_before_embed_list = [
fi.input_points_before_embed for fi in chunk_find_inputs
]
batched_input_points_before_embed = (
torch.cat(input_points_before_embed_list, dim=0)
if input_points_before_embed_list[0] is not None
else None
)
# Create batched FindStage
batched_find_input = FindStage(
img_ids=batched_img_ids,
img_ids_np=batched_img_ids_np,
text_ids=batched_text_ids,
input_boxes=batched_input_boxes,
input_boxes_mask=batched_input_boxes_mask,
input_boxes_label=batched_input_boxes_label,
input_points=batched_input_points,
input_points_mask=batched_input_points_mask,
ptrs=None, # Not batching pointers for now
ptrs_seg=None,
object_ids=None,
input_boxes_before_embed=batched_input_boxes_before_embed,
input_points_before_embed=batched_input_points_before_embed,
)
return batched_find_input
def _batch_geometric_prompts(
self,
geometric_prompts: List[Prompt],
chunk_start: int,
chunk_end: int,
) -> Prompt:
"""
Batch multiple Prompt objects into a single batched Prompt.
Args:
geometric_prompts: List of Prompt objects for all frames.
chunk_start: Start index of the chunk.
chunk_end: End index of the chunk (exclusive).
Returns:
A single Prompt with batched tensors.
"""
chunk_prompts = [geometric_prompts[i] for i in range(chunk_start, chunk_end)]
return self._batch_geometric_prompts_from_list(chunk_prompts)
def _batch_geometric_prompts_from_list(
self,
chunk_prompts: List[Prompt],
) -> Prompt:
"""
Batch a list of Prompt objects into a single batched Prompt.
Prompt uses seq-first, batch-second convention:
- box_embeddings: N_boxes x B x C_box - batch along dim 1
- box_mask: B x N_boxes - batch along dim 0
- box_labels: N_boxes x B - batch along dim 1
- point_embeddings: N_points x B x C_point - batch along dim 1
- point_mask: B x N_points - batch along dim 0
- point_labels: N_points x B - batch along dim 1
Args:
chunk_prompts: List of Prompt objects to batch.
Returns:
A single Prompt with batched tensors.
"""
# Helper function to batch tensors along specified dimension
def batch_tensors(tensors, dim):
if tensors[0] is None:
return None
return torch.cat(tensors, dim=dim)
# Batch box embeddings (N_boxes x B x C_box - batch along dim 1)
box_embeddings_list = [p.box_embeddings for p in chunk_prompts]
batched_box_embeddings = batch_tensors(box_embeddings_list, dim=1)
# Batch box mask (B x N_boxes - batch along dim 0)
box_mask_list = [p.box_mask for p in chunk_prompts]
batched_box_mask = batch_tensors(box_mask_list, dim=0)
# Batch box labels (N_boxes x B - batch along dim 1)
box_labels_list = [p.box_labels for p in chunk_prompts]
batched_box_labels = batch_tensors(box_labels_list, dim=1)
# Batch point embeddings (N_points x B x C_point - batch along dim 1)
point_embeddings_list = [p.point_embeddings for p in chunk_prompts]
batched_point_embeddings = batch_tensors(point_embeddings_list, dim=1)
# Batch point mask (B x N_points - batch along dim 0)
point_mask_list = [p.point_mask for p in chunk_prompts]
batched_point_mask = batch_tensors(point_mask_list, dim=0)
# Batch point labels (N_points x B - batch along dim 1)
point_labels_list = [p.point_labels for p in chunk_prompts]
batched_point_labels = batch_tensors(point_labels_list, dim=1)
# Create batched Prompt
batched_prompt = Prompt(
box_embeddings=batched_box_embeddings,
box_mask=batched_box_mask,
box_labels=batched_box_labels,
point_embeddings=batched_point_embeddings,
point_mask=batched_point_mask,
point_labels=batched_point_labels,
)
return batched_prompt
class Sam3MultiplexDetector(Sam3MultiplexImageBase):
def __init__(
self,
*args,
async_all_gather=True,
gather_backbone_out=None,
is_multiplex=False,
**kwargs,
):
super().__init__(*args, **kwargs)
self.rank = int(os.getenv("RANK", "0"))
self.world_size = int(os.getenv("WORLD_SIZE", "1"))
self.async_all_gather = async_all_gather
# if gather_backbone is not set, default to gathering only for `SAM3VLBackbone`
if gather_backbone_out is None:
gather_backbone_out = isinstance(self.backbone, SAM3VLBackbone) or (
SAM3VLBackboneTri is not None
and isinstance(self.backbone, SAM3VLBackboneTri)
)
self.gather_backbone_out = gather_backbone_out
self.is_multiplex = is_multiplex
def forward_video_grounding_multigpu(
self,
backbone_out,
find_inputs,
geometric_prompt: Prompt,
frame_idx,
num_frames,
# `multigpu_buffer` is a dict to cache FA outputs in a chunk between different calls
multigpu_buffer,
track_in_reverse=False,
# whether to also return the SAM2 backbone features (in addition to FA results)
return_sam2_backbone_feats=False,
# whether to perform NMS and suppress the scores of those detections removed by NMS
run_nms=False,
nms_prob_thresh=None,
nms_iou_thresh=None,
nms_use_iom=False,
# tracking bounds to respect max_frame_num_to_track
max_frame_num_to_track=None,
propagate_in_video_start_frame_idx=None,
# feature_cache for buffered backbone computation
feature_cache=None,
**kwargs,
):
"""
Compute the FA detection outputs in a distributed manner, where all GPUs process
a chunk of frames (equal to the number of GPUs) at once and store them in cache.
"""
# Calculate valid frame range based on max_frame_num_to_track
# We prevent pre-fetching beyond the tracking window relative to current frame
if max_frame_num_to_track is not None:
if propagate_in_video_start_frame_idx is None:
propagate_in_video_start_frame_idx = 0
if track_in_reverse:
# When going backwards, limit how far back we can go from current frame
valid_frame_start = max(
0,
propagate_in_video_start_frame_idx - max_frame_num_to_track + 1,
)
valid_frame_end = num_frames
else:
# When going forwards, limit how far ahead we can go from current frame
valid_frame_start = 0
valid_frame_end = min(
num_frames,
propagate_in_video_start_frame_idx + max_frame_num_to_track,
)
else:
# No tracking limit specified, use full video range
valid_frame_start = 0
valid_frame_end = num_frames
# Step 1: fetch the FA outputs in the current chunk from buffer
frame_idx_curr_b = frame_idx - frame_idx % self.world_size
frame_idx_curr_e = min(frame_idx_curr_b + self.world_size, num_frames)
# Clamp the current chunk to the valid tracking range
frame_idx_curr_b = max(frame_idx_curr_b, valid_frame_start)
frame_idx_curr_e = min(frame_idx_curr_e, valid_frame_end)
# in case the current frame's FA results are not in the buffer yet, build the current chunk
# (this should only happen on the first chunk, since we are also building the next chunk below)
if frame_idx not in multigpu_buffer:
with torch.profiler.record_function("build_multigpu_buffer_next_chunk1"):
self._build_multigpu_buffer_next_chunk(
backbone_out=backbone_out,
find_inputs=find_inputs,
geometric_prompt=geometric_prompt,
frame_idx_begin=frame_idx_curr_b,
frame_idx_end=frame_idx_curr_e,
num_frames=num_frames,
multigpu_buffer=multigpu_buffer,
run_nms=run_nms,
nms_prob_thresh=nms_prob_thresh,
nms_iou_thresh=nms_iou_thresh,
nms_use_iom=nms_use_iom,
feature_cache=feature_cache,
)
# read out the current frame's results from `multigpu_buffer`
out = {}
for k, (v, handle) in multigpu_buffer[frame_idx].items():
if self.is_multiplex:
if (
k.startswith("interactive_backbone_")
or k.startswith("propagation_backbone_")
) and not return_sam2_backbone_feats:
continue
else:
if k.startswith("sam2_backbone_") and not return_sam2_backbone_feats:
continue
if handle is not None:
handle.wait() # wait for async all-gather to finish
out[k] = v
# Step 2: remove FA outputs of the previous chunk from cache to save GPU memory
if not track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
frame_idx_prev_e = frame_idx_curr_b
frame_idx_prev_b = frame_idx_curr_b - self.world_size
elif track_in_reverse and frame_idx_curr_e < num_frames:
frame_idx_prev_b = frame_idx_curr_e
frame_idx_prev_e = min(frame_idx_prev_b + self.world_size, num_frames)
else:
frame_idx_prev_b = frame_idx_prev_e = None
if frame_idx_prev_b is not None:
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
multigpu_buffer.pop(frame_idx_rm, None)
# Step 3: compute and cache FA outputs of the next chunk ahead of time
# (so that we can overlap computation with all-gather transfer)
# Respect tracking bounds when calculating next chunk
if not track_in_reverse and frame_idx_curr_e < valid_frame_end:
frame_idx_next_b = frame_idx_curr_e
frame_idx_next_e = min(frame_idx_next_b + self.world_size, valid_frame_end)
elif (
track_in_reverse and frame_idx_curr_b - self.world_size >= valid_frame_start
):
frame_idx_next_e = frame_idx_curr_b
frame_idx_next_b = max(
frame_idx_curr_b - self.world_size, valid_frame_start
)
else:
frame_idx_next_b = frame_idx_next_e = None
if frame_idx_next_b is not None and frame_idx_next_b not in multigpu_buffer:
with torch.profiler.record_function("build_multigpu_buffer_next_chunk2"):
self._build_multigpu_buffer_next_chunk(
backbone_out=backbone_out,
find_inputs=find_inputs,
geometric_prompt=geometric_prompt,
frame_idx_begin=frame_idx_next_b,
frame_idx_end=frame_idx_next_e,
num_frames=num_frames,
multigpu_buffer=multigpu_buffer,
run_nms=run_nms,
nms_prob_thresh=nms_prob_thresh,
nms_iou_thresh=nms_iou_thresh,
feature_cache=feature_cache,
)
return out, backbone_out
def _build_multigpu_buffer_next_chunk(
self,
backbone_out,
find_inputs,
geometric_prompt: Prompt,
frame_idx_begin,
frame_idx_end,
num_frames,
multigpu_buffer,
run_nms=False,
nms_prob_thresh=None,
nms_iou_thresh=None,
nms_use_iom=False,
feature_cache=None,
):
"""Compute FA outputs on a chunk of frames and store their results in multigpu_buffer."""
# each GPU computes FA on one frame in the chunk (in a round-robin manner)
frame_idx_local_gpu = min(frame_idx_begin + self.rank, frame_idx_end - 1)
# `forward_grounding` (from base class `Sam3MultiplexImageBase`) runs FA on a single frame
with torch.profiler.record_function("forward_grounding"):
out_local = self.forward_grounding(
backbone_out=backbone_out,
# HACK: Since find_inputs is on GPU having to realloc is expensive so changing the values in place for the prod usecase
# i.e. when using the streaming frame loader resource instead of local file. For non-prod is always
# frame_idx_local_gpu < len(find_inputs) so should be a no-op
find_input=find_inputs[frame_idx_local_gpu % len(find_inputs)],
find_target=None,
geometric_prompt=geometric_prompt,
feature_cache=feature_cache,
)
if run_nms:
with torch.profiler.record_function("nms_masks"):
# run NMS as a post-processing step on top of the detection outputs
assert nms_prob_thresh is not None and nms_iou_thresh is not None
pred_probs = out_local["pred_logits"].squeeze(-1).sigmoid()
pred_masks = out_local["pred_masks"]
# loop over text prompts (not an overhead for demo where there's only 1 prompt)
for prompt_idx in range(pred_probs.size(0)):
keep = nms_masks(
pred_probs=pred_probs[prompt_idx],
pred_masks=pred_masks[prompt_idx],
prob_threshold=nms_prob_thresh,
iou_threshold=nms_iou_thresh,
nms_use_iom=nms_use_iom,
do_compile=getattr(self, "compile_model", False),
running_in_prod=getattr(self, "running_in_prod", False),
)
# set a very low threshold for those detections removed by NMS
out_local["pred_logits"][prompt_idx, :, 0] -= 1e4 * (~keep).float()
if self.gather_backbone_out:
# gather the SAM 2 backbone features across GPUs
if self.is_multiplex:
# Note that we should not need to compute the interaction features every frame
# TODO: rooms for optimization
# Interaction features
inte_feats = out_local["prev_encoder_out"]["backbone_out"][
"interactive"
]
assert inte_feats["vision_mask"] is None
assert (
len(inte_feats["backbone_fpn"]) == 3
) # SAM2 backbone always have 3 levels
assert all(x.mask is None for x in inte_feats["backbone_fpn"])
# cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
# a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
inte_backbone_fpn_bf16 = [
x.to(torch.bfloat16) for x in inte_feats["backbone_fpn"]
]
inte_fpn0, inte_fpn_handle0 = self._gather_tensor(
inte_backbone_fpn_bf16[0].tensors
)
inte_fpn1, inte_fpn_handle1 = self._gather_tensor(
inte_backbone_fpn_bf16[1].tensors
)
inte_fpn2, inte_fpn_handle2 = self._gather_tensor(
inte_backbone_fpn_bf16[2].tensors
)
# vision_pos_enc is the same on all frames, so no need to all-gather them
inte_vision_pos_enc = inte_feats["vision_pos_enc"]
feats = out_local["prev_encoder_out"]["backbone_out"]["sam2_backbone_out"]
assert feats["vision_mask"] is None
assert len(feats["backbone_fpn"]) == 3 # SAM2 backbone always have 3 levels
assert all(x.mask is None for x in feats["backbone_fpn"])
# cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
# a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
backbone_fpn_bf16 = [x.to(torch.bfloat16) for x in feats["backbone_fpn"]]
fpn0, fpn_handle0 = self._gather_tensor(backbone_fpn_bf16[0].tensors)
fpn1, fpn_handle1 = self._gather_tensor(backbone_fpn_bf16[1].tensors)
fpn2, fpn_handle2 = self._gather_tensor(backbone_fpn_bf16[2].tensors)
# vision_pos_enc is the same on all frames, so no need to all-gather them
vision_pos_enc = feats["vision_pos_enc"]
# trim the FA output to only include the necessary keys
out_local = {
"pred_logits": out_local["pred_logits"],
"pred_boxes": out_local["pred_boxes"],
"pred_boxes_xyxy": out_local["pred_boxes_xyxy"],
"pred_masks": out_local["pred_masks"],
"pred_object_ids": self._get_dummy_object_ids(out_local["pred_logits"]),
}
# gather the results: after this step, each GPU will receive FA outputs on
# all frames in the chunk and store them in `multigpu_buffer`
out_gathered = {k: self._gather_tensor(v) for k, v in out_local.items()}
for rank in range(self.world_size):
frame_idx_to_save = frame_idx_begin + rank
if frame_idx_to_save >= num_frames:
continue
frame_buffer = {
k: (v[rank], handle) for k, (v, handle) in out_gathered.items()
}
if self.gather_backbone_out:
# also add gathered SAM 2 backbone features to frame_buffer
if self.is_multiplex:
frame_buffer["interactive_backbone_fpn_0"] = (
inte_fpn0[rank],
inte_fpn_handle0,
)
frame_buffer["interactive_backbone_fpn_1"] = (
inte_fpn1[rank],
inte_fpn_handle1,
)
frame_buffer["interactive_backbone_fpn_2"] = (
inte_fpn2[rank],
inte_fpn_handle2,
)
frame_buffer["interactive_backbone_pos_enc"] = (
inte_vision_pos_enc,
None,
)
frame_buffer["sam2_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
frame_buffer["sam2_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None)
multigpu_buffer[frame_idx_to_save] = frame_buffer
def _gather_tensor(self, x):
if self.world_size == 1:
return [x], None
async_op = self.async_all_gather
# here `.contiguous()` is required -- otherwise NCCL all_gather
# sometimes gives wrong results (based on Ronghang's observations)
x = x.contiguous() # ensure contiguous memory for NCCL
output_list = [torch.empty_like(x) for _ in range(self.world_size)]
handle = torch.distributed.all_gather(output_list, x, async_op=async_op)
return output_list, handle
def forward_video_grounding_batched_multigpu(
self,
backbone_out,
find_inputs,
geometric_prompt: Prompt,
frame_idx,
num_frames,
# `grounding_cache` is a dict to cache FA outputs in a chunk between different calls
grounding_cache,
track_in_reverse=False,
# whether to also return the SAM2 backbone features (in addition to FA results)
return_sam2_backbone_feats=False,
# whether to perform NMS and suppress the scores of those detections removed by NMS
run_nms=False,
nms_prob_thresh=None,
nms_iou_thresh=None,
nms_use_iom=False,
# tracking bounds to respect max_frame_num_to_track
max_frame_num_to_track=None,
propagate_in_video_start_frame_idx=None,
# feature_cache for buffered backbone computation
feature_cache=None,
# batch_size for batched forward_grounding (default: 16)
batch_size=16,
):
"""
Fully batched forward_grounding that processes chunks of frames together on each GPU.
Unlike forward_video_grounding_multigpu which processes 1 frame per GPU per chunk,
this method processes `batch_size` frames at once using the batched forward_grounding
approach from Sam3MultiplexImageBase.
For single-GPU (world_size=1), this is equivalent to forward_grounding_batched.
For multi-GPU, each GPU processes batch_size frames in parallel.
Args:
backbone_out: Dictionary containing backbone outputs and image batch.
find_inputs: List of FindStage objects for all frames.
geometric_prompt: Prompt object (used as template, individual prompts are
constructed from find_inputs for batching).
frame_idx: Current frame index to process.
num_frames: Total number of frames in the video.
grounding_cache: Dictionary to cache grounding outputs.
track_in_reverse: If True, processing in reverse frame order.
return_sam2_backbone_feats: Whether to also return SAM2 backbone features.
run_nms: Whether to perform NMS on detection outputs.
nms_prob_thresh: Probability threshold for NMS.
nms_iou_thresh: IoU threshold for NMS.
nms_use_iom: Whether to use IoM for NMS.
max_frame_num_to_track: Maximum number of frames to track.
propagate_in_video_start_frame_idx: Start frame index for propagation.
feature_cache: Optional dictionary for backbone feature caching.
batch_size: Number of frames to batch together per GPU (default: 16).
Returns:
Tuple of (out, backbone_out) where out contains detection results for frame_idx.
"""
# Calculate valid frame range based on max_frame_num_to_track
if max_frame_num_to_track is not None:
if propagate_in_video_start_frame_idx is None:
propagate_in_video_start_frame_idx = 0
if track_in_reverse:
valid_frame_start = (
propagate_in_video_start_frame_idx - max_frame_num_to_track + 1
)
valid_frame_end = propagate_in_video_start_frame_idx
else:
valid_frame_start = propagate_in_video_start_frame_idx
valid_frame_end = (
propagate_in_video_start_frame_idx + max_frame_num_to_track
)
else:
valid_frame_start = 0
valid_frame_end = num_frames
# Initialize grounding_buffer if not present
if "grounding_buffer" not in grounding_cache:
grounding_cache["grounding_buffer"] = {}
# Calculate chunk boundaries - use batch_size instead of world_size
chunk_start = (frame_idx // batch_size) * batch_size
chunk_end = min(chunk_start + batch_size, valid_frame_end)
chunk_key = (chunk_start, chunk_end)
# Process chunk if not already cached
if chunk_key not in grounding_cache["grounding_buffer"]:
with torch.profiler.record_function(
"forward_grounding_batched.process_chunk"
):
chunk_outputs = self._process_grounding_chunk_batched(
backbone_out=backbone_out,
find_inputs=find_inputs,
chunk_start=chunk_start,
chunk_end=chunk_end,
run_nms=run_nms,
nms_prob_thresh=nms_prob_thresh,
nms_iou_thresh=nms_iou_thresh,
nms_use_iom=nms_use_iom,
feature_cache=feature_cache,
return_sam2_backbone_feats=return_sam2_backbone_feats,
)
grounding_cache["grounding_buffer"][chunk_key] = chunk_outputs
# Auto-cleanup previous chunks
self._cleanup_previous_chunks_multigpu(
grounding_cache=grounding_cache,
current_chunk_key=chunk_key,
batch_size=batch_size,
num_frames=num_frames,
track_in_reverse=track_in_reverse,
)
# Retrieve the cached output for this frame
chunk_outputs = grounding_cache["grounding_buffer"][chunk_key]
local_idx = frame_idx - chunk_start
# Slice out the output for this specific frame
out = self._slice_batched_output(
chunk_outputs, local_idx, return_sam2_backbone_feats
)
return out, backbone_out
def _process_grounding_chunk_batched(
self,
backbone_out,
find_inputs,
chunk_start: int,
chunk_end: int,
run_nms: bool,
nms_prob_thresh,
nms_iou_thresh,
nms_use_iom: bool,
feature_cache,
return_sam2_backbone_feats: bool,
):
"""
Process a chunk of frames through the full forward_grounding pipeline in batch.
"""
chunk_size = chunk_end - chunk_start
# Build geometric prompts for the chunk
chunk_geo_prompts = [
self._get_geo_prompt_from_find_input(find_inputs[i % len(find_inputs)])
for i in range(chunk_start, chunk_end)
]
# Batch the find_inputs for this chunk
batched_find_input = self._batch_find_inputs(
find_inputs, chunk_start, chunk_end
)
# Batch the geometric prompts
batched_geometric_prompt = self._batch_geometric_prompts_from_list(
chunk_geo_prompts
)
# Run forward_grounding on the batched input
with torch.profiler.record_function("forward_grounding_batched.forward"):
out = self.forward_grounding(
backbone_out=backbone_out,
find_input=batched_find_input,
find_target=None,
geometric_prompt=batched_geometric_prompt,
feature_cache=feature_cache,
)
# Apply NMS per frame in the batch
if run_nms:
with torch.profiler.record_function("forward_grounding_batched.nms"):
assert nms_prob_thresh is not None and nms_iou_thresh is not None
pred_probs = out["pred_logits"].squeeze(-1).sigmoid()
pred_masks = out["pred_masks"]
# pred_probs shape: [batch_size, num_queries]
# pred_masks shape: [batch_size, num_queries, H, W]
# Use batched NMS to process all frames at once
keep = nms_masks(
pred_probs=pred_probs,
pred_masks=pred_masks,
prob_threshold=nms_prob_thresh,
iou_threshold=nms_iou_thresh,
nms_use_iom=nms_use_iom,
do_compile=getattr(self, "compile_model", False),
running_in_prod=getattr(self, "running_in_prod", False),
)
# Set a very low threshold for detections removed by NMS
# keep shape: [batch_size, num_queries]
out["pred_logits"][:, :, 0] -= 1e4 * (~keep).float()
# Extract SAM2 backbone features if requested
if return_sam2_backbone_feats and "prev_encoder_out" in out:
backbone_data = out["prev_encoder_out"]["backbone_out"]
if self.is_multiplex and "interactive" in backbone_data:
out["_interactive_backbone"] = backbone_data["interactive"]
if "sam2_backbone_out" in backbone_data:
out["_sam2_backbone"] = backbone_data["sam2_backbone_out"]
out["_chunk_size"] = chunk_size
return out
def _slice_batched_output(
self,
chunk_outputs,
local_idx: int,
return_sam2_backbone_feats: bool,
):
"""
Slice a single frame's output from the batched chunk outputs.
"""
out = {}
# Keys to slice at batch dimension
batch_dim_keys = {
"pred_logits",
"pred_boxes",
"pred_boxes_xyxy",
"pred_masks",
"pred_logits_o2m",
"pred_boxes_o2m",
"pred_boxes_xyxy_o2m",
"pred_masks_o2m",
"queries",
"presence_logit_dec",
}
# Keys to skip
skip_keys = {
"_chunk_size",
"_interactive_backbone",
"_sam2_backbone",
"prev_encoder_out",
"encoder_hidden_states",
"aux_outputs",
}
for key, value in chunk_outputs.items():
if key in skip_keys:
continue
if key in batch_dim_keys and isinstance(value, torch.Tensor):
out[key] = value[local_idx : local_idx + 1]
elif isinstance(value, torch.Tensor):
try:
out[key] = value[local_idx : local_idx + 1]
except (IndexError, RuntimeError):
out[key] = value
# Add object IDs
if "pred_logits" in out:
out["pred_object_ids"] = self._get_dummy_object_ids(out["pred_logits"])
# Add SAM2 backbone features if requested
if return_sam2_backbone_feats:
if "_sam2_backbone" in chunk_outputs:
sam2_bb = chunk_outputs["_sam2_backbone"]
out["sam2_backbone_fpn_0"] = sam2_bb["backbone_fpn"][0].tensors[
local_idx : local_idx + 1
]
out["sam2_backbone_fpn_1"] = sam2_bb["backbone_fpn"][1].tensors[
local_idx : local_idx + 1
]
out["sam2_backbone_fpn_2"] = sam2_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1
]
out["sam2_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in sam2_bb["vision_pos_enc"]
]
if self.is_multiplex and "_interactive_backbone" in chunk_outputs:
inte_bb = chunk_outputs["_interactive_backbone"]
out["interactive_backbone_fpn_0"] = inte_bb["backbone_fpn"][0].tensors[
local_idx : local_idx + 1
]
out["interactive_backbone_fpn_1"] = inte_bb["backbone_fpn"][1].tensors[
local_idx : local_idx + 1
]
out["interactive_backbone_fpn_2"] = inte_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1
]
out["interactive_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in inte_bb["vision_pos_enc"]
]
return out
def _cleanup_previous_chunks_multigpu(
self,
grounding_cache,
current_chunk_key,
batch_size: int,
num_frames: int,
track_in_reverse: bool,
):
"""Remove previous chunks from cache to save GPU memory."""
chunk_start, chunk_end = current_chunk_key
if not track_in_reverse:
prev_chunk_start = chunk_start - batch_size
if prev_chunk_start >= 0:
prev_chunk_end = chunk_start
prev_chunk_key = (prev_chunk_start, prev_chunk_end)
# Cleanup grounding_buffer entry
chunk = grounding_cache["grounding_buffer"].pop(prev_chunk_key, None)
if chunk is not None:
del chunk
else:
next_chunk_start = chunk_end
if next_chunk_start < num_frames:
next_chunk_end = min(next_chunk_start + batch_size, num_frames)
next_chunk_key = (next_chunk_start, next_chunk_end)
grounding_cache["grounding_buffer"].pop(next_chunk_key, None)
+369
View File
@@ -0,0 +1,369 @@
import logging
import numpy as np
import torch
from sam3 import perflib
try:
# Ronghang's generic GPU NMS implementation; install via
# pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms
from torch_generic_nms import generic_nms
GENERIC_NMS_AVAILABLE = True
except ImportError:
GENERIC_NMS_AVAILABLE = False
from sam3.perflib.masks_ops import mask_iou
from sam3.train.masks_ops import mask_iom
def nms_masks(
pred_probs: torch.Tensor,
pred_masks: torch.Tensor,
prob_threshold: float,
iou_threshold: float,
nms_use_iom: bool = False,
do_compile: bool = False,
running_in_prod: bool = False,
) -> torch.Tensor:
"""
Args:
- pred_probs: (num_det,) or (B, num_det) float Tensor, containing the score (probability) of each detection
- pred_masks: (num_det, H_mask, W_mask) or (B, num_det, H_mask, W_mask) float Tensor, containing the binary segmentation mask of each detection
- prob_threshold: float, score threshold to prefilter detections (NMS is performed on detections above threshold)
- iou_threshold: float, mask IoU threshold for NMS (it would also be used as IoM threshold if `nms_use_iom` is True)
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
- do_compile: bool, whether to compile the function for optimization
- running_in_prod: bool, whether the function is running in production (ie, in Instagram)
Returns:
- keep: (num_det,) or (B, num_det) bool Tensor, indicating whether each detection is kept after score thresholding + NMS
"""
if do_compile and perflib.is_enabled:
# Apply torch.compile with the same settings as before
compiled_fn = torch.compile(
_nms_masks_core,
mode="max-autotune",
fullgraph=True,
# dynamic=False,
)
return compiled_fn(
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
)
else:
return _nms_masks_core(
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
)
def _nms_masks_core(
pred_probs: torch.Tensor,
pred_masks: torch.Tensor,
prob_threshold: float,
iou_threshold: float,
nms_use_iom: bool = False,
) -> torch.Tensor:
"""Core NMS implementation without compilation.
Supports both single-frame and batched inputs:
- Single-frame: pred_probs (num_det,), pred_masks (num_det, H, W)
- Batched: pred_probs (B, num_det), pred_masks (B, num_det, H, W)
Returns:
- keep: bool Tensor with same leading dimensions as input, indicating kept detections
"""
# Check if input is batched (has batch dimension)
is_batched = pred_probs.dim() == 2
if is_batched:
return _nms_masks_core_batched(
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
)
else:
# Single-frame input: use original logic
return _nms_masks_core_single(
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
)
def _nms_masks_core_batched(
pred_probs: torch.Tensor,
pred_masks: torch.Tensor,
prob_threshold: float,
iou_threshold: float,
nms_use_iom: bool = False,
) -> torch.Tensor:
"""Core NMS implementation for batched inputs using vectorized operations.
Args:
- pred_probs: (B, num_det) float Tensor
- pred_masks: (B, num_det, H_mask, W_mask) float Tensor
- prob_threshold: float, score threshold to prefilter detections
- iou_threshold: float, mask IoU/IoM threshold for NMS
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
Returns:
- keep: (B, num_det) bool Tensor
"""
B, num_det, H, W = pred_masks.shape
device = pred_masks.device
is_valid = pred_probs > prob_threshold # (B, num_det)
masks_binary = pred_masks > 0 # (B, num_det, H, W)
if perflib.is_enabled:
# Compute batched pairwise IoU/IoM
if nms_use_iom:
overlaps = _batched_mask_iom(masks_binary) # (B, num_det, num_det)
else:
overlaps = _batched_mask_iou(masks_binary) # (B, num_det, num_det)
keep = _batched_generic_nms_mask(overlaps, pred_probs, is_valid, iou_threshold)
return keep
# Non-perflib path: compute batched IoU/IoM
if nms_use_iom:
overlaps = _batched_mask_iom(masks_binary) # (B, num_det, num_det)
else:
overlaps = _batched_mask_iou(masks_binary) # (B, num_det, num_det)
# Apply batched NMS
keep = _batched_generic_nms_mask(overlaps, pred_probs, is_valid, iou_threshold)
return keep
def _batched_mask_iou(masks: torch.Tensor) -> torch.Tensor:
"""Compute batched pairwise IoU for masks.
Args:
- masks: (B, N, H, W) bool Tensor
Returns:
- ious: (B, N, N) float Tensor
"""
B, N, H, W = masks.shape
# Flatten spatial dims: (B, N, H*W)
masks_flat = masks.reshape(B, N, -1).float()
# Compute intersection via batched matrix multiplication: (B, N, N)
intersection = torch.bmm(masks_flat, masks_flat.transpose(1, 2))
# Compute areas: (B, N)
areas = masks_flat.sum(dim=-1)
# Compute union: (B, N, N)
union = areas.unsqueeze(2) + areas.unsqueeze(1) - intersection
return intersection / (union + 1e-8)
def _batched_mask_iom(masks: torch.Tensor) -> torch.Tensor:
"""Compute batched pairwise IoM (Intersection over Minimum) for masks.
Args:
- masks: (B, N, H, W) bool Tensor
Returns:
- ioms: (B, N, N) float Tensor
"""
B, N, H, W = masks.shape
# Flatten spatial dims: (B, N, H*W)
masks_flat = masks.reshape(B, N, -1).float()
# Compute intersection via batched matrix multiplication: (B, N, N)
intersection = torch.bmm(masks_flat, masks_flat.transpose(1, 2))
# Compute areas: (B, N)
areas = masks_flat.sum(dim=-1)
# Compute min area: (B, N, N)
min_area = torch.minimum(areas.unsqueeze(2), areas.unsqueeze(1))
return intersection / (min_area + 1e-8)
def _batched_generic_nms_mask(
ious: torch.Tensor,
scores: torch.Tensor,
is_valid: torch.Tensor,
iou_threshold: float,
) -> torch.Tensor:
"""Batched NMS using vectorized operations.
Args:
- ious: (B, N, N) float Tensor, pairwise IoU/IoM matrix
- scores: (B, N) float Tensor, detection scores
- is_valid: (B, N) bool Tensor, valid detections mask
- iou_threshold: float, threshold for suppression
Returns:
- keep: (B, N) bool Tensor
"""
B, N = scores.shape
device = scores.device
# Sort by score descending for each batch: (B, N)
order = scores.argsort(dim=-1, descending=True)
# Create batch indices for advanced indexing
batch_idx = torch.arange(B, device=device).unsqueeze(1).expand(B, N)
# Reorder IoU matrix according to sorted scores: (B, N, N)
# ious_sorted[b, i, j] = ious[b, order[b, i], order[b, j]]
ious_sorted = ious[batch_idx.unsqueeze(2), order.unsqueeze(2), order.unsqueeze(1)]
# Create threshold mask: (B, N, N)
threshold_mask = ious_sorted > iou_threshold
# Initialize keep mask with valid detections in sorted order: (B, N)
keep = is_valid[batch_idx, order]
# Upper triangular mask to avoid double processing: (N, N)
triu = torch.triu(torch.ones(N, N, device=device, dtype=torch.bool), diagonal=1)
# Vectorized NMS - iterate through detections
for i in range(N):
# For each position i, suppress later detections with high overlap
# Only suppress if current detection is kept
suppress = (
threshold_mask[:, i, :] & triu[i].unsqueeze(0) & keep[:, i].unsqueeze(1)
)
keep = keep & ~suppress
# Return keep mask in original order: (B, N)
original_keep = torch.zeros_like(keep)
original_keep[batch_idx, order] = keep
return original_keep
def _nms_masks_core_single(
pred_probs: torch.Tensor,
pred_masks: torch.Tensor,
prob_threshold: float,
iou_threshold: float,
nms_use_iom: bool = False,
) -> torch.Tensor:
"""Core NMS implementation for a single frame (no batch dimension).
Args:
- pred_probs: (num_det,) float Tensor
- pred_masks: (num_det, H_mask, W_mask) float Tensor
- prob_threshold: float, score threshold to prefilter detections
- iou_threshold: float, mask IoU/IoM threshold for NMS
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
Returns:
- keep: (num_det,) bool Tensor
"""
is_valid = pred_probs > prob_threshold # (num_det,)
if perflib.is_enabled:
masks_binary = pred_masks > 0 # (num_det, H_mask, W_mask)
if nms_use_iom:
ious = perf_mask_iom(masks_binary, masks_binary) # (num_det, num_det)
else:
ious = perf_mask_iou(masks_binary, masks_binary) # (num_det, num_det)
kept_mask = generic_nms_mask(ious, pred_probs, is_valid, iou_threshold)
return kept_mask
# prefilter the detections with prob_threshold ("valid" are those above prob_threshold)
probs = pred_probs[is_valid] # (num_valid,)
masks_binary = pred_masks[is_valid] > 0 # (num_valid, H_mask, W_mask)
if probs.numel() == 0:
return is_valid # no valid detection, return empty keep mask
if nms_use_iom:
overlaps = mask_iom(masks_binary, masks_binary) # (num_valid, num_valid)
else:
overlaps = mask_iou(masks_binary, masks_binary) # (num_valid, num_valid)
# kept_inds are the indices among `probs` of those kept detections after NMS
if GENERIC_NMS_AVAILABLE:
kept_inds = generic_nms(overlaps, probs, iou_threshold, use_iou_matrix=True)
else:
logging.warning(
"Falling back to CPU mask NMS implementation -- please install `torch_generic_nms` via\n\t"
'pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms'
)
kept_inds = generic_nms_cpu(overlaps, probs, iou_threshold)
# valid_inds are the indices among `probs` of valid detections before NMS (or -1 for invalid)
valid_inds = torch.where(is_valid, is_valid.cumsum(dim=0) - 1, -1) # (num_det,)
keep = torch.isin(valid_inds, kept_inds) # (num_det,)
return keep
def generic_nms_cpu(
ious: torch.Tensor, scores: torch.Tensor, iou_threshold=0.5
) -> torch.Tensor:
"""
A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix. (CPU implementation
based on https://github.com/jwyang/faster-rcnn.pytorch/blob/master/lib/model/nms/nms_cpu.py)
"""
ious_np = ious.float().detach().cpu().numpy()
scores_np = scores.float().detach().cpu().numpy()
order = scores_np.argsort()[::-1]
kept_inds = []
while order.size > 0:
i = order.item(0)
kept_inds.append(i)
inds = np.where(ious_np[i, order[1:]] <= iou_threshold)[0]
order = order[inds + 1]
return torch.tensor(kept_inds, dtype=torch.int64, device=scores.device)
def generic_nms_mask(
ious: torch.Tensor, scores: torch.Tensor, is_valid: torch.Tensor, iou_threshold=0.5
) -> torch.Tensor:
"""
A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix. (CPU implementation
using vectorized operations similar to nms_masks_kernel)
"""
# Sort by score descending
order = scores.argsort(descending=True)
# Reorder IoU matrix according to sorted scores
ious_sorted = ious[order][:, order]
# Create threshold mask
threshold_mask = ious_sorted > iou_threshold
# Initialize keep mask
# keep = torch.ones(len(scores), device=ious.device, dtype=torch.bool)
keep = is_valid[order]
# Upper triangular mask to avoid double processing
tr = torch.triu(torch.ones_like(threshold_mask), diagonal=1)
# Vectorized NMS
for i in range(len(scores)):
# Suppress all boxes that have high IoU with current box
m = threshold_mask[i]
keep = torch.where(m & tr[i], torch.zeros_like(keep), keep)
# Return keep mask in original order
original_keep = torch.zeros_like(keep)
original_keep[order] = keep
return original_keep
def perf_mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
"""
Compute the IoU (Intersection over Union) between predicted masks and ground truth masks.
Args:
- pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks
- gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks
Returns:
- ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks
"""
assert pred_masks.dtype == gt_masks.dtype == torch.bool
from sam3.perflib.iou import pairwise_iou
return pairwise_iou(pred_masks, gt_masks, eps=None)
def perf_mask_iom(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
assert pred_masks.dtype == gt_masks.dtype == torch.bool
from sam3.perflib.iou import pairwise_iom
return pairwise_iom(pred_masks, gt_masks)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,63 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
# pyre-unsafe
"""
Sam3MultiplexVideoPredictor — user-facing entry point for SAM 3.1 multiplex.
Ported from onevision Sam3Model (webdemo/ta/models/sam3_model.py).
Handles warm-up compilation, bf16 autocast, and session management
via the shared Sam3BasePredictor handle_request/handle_stream_request API.
"""
from typing import Dict, Optional
import torch
from sam3.logger import get_logger
from sam3.model.sam3_base_predictor import Sam3BasePredictor
logger = get_logger(__name__)
class Sam3MultiplexVideoPredictor(Sam3BasePredictor):
"""
User-facing predictor for SAM 3.1 multiplex video tracking.
Wraps Sam3MultiplexTrackingWithInteractivity with:
- bf16 autocast
- Warm-up compilation (when compile=True)
- Session expiration management
- handle_request / handle_stream_request dispatch API (from Sam3BasePredictor)
"""
def __init__(
self,
model,
session_expiration_sec=1200,
default_output_prob_thresh=0.5,
async_loading_frames=True,
warm_up=False,
):
super().__init__()
self.model = model
self.session_expiration_sec = session_expiration_sec
self.default_output_prob_thresh = default_output_prob_thresh
self.async_loading_frames = async_loading_frames
# turn on tfloat32 for Ampere GPUs
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
# use bfloat16 inference for Flash Attention kernel
self.bf16_context = torch.autocast(device_type="cuda", dtype=torch.bfloat16)
self.bf16_context.__enter__()
if warm_up:
self.model._warm_up_complete = False
self.model.warm_up_compilation()
self.model._warm_up_complete = True
def _extend_expiration_time(self, session):
"""Update last-use time and store session expiration timeout."""
super()._extend_expiration_time(session)
if self.session_expiration_sec:
session["expiration_sec"] = self.session_expiration_sec
+11 -1
View File
@@ -367,7 +367,17 @@ def get_best_gt_match_from_multimasks(pred_multimasks, gt_masks, pred_scores=Non
return best_pred_mask
def fill_holes_in_mask_scores(mask, max_area, fill_holes=True, remove_sprinkles=True):
def fill_holes_in_mask_scores(
mask,
max_area=None,
fill_holes=True,
remove_sprinkles=True,
fill_hole_area=None,
sprinkle_removal_area=None,
):
# Support onevision-style keyword args
if fill_hole_area is not None and max_area is None:
max_area = fill_hole_area
"""
A post processor to fill small holes in mask scores with area under `max_area`.
Holes are those small connected components in either background or foreground.
+317 -88
View File
@@ -8,8 +8,9 @@ import math
import os
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Set
from typing import Any, Dict, List, Optional, Set, Tuple
import numpy as np
import numpy.typing as npt
@@ -22,7 +23,7 @@ from sam3.model.box_ops import fast_diag_box_iou
from sam3.model.data_misc import BatchedDatapoint
from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores, mask_to_box
from sam3.perflib.masks_ops import mask_iou
from sam3.train.masks_ops import rle_encode
from sam3.train.masks_ops import mask_iom, rle_encode
from torch import nn, Tensor
logger = get_logger(__name__)
@@ -33,6 +34,226 @@ class MaskletConfirmationStatus(Enum):
CONFIRMED = 2 # confirmed by at least one detection
@dataclass
class RealizedAssociateDetTrkresult:
new_det_fa_inds: np.array
unmatched_trk_obj_ids: np.array
det_to_matched_trk_obj_ids: Dict[int, np.array]
trk_id_to_max_iou_high_conf_det: Dict[int, int]
empty_trk_obj_ids: np.array
new_det_obj_ids: Optional[np.array] = None
new_det_gpu_ids: Optional[np.array] = None
num_obj_dropped_due_to_limit: Optional[int] = None
def get_new_det_gpu_ids(
self, tracker_metadata_prev, is_image_only, det_scores, tracking_obj
):
with torch.profiler.record_function("get_new_det_gpu_ids"):
if self.new_det_obj_ids is None:
det_scores_np: np.ndarray = det_scores.cpu().numpy()
prev_obj_num = np.sum(tracker_metadata_prev["num_obj_per_gpu"])
new_det_num = len(self.new_det_fa_inds)
num_obj_dropped_due_to_limit = 0
if (
not is_image_only
and prev_obj_num + new_det_num > tracking_obj.max_num_objects
):
logger.warning(
f"hitting {tracking_obj.max_num_objects=} with {new_det_num=} and {prev_obj_num=}"
)
new_det_num_to_keep = tracking_obj.max_num_objects - prev_obj_num
num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
self.new_det_fa_inds = tracking_obj._drop_new_det_with_obj_limit(
self.new_det_fa_inds, det_scores_np, new_det_num_to_keep
)
assert len(self.new_det_fa_inds) == new_det_num_to_keep
new_det_num = len(self.new_det_fa_inds)
new_det_start_obj_id = tracker_metadata_prev["max_obj_id"] + 1
new_det_obj_ids = new_det_start_obj_id + np.arange(new_det_num)
if tracking_obj.is_multiplex:
prev_workload_per_gpu = tracker_metadata_prev["num_buc_per_gpu"]
else:
prev_workload_per_gpu = tracker_metadata_prev["num_obj_per_gpu"]
new_det_gpu_ids = tracking_obj._assign_new_det_to_gpus(
new_det_num=new_det_num,
prev_workload_per_gpu=prev_workload_per_gpu,
)
self.new_det_obj_ids = new_det_obj_ids
self.new_det_gpu_ids = new_det_gpu_ids
self.num_obj_dropped_due_to_limit = num_obj_dropped_due_to_limit
return (
self.new_det_obj_ids,
self.new_det_gpu_ids,
self.num_obj_dropped_due_to_limit,
)
def realize_adt_result(adt_lazy_result, tracker_metadata_prev, det_mask_preds):
if isinstance(adt_lazy_result, LazyAssociateDetTrkResult):
adt_lazy_result._convert_to_numpy()
return adt_lazy_result._create_cpu_metadata(
tracker_metadata_prev["obj_ids_all_gpu"], det_mask_preds
)
return adt_lazy_result
class LazyAssociateDetTrkResult:
def __init__(
self,
trk_is_unmatched: Tensor,
trk_is_nonempty: Tensor,
is_new_det: Tensor,
det_to_max_iou_trk_idx: Tensor,
det_is_high_conf: Tensor,
det_is_high_iou: Tensor,
det_keep: Tensor,
im_mask: Tensor,
):
self.trk_is_unmatched = trk_is_unmatched
self.trk_is_nonempty = trk_is_nonempty
self.is_new_det = is_new_det
self.det_to_max_iou_trk_idx = det_to_max_iou_trk_idx
self.det_is_high_conf = det_is_high_conf
self.det_is_high_iou = det_is_high_iou
self.det_keep = det_keep
self.im_mask = im_mask
def _convert_to_numpy(self):
with torch.profiler.record_function("Convert to numpy"):
self.trk_is_unmatched = self.trk_is_unmatched.cpu().numpy()
self.trk_is_nonempty = self.trk_is_nonempty.cpu().numpy()
self.is_new_det = self.is_new_det.cpu().numpy()
self.det_to_max_iou_trk_idx = self.det_to_max_iou_trk_idx.cpu().numpy()
self.det_is_high_conf = self.det_is_high_conf.cpu().numpy()
self.det_is_high_iou = self.det_is_high_iou.cpu().numpy()
self.det_keep = self.det_keep.cpu().numpy().tolist()
self.im_mask = self.im_mask.cpu().numpy()
def _create_cpu_metadata(self, trk_obj_ids, det_masks):
with torch.profiler.record_function("_create_cpu_metadata"):
unmatched_trk_obj_ids = trk_obj_ids[self.trk_is_unmatched]
empty_trk_obj_ids = trk_obj_ids[~self.trk_is_nonempty]
new_det_fa_inds = np.nonzero(self.is_new_det)[0]
det_is_high_conf_and_iou = set(
np.nonzero(self.det_is_high_conf & self.det_is_high_iou)[0]
)
det_to_matched_trk_obj_ids = {}
trk_id_to_max_iou_high_conf_det = {}
for d in range(det_masks.size(0)):
if self.det_keep[d]:
det_to_matched_trk_obj_ids[d] = trk_obj_ids[self.im_mask[d, :]]
if d in det_is_high_conf_and_iou:
trk_obj_id = trk_obj_ids[self.det_to_max_iou_trk_idx[d]].item()
trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
return RealizedAssociateDetTrkresult(
new_det_fa_inds=new_det_fa_inds,
unmatched_trk_obj_ids=unmatched_trk_obj_ids,
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
trk_id_to_max_iou_high_conf_det=trk_id_to_max_iou_high_conf_det,
empty_trk_obj_ids=empty_trk_obj_ids,
)
def _associate_det_trk_compilable(
det_masks,
det_scores,
det_keep,
trk_masks,
new_det_thresh,
iou_threshold_trk,
iou_threshold,
HIGH_CONF_THRESH,
use_iom_recondition,
o2o_matching_masklets_enable,
iom_thresh_recondition,
iou_thresh_recondition,
):
det_masks_binary = det_masks > 0
det_masks_binary[~det_keep] = 0
trk_masks_binary = trk_masks > 0
intersection_metric = None
if use_iom_recondition:
intersection_metric = mask_iom(det_masks_binary, trk_masks_binary) # (N, M)
else:
intersection_metric = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
assert not o2o_matching_masklets_enable, "Temporarily disabled support for o2o_matching_masklets_enable, due to optimizations."
if o2o_matching_masklets_enable:
intersection_metric_np = intersection_metric.cpu().numpy()
from scipy.optimize import linear_sum_assignment
cost_matrix = 1 - intersection_metric_np
row_ind, col_ind = linear_sum_assignment(cost_matrix)
trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
for d, t in zip(row_ind, col_ind):
if intersection_metric_np[d, t] >= iou_threshold_trk:
trk_is_matched[t] = True
trk_is_matched = torch.from_numpy(trk_is_matched)
trk_is_matched = trk_is_matched.to(device=intersection_metric.device)
else:
trk_is_matched = (intersection_metric >= iou_threshold_trk).any(dim=0)
# Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
trk_is_nonempty = trk_masks_binary.any(dim=(1, 2))
trk_is_unmatched = torch.logical_and(trk_is_nonempty, ~trk_is_matched)
# For detections: allow many tracks to match to the same detection (many-to-one)
# So, a detection is 'new' if it does not match any track above threshold
is_new_det = torch.logical_and(
torch.logical_and((det_scores >= new_det_thresh), (det_keep)),
torch.logical_not(torch.any(intersection_metric >= iou_threshold, dim=1)),
)
intersection_thresh_recond = (
iom_thresh_recondition if use_iom_recondition else iou_thresh_recondition
)
# if a detection matches to many tracks with high IoU or vice versa, we do not consider it for reconditioning as it might be ambiguous
det_match_to_many_trk = (intersection_metric >= intersection_thresh_recond).sum(
dim=1
) > 1
trk_match_to_many_det = (intersection_metric >= intersection_thresh_recond).sum(
dim=0
) > 1
# # zero out these ambiguous matches
# intersection_metric[:, trk_match_to_many_det] = (
# 0.0 # only consider unique matches
# )
# intersection_metric[det_match_to_many_trk, :] = (
# 0.0 # only consider unique matches
# )
intersection_metric = torch.where(
trk_match_to_many_det.unsqueeze(0),
torch.zeros_like(intersection_metric),
intersection_metric,
)
intersection_metric = torch.where(
det_match_to_many_trk.unsqueeze(1),
torch.zeros_like(intersection_metric),
intersection_metric,
)
det_to_max_iou_trk_idx = torch.argmax(intersection_metric, dim=1)
det_is_high_conf = ((det_scores >= HIGH_CONF_THRESH) & det_keep) & ~is_new_det
det_is_high_iou = (
torch.amax(intersection_metric, dim=1) >= intersection_thresh_recond
)
im_mask = intersection_metric >= iou_threshold
return (
trk_is_unmatched,
trk_is_nonempty,
is_new_det,
det_to_max_iou_trk_idx,
det_is_high_conf,
det_is_high_iou,
det_keep,
im_mask,
)
class Sam3VideoBase(nn.Module):
def __init__(
self,
@@ -516,17 +737,7 @@ class Sam3VideoBase(nn.Module):
is_image_only: bool = False,
):
# initialize new metadata from previous metadata (its values will be updated later)
tracker_metadata_new = {
"obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
"obj_ids_all_gpu": None, # will be filled later
"num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
"obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
"obj_id_to_tracker_score_frame_wise": deepcopy(
tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]
),
"obj_id_to_last_occluded": {}, # will be filled later
"max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
}
tracker_metadata_new = self._create_planning_metadata(tracker_metadata_prev)
# Initialize reconditioned_obj_ids early to avoid UnboundLocalError
reconditioned_obj_ids = set()
@@ -619,9 +830,9 @@ class Sam3VideoBase(nn.Module):
num_obj_dropped_due_to_limit,
trk_id_to_max_iou_high_conf_det,
]
assert len(update_plan) == NUM_BROADCAST_ITEMS, (
f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
)
assert (
len(update_plan) == NUM_BROADCAST_ITEMS
), f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
self.broadcast_python_obj_cpu(update_plan, src=0)
elif self.rank > 0 and self.world_size > 1:
update_plan = [
@@ -841,9 +1052,9 @@ class Sam3VideoBase(nn.Module):
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
batch_size = tracker_low_res_masks_global.size(0)
if batch_size > 0:
assert len(obj_ids_global) == batch_size, (
f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
)
assert (
len(obj_ids_global) == batch_size
), f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
NEVER_OCCLUDED = -1
ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
last_occluded_prev = torch.cat(
@@ -901,6 +1112,7 @@ class Sam3VideoBase(nn.Module):
orig_vid_height: int,
orig_vid_width: int,
feature_cache: Dict,
tracker_metadata_new=None,
):
# initialize tracking scores with detection scores
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
@@ -931,8 +1143,31 @@ class Sam3VideoBase(nn.Module):
if len(obj_ids_newly_removed) > 0:
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
self._post_execution_phase_hook(tracker_states_local, tracker_metadata_new)
return tracker_states_local
def _create_planning_metadata(self, tracker_metadata_prev):
"""Create the metadata dict for the planning phase from previous metadata."""
from copy import deepcopy
score_key = "obj_id_to_tracker_score_frame_wise"
if score_key not in tracker_metadata_prev:
score_key = "obj_id_to_sam2_score_frame_wise"
metadata = {
"obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
"obj_ids_all_gpu": None,
"num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
"obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
score_key: deepcopy(tracker_metadata_prev[score_key]),
"obj_id_to_last_occluded": {},
"max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
}
return metadata
def _post_execution_phase_hook(self, tracker_states_local, tracker_metadata_new):
"""Hook for subclasses to add post-execution logic. Default: no-op."""
pass
def build_outputs(
self,
frame_idx: int,
@@ -1022,9 +1257,9 @@ class Sam3VideoBase(nn.Module):
reverse: bool = False,
):
# Suppress overlapping masks for objects that were most recently occluded
assert binary_low_res_masks.dtype == torch.bool, (
f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
)
assert (
binary_low_res_masks.dtype == torch.bool
), f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
to_suppress = torch.zeros(
binary_low_res_masks.size(0),
device=binary_low_res_masks.device,
@@ -1129,9 +1364,9 @@ class Sam3VideoBase(nn.Module):
num_frames_propagated += 1
# only 1 frames should be propagated
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
)
assert (
num_frames_propagated == 1 and out_frame_idx == frame_idx
), f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
assert isinstance(out_obj_ids, list)
obj_ids_local.extend(out_obj_ids)
low_res_masks_list.append(out_low_res_masks.squeeze(1))
@@ -1180,6 +1415,7 @@ class Sam3VideoBase(nn.Module):
to any detections on this frame (for unmatched, we only count masklets with >0 area)
- det_to_matched_trk_obj_ids: dict[int, npt.NDArray]: mapping from detector's detection indices
to the list of matched tracklet object IDs
- trk_id_to_max_iou_high_conf_det: dict mapping track obj_id to the highest-IoU high-conf detection idx
- empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
"""
iou_threshold = self.assoc_iou_thresh
@@ -1188,9 +1424,9 @@ class Sam3VideoBase(nn.Module):
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
assert trk_masks.size(0) == len(trk_obj_ids), (
f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
)
assert (
trk_masks.size(0) == len(trk_obj_ids)
), f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
if trk_masks.size(0) == 0:
# all detections are new
new_det_fa_inds = np.arange(det_masks.size(0))
@@ -1239,61 +1475,40 @@ class Sam3VideoBase(nn.Module):
align_corners=False,
).squeeze(1)
det_masks_binary = det_masks > 0
trk_masks_binary = trk_masks > 0
ious = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
ious_np = ious.cpu().numpy()
if self.o2o_matching_masklets_enable:
from scipy.optimize import linear_sum_assignment
# Hungarian matching for tracks (one-to-one: each track matches at most one detection)
cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
row_ind, col_ind = linear_sum_assignment(cost_matrix)
trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
for d, t in zip(row_ind, col_ind):
if ious_np[d, t] >= iou_threshold_trk:
trk_is_matched[t] = True
else:
trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
# Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
# also record masklets that have zero area in SAM 2 prediction
empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
# For detections: allow many tracks to match to the same detection (many-to-one)
# So, a detection is 'new' if it does not match any track above threshold
is_new_det = np.logical_and(
det_scores_np >= new_det_thresh,
np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
# Convert numpy scores to tensor for the compilable function
det_scores = torch.from_numpy(det_scores_np).to(det_masks.device)
det_keep = torch.ones(
det_masks.size(0), dtype=torch.bool, device=det_masks.device
)
new_det_fa_inds = np.nonzero(is_new_det)[0]
# for each detection, which tracks it matched to (above threshold)
det_to_matched_trk_obj_ids = {}
trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
HIGH_CONF_THRESH = 0.8
HIGH_IOU_THRESH = 0.8
det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
det_is_high_conf = (det_scores_np >= HIGH_CONF_THRESH) & ~is_new_det
det_is_high_iou = np.max(ious_np, axis=1) >= HIGH_IOU_THRESH
det_is_high_conf_and_iou = set(
np.nonzero(det_is_high_conf & det_is_high_iou)[0]
# Call the GPU-native compilable function
adt_result_tensors = _associate_det_trk_compilable(
det_masks=det_masks,
det_scores=det_scores,
det_keep=det_keep,
trk_masks=trk_masks,
new_det_thresh=new_det_thresh,
iou_threshold_trk=iou_threshold_trk,
iou_threshold=iou_threshold,
HIGH_CONF_THRESH=0.8,
use_iom_recondition=getattr(self, "use_iom_recondition", False),
o2o_matching_masklets_enable=self.o2o_matching_masklets_enable,
iom_thresh_recondition=getattr(self, "iom_thresh_recondition", 0.8),
iou_thresh_recondition=getattr(self, "iou_thresh_recondition", 0.8),
)
for d in range(det_masks.size(0)):
det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
if d in det_is_high_conf_and_iou:
trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
# Wrap in LazyAssociateDetTrkResult and immediately realize to numpy
# for backward compatibility with existing callers
lazy_result = LazyAssociateDetTrkResult(*adt_result_tensors)
lazy_result._convert_to_numpy()
realized = lazy_result._create_cpu_metadata(trk_obj_ids, det_masks)
return (
new_det_fa_inds,
unmatched_trk_obj_ids,
det_to_matched_trk_obj_ids,
trk_id_to_max_iou_high_conf_det,
empty_trk_obj_ids,
realized.new_det_fa_inds,
realized.unmatched_trk_obj_ids,
realized.det_to_matched_trk_obj_ids,
realized.trk_id_to_max_iou_high_conf_det,
realized.empty_trk_obj_ids,
)
def _assign_new_det_to_gpus(self, new_det_num, prev_workload_per_gpu):
@@ -1601,21 +1816,35 @@ class Sam3VideoBase(nn.Module):
def _initialize_metadata(self):
"""Initialize metadata for the masklets."""
is_multiplex = getattr(self, "is_multiplex", False)
score_key = (
"obj_id_to_sam2_score_frame_wise"
if is_multiplex
else "obj_id_to_tracker_score_frame_wise"
)
tracker_metadata = {
"obj_ids_per_gpu": [np.array([], np.int64) for _ in range(self.world_size)],
"obj_ids_all_gpu": np.array([], np.int64),
"num_obj_per_gpu": np.zeros(self.world_size, np.int64),
"max_obj_id": -1,
"obj_id_to_score": {},
"obj_id_to_tracker_score_frame_wise": defaultdict(dict),
score_key: defaultdict(dict),
"obj_id_to_last_occluded": {},
}
if self.rank == 0:
# "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
# - obj_first_frame_idx: obj_id --> first frame index where the object was detected
# - unmatched_frame_inds: obj_id --> [mismatched frame indices]
# - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
# - removed_obj_ids: object IDs that are suppressed via hot-start
if is_multiplex:
tracker_metadata["gpu_metadata"] = {
"N_obj": 0
} # GPU-side metadata for sync-free hotstart
tracker_metadata["num_buc_per_gpu"] = np.zeros(self.world_size, np.int64)
# "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
# - obj_first_frame_idx: obj_id --> first frame index where the object was detected
# - unmatched_frame_inds: obj_id --> [mismatched frame indices]
# - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
# - removed_obj_ids: object IDs that are suppressed via hot-start
# In multiplex mode, rank0_metadata is always included (all GPUs need it).
# In non-multiplex mode, only rank 0 stores it.
if is_multiplex or self.rank == 0:
rank0_metadata = {
"obj_first_frame_idx": {},
"unmatched_frame_inds": defaultdict(list),
@@ -1654,9 +1883,9 @@ class Sam3VideoBase(nn.Module):
# a) first, expand "confirmation_data" to include new masklets added in this frame
status_prev = confirmation_data["status"]
consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
)
assert (
status_prev.shape == obj_ids_all_gpu_prev.shape
), f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
obj_id_to_updated_idx = {
obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
+22 -24
View File
@@ -554,9 +554,7 @@ class Sam3VideoInference(Sam3VideoBase):
assert (
"cached_frame_outputs" in inference_state
and frame_idx in inference_state["cached_frame_outputs"]
), (
"No cached outputs found. Ensure normal propagation has run first to populate the cache."
)
), "No cached outputs found. Ensure normal propagation has run first to populate the cache."
cached_outputs = inference_state["cached_frame_outputs"][frame_idx]
obj_id_to_mask = cached_outputs.copy()
@@ -564,9 +562,9 @@ class Sam3VideoInference(Sam3VideoBase):
# Update with refined masks if provided
if refined_obj_id_to_mask is not None:
for obj_id, refined_mask in refined_obj_id_to_mask.items():
assert refined_mask is not None, (
f"Refined mask data must be provided for obj_id {obj_id}"
)
assert (
refined_mask is not None
), f"Refined mask data must be provided for obj_id {obj_id}"
obj_id_to_mask[obj_id] = refined_mask
return obj_id_to_mask
@@ -855,12 +853,12 @@ class Sam3VideoInference(Sam3VideoBase):
logger.debug("Running add_prompt on frame %d", frame_idx)
num_frames = inference_state["num_frames"]
assert text_str is not None or boxes_xywh is not None, (
"at least one type of prompt (text, boxes) must be provided"
)
assert 0 <= frame_idx < num_frames, (
f"{frame_idx=} is out of range for a total of {num_frames} frames"
)
assert (
text_str is not None or boxes_xywh is not None
), "at least one type of prompt (text, boxes) must be provided"
assert (
0 <= frame_idx < num_frames
), f"{frame_idx=} is out of range for a total of {num_frames} frames"
# since it's a semantic prompt, we start over
self.reset_state(inference_state)
@@ -1201,9 +1199,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
"propagation_partial",
"propagation_fetch",
]
assert action_type in instance_actions + propagation_actions, (
f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
)
assert (
action_type in instance_actions + propagation_actions
), f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
action = {
"type": action_type,
"frame_idx": frame_idx,
@@ -1371,12 +1369,12 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
):
if points is not None:
# Tracker instance prompts
assert text_str is None and boxes_xywh is None, (
"When points are provided, text_str and boxes_xywh must be None."
)
assert obj_id is not None, (
"When points are provided, obj_id must be provided."
)
assert (
text_str is None and boxes_xywh is None
), "When points are provided, text_str and boxes_xywh must be None."
assert (
obj_id is not None
), "When points are provided, obj_id must be provided."
return self.add_tracker_new_points(
inference_state,
frame_idx,
@@ -1492,9 +1490,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
tracker_states = self._get_tracker_inference_states_by_obj_ids(
inference_state, [obj_id]
)
assert len(tracker_states) == 1, (
f"[rank={self.rank}] Multiple Tracker inference states found for the same object id."
)
assert (
len(tracker_states) == 1
), f"[rank={self.rank}] Multiple Tracker inference states found for the same object id."
tracker_state = tracker_states[0]
# log
+21 -214
View File
@@ -17,14 +17,12 @@ from typing import List, Optional
import psutil
import torch
from sam3.logger import get_logger
from sam3.model.sam3_base_predictor import Sam3BasePredictor
logger = get_logger(__name__)
class Sam3VideoPredictor:
# a global dictionary that holds all inference states for this model (key is session_id)
_ALL_INFERENCE_STATES = {}
class Sam3VideoPredictor(Sam3BasePredictor):
def __init__(
self,
checkpoint_path=None,
@@ -37,6 +35,7 @@ class Sam3VideoPredictor:
apply_temporal_disambiguation: bool = True,
compile: bool = False,
):
super().__init__()
self.async_loading_frames = async_loading_frames
self.video_loader_type = video_loader_type
from sam3.model_builder import build_sam3_video_model
@@ -55,124 +54,14 @@ class Sam3VideoPredictor:
.eval()
)
@torch.inference_mode()
def handle_request(self, request):
"""Dispatch a request based on its type."""
request_type = request["type"]
if request_type == "start_session":
return self.start_session(
resource_path=request["resource_path"],
session_id=request.get("session_id", None),
)
elif request_type == "add_prompt":
return self.add_prompt(
session_id=request["session_id"],
frame_idx=request["frame_index"],
text=request.get("text", None),
points=request.get("points", None),
point_labels=request.get("point_labels", None),
bounding_boxes=request.get("bounding_boxes", None),
bounding_box_labels=request.get("bounding_box_labels", None),
obj_id=request.get("obj_id", None),
)
elif request_type == "remove_object":
return self.remove_object(
session_id=request["session_id"],
obj_id=request["obj_id"],
is_user_action=request.get("is_user_action", True),
)
elif request_type == "reset_session":
return self.reset_session(session_id=request["session_id"])
elif request_type == "close_session":
return self.close_session(session_id=request["session_id"])
else:
raise RuntimeError(f"invalid request type: {request_type}")
@torch.inference_mode()
def handle_stream_request(self, request):
"""Dispatch a stream request based on its type."""
request_type = request["type"]
if request_type == "propagate_in_video":
yield from self.propagate_in_video(
session_id=request["session_id"],
propagation_direction=request.get("propagation_direction", "both"),
start_frame_idx=request.get("start_frame_index", None),
max_frame_num_to_track=request.get("max_frame_num_to_track", None),
)
else:
raise RuntimeError(f"invalid request type: {request_type}")
def start_session(self, resource_path, session_id=None):
"""
Start a new inference session on an image or a video. Here `resource_path`
can be either a path to an image file (for image inference) or an MP4 file
or directory with JPEG video frames (for video inference).
If `session_id` is defined, it will be used as identifier for the
session. If it is not defined, the start_session function will create
a session id and return it.
"""
# get an initial inference_state from the model
inference_state = self.model.init_state(
resource_path=resource_path,
async_loading_frames=self.async_loading_frames,
video_loader_type=self.video_loader_type,
)
if not session_id:
session_id = str(uuid.uuid4())
self._ALL_INFERENCE_STATES[session_id] = {
"state": inference_state,
"session_id": session_id,
"start_time": time.time(),
}
logger.debug(
f"started new session {session_id}; {self._get_session_stats()}; "
f"{self._get_torch_and_gpu_properties()}"
)
return {"session_id": session_id}
def add_prompt(
self,
session_id: str,
frame_idx: int,
text: Optional[str] = None,
points: Optional[List[List[float]]] = None,
point_labels: Optional[List[int]] = None,
bounding_boxes: Optional[List[List[float]]] = None,
bounding_box_labels: Optional[List[int]] = None,
obj_id: Optional[int] = None,
):
"""Add text, box and/or point prompt on a specific video frame."""
logger.debug(
f"add prompt on frame {frame_idx} in session {session_id}: "
f"{text=}, {points=}, {point_labels=}, "
f"{bounding_boxes=}, {bounding_box_labels=}"
)
session = self._get_session(session_id)
inference_state = session["state"]
frame_idx, outputs = self.model.add_prompt(
inference_state=inference_state,
frame_idx=frame_idx,
text_str=text,
points=points,
point_labels=point_labels,
boxes_xywh=bounding_boxes,
box_labels=bounding_box_labels,
obj_id=obj_id,
)
return {"frame_index": frame_idx, "outputs": outputs}
def remove_object(
self,
session_id: str,
obj_id: int,
frame_idx: int = 0,
obj_id: int = 0,
is_user_action: bool = True,
):
"""Remove an object from tracking."""
logger.debug(
f"remove object {obj_id} in session {session_id}: {is_user_action=}"
)
"""Remove an object from tracking (SAM3 uses a simpler remove_object API)."""
session = self._get_session(session_id)
inference_state = session["state"]
@@ -183,111 +72,29 @@ class Sam3VideoPredictor:
)
return {"is_success": True}
def propagate_in_video(
self,
session_id,
propagation_direction,
start_frame_idx,
max_frame_num_to_track,
):
"""Propagate the added prompts to get grounding results on all video frames."""
logger.debug(
f"propagate in video in session {session_id}: "
f"{propagation_direction=}, {start_frame_idx=}, {max_frame_num_to_track=}"
)
try:
session = self._get_session(session_id)
inference_state = session["state"]
if propagation_direction not in ["both", "forward", "backward"]:
raise ValueError(
f"invalid propagation direction: {propagation_direction}"
)
# First doing the forward propagation
if propagation_direction in ["both", "forward"]:
for frame_idx, outputs in self.model.propagate_in_video(
inference_state=inference_state,
start_frame_idx=start_frame_idx,
max_frame_num_to_track=max_frame_num_to_track,
reverse=False,
):
yield {"frame_index": frame_idx, "outputs": outputs}
# Then doing the backward propagation (reverse in time)
if propagation_direction in ["both", "backward"]:
for frame_idx, outputs in self.model.propagate_in_video(
inference_state=inference_state,
start_frame_idx=start_frame_idx,
max_frame_num_to_track=max_frame_num_to_track,
reverse=True,
):
yield {"frame_index": frame_idx, "outputs": outputs}
finally:
# Log upon completion (so that e.g. we can see if two propagations happen in parallel).
# Using `finally` here to log even when the tracking is aborted with GeneratorExit.
logger.debug(
f"propagation ended in session {session_id}; {self._get_session_stats()}"
)
def reset_session(self, session_id):
"""Reset the session to its initial state (as when it's initial opened)."""
logger.debug(f"reset session {session_id}")
session = self._get_session(session_id)
inference_state = session["state"]
self.model.reset_state(inference_state)
return {"is_success": True}
def close_session(self, session_id):
"""
Close a session. This method is idempotent and can be called multiple
times on the same "session_id".
"""
session = self._ALL_INFERENCE_STATES.pop(session_id, None)
if session is None:
logger.warning(
f"cannot close session {session_id} as it does not exist (it might have expired); "
f"{self._get_session_stats()}"
)
else:
del session
gc.collect()
logger.info(f"removed session {session_id}; {self._get_session_stats()}")
return {"is_success": True}
def _get_session(self, session_id):
session = self._ALL_INFERENCE_STATES.get(session_id, None)
if session is None:
raise RuntimeError(
f"Cannot find session {session_id}; it might have expired"
)
return session
def _get_session_stats(self):
"""Get a statistics string for live sessions and their GPU usage."""
# print both the session ids and their video frame numbers
live_session_strs = [
f"'{session_id}' ({session['state']['num_frames']} frames)"
for session_id, session in self._ALL_INFERENCE_STATES.items()
]
session_stats_str = (
f"live sessions: [{', '.join(live_session_strs)}], GPU memory: "
f"{torch.cuda.memory_allocated() // 1024**2} MiB used and "
f"{torch.cuda.memory_reserved() // 1024**2} MiB reserved"
f" (max over time: {torch.cuda.max_memory_allocated() // 1024**2} MiB used "
f"and {torch.cuda.max_memory_reserved() // 1024**2} MiB reserved)"
live_session_strs = []
for sid, s in self._all_inference_states.items():
nf = s["state"]["num_frames"]
live_session_strs.append(f"'{sid}' ({nf} frames)")
joined = ", ".join(live_session_strs)
mem_alloc = torch.cuda.memory_allocated() // 1024**2
mem_res = torch.cuda.memory_reserved() // 1024**2
max_alloc = torch.cuda.max_memory_allocated() // 1024**2
max_res = torch.cuda.max_memory_reserved() // 1024**2
return (
f"live sessions: [{joined}], GPU memory: "
f"{mem_alloc} MiB used and {mem_res} MiB reserved"
f" (max over time: {max_alloc} MiB used and {max_res} MiB reserved)"
)
return session_stats_str
def _get_torch_and_gpu_properties(self):
"""Get a string for PyTorch and GPU properties (for logging and debugging)."""
torch_and_gpu_str = (
"""Get a string for PyTorch and GPU properties."""
return (
f"torch: {torch.__version__} with CUDA arch {torch.cuda.get_arch_list()}, "
f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
)
return torch_and_gpu_str
def shutdown(self):
"""Shutdown the predictor and clear all sessions."""
self._ALL_INFERENCE_STATES.clear()
class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
+3 -3
View File
@@ -318,9 +318,9 @@ class VETextEncoder(nn.Module):
# The text is already encoded, use as is.
text_attention_mask, text_memory_resized, tokenized = text
inputs_embeds = tokenized["inputs_embeds"]
assert input_boxes is None or len(input_boxes) == 0, (
"Can't replace boxes in text if it's already encoded"
)
assert (
input_boxes is None or len(input_boxes) == 0
), "Can't replace boxes in text if it's already encoded"
# Note that the input_embeds are returned in pytorch's convention (sequence first)
return (
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+171 -20
View File
@@ -22,13 +22,58 @@ import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
try:
from timm.layers import DropPath, Mlp, trunc_normal_
from timm.layers import DropPath, trunc_normal_
except ModuleNotFoundError:
# compatibility for older timm versions
from timm.models.layers import DropPath, Mlp, trunc_normal_
from timm.models.layers import DropPath, trunc_normal_
from sam3.model.data_misc import NestedTensor
from sam3.model.model_misc import AttentionType, LayerScale
from sam3.perflib.fused import addmm_act
from sam3.sam.rope import apply_rotary_enc_real, VisionRotaryEmbeddingVE
from torch import Tensor
from .model_misc import LayerScale
class Mlp(nn.Module):
"""MLP as used in Vision Transformer, MLP-Mixer and related networks"""
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
norm_layer=None,
bias=True,
drop=0.0,
use_conv=False,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
if isinstance(bias, bool):
bias = (bias, bias)
if isinstance(drop, (int, float)):
drop_probs = (drop, drop)
else:
drop_probs = drop
linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0])
self.act = act_layer()
self.drop1 = nn.Dropout(drop_probs[0])
self.norm = (
norm_layer(hidden_features) if norm_layer is not None else nn.Identity()
)
self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1])
self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x):
x = addmm_act(type(self.act), self.fc1, x)
x = self.drop1(x)
x = self.norm(x)
x = self.fc2(x)
x = self.drop2(x)
return x
def init_t_xy(
@@ -349,11 +394,16 @@ class Attention(nn.Module):
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
input_size: Optional[Tuple[int, int]] = None,
attn_type: AttentionType = AttentionType.Vanilla,
cls_token: bool = False,
use_rope: bool = False,
rope_theta: float = 10000.0,
rope_pt_size: Optional[Tuple[int, int]] = None,
rope_interp: bool = False,
rope_tiled: bool = False,
use_ve_rope: bool = False,
use_fa3: bool = False,
use_rope_real: bool = False,
):
"""
Args:
@@ -369,7 +419,9 @@ class Attention(nn.Module):
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
rope_theta: control frequencies of rope
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
rope_tiled: whether to tile rope or not; tile expected to be of size rope_pt_size x rope_pt_size
rope_interp: whether to interpolate (or extrapolate) rope to match input size
use_ve_rope: use ve orig rope implementation, if small numerical differences are important (normally not)
"""
super().__init__()
self.num_heads = num_heads
@@ -377,6 +429,7 @@ class Attention(nn.Module):
self.scale = self.head_dim**-0.5
self.cls_token = cls_token
self.attn_type = attn_type
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.proj = nn.Linear(dim, dim)
@@ -388,6 +441,10 @@ class Attention(nn.Module):
self.rope_theta = rope_theta
self.rope_pt_size = rope_pt_size
self.rope_interp = rope_interp
self.rope_tiled = rope_tiled
self.use_ve_rope = use_ve_rope
self.use_fa3 = use_fa3
self.use_rope_real = use_rope_real
# init rel_pos embeddings and rope
self._setup_rel_pos(rel_pos_zero_init)
@@ -430,6 +487,15 @@ class Attention(nn.Module):
if self.rope_pt_size is None:
self.rope_pt_size = self.input_size
if self.use_ve_rope:
assert not self.rope_tiled, "not supported"
self.rope = VisionRotaryEmbeddingVE(
dim=self.head_dim // 2,
seq_len=self.input_size[0],
pt_seq_len=self.rope_pt_size[0],
)
return
# initialize 2d rope freqs
self.compute_cis = partial(
compute_axial_cis,
@@ -437,16 +503,40 @@ class Attention(nn.Module):
theta=self.rope_theta,
)
# interpolate rope
scale_pos = 1.0
if self.rope_interp:
scale_pos = self.rope_pt_size[0] / self.input_size[0]
# get scaled freqs_cis
freqs_cis = self.compute_cis(
end_x=self.input_size[0],
end_y=self.input_size[1],
scale_pos=scale_pos,
)
if self.rope_pt_size != self.input_size and self.rope_tiled:
assert not self.rope_interp
# window/tiled rope
freqs_cis = self.compute_cis(
end_x=self.rope_pt_size[0], end_y=self.rope_pt_size[1]
)
# check dims are tileable
rh, rw = (
self.input_size[0] // self.rope_pt_size[0],
self.input_size[1] // self.rope_pt_size[1],
)
assert rh >= 1, rw >= 1
assert (
self.input_size[0] % self.rope_pt_size[0] == 0
and self.input_size[1] % self.rope_pt_size[1] == 0
)
# restore spatial shape, tile and then flatten spatial dims
freqs_cis = (
freqs_cis.reshape(self.rope_pt_size[0], self.rope_pt_size[1], -1)
.tile(rh, rw, 1)
.reshape(-1, freqs_cis.shape[-1])
)
else:
# interpolate rope
scale_pos = 1.0
if self.rope_interp:
scale_pos = self.rope_pt_size[0] / self.input_size[0]
# get scaled freqs_cis
freqs_cis = self.compute_cis(
end_x=self.input_size[0],
end_y=self.input_size[1],
scale_pos=scale_pos,
)
if self.cls_token:
t = torch.zeros(
self.head_dim // 2,
@@ -457,12 +547,27 @@ class Attention(nn.Module):
freqs_cis = torch.cat([cls_freqs_cis, freqs_cis], dim=0)
self.register_buffer("freqs_cis", freqs_cis)
if self.use_rope_real:
self.register_buffer("freqs_cis_real", freqs_cis.real)
self.register_buffer("freqs_cis_imag", freqs_cis.imag)
def _apply_rope(self, q, k) -> Tuple[Tensor, Tensor]:
if not self.use_rope:
return q, k
if self.use_ve_rope:
dtype = q.dtype
return self.rope(q).to(dtype), self.rope(k).to(dtype)
assert self.freqs_cis is not None
if self.use_rope_real:
return apply_rotary_enc_real(
q,
k,
freqs_cis_imag=self.freqs_cis_imag,
freqs_cis_real=self.freqs_cis_real,
)
return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis)
def forward(self, x: Tensor) -> Tensor:
@@ -501,7 +606,17 @@ class Attention(nn.Module):
q = q.reshape(B, self.num_heads, H * W, -1)
k = k.reshape(B, self.num_heads, H * W, -1)
x = F.scaled_dot_product_attention(q, k, v)
if self.attn_type == AttentionType.Vanilla:
if self.use_fa3:
from sam3.perflib.fa3 import flash_attn_func
x = flash_attn_func(
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
).transpose(1, 2)
else:
x = F.scaled_dot_product_attention(q, k, v)
else:
raise NotImplementedError
if ndim == 4:
x = (
@@ -541,6 +656,9 @@ class Block(nn.Module):
cls_token: bool = False,
dropout: float = 0.0,
init_values: Optional[float] = None,
attn_type: AttentionType = AttentionType.Vanilla,
use_fa3: bool = False,
use_rope_real: bool = False,
):
"""
Args:
@@ -561,8 +679,10 @@ class Block(nn.Module):
cls_token: whether a cls_token is present.
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
rope_tiled: whether to tile rope or not; tile expected to be of size rope_pt_size x rope_pt_size
rope_interp: whether to interpolate (or extrapolate) rope to match target input size,
expected to specify source size as rope_pt_size.
use_ve_rope: use ve orig rope implementation, if small numerical differences are important (normally not)
"""
super().__init__()
self.norm1 = norm_layer(dim)
@@ -573,10 +693,15 @@ class Block(nn.Module):
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
input_size=input_size if window_size == 0 else (window_size, window_size),
attn_type=attn_type,
use_rope=use_rope,
rope_pt_size=rope_pt_size,
rope_tiled=rope_tiled,
rope_interp=rope_interp,
use_ve_rope=use_ve_rope,
cls_token=cls_token,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
)
self.ls1 = (
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
@@ -642,19 +767,24 @@ class ViT(nn.Module):
window_size: int = 14,
global_att_blocks: Tuple[int, ...] = (2, 5, 8, 11),
use_rope: bool = False,
use_tiled_rope: bool = False,
rope_pt_size: Optional[int] = None,
use_interp_rope: bool = False,
use_ve_rope: bool = False,
use_act_checkpoint: bool = True,
pretrain_img_size: int = 224,
pretrain_use_cls_token: bool = True,
retain_cls_token: bool = True,
dropout: float = 0.0,
return_interm_layers: bool = False,
init_values: Optional[float] = None, # for layerscale
attn_type: AttentionType = AttentionType.Vanilla,
ln_pre: bool = False,
ln_post: bool = False,
bias_patch_embed: bool = True,
compile_mode: Optional[str] = None,
use_act_checkpoint: bool = True,
use_fa3: bool = False,
use_rope_real: bool = False,
):
"""
Args:
@@ -708,9 +838,9 @@ class ViT(nn.Module):
self.retain_cls_token = retain_cls_token
if self.retain_cls_token:
assert pretrain_use_cls_token
assert len(window_block_indexes) == 0, (
"windowing not supported with cls token"
)
assert (
len(window_block_indexes) == 0
), "windowing not supported with cls token"
assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token"
@@ -768,10 +898,15 @@ class ViT(nn.Module):
if rope_pt_size is None
else (rope_pt_size, rope_pt_size)
),
rope_tiled=use_tiled_rope,
use_ve_rope=use_ve_rope,
rope_interp=use_interp_rope,
cls_token=self.retain_cls_token,
dropout=dropout,
init_values=init_values,
attn_type=attn_type,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
)
if i not in window_block_indexes:
@@ -812,7 +947,14 @@ class ViT(nn.Module):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
def forward(self, tensor_list):
if isinstance(tensor_list, NestedTensor):
x = tensor_list.tensors
mask = tensor_list.mask
else:
x = tensor_list
mask = None
x = self.patch_embed(x)
h, w = x.shape[1], x.shape[2]
@@ -835,6 +977,7 @@ class ViT(nn.Module):
x = self.ln_pre(x)
outputs = []
masks = None
for i, blk in enumerate(self.blocks):
if self.use_act_checkpoint and self.training:
x = checkpoint.checkpoint(blk, x, use_reentrant=False)
@@ -856,7 +999,15 @@ class ViT(nn.Module):
feats.shape[0], h, w, feats.shape[-1]
).permute(0, 3, 1, 2)
outputs.append(feats)
if isinstance(tensor_list, NestedTensor):
# Optimization, if the mask is all False, just ignore it
if mask is not None and mask.any() and masks is None:
masks = F.interpolate(
mask[None].float(), size=feats.shape[-2:]
).bool()[0]
outputs.append(NestedTensor(feats, masks))
else:
outputs.append(feats)
return outputs
+254 -1
View File
@@ -12,7 +12,8 @@ import torch.nn as nn
from torch.nn.attention import sdpa_kernel, SDPBackend
from .act_ckpt_utils import activation_ckpt_wrapper
from .necks import Sam3DualViTDetNeck
from .data_misc import NestedTensor
from .necks import Sam3DualViTDetNeck, Sam3TriViTDetNeck
class SAM3VLBackbone(nn.Module):
@@ -175,3 +176,255 @@ class SAM3VLBackbone(nn.Module):
)
return output
class SAM3VLBackboneTri(SAM3VLBackbone):
"""VL backbone with triple-head vision (sam3, interactive, propagation) + text encoder."""
def __init__(self, visual, text, compile_visual=False, scalp=0):
super().__init__(
visual=visual, text=text, compile_visual=compile_visual, scalp=scalp
)
assert isinstance(
self.vision_backbone, Sam3TriViTDetNeck
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
def forward_image(
self,
samples,
*,
need_sam3_out: bool = True,
need_interactive_out: bool = True,
need_propagation_out: bool = True,
):
return activation_ckpt_wrapper(self._forward_image_tri_no_act_ckpt)(
samples=samples,
need_sam3_out=need_sam3_out,
need_interactive_out=need_interactive_out,
need_propagation_out=need_propagation_out,
act_ckpt_enable=self.act_ckpt_whole_vision_backbone and self.training,
)
def _forward_image_tri_no_act_ckpt(
self,
samples,
need_sam3_out=True,
need_interactive_out=True,
need_propagation_out=True,
):
(
sam3_features,
sam3_pos,
interactive_features,
interactive_pos,
propagation_features,
propagation_pos,
) = self.vision_backbone.forward(
samples,
need_sam3_out=need_sam3_out,
need_interactive_out=need_interactive_out,
need_propagation_out=need_propagation_out,
)
if self.scalp > 0:
sam3_features, sam3_pos = (
sam3_features[: -self.scalp],
sam3_pos[: -self.scalp],
)
interactive_features, interactive_pos = (
interactive_features[: -self.scalp],
interactive_pos[: -self.scalp],
)
propagation_features, propagation_pos = (
propagation_features[: -self.scalp],
propagation_pos[: -self.scalp],
)
output = {}
if need_sam3_out:
sam3_last = sam3_features[-1]
output.update(
{
"vision_features": sam3_last.tensors,
"vision_mask": sam3_last.mask,
"vision_pos_enc": sam3_pos,
"backbone_fpn": sam3_features,
}
)
if need_interactive_out:
inte_last = interactive_features[-1]
output["interactive"] = {
"vision_features": inte_last.tensors,
"vision_mask": inte_last.mask,
"vision_pos_enc": interactive_pos,
"backbone_fpn": interactive_features,
}
if need_propagation_out:
prop_last = propagation_features[-1]
output["sam2_backbone_out"] = {
"vision_features": prop_last.tensors,
"vision_mask": prop_last.mask,
"vision_pos_enc": propagation_pos,
"backbone_fpn": propagation_features,
}
return output
class VisionOnly(nn.Module):
def __init__(
self,
visual,
n_features,
forward_in_chunk_for_eval=False,
eval_chunk_size=4,
eval_cast_to_cpu=False,
scalp=0,
compile_mode: str = None,
compile_extra_args: Optional[dict] = None,
):
super().__init__()
self.vision_backbone = visual
self.should_compile = compile_mode is not None or compile_extra_args is not None
self.compile_mode = compile_mode
self.compile_extra_args = compile_extra_args or {}
self.compiled = False
self.n_features = n_features
self.forward_in_chunk_for_eval = forward_in_chunk_for_eval
self.eval_chunk_size = eval_chunk_size
self.eval_cast_to_cpu = eval_cast_to_cpu
self.scalp = scalp
def _compile(self):
if self.should_compile and not self.compiled:
self.vision_backbone = torch.compile(
self.vision_backbone, mode=self.compile_mode, **self.compile_extra_args
)
self.compiled = True
def forward_image(self, samples):
self._compile()
# Forward through backbone
features, pos = self.vision_backbone(samples)
if self.scalp > 0:
features, pos = features[: -self.scalp], pos[: -self.scalp]
elif self.scalp < 0:
features.pop(self.scalp)
pos.pop(self.scalp)
src, mask = features[-1].decompose()
output = {
"vision_features": src,
"vision_mask": mask,
"vision_pos_enc": pos,
"backbone_fpn": features,
}
return output
def forward_text(
self,
captions,
input_boxes=None,
additional_text=None,
device="cuda",
):
bs = len(captions)
output = {
"language_features": torch.zeros((0, bs, self.n_features), device=device),
"language_mask": torch.zeros((bs, 0), device=device),
}
return output
class TriHeadVisionOnly(VisionOnly):
def __init__(
self,
visual,
n_features,
forward_in_chunk_for_eval=False,
eval_chunk_size=4,
eval_cast_to_cpu=False,
scalp=0,
compile_mode: str = None,
compile_extra_args: Optional[dict] = None,
):
super().__init__(
visual=visual,
n_features=n_features,
forward_in_chunk_for_eval=forward_in_chunk_for_eval,
eval_chunk_size=eval_chunk_size,
eval_cast_to_cpu=eval_cast_to_cpu,
scalp=scalp,
compile_mode=compile_mode,
compile_extra_args=compile_extra_args,
)
assert isinstance(
self.vision_backbone, Sam3TriViTDetNeck
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
def forward_image(
self,
samples,
*,
need_sam3_out: bool = True,
need_interactive_out: bool = True,
need_propagation_out: bool = True,
):
self._compile()
# Forward through backbone
(
sam3_features,
sam3_pos,
interactive_features,
interactive_pos,
propagation_features,
propagation_pos,
) = self.vision_backbone(
samples,
need_sam3_out=need_sam3_out,
need_interactive_out=need_interactive_out,
need_propagation_out=need_propagation_out,
)
if self.scalp > 0:
sam3_features, sam3_pos = (
sam3_features[: -self.scalp],
sam3_pos[: -self.scalp],
)
interactive_features, interactive_pos = (
interactive_features[: -self.scalp],
interactive_pos[: -self.scalp],
)
propagation_features, propagation_pos = (
propagation_features[: -self.scalp],
propagation_pos[: -self.scalp],
)
output = {}
if need_sam3_out:
sam3_last = sam3_features[-1]
output.update(
{
"vision_features": sam3_last.tensors,
"vision_mask": sam3_last.mask,
"vision_pos_enc": sam3_pos,
"backbone_fpn": sam3_features,
}
)
if need_interactive_out:
inte_last = interactive_features[-1]
output["interactive"] = {
"vision_features": inte_last.tensors,
"vision_mask": inte_last.mask,
"vision_pos_enc": interactive_pos,
"backbone_fpn": interactive_features,
}
if need_propagation_out:
prop_last = propagation_features[-1]
output["sam2_backbone_out"] = {
"vision_features": prop_last.tensors,
"vision_mask": prop_last.mask,
"vision_pos_enc": propagation_pos,
"backbone_fpn": propagation_features,
}
return output
+538 -17
View File
@@ -11,10 +11,13 @@ import torch.nn as nn
from huggingface_hub import hf_hub_download
from iopath.common.file_io import g_pathmgr
from sam3.model.decoder import (
DecoupledTransformerDecoderLayerv2,
SimpleRoPEAttention,
TransformerDecoder,
TransformerDecoderLayer,
TransformerDecoderLayerv2,
TransformerEncoderCrossAttention,
TransformerEncoderDecoupledCrossAttention,
)
from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
from sam3.model.geometry_encoders import SequenceGeometryEncoder
@@ -31,7 +34,8 @@ from sam3.model.model_misc import (
MultiheadAttentionWrapper as MultiheadAttention,
TransformerWrapper,
)
from sam3.model.necks import Sam3DualViTDetNeck
from sam3.model.multiplex_utils import MultiplexController
from sam3.model.necks import Sam3DualViTDetNeck, Sam3TriViTDetNeck
from sam3.model.position_encoding import PositionEmbeddingSine
from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
@@ -40,8 +44,9 @@ from sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceIntera
from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
from sam3.model.text_encoder_ve import VETextEncoder
from sam3.model.tokenizer_ve import SimpleTokenizer
from sam3.model.video_tracking_multiplex import VideoTrackingDynamicMultiplex
from sam3.model.vitdet import ViT
from sam3.model.vl_combiner import SAM3VLBackbone
from sam3.model.vl_combiner import SAM3VLBackbone, SAM3VLBackboneTri, TriHeadVisionOnly
from sam3.sam.transformer import RoPEAttention
@@ -69,7 +74,7 @@ def _create_position_encoding(precompute_resolution=None):
)
def _create_vit_backbone(compile_mode=None):
def _create_vit_backbone(compile_mode=None, use_fa3=False, use_rope_real=False):
"""Create ViT backbone for visual feature extraction."""
return ViT(
img_size=1008,
@@ -96,6 +101,8 @@ def _create_vit_backbone(compile_mode=None):
return_interm_layers=False,
bias_patch_embed=False,
compile_mode=compile_mode,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
)
@@ -115,7 +122,7 @@ def _create_vl_backbone(vit_neck, text_encoder):
return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
def _create_transformer_encoder() -> TransformerEncoderFusion:
def _create_transformer_encoder(use_fa3=False) -> TransformerEncoderFusion:
"""Create transformer encoder with its layer."""
encoder_layer = TransformerEncoderLayer(
activation="relu",
@@ -131,12 +138,14 @@ def _create_transformer_encoder() -> TransformerEncoderFusion:
dropout=0.1,
embed_dim=256,
batch_first=True,
use_fa3=use_fa3,
),
cross_attention=MultiheadAttention(
num_heads=8,
dropout=0.1,
embed_dim=256,
batch_first=True,
use_fa3=use_fa3,
),
)
@@ -153,7 +162,7 @@ def _create_transformer_encoder() -> TransformerEncoderFusion:
return encoder
def _create_transformer_decoder() -> TransformerDecoder:
def _create_transformer_decoder(use_fa3=False) -> TransformerDecoder:
"""Create transformer decoder with its layer."""
decoder_layer = TransformerDecoderLayer(
activation="relu",
@@ -164,6 +173,7 @@ def _create_transformer_decoder() -> TransformerDecoder:
num_heads=8,
dropout=0.1,
embed_dim=256,
use_fa3=use_fa3,
),
n_heads=8,
use_text_cross_attention=True,
@@ -204,7 +214,7 @@ def _create_dot_product_scoring():
return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
def _create_segmentation_head(compile_mode=None):
def _create_segmentation_head(compile_mode=None, use_fa3=False):
"""Create segmentation head with pixel decoder."""
pixel_decoder = PixelDecoder(
num_upsampling_stages=3,
@@ -217,6 +227,7 @@ def _create_segmentation_head(compile_mode=None):
num_heads=8,
dropout=0,
embed_dim=256,
use_fa3=use_fa3,
)
segmentation_head = UniversalSegmentationHead(
@@ -515,10 +526,12 @@ def _create_vision_backbone(
return vit_neck
def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper:
def _create_sam3_transformer(
has_presence_token: bool = True, use_fa3: bool = False
) -> TransformerWrapper:
"""Create SAM3 transformer encoder and decoder."""
encoder: TransformerEncoderFusion = _create_transformer_encoder()
decoder: TransformerDecoder = _create_transformer_decoder()
encoder: TransformerEncoderFusion = _create_transformer_encoder(use_fa3=use_fa3)
decoder: TransformerDecoder = _create_transformer_decoder(use_fa3=use_fa3)
return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
@@ -630,7 +643,7 @@ def build_sam3_image_model(
eval_mode,
)
if load_from_HF and checkpoint_path is None:
checkpoint_path = download_ckpt_from_hf()
checkpoint_path = download_ckpt_from_hf(version="sam3")
# Load checkpoint if provided
if checkpoint_path is not None:
_load_checkpoint(model, checkpoint_path)
@@ -641,12 +654,22 @@ def build_sam3_image_model(
return model
def download_ckpt_from_hf():
SAM3_MODEL_ID = "facebook/sam3"
SAM3_CKPT_NAME = "sam3.pt"
SAM3_CFG_NAME = "config.json"
_ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME)
checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME)
def download_ckpt_from_hf(version="sam3"):
"""Download model checkpoint from HuggingFace Hub.
Args:
version: "sam3" or "sam3.1"
"""
if version == "sam3.1":
repo_id = "facebook/sam3.1"
ckpt_name = "sam3.1_multiplex.pt"
cfg_name = "config.json"
else:
repo_id = "facebook/sam3"
ckpt_name = "sam3.pt"
cfg_name = "config.json"
_ = hf_hub_download(repo_id=repo_id, filename=cfg_name)
checkpoint_path = hf_hub_download(repo_id=repo_id, filename=ckpt_name)
return checkpoint_path
@@ -772,7 +795,7 @@ def build_sam3_video_model(
# Load checkpoint if provided
if load_from_HF and checkpoint_path is None:
checkpoint_path = download_ckpt_from_hf()
checkpoint_path = download_ckpt_from_hf(version="sam3")
if checkpoint_path is not None:
with g_pathmgr.open(checkpoint_path, "rb") as f:
ckpt = torch.load(f, map_location="cpu", weights_only=True)
@@ -795,3 +818,501 @@ def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs):
return Sam3VideoPredictorMultiGPU(
*model_args, gpus_to_use=gpus_to_use, **model_kwargs
)
def _create_multiplex_maskmem_backbone(multiplex_count=16):
"""Create the multiplex memory encoder with per-object mask channels."""
position_encoding = PositionEmbeddingSine(
num_pos_feats=256,
normalize=True,
scale=None,
temperature=10000,
precompute_resolution=1008,
)
mask_downsampler = SimpleMaskDownSampler(
kernel_size=3,
stride=2,
padding=1,
interpol_size=[1152, 1152],
multiplex_count=multiplex_count,
starting_out_chan=4,
input_channel_multiplier=2,
)
cx_block_layer = CXBlock(
dim=256,
kernel_size=7,
padding=3,
layer_scale_init_value=1.0e-06,
use_dwconv=True,
)
fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
maskmem_backbone = SimpleMaskEncoder(
out_dim=256,
position_encoding=position_encoding,
mask_downsampler=mask_downsampler,
fuser=fuser,
)
return maskmem_backbone
def _create_multiplex_transformer(use_fa3=False, use_rope_real=False):
"""Create the decoupled transformer for multiplex memory attention."""
self_attention_rope = SimpleRoPEAttention(
d_model=256,
num_heads=8,
dropout_p=0.1,
rope_theta=10000.0,
feat_sizes=[72, 72],
use_fa3=use_fa3,
use_rope_real=use_rope_real,
)
cross_attention_rope = SimpleRoPEAttention(
d_model=256,
num_heads=8,
dropout_p=0.1,
rope_theta=10000.0,
feat_sizes=[72, 72],
rope_k_repeat=True,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
)
encoder_layer = DecoupledTransformerDecoderLayerv2(
activation="gelu",
d_model=256,
num_heads=8,
dropout=0.1,
dim_feedforward=2048,
pos_enc_at_attn=False,
pre_norm=True,
pos_enc_at_cross_attn_keys=True,
pos_enc_at_cross_attn_queries=False,
self_attention_rope=self_attention_rope,
cross_attention_rope=cross_attention_rope,
)
encoder = TransformerEncoderDecoupledCrossAttention(
d_model=256,
frozen=False,
pos_enc_at_input=True,
use_image_in_output=False,
layer=encoder_layer,
num_layers=4,
use_act_checkpoint=False,
batch_first=True,
)
transformer = TransformerWrapper(
encoder=encoder,
decoder=None,
d_model=256,
)
return transformer
def _create_multiplex_tri_backbone(
compile_mode=None, use_fa3=False, use_rope_real=False
):
"""Create the TriHead vision backbone for multiplex model."""
position_encoding = _create_position_encoding(precompute_resolution=1008)
vit_backbone = _create_vit_backbone(
compile_mode=compile_mode, use_fa3=use_fa3, use_rope_real=use_rope_real
)
tri_neck = Sam3TriViTDetNeck(
trunk=vit_backbone,
position_encoding=position_encoding,
d_model=256,
scale_factors=[4.0, 2.0, 1.0],
)
return tri_neck
def build_sam3_multiplex_video_model(
checkpoint_path: Optional[str] = None,
load_from_HF=True,
multiplex_count: int = 16,
use_fa3: bool = False,
use_rope_real: bool = False,
strict_state_dict_loading: bool = True,
device="cuda" if torch.cuda.is_available() else "cpu",
compile=False,
):
"""
Build SAM3 multiplex video tracking model.
Args:
checkpoint_path: Optional path to checkpoint file
multiplex_count: Number of objects per multiplex bucket
use_fa3: Whether to use FlashAttention 3
use_rope_real: Whether to use real-valued RoPE (for compile compat)
strict_state_dict_loading: Whether to use strict state dict loading
device: Device to place model on
compile: Whether to compile model components
Returns:
VideoTrackingDynamicMultiplex: The instantiated multiplex tracking model
"""
# Build multiplex-specific components
maskmem_backbone = _create_multiplex_maskmem_backbone(
multiplex_count=multiplex_count
)
transformer = _create_multiplex_transformer(
use_fa3=use_fa3, use_rope_real=use_rope_real
)
tri_neck = _create_multiplex_tri_backbone(
compile_mode="max-autotune" if compile else None
)
backbone = TriHeadVisionOnly(
visual=tri_neck,
n_features=256,
scalp=0,
)
multiplex_controller = MultiplexController(
multiplex_count=multiplex_count,
eval_multiplex_count=multiplex_count,
)
# Build the multiplex model (use demo class for init_state and other demo methods)
from sam3.model.video_tracking_multiplex_demo import Sam3VideoTrackingMultiplexDemo
model = Sam3VideoTrackingMultiplexDemo(
backbone=backbone,
transformer=transformer,
maskmem_backbone=maskmem_backbone,
multiplex_controller=multiplex_controller,
image_size=1008,
backbone_stride=14,
num_maskmem=7,
# Multiplex-specific settings
use_high_res_features_in_sam=True,
use_obj_ptrs_in_encoder=True,
max_obj_ptrs_in_encoder=16,
add_tpos_enc_to_obj_ptrs=True,
proj_tpos_enc_in_obj_ptrs=True,
use_mlp_for_obj_ptr_proj=True,
pred_obj_scores=True,
pred_obj_scores_mlp=True,
fixed_no_obj_ptr=True,
use_no_obj_ptr=True,
use_linear_no_obj_ptr=True,
no_obj_embed_spatial=True,
sincos_tpos_enc=True,
# Multimask settings
multimask_output_in_sam=True,
multimask_output_for_tracking=True,
multimask_min_pt_num=0,
multimask_max_pt_num=1,
use_multimask_token_for_obj_ptr=True,
num_multimask_outputs=3,
# Memory encoder settings
apply_sigmoid_to_mask_logits_for_mem_enc=True,
sigmoid_scale_for_mem_enc=2.0,
sigmoid_bias_for_mem_enc=-1.0,
non_overlap_masks_for_mem_enc=False,
# Suppression/conditional embeddings
add_output_suppression_embeddings=True,
add_object_conditional_embeddings=False,
condition_as_mask_input=True,
condition_as_mask_input_fg=1.0,
condition_as_mask_input_bg=0.0,
# Memory settings
use_maskmem_tpos_v2=True,
save_image_features=True,
randomness_fix=True,
# Interaction settings
use_mask_input_as_output_without_sam=True,
directly_add_no_mem_embed=True,
iou_prediction_use_sigmoid=False,
forward_backbone_per_frame_for_eval=True,
offload_output_to_cpu_for_eval=False,
trim_past_non_cond_mem_for_eval=False,
max_cond_frames_in_attn=4,
# Dynamic multiplex settings
is_dynamic_model=True,
# SAM mask decoder extra args
sam_mask_decoder_extra_args={
"dynamic_multimask_via_stability": True,
"dynamic_multimask_stability_delta": 0.05,
"dynamic_multimask_stability_thresh": 0.98,
},
compile_all_components=compile,
use_memory_selection=False,
)
# Load checkpoint if provided
if load_from_HF and checkpoint_path is None:
checkpoint_path = download_ckpt_from_hf(version="sam3.1")
if checkpoint_path is not None:
with g_pathmgr.open(checkpoint_path, "rb") as f:
ckpt = torch.load(f, map_location="cpu", weights_only=True)
if "model" in ckpt and isinstance(ckpt["model"], dict):
ckpt = ckpt["model"]
missing_keys, unexpected_keys = model.load_state_dict(
ckpt, strict=strict_state_dict_loading
)
if missing_keys:
print(f"Missing keys: {missing_keys}")
if unexpected_keys:
print(f"Unexpected keys: {unexpected_keys}")
model.to(device=device)
return model
def build_sam3_multiplex_video_predictor(
checkpoint_path: Optional[str] = None,
bpe_path: Optional[str] = None,
max_num_objects: int = 16,
multiplex_count: int = 16,
use_fa3: bool = True,
use_rope_real: bool = True,
compile: bool = False,
warm_up: bool = False,
session_expiration_sec: int = 1200,
default_output_prob_thresh: float = 0.5,
async_loading_frames: bool = True,
):
"""
Build a fully-initialized Sam3MultiplexVideoPredictor.
This is the recommended entry point for SAM 3.1 multiplex video tracking.
It builds the full model stack (tracker + detector + demo model), loads
the checkpoint, and wraps everything in Sam3MultiplexVideoPredictor with
handle_request / handle_stream_request API.
Args:
checkpoint_path: Path to the merged multiplex checkpoint
bpe_path: Path to the BPE tokenizer vocabulary
max_num_objects: Maximum number of tracked objects
multiplex_count: Number of objects per multiplex bucket
use_fa3: Whether to use FlashAttention 3
use_rope_real: Whether to use real-valued RoPE (for compile compat)
compile: Whether to enable torch.compile on model components
warm_up: Whether to run warm-up compilation (requires compile=True)
session_expiration_sec: Session expiration timeout in seconds
default_output_prob_thresh: Default probability threshold for output masks
async_loading_frames: Whether to load frames asynchronously
Returns:
Sam3MultiplexVideoPredictor: The fully-initialized predictor
"""
if bpe_path is None:
bpe_path = pkg_resources.resource_filename(
"sam3", "assets/bpe_simple_vocab_16e6.txt.gz"
)
from sam3.model.sam3_multiplex_base import Sam3MultiplexPredictorWrapper
from sam3.model.sam3_multiplex_detector import Sam3MultiplexDetector
from sam3.model.sam3_multiplex_tracking import (
Sam3MultiplexTrackingWithInteractivity,
)
from sam3.model.sam3_multiplex_video_predictor import Sam3MultiplexVideoPredictor
# Build tracker
tracker_model = build_sam3_multiplex_video_model(
checkpoint_path=checkpoint_path,
load_from_HF=False,
multiplex_count=multiplex_count,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
compile=False,
strict_state_dict_loading=False,
)
del tracker_model.backbone
tracker_model.backbone = None
sam2_predictor = Sam3MultiplexPredictorWrapper(
model=tracker_model,
per_obj_inference=False,
fill_hole_area=0,
is_multiplex=True,
is_multiplex_dynamic=True,
)
# Build detector
tri_neck = _create_multiplex_tri_backbone(
compile_mode=None, use_fa3=use_fa3, use_rope_real=use_rope_real
)
text_encoder = _create_text_encoder(bpe_path)
backbone = SAM3VLBackboneTri(scalp=0, visual=tri_neck, text=text_encoder)
transformer = _create_sam3_transformer(use_fa3=use_fa3)
segmentation_head = _create_segmentation_head(use_fa3=use_fa3)
geometry_encoder = _create_geometry_encoder()
dot_prod_scoring = _create_dot_product_scoring()
detector = Sam3MultiplexDetector(
num_feature_levels=1,
backbone=backbone,
transformer=transformer,
segmentation_head=segmentation_head,
semantic_segmentation_head=None,
input_geometry_encoder=geometry_encoder,
use_early_fusion=True,
use_dot_prod_scoring=True,
dot_prod_scoring=dot_prod_scoring,
supervise_joint_box_scores=True,
is_multiplex=True,
)
# Assemble demo model
demo_model = Sam3MultiplexTrackingWithInteractivity(
tracker=sam2_predictor,
detector=detector,
score_threshold_detection=0.4,
det_nms_thresh=0.1,
det_nms_use_iom=True,
assoc_iou_thresh=0.1,
new_det_thresh=0.65,
hotstart_delay=15,
hotstart_unmatch_thresh=8,
hotstart_dup_thresh=8,
suppress_unmatched_only_within_hotstart=False,
suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
suppress_det_close_to_boundary=True,
fill_hole_area=0, # OV effectively 0 (Sam3MultiplexTrackerPredictor Hydra override clobbers yaml's 16)
recondition_every_nth_frame=16,
use_iom_recondition=True,
iom_thresh_recondition=0.5,
masklet_confirmation_enable=True,
reconstruction_bbox_iou_thresh=-1,
reconstruction_bbox_det_score=0.8,
max_num_objects=max_num_objects,
postprocess_batch_size=16,
use_batched_grounding=True,
batched_grounding_batch_size=16,
max_num_kboxes=0,
sprinkle_removal_area=0,
is_multiplex=True,
image_size=1008,
image_mean=(0.5, 0.5, 0.5),
image_std=(0.5, 0.5, 0.5),
compile_model=compile,
)
# Load checkpoint (auto-download from HuggingFace if not provided)
if checkpoint_path is None:
checkpoint_path = download_ckpt_from_hf(version="sam3.1")
if checkpoint_path is not None:
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
if "model" in ckpt and isinstance(ckpt["model"], dict):
ckpt = ckpt["model"]
# Remap checkpoint keys if needed (internal naming -> OSS naming)
# HF checkpoints are already remapped; local checkpoints may use old naming
needs_remap = any(
k.startswith("sam3_model.") or k.startswith("sam2_predictor.") for k in ckpt
)
if needs_remap:
remapped_ckpt = {}
for k, v in ckpt.items():
new_k = k
if k.startswith("sam3_model."):
new_k = "detector." + k[len("sam3_model.") :]
elif k.startswith("sam2_predictor."):
new_k = "tracker." + k[len("sam2_predictor.") :]
remapped_ckpt[new_k] = v
ckpt = remapped_ckpt
missing_keys, unexpected_keys = demo_model.load_state_dict(ckpt, strict=False)
if missing_keys:
print(f"Missing keys ({len(missing_keys)}): {missing_keys[:10]}...")
if unexpected_keys:
print(
f"Unexpected keys ({len(unexpected_keys)}): {unexpected_keys[:10]}..."
)
demo_model.cuda().eval()
# Wrap in predictor
predictor = Sam3MultiplexVideoPredictor(
model=demo_model,
session_expiration_sec=session_expiration_sec,
default_output_prob_thresh=default_output_prob_thresh,
async_loading_frames=async_loading_frames,
warm_up=warm_up,
)
return predictor
def build_sam3_predictor(
checkpoint_path: Optional[str] = None,
bpe_path: Optional[str] = None,
version: str = "sam3.1", # "sam3" or "sam3.1"
compile: bool = False,
warm_up: bool = False,
# SAM 3.1 specific
max_num_objects: int = 16,
multiplex_count: int = 16,
# Common
use_fa3: bool = True,
use_rope_real: bool = True,
async_loading_frames: bool = True,
**kwargs,
):
"""
Build a SAM3 video predictor.
Args:
checkpoint_path: Path to model checkpoint
bpe_path: Path to BPE tokenizer vocabulary
version: Model version - "sam3" for base or "sam3.1" for multiplex
compile: Enable torch.compile for ~2x speedup (SAM 3.1 only currently)
warm_up: Run warm-up compilation passes
max_num_objects: Maximum tracked objects (SAM 3.1 only)
multiplex_count: Objects per multiplex bucket (SAM 3.1 only)
use_fa3: Use Flash Attention 3
use_rope_real: Use real-valued RoPE
async_loading_frames: Load video frames asynchronously
**kwargs: Additional arguments passed to the underlying builder
Returns:
A predictor with handle_request() and handle_stream_request() API.
Both versions support: start_session, add_prompt, propagate_in_video,
remove_object, reset_session, close_session.
Example:
# SAM 3.1 (auto-downloads from HuggingFace):
predictor = build_sam3_predictor(version="sam3.1", compile=True)
# SAM 3 (auto-downloads from HuggingFace):
predictor = build_sam3_predictor(version="sam3")
# Or with a local checkpoint:
predictor = build_sam3_predictor(checkpoint_path="path/to/ckpt.pt", version="sam3.1")
# Both use the same API:
response = predictor.handle_request({"type": "start_session", "resource_path": video_dir})
session_id = response["session_id"]
predictor.handle_request({"type": "add_prompt", "session_id": session_id, "frame_index": 0, "text": "person"})
for out in predictor.handle_stream_request({"type": "propagate_in_video", "session_id": session_id}):
masks = out["out_binary_masks"]
"""
if version == "sam3.1":
return build_sam3_multiplex_video_predictor(
checkpoint_path=checkpoint_path,
bpe_path=bpe_path,
max_num_objects=max_num_objects,
multiplex_count=multiplex_count,
use_fa3=use_fa3,
use_rope_real=use_rope_real,
compile=compile,
warm_up=warm_up,
async_loading_frames=async_loading_frames,
**kwargs,
)
elif version == "sam3":
return build_sam3_video_predictor(
checkpoint_path=checkpoint_path,
bpe_path=bpe_path,
compile=compile,
async_loading_frames=async_loading_frames,
**kwargs,
)
else:
raise ValueError(f"Unknown version: {version!r}. Use 'sam3' or 'sam3.1'.")
+38 -16
View File
@@ -2,7 +2,11 @@
# pyre-unsafe
from functools import wraps
import torch
from sam3.model.data_misc import BatchedDatapoint, NestedTensor
from torch.utils._pytree import tree_map_only
def recursive_fn_factory(fn):
@@ -13,15 +17,18 @@ def recursive_fn_factory(fn):
return [recursive_fn(t) for t in b]
if isinstance(b, tuple):
return tuple(recursive_fn(t) for t in b)
if isinstance(b, NestedTensor):
tensors = fn(b.tensors)
if b.mask is None:
mask = None
else:
mask = fn(b.mask)
return NestedTensor(tensors=tensors, mask=mask)
if isinstance(b, torch.Tensor):
return fn(b)
# Yes, writing out an explicit white list of
# trivial types is tedious, but so are bugs that
# come from not applying fn, when expected to have
# applied it.
if b is None:
return b
trivial_types = [bool, int]
trivial_types = [bool, int, float]
for t in trivial_types:
if isinstance(b, t):
return b
@@ -34,20 +41,41 @@ recursive_contiguous = recursive_fn_factory(lambda x: x.contiguous())
recursive_clone = recursive_fn_factory(torch.clone)
def clone_output_wrapper(f):
"""
Clone the CUDA output tensors of a function to avoid in-place operations.
Uses tree_map_only (C-optimized pytree traversal) matching onevision's pattern.
Requires NestedTensor to be registered as a pytree node (see data_misc.py).
"""
@wraps(f)
def wrapped(*args, **kwargs):
outputs = f(*args, **kwargs)
return tree_map_only(
torch.Tensor, lambda t: t.clone() if t.is_cuda else t, outputs
)
return wrapped
def compile_wrapper(
fn, *, mode="max-autotune", fullgraph=True, dynamic=False, name=None
):
"""Compile with recursive_contiguous on inputs and recursive_clone on outputs.
Used for SAM2 tracker components that need contiguous inputs for CUDA graphs."""
compiled_fn = torch.compile(fn, mode=mode, fullgraph=fullgraph, dynamic=dynamic)
def compiled_fn_wrapper(*args, **kwargs):
with torch.autograd.profiler.record_function(
f"compiled {fn}" if name is None else name
):
cont_args = recursive_contiguous(args)
cont_kwargs = recursive_contiguous(kwargs)
result = compiled_fn(*cont_args, **cont_kwargs)
cloned_result = recursive_clone(result)
return cloned_result
CUDAGRAPH_MODES = ["max-autotune", "reduce-overhead"]
args = recursive_contiguous(args)
kwargs = recursive_contiguous(kwargs)
result = compiled_fn(*args, **kwargs)
if mode in CUDAGRAPH_MODES:
result = recursive_clone(result)
return result
return compiled_fn_wrapper
@@ -56,11 +84,6 @@ def shape_logging_wrapper(fn, keep_kwargs, enable_logging=False):
"""
Wraps a function and prints the shapes of all tensor inputs.
Only prints when a new combination of shapes is seen.
Thread-safe.
Args:
fn: Function to wrap
enable_logging: Boolean flag to enable/disable logging
"""
seen_shapes = set()
@@ -89,7 +112,6 @@ def shape_logging_wrapper(fn, keep_kwargs, enable_logging=False):
print(f"[ShapeLogger] New input shapes for {fn.__qualname__}: {shapes}")
return fn(*args, **kwargs)
# Allow toggling the flag at runtime
wrapper.enable_logging = enable_logging
def set_logging(enabled=False):
+6 -6
View File
@@ -36,9 +36,9 @@ def connected_components_cpu(input_tensor: torch.Tensor):
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
input_tensor = input_tensor.squeeze(1)
else:
assert input_tensor.dim() == 3, (
"Input tensor must be (B, H, W) or (B, 1, H, W)."
)
assert (
input_tensor.dim() == 3
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
batch_size = input_tensor.shape[0]
labels_list = []
@@ -67,9 +67,9 @@ def connected_components(input_tensor: torch.Tensor):
if input_tensor.dim() == 3:
input_tensor = input_tensor.unsqueeze(1)
assert input_tensor.dim() == 4 and input_tensor.shape[1] == 1, (
"Input tensor must be (B, H, W) or (B, 1, H, W)."
)
assert (
input_tensor.dim() == 4 and input_tensor.shape[1] == 1
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
if input_tensor.is_cuda:
if HAS_CC_TORCH:
+25
View File
@@ -0,0 +1,25 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
# pyre-unsafe
import torch
addmm_act_op = torch.ops.aten._addmm_activation
def addmm_act(activation, linear, mat1):
if torch.is_grad_enabled():
raise ValueError("Expected grad to be disabled.")
self = linear.bias.detach()
mat2 = linear.weight.detach()
self = self.to(torch.bfloat16)
mat1 = mat1.to(torch.bfloat16)
mat2 = mat2.to(torch.bfloat16)
mat1_flat = mat1.view(-1, mat1.shape[-1])
if activation in [torch.nn.functional.relu, torch.nn.ReLU]:
y = addmm_act_op(self, mat1_flat, mat2.t(), beta=1, alpha=1, use_gelu=False)
return y.view(mat1.shape[:-1] + (y.shape[-1],))
if activation in [torch.nn.functional.gelu, torch.nn.GELU]:
y = addmm_act_op(self, mat1_flat, mat2.t(), beta=1, alpha=1, use_gelu=True)
return y.view(mat1.shape[:-1] + (y.shape[-1],))
raise ValueError(f"Unexpected activation {activation}")
+38
View File
@@ -0,0 +1,38 @@
import torch
def pairwise_iou(pred_masks, gt_masks, eps=1e-6):
N, H, W = pred_masks.shape
M = gt_masks.shape[0]
# Flatten and convert to float for matmul
pred_flat = pred_masks.reshape(N, -1).float()
gt_flat = gt_masks.reshape(M, -1).float()
# Intersection: (N, M)
intersection = torch.matmul(pred_flat, gt_flat.t())
# Areas
area_pred = pred_flat.sum(dim=1, keepdim=True) # (N, 1)
area_gt = gt_flat.sum(dim=1, keepdim=True) # (M, 1)
# Union: (N, M)
union = area_pred + area_gt.t() - intersection
if eps is None:
iou = intersection / union.clamp(min=1)
else:
iou = intersection / (union + eps)
return iou # shape: (N, M)
def pairwise_iom(pred_masks, gt_masks, eps=1e-8):
N, H, W = pred_masks.shape
M = gt_masks.shape[0]
# Flatten and convert to float for matmul
pred_flat = pred_masks.reshape(N, -1).float()
gt_flat = gt_masks.reshape(M, -1).float()
# Intersection: (N, M)
intersection = torch.matmul(pred_flat, gt_flat.t())
# Areas
area_pred = pred_flat.sum(dim=1, keepdim=True) # (N, 1)
area_gt = gt_flat.sum(dim=1, keepdim=True) # (M, 1)
# Union: (N, M)
min_area = torch.min(area_pred, area_gt)
iou = intersection / (min_area + eps)
return iou # shape: (N, M)
+11 -10
View File
@@ -50,6 +50,8 @@ def masks_to_boxes(masks: torch.Tensor, obj_ids: list[int]):
def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
"""
Compute the IoU (Intersection over Union) between predicted masks and ground truth masks.
Uses matmul-based vectorized intersection for Tensor Core acceleration.
Args:
- pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks
- gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks
@@ -57,15 +59,14 @@ def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
- ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks
"""
assert pred_masks.dtype == gt_masks.dtype == torch.bool
N, H, W = pred_masks.shape
M, _, _ = gt_masks.shape
assert pred_masks.shape[1:] == gt_masks.shape[1:]
# Flatten masks: (N, 1, H*W) and (1, M, H*W)
pred_flat = pred_masks.view(N, 1, H * W)
gt_flat = gt_masks.view(1, M, H * W)
# Matmul-based intersection (uses Tensor Cores via float mm)
m1_flat = pred_masks.flatten(1).float()
m2_flat = gt_masks.flatten(1).float()
intersection = torch.mm(m1_flat, m2_flat.t())
# Compute intersection and union: (N, M)
intersection = (pred_flat & gt_flat).sum(dim=2).float()
union = (pred_flat | gt_flat).sum(dim=2).float()
ious = intersection / union.clamp(min=1)
return ious # shape: (N, M)
area1 = m1_flat.sum(dim=1)
area2 = m2_flat.sum(dim=1)
union = area1[:, None] + area2[None, :] - intersection
return intersection / union.clamp(min=1)
+6 -6
View File
@@ -407,16 +407,16 @@ def connected_components_triton(input_tensor: torch.Tensor):
- A BxHxW output tensor with dense labels. Background is 0.
- A BxHxW tensor with the size of the connected component for each pixel.
"""
assert input_tensor.is_cuda and input_tensor.is_contiguous(), (
"Input tensor must be a contiguous CUDA tensor."
)
assert (
input_tensor.is_cuda and input_tensor.is_contiguous()
), "Input tensor must be a contiguous CUDA tensor."
out_shape = input_tensor.shape
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
input_tensor = input_tensor.squeeze(1)
else:
assert input_tensor.dim() == 3, (
"Input tensor must be (B, H, W) or (B, 1, H, W)."
)
assert (
input_tensor.dim() == 3
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
B, H, W = input_tensor.shape
numel = B * H * W
+3 -3
View File
@@ -202,9 +202,9 @@ class MaskDecoder(nn.Module):
assert image_embeddings.shape[0] == tokens.shape[0]
src = image_embeddings
src = src + dense_prompt_embeddings
assert image_pe.size(0) == 1, (
"image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
)
assert (
image_pe.size(0) == 1
), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
b, c, h, w = src.shape
+3 -3
View File
@@ -204,9 +204,9 @@ class Attention(nn.Module):
self.internal_dim = embedding_dim // downsample_rate
self.num_heads = num_heads
self.use_fa3 = use_fa3
assert self.internal_dim % num_heads == 0, (
"num_heads must divide embedding_dim."
)
assert (
self.internal_dim % num_heads == 0
), "num_heads must divide embedding_dim."
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
+3 -3
View File
@@ -142,9 +142,9 @@ class COCO_FROM_JSON:
self.prompts = {}
for loc_dict in prompts:
self.prompts[int(loc_dict["id"])] = loc_dict["name"]
assert len(self.prompts) == len(self._sorted_cat_ids), (
"Number of prompts must match number of categories"
)
assert len(self.prompts) == len(
self._sorted_cat_ids
), "Number of prompts must match number of categories"
def getDatapointIds(self):
"""Return all datapoint indices for training."""
+3 -3
View File
@@ -216,9 +216,9 @@ def collate_fn_api(
text_batch.append(q.query_text)
stages[stage_id].text_ids.append(text_batch.index(q.query_text))
assert q.inference_metadata is not None, (
"inference_metadata must be provided when FindQueryLoaded is created."
)
assert (
q.inference_metadata is not None
), "inference_metadata must be provided when FindQueryLoaded is created."
for f in fields(q.inference_metadata):
getattr(find_metadatas[stage_id], f.name).append(
getattr(q.inference_metadata, f.name)
+6 -6
View File
@@ -233,9 +233,9 @@ class CustomCocoDetectionAPI(VisionDataset):
if self.coco is not None:
return
assert g_pathmgr.isfile(self.annFile), (
f"please provide valid annotation file. Missing: {self.annFile}"
)
assert g_pathmgr.isfile(
self.annFile
), f"please provide valid annotation file. Missing: {self.annFile}"
annFile = g_pathmgr.get_local_path(self.annFile)
if self.coco is not None:
@@ -325,9 +325,9 @@ class CustomCocoDetectionAPI(VisionDataset):
else:
num_queries_per_stage = stage2num_queries.most_common(1)[0][1]
for stage, num_queries in stage2num_queries.items():
assert num_queries == num_queries_per_stage, (
f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}"
)
assert (
num_queries == num_queries_per_stage
), f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}"
for query in queries:
h, w = id2imsize[query["image_id"]]
+4 -3
View File
@@ -15,6 +15,7 @@ from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
import torchvision
# from decord import cpu, VideoReader
from iopath.common.file_io import PathManager
@@ -218,9 +219,9 @@ class VideoGroundingDataset(Sam3ImageDataset):
for query in filtered_queries:
ptr_x_is_empty = query["ptr_x_query_id"] in [None, -1]
ptr_y_is_empty = query["ptr_y_query_id"] in [None, -1]
assert ptr_x_is_empty and ptr_y_is_empty, (
"Remapping stage ids is not supported for queries with non-empty ptr_x or ptr_y pointers"
)
assert (
ptr_x_is_empty and ptr_y_is_empty
), "Remapping stage ids is not supported for queries with non-empty ptr_x or ptr_y pointers"
query["query_processing_order"] = stage_id_old2new[
query["query_processing_order"]
]
+6 -12
View File
@@ -324,9 +324,7 @@ class IABCEMdetr(LossWithWeights):
if num_det_queries is not None:
logging.warning("note: it's not needed to set num_det_queries anymore")
if self.use_separate_loss_for_det_and_trk:
assert not self.weak_loss, (
"Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
)
assert not self.weak_loss, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
self.det_exhaustive_loss_scale_pos = det_exhaustive_loss_scale_pos
self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
@@ -341,9 +339,7 @@ class IABCEMdetr(LossWithWeights):
and det_non_exhaustive_loss_scale_neg == 1.0
and trk_loss_scale_pos == 1.0
and trk_loss_scale_neg == 1.0
), (
"If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
)
), "If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
def get_loss(self, outputs, targets, indices, num_boxes):
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
@@ -444,9 +440,7 @@ class IABCEMdetr(LossWithWeights):
pass
if self.weak_loss:
assert not self.use_separate_loss_for_det_and_trk, (
"Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
)
assert not self.use_separate_loss_for_det_and_trk, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
# nullify the negative loss for the non-exhaustive classes
assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
@@ -500,9 +494,9 @@ class IABCEMdetr(LossWithWeights):
loss_bce = loss_bce.mean()
else:
assert isinstance(self.pad_n_queries, int)
assert loss_bce.size(1) < self.pad_n_queries, (
f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
)
assert (
loss_bce.size(1) < self.pad_n_queries
), f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
bce_f1 = torchmetrics.functional.f1_score(
+21 -5
View File
@@ -36,6 +36,23 @@ def instance_masks_to_semantic_masks(
return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
def mask_intersection_vectorized(masks1, masks2):
"""
Vectorized computation of mask intersection using Matrix Multiplication.
Args:
masks1: tensor of shape (N, H, W)
masks2: tensor of shape (M, H, W)
Returns:
tensor of shape (N, M)
"""
# Cast to float for Tensor Core acceleration via torch.mm
m1_flat = masks1.flatten(1).float()
m2_flat = masks2.flatten(1).float()
intersection = torch.mm(m1_flat, m2_flat.t())
return intersection.long()
def mask_intersection(masks1, masks2, block_size=16):
"""Compute the intersection of two sets of masks, without blowing the memory"""
@@ -63,8 +80,7 @@ def mask_iom(masks1, masks2):
assert masks1.shape[1:] == masks2.shape[1:]
assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
# intersection = (masks1[:, None] * masks2[None]).flatten(-2).sum(-1)
intersection = mask_intersection(masks1, masks2)
intersection = mask_intersection_vectorized(masks1, masks2)
area1 = masks1.flatten(-2).sum(-1)
area2 = masks2.flatten(-2).sum(-1)
min_area = torch.min(area1[:, None], area2[None, :])
@@ -103,9 +119,9 @@ def dilation(mask, kernel_size):
assert mask.ndim == 3
kernel_size = int(kernel_size)
assert kernel_size % 2 == 1, (
f"Dilation expects a odd kernel size, got {kernel_size}"
)
assert (
kernel_size % 2 == 1
), f"Dilation expects a odd kernel size, got {kernel_size}"
if mask.is_cuda:
m = mask.unsqueeze(1).to(torch.float16)
+12 -12
View File
@@ -59,9 +59,9 @@ class HungarianMatcher(nn.Module):
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
"all costs cant be 0"
)
assert (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
), "all costs cant be 0"
self.focal_loss = focal_loss
self.focal_alpha = focal_alpha
self.focal_gamma = focal_gamma
@@ -196,9 +196,9 @@ class BinaryHungarianMatcher(nn.Module):
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
self.norm = nn.Sigmoid()
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
"all costs cant be 0"
)
assert (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
), "all costs cant be 0"
@torch.no_grad()
def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
@@ -321,9 +321,9 @@ class BinaryFocalHungarianMatcher(nn.Module):
self.alpha = alpha
self.gamma = gamma
self.stable = stable
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
"all costs cant be 0"
)
assert (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
), "all costs cant be 0"
@torch.no_grad()
def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1):
@@ -469,9 +469,9 @@ class BinaryHungarianMatcherV2(nn.Module):
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
self.norm = nn.Sigmoid()
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
"all costs cant be 0"
)
assert (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
), "all costs cant be 0"
self.focal = focal
if focal:
self.alpha = alpha
+6 -6
View File
@@ -211,9 +211,9 @@ def unix_module_cls_pattern_to_parameter_names(
"match any classes in the model"
)
matching_parameters = module_cls_to_param_names[module_cls]
assert len(matching_parameters) > 0, (
f"module_cls_name {module_cls_name} does not contain any parameters in the model"
)
assert (
len(matching_parameters) > 0
), f"module_cls_name {module_cls_name} does not contain any parameters in the model"
logging.info(
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
)
@@ -239,9 +239,9 @@ def unix_param_pattern_to_parameter_names(
allowed_parameter_names = []
for param_name in filter_param_names:
matching_parameters = set(fnmatch.filter(parameter_names, param_name))
assert len(matching_parameters) >= 1, (
f"param_name {param_name} does not match any parameters in the model"
)
assert (
len(matching_parameters) >= 1
), f"param_name {param_name} does not match any parameters in the model"
logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}")
allowed_parameter_names.append(matching_parameters)
return set.union(*allowed_parameter_names)
+3 -3
View File
@@ -209,9 +209,9 @@ def main(args) -> None:
},
}
if "include_nodes" in submitit_conf:
assert len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes, (
"Not enough nodes"
)
assert (
len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes
), "Not enough nodes"
job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
submitit_conf["include_nodes"]
)
+21 -21
View File
@@ -209,9 +209,9 @@ class Trainer:
set_seeds(seed_value, self.max_epochs, self.distributed_rank)
log_env_variables()
assert is_dist_avail_and_initialized(), (
"Torch distributed needs to be initialized before calling the trainer."
)
assert (
is_dist_avail_and_initialized()
), "Torch distributed needs to be initialized before calling the trainer."
self._setup_components() # Except Optimizer everything is setup here.
self._move_to_device()
@@ -221,9 +221,9 @@ class Trainer:
self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
if self.checkpoint_conf.resume_from is not None:
assert os.path.exists(self.checkpoint_conf.resume_from), (
f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
)
assert os.path.exists(
self.checkpoint_conf.resume_from
), f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
if self.distributed_rank == 0 and not os.path.exists(dst):
# Copy the "resume_from" checkpoint to the checkpoint folder
@@ -471,9 +471,9 @@ class Trainer:
return self.loss[key]
assert key != "all", "Loss must be specified for key='all'"
assert "default" in self.loss, (
f"Key {key} not found in losss, and no default provided"
)
assert (
"default" in self.loss
), f"Key {key} not found in losss, and no default provided"
return self.loss["default"]
def _find_meter(self, phase: str, key: str):
@@ -916,12 +916,12 @@ class Trainer:
self.optim.zero_grad(set_to_none=True)
if self.gradient_accumulation_steps > 1:
assert isinstance(batch, list), (
f"Expected a list of batches, got {type(batch)}"
)
assert len(batch) == self.gradient_accumulation_steps, (
f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
)
assert isinstance(
batch, list
), f"Expected a list of batches, got {type(batch)}"
assert (
len(batch) == self.gradient_accumulation_steps
), f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
accum_steps = len(batch)
else:
accum_steps = 1
@@ -1033,9 +1033,9 @@ class Trainer:
def _check_val_key_match(self, val_keys, phase):
if val_keys is not None:
# Check if there are any duplicates
assert len(val_keys) == len(set(val_keys)), (
f"Duplicate keys in val datasets, keys: {val_keys}"
)
assert len(val_keys) == len(
set(val_keys)
), f"Duplicate keys in val datasets, keys: {val_keys}"
# Check that the keys match the meter keys
if self.meters_conf is not None and phase in self.meters_conf:
@@ -1049,9 +1049,9 @@ class Trainer:
loss_keys = set(self.loss_conf.keys()) - set(["all"])
if "default" not in loss_keys:
for k in val_keys:
assert k in loss_keys, (
f"Error: key {k} is not defined in the losses, and no default is set"
)
assert (
k in loss_keys
), f"Error: key {k} is not defined in the losses, and no default is set"
def _setup_components(self):
# Get the keys for all the val datasets, if any
+3 -3
View File
@@ -276,9 +276,9 @@ class RandomSizeCrop:
max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
)
result_img, result_target = crop(img, target, [j, i, h, w])
assert len(result_target["boxes"]) == init_boxes, (
f"img_w={img.width}\timg_h={img.height}\tminX={minX}\tminY={minY}\tmaxX={maxX}\tmaxY={maxY}\tminW={minW}\tminH={minH}\tmaxW={maxW}\tmaxH={maxH}\tw={w}\th={h}\ti={i}\tj={j}\tinit_boxes={init_boxes_tensor}\tresults={result_target['boxes']}"
)
assert (
len(result_target["boxes"]) == init_boxes
), f"img_w={img.width}\timg_h={img.height}\tminX={minX}\tminY={minY}\tmaxX={maxX}\tmaxY={maxY}\tminW={minW}\tminH={minH}\tmaxW={maxW}\tmaxH={maxH}\tw={w}\th={h}\ti={i}\tj={j}\tinit_boxes={init_boxes_tensor}\tresults={result_target['boxes']}"
return result_img, result_target
else:
@@ -379,9 +379,9 @@ class FlexibleFilterFindGetQueries:
if len(new_find_queries) == 0:
start_with_zero_check = True
assert start_with_zero_check, (
"Invalid Find queries, they need to start at query_processing_order = 0"
)
assert (
start_with_zero_check
), "Invalid Find queries, they need to start at query_processing_order = 0"
datapoint.find_queries = new_find_queries
+3 -3
View File
@@ -249,9 +249,9 @@ class RandomGeometricInputsAPI:
def _get_target_object(self, datapoint, query):
img = datapoint.images[query.image_id]
targets = query.object_ids_output
assert len(targets) == 1, (
"Geometric queries only support a single target object."
)
assert (
len(targets) == 1
), "Geometric queries only support a single target object."
target_idx = targets[0]
return img.objects[target_idx]
+3 -3
View File
@@ -36,9 +36,9 @@ def unix_pattern_to_parameter_names(
parameter_names = []
for param_name in constraints:
matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
assert len(matching_parameters) > 0, (
f"param_names {param_name} don't match any param in the given names."
)
assert (
len(matching_parameters) > 0
), f"param_names {param_name} don't match any param in the given names."
parameter_names.append(matching_parameters)
return set.union(*parameter_names)
+3 -3
View File
@@ -82,9 +82,9 @@ def get_machine_local_and_dist_rank():
"""
local_rank = int(os.environ.get("LOCAL_RANK", None))
distributed_rank = int(os.environ.get("RANK", None))
assert local_rank is not None and distributed_rank is not None, (
"Please the set the RANK and LOCAL_RANK environment variables."
)
assert (
local_rank is not None and distributed_rank is not None
), "Please the set the RANK and LOCAL_RANK environment variables."
return local_rank, distributed_rank
+15 -15
View File
@@ -158,22 +158,22 @@ def plot_mask(mask, color="r", ax=None):
def normalize_bbox(bbox_xywh, img_w, img_h):
# Assumes bbox_xywh is in XYWH format
if isinstance(bbox_xywh, list):
assert len(bbox_xywh) == 4, (
"bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
)
assert (
len(bbox_xywh) == 4
), "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
normalized_bbox = bbox_xywh.copy()
normalized_bbox[0] /= img_w
normalized_bbox[1] /= img_h
normalized_bbox[2] /= img_w
normalized_bbox[3] /= img_h
else:
assert isinstance(bbox_xywh, torch.Tensor), (
"Only torch tensors are supported for batching."
)
assert isinstance(
bbox_xywh, torch.Tensor
), "Only torch tensors are supported for batching."
normalized_bbox = bbox_xywh.clone()
assert normalized_bbox.size(-1) == 4, (
"bbox_xywh tensor must have last dimension of size 4."
)
assert (
normalized_bbox.size(-1) == 4
), "bbox_xywh tensor must have last dimension of size 4."
normalized_bbox[..., 0] /= img_w
normalized_bbox[..., 1] /= img_h
normalized_bbox[..., 2] /= img_w
@@ -245,9 +245,9 @@ def visualize_formatted_frame_output(
num_outputs = len(outputs_list)
if titles is None:
titles = [f"Set {i + 1}" for i in range(num_outputs)]
assert len(titles) == num_outputs, (
"length of `titles` should match that of `outputs_list` if not None."
)
assert (
len(titles) == num_outputs
), "length of `titles` should match that of `outputs_list` if not None."
_, axes = plt.subplots(1, num_outputs, figsize=figsize)
if num_outputs == 1:
@@ -703,9 +703,9 @@ def get_all_annotations_for_frame(
# Get the frame
video_df_current = video_df[video_df.id == video_id]
assert len(video_df_current) == 1, (
f"Expected 1 video row, got {len(video_df_current)}"
)
assert (
len(video_df_current) == 1
), f"Expected 1 video row, got {len(video_df_current)}"
video_row = video_df_current.iloc[0]
file_name = video_row.file_names[frame_idx]
file_path = os.path.join(