Apply linter

Summary: Applies lint

Reviewed By: arpitkalla

Differential Revision: D98515496

fbshipit-source-id: 967c9bf19ef7e1e25906204075c37c8461ed2a0e
This commit is contained in:
Joseph Greer
2026-03-27 12:40:51 -07:00
committed by meta-codesync[bot]
parent 9f22cb976f
commit 5a3143c652
54 changed files with 618 additions and 618 deletions
+3 -3
View File
@@ -296,9 +296,9 @@ def agent_inference(
assert LATEST_SAM3_TEXT_PROMPT != "" assert LATEST_SAM3_TEXT_PROMPT != ""
# Make sure that the last message is a image # Make sure that the last message is a image
assert ( assert messages[-1]["content"][1]["type"] == "image", (
messages[-1]["content"][1]["type"] == "image" "Second content element should be an image"
), "Second content element should be an image" )
messages.pop() # Remove the last user message messages.pop() # Remove the last user message
# Add simplified replacement message # Add simplified replacement message
simplified_message = { simplified_message = {
+10 -10
View File
@@ -84,9 +84,9 @@ class BoxMode(IntEnum):
], "Relative mode not yet supported!" ], "Relative mode not yet supported!"
if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS: if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:
assert ( assert arr.shape[-1] == 5, (
arr.shape[-1] == 5 "The last dimension of input shape must be 5 for XYWHA format"
), "The last dimension of input shape must be 5 for XYWHA format" )
original_dtype = arr.dtype original_dtype = arr.dtype
arr = arr.double() arr = arr.double()
@@ -244,9 +244,9 @@ class Boxes:
if isinstance(item, int): if isinstance(item, int):
return Boxes(self.tensor[item].view(1, -1)) return Boxes(self.tensor[item].view(1, -1))
b = self.tensor[item] b = self.tensor[item]
assert ( assert b.dim() == 2, (
b.dim() == 2 "Indexing on Boxes with {} failed to return a matrix!".format(item)
), "Indexing on Boxes with {} failed to return a matrix!".format(item) )
return Boxes(b) return Boxes(b)
def __len__(self) -> int: def __len__(self) -> int:
@@ -424,10 +424,10 @@ def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
Returns: Returns:
Tensor: iou, sized [N]. Tensor: iou, sized [N].
""" """
assert len(boxes1) == len( assert len(boxes1) == len(boxes2), (
boxes2 "boxlists should have the samenumber of entries, got {}, {}".format(
), "boxlists should have the samenumber of entries, got {}, {}".format( len(boxes1), len(boxes2)
len(boxes1), len(boxes2) )
) )
area1 = boxes1.area() # [N] area1 = boxes1.area() # [N]
area2 = boxes2.area() # [N] area2 = boxes2.area() # [N]
+4 -4
View File
@@ -141,10 +141,10 @@ class BitMasks:
if isinstance(item, int): if isinstance(item, int):
return BitMasks(self.tensor[item].unsqueeze(0)) return BitMasks(self.tensor[item].unsqueeze(0))
m = self.tensor[item] m = self.tensor[item]
assert ( assert m.dim() == 3, (
m.dim() == 3 "Indexing on BitMasks with {} returns a tensor with shape {}!".format(
), "Indexing on BitMasks with {} returns a tensor with shape {}!".format( item, m.shape
item, m.shape )
) )
return BitMasks(m) return BitMasks(m)
+3 -3
View File
@@ -363,9 +363,9 @@ class RotatedBoxes(Boxes):
if isinstance(item, int): if isinstance(item, int):
return RotatedBoxes(self.tensor[item].view(1, -1)) return RotatedBoxes(self.tensor[item].view(1, -1))
b = self.tensor[item] b = self.tensor[item]
assert ( assert b.dim() == 2, (
b.dim() == 2 "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
), "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item) )
return RotatedBoxes(b) return RotatedBoxes(b)
def __len__(self) -> int: def __len__(self) -> int:
+3 -3
View File
@@ -221,9 +221,9 @@ class _PanopticPrediction:
empty_ids.append(id) empty_ids.append(id)
if len(empty_ids) == 0: if len(empty_ids) == 0:
return np.zeros(self._seg.shape, dtype=np.uint8) return np.zeros(self._seg.shape, dtype=np.uint8)
assert ( assert len(empty_ids) == 1, (
len(empty_ids) == 1 ">1 ids corresponds to no labels. This is currently not supported"
), ">1 ids corresponds to no labels. This is currently not supported" )
return (self._seg != empty_ids[0]).numpy().astype(np.bool) return (self._seg != empty_ids[0]).numpy().astype(np.bool)
def semantic_masks(self): def semantic_masks(self):
+18 -18
View File
@@ -126,9 +126,9 @@ class COCOCustom(COCO):
# MODIFICATION: faster and cached subset check # MODIFICATION: faster and cached subset check
if not hasattr(self, "img_id_set"): if not hasattr(self, "img_id_set"):
self.img_id_set = set(self.getImgIds()) self.img_id_set = set(self.getImgIds())
assert set(annsImgIds).issubset( assert set(annsImgIds).issubset(self.img_id_set), (
self.img_id_set "Results do not correspond to current coco set"
), "Results do not correspond to current coco set" )
# END MODIFICATION # END MODIFICATION
if "caption" in anns[0]: if "caption" in anns[0]:
imgIds = set([img["id"] for img in res.dataset["images"]]) & set( imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
@@ -301,9 +301,9 @@ class CGF1Eval(COCOeval):
TP = (match_scores >= thresh).sum() TP = (match_scores >= thresh).sum()
FP = len(dt) - TP FP = len(dt) - TP
FN = len(gt) - TP FN = len(gt) - TP
assert ( assert FP >= 0 and FN >= 0, (
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}"
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}" )
TPs.append(TP) TPs.append(TP)
FPs.append(FP) FPs.append(FP)
FNs.append(FN) 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) > 0, "No ground truth provided for evaluation."
assert len(self.coco_gts) == len( assert len(self.coco_gts) == len(self.coco_evals), (
self.coco_evals "Mismatch in number of ground truths and evaluators."
), "Mismatch in number of ground truths and evaluators." )
if self.verbose: if self.verbose:
print(f"Loading predictions from {pred_file}") print(f"Loading predictions from {pred_file}")
@@ -668,17 +668,17 @@ class CGF1Evaluator:
if len(scorings) == 1: if len(scorings) == 1:
return scorings[0] return scorings[0]
assert ( assert scorings[0].ndim == 3, (
scorings[0].ndim == 3 f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}" )
assert ( assert scorings[0].shape[0] == 1, (
scorings[0].shape[0] == 1 f"Expecting a single category, got {scorings[0].shape[0]}"
), f"Expecting a single category, got {scorings[0].shape[0]}" )
for scoring in scorings: for scoring in scorings:
assert ( assert scoring.shape == scorings[0].shape, (
scoring.shape == scorings[0].shape f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}" )
selected_imgs = [] selected_imgs = []
for img_id in range(scorings[0].shape[-1]): for img_id in range(scorings[0].shape[-1]):
+3 -3
View File
@@ -751,9 +751,9 @@ def loadRes(self, resFile):
anns = resFile anns = resFile
assert type(anns) == list, "results in not an array of objects" assert type(anns) == list, "results in not an array of objects"
annsImgIds = [ann["image_id"] for ann in anns] annsImgIds = [ann["image_id"] for ann in anns]
assert set(annsImgIds) == ( assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
set(annsImgIds) & set(self.getImgIds()) "Results do not correspond to current coco set"
), "Results do not correspond to current coco set" )
if "caption" in anns[0]: if "caption" in anns[0]:
imgIds = set([img["id"] for img in res.dataset["images"]]) & set( imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
[ann["image_id"] for ann in anns] [ann["image_id"] for ann in anns]
+3 -3
View File
@@ -83,9 +83,9 @@ class PredictionDumper:
self.merge_predictions = merge_predictions self.merge_predictions = merge_predictions
self.pred_file_evaluators = pred_file_evaluators self.pred_file_evaluators = pred_file_evaluators
if self.pred_file_evaluators is not None: if self.pred_file_evaluators is not None:
assert ( assert merge_predictions, (
merge_predictions "merge_predictions must be True if pred_file_evaluators are provided"
), "merge_predictions must be True if pred_file_evaluators are provided" )
assert self.dump_dir is not None, "dump_dir must be provided" assert self.dump_dir is not None, "dump_dir must be provided"
if is_main_process(): if is_main_process():
+12 -12
View File
@@ -154,9 +154,9 @@ class DemoEval(COCOeval):
TP = (match_scores >= thresh).sum() TP = (match_scores >= thresh).sum()
FP = len(dt) - TP FP = len(dt) - TP
FN = len(gt) - TP FN = len(gt) - TP
assert ( assert FP >= 0 and FN >= 0, (
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}"
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}" )
TPs.append(TP) TPs.append(TP)
FPs.append(FP) FPs.append(FP)
FNs.append(FN) FNs.append(FN)
@@ -526,17 +526,17 @@ class DemoEvaluator(CocoEvaluator):
if len(scorings) == 1: if len(scorings) == 1:
return scorings[0] return scorings[0]
assert ( assert scorings[0].ndim == 3, (
scorings[0].ndim == 3 f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}" )
assert ( assert scorings[0].shape[0] == 1, (
scorings[0].shape[0] == 1 f"Expecting a single category, got {scorings[0].shape[0]}"
), f"Expecting a single category, got {scorings[0].shape[0]}" )
for scoring in scorings: for scoring in scorings:
assert ( assert scoring.shape == scorings[0].shape, (
scoring.shape == scorings[0].shape f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}" )
selected_imgs = [] selected_imgs = []
for img_id in range(scorings[0].shape[-1]): for img_id in range(scorings[0].shape[-1]):
+9 -7
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. ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
""" """
if ret_tensordict: if ret_tensordict:
assert ( assert consistent is True, (
consistent is True "We don't support returning TensorDict if the outputs have different shapes"
), "We don't support returning TensorDict if the outputs have different shapes" # NOTE: It's possible but we don't support it. ) # NOTE: It's possible but we don't support it.
assert self.detection_threshold <= 0.0, "TODO: implement?" assert self.detection_threshold <= 0.0, "TODO: implement?"
try: try:
from tensordict import TensorDict from tensordict import TensorDict
@@ -118,7 +118,9 @@ class PostProcessImage(nn.Module):
if boxes is None: if boxes is None:
assert out_masks is not 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) B = len(out_masks)
boxes = [None] * B boxes = [None] * B
scores = [None] * B scores = [None] * B
@@ -418,9 +420,9 @@ class PostProcessAPIVideo(PostProcessImage):
if video_id == -1: if video_id == -1:
video_id = unique_vid_id.item() video_id = unique_vid_id.item()
else: else:
assert ( assert video_id == unique_vid_id.item(), (
video_id == unique_vid_id.item() "We can only postprocess one video per datapoint"
), "We can only postprocess one video per datapoint" )
# keeping track of which objects appear in the current frame # keeping track of which objects appear in the current frame
obj_ids_per_frame = frame_outs["pred_object_ids"] obj_ids_per_frame = frame_outs["pred_object_ids"]
assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2) 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 anns = resFile
assert type(anns) == list, "results is not an array of objects" assert type(anns) == list, "results is not an array of objects"
annsImgIds = [ann["image_id"] for ann in anns] annsImgIds = [ann["image_id"] for ann in anns]
assert set(annsImgIds) == ( assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
set(annsImgIds) & set(self.getImgIds()) "Results do not correspond to current coco set"
), "Results do not correspond to current coco set" )
if "bboxes" in anns[0] and not anns[0]["bboxes"] == []: if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"]) res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
for id, ann in enumerate(anns): for id, ann in enumerate(anns):
+16 -18
View File
@@ -109,9 +109,7 @@ class YTVISevalMixin:
) # Num preds x Num GTS x Num frames ) # Num preds x Num GTS x Num frames
inter = inter.sum(-1) inter = inter.sum(-1)
union = union.sum(-1) union = union.sum(-1)
assert ( assert (union > 0).all(), (
union > 0
).all(), (
"There exists a tracklet with zero GTs across time. This is suspicious" "There exists a tracklet with zero GTs across time. This is suspicious"
) )
return inter / union return inter / union
@@ -136,9 +134,9 @@ class YTVISevalMixin:
iou = inter / union iou = inter / union
assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation" assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation"
else: else:
assert np.isclose(inter, 0) and np.isclose( assert np.isclose(inter, 0) and np.isclose(union, 0), (
union, 0 "Encountered an error in IoU computation"
), "Encountered an error in IoU computation" )
iou = 1 iou = 1
return iou return iou
@@ -206,16 +204,16 @@ class YTVISResultsWriter:
if len(prediction) == 0: if len(prediction) == 0:
continue continue
for k in ["boxes", "scores", "labels"]: for k in ["boxes", "scores", "labels"]:
assert ( assert k in prediction, (
k in prediction f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
), f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}" )
if self.save_per_frame_scores: if self.save_per_frame_scores:
assert ( assert "per_frame_scores" in prediction, (
"per_frame_scores" in prediction f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
), f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}" )
assert xor( assert xor("masks" in prediction, "masks_rle" in prediction), (
"masks" in prediction, "masks_rle" in prediction f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
), f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}" )
boxes = prediction["boxes"] boxes = prediction["boxes"]
boxes = convert_to_xywh(boxes).tolist() boxes = convert_to_xywh(boxes).tolist()
@@ -223,9 +221,9 @@ class YTVISResultsWriter:
labels = prediction["labels"].tolist() labels = prediction["labels"].tolist()
if "masks" in prediction: if "masks" in prediction:
masks = prediction["masks"].squeeze(2) masks = prediction["masks"].squeeze(2)
assert ( assert masks.ndim == 4, (
masks.ndim == 4 "Expected masks to be of shape(N_preds,T_frames,H,W)"
), "Expected masks to be of shape(N_preds,T_frames,H,W)" )
areas = [mask.flatten(1).sum(1).tolist() for mask in masks] areas = [mask.flatten(1).sum(1).tolist() for mask in masks]
rles = [rle_encode(masklet) for masklet 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.""" """A command line logger."""
if "LOG_LEVEL" in os.environ: if "LOG_LEVEL" in os.environ:
level = os.environ["LOG_LEVEL"].upper() level = os.environ["LOG_LEVEL"].upper()
assert ( assert level in LOG_LEVELS, (
level in LOG_LEVELS f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
), f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}" )
level = LOG_LEVELS[level] level = LOG_LEVELS[level]
logger = logging.getLogger(name) logger = logging.getLogger(name)
logger.setLevel(level) logger.setLevel(level)
+3 -3
View File
@@ -75,9 +75,9 @@ def interpolate(
input, size, scale_factor, mode, align_corners input, size, scale_factor, mode, align_corners
) )
assert ( assert input.shape[0] != 0 or input.shape[1] != 0, (
input.shape[0] != 0 or input.shape[1] != 0 "At least one of the two first dimensions must be non zero"
), "At least one of the two first dimensions must be non zero" )
if input.shape[1] == 0: if input.shape[1] == 0:
# Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim # Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim
+25 -24
View File
@@ -444,9 +444,9 @@ class TransformerDecoder(nn.Module):
- valid_ratios/spatial_shapes: bs, nlevel, 2 - valid_ratios/spatial_shapes: bs, nlevel, 2
""" """
if memory_mask is not None: if memory_mask is not None:
assert ( assert self.boxRPB == "none", (
self.boxRPB == "none" "inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
), "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 apply_dac = apply_dac if apply_dac is not None else self.dac
if apply_dac: if apply_dac:
@@ -516,18 +516,18 @@ class TransformerDecoder(nn.Module):
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
if self.boxRPB != "none" and reference_boxes is not None: if self.boxRPB != "none" and reference_boxes is not None:
assert ( assert spatial_shapes.shape[0] == 1, (
spatial_shapes.shape[0] == 1 "only single scale support implemented"
), "only single scale support implemented" )
memory_mask = self._get_rpb_matrix( memory_mask = self._get_rpb_matrix(
reference_boxes, reference_boxes,
(spatial_shapes[0, 0], spatial_shapes[0, 1]), (spatial_shapes[0, 0], spatial_shapes[0, 1]),
) )
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W) memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
if self.training: if self.training:
assert ( assert self.use_act_checkpoint, (
self.use_act_checkpoint "Activation checkpointing not enabled in the decoder"
), "Activation checkpointing not enabled in the decoder" )
output, presence_out = activation_ckpt_wrapper(layer)( output, presence_out = activation_ckpt_wrapper(layer)(
tgt=output, tgt=output,
tgt_query_pos=query_pos, tgt_query_pos=query_pos,
@@ -676,9 +676,9 @@ class TransformerEncoderCrossAttention(nn.Module):
src_pos[0], src_pos[0],
) )
assert ( assert src.shape[1] == prompt.shape[1], (
src.shape[1] == prompt.shape[1] "Batch size must be the same for src and prompt"
), "Batch size must be the same for src and prompt" )
output = src output = src
@@ -1291,12 +1291,12 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
memory_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* num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
): ):
assert ( assert src.shape[1] == memory.shape[1], (
src.shape[1] == memory.shape[1] "Batch size must be the same for src and memory"
), "Batch size must be the same for src and memory" )
assert ( assert image.shape[1] == memory_image.shape[1], (
image.shape[1] == memory_image.shape[1] "Batch size must be the same for image and memory_image"
), "Batch size must be the same for image and memory_image" )
output = src output = src
@@ -1315,9 +1315,9 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
if memory_image.shape[1] != memory.shape[1]: if memory_image.shape[1] != memory.shape[1]:
# Pad memory_image with zeros, to accodmate object pointers # Pad memory_image with zeros, to accodmate object pointers
assert ( assert (memory.shape[1] - memory_image.shape[1]) == num_obj_ptr_tokens, (
(memory.shape[1] - memory_image.shape[1]) == num_obj_ptr_tokens f"{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.cat(
[ [
memory_image, memory_image,
@@ -1332,9 +1332,10 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
) )
if memory_image_pos is not None: if memory_image_pos is not None:
assert ( assert (
(memory_pos.shape[1] - memory_image_pos.shape[1]) memory_pos.shape[1] - memory_image_pos.shape[1]
== num_obj_ptr_tokens ) == num_obj_ptr_tokens, (
), f"{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 # 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 = torch.cat(
[ [
+9 -9
View File
@@ -322,9 +322,9 @@ class TransformerEncoder(nn.Module):
return reference_points return reference_points
def _prepare_multilevel_features(self, srcs, masks, pos_embeds): def _prepare_multilevel_features(self, srcs, masks, pos_embeds):
assert ( assert len(srcs) == self.num_feature_levels, (
len(srcs) == self.num_feature_levels "mismatch between expected and received # of feature levels"
), "mismatch between expected and received # of feature levels" )
src_flatten = [] src_flatten = []
mask_flatten = [] mask_flatten = []
@@ -406,9 +406,9 @@ class TransformerEncoder(nn.Module):
- spatial_shapes: Spatial dimensions of each feature level - spatial_shapes: Spatial dimensions of each feature level
- valid_ratios: Valid ratios for each feature level - valid_ratios: Valid ratios for each feature level
""" """
assert ( assert len(src) == self.num_feature_levels, (
len(src) == self.num_feature_levels "must be equal to num_feature_levels"
), "must be equal to num_feature_levels" )
if src_key_padding_masks is not None: if src_key_padding_masks is not None:
assert len(src_key_padding_masks) == self.num_feature_levels assert len(src_key_padding_masks) == self.num_feature_levels
if pos is not None: if pos is not None:
@@ -538,9 +538,9 @@ class TransformerEncoderFusion(TransformerEncoder):
else None else None
) )
else: else:
assert all( assert all(x.dim == 4 for x in src), (
x.dim == 4 for x in src "expected list of (bs, c, h, w) tensors"
), "expected list of (bs, c, h, w) tensors" )
if self.add_pooled_text_to_img_feat: if self.add_pooled_text_to_img_feat:
# Fusion: Add mean pooled text to image features # Fusion: Add mean pooled text to image features
+99 -112
View File
@@ -147,54 +147,42 @@ class Prompt:
) )
# Dimension checks # Dimension checks
assert ( assert box_embeddings is not None and list(box_embeddings.shape[:2]) == [
box_embeddings is not None box_seq_len,
and list(box_embeddings.shape[:2]) bs,
== [ ], (
box_seq_len, f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
bs, )
] assert box_mask is not None and list(box_mask.shape) == [
), f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}" bs,
assert ( box_seq_len,
box_mask is not None ], (
and list(box_mask.shape) f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
== [ )
bs, assert point_embeddings is not None and list(point_embeddings.shape[:2]) == [
box_seq_len, point_seq_len,
] bs,
), f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}" ], (
assert ( f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
point_embeddings is not None )
and list(point_embeddings.shape[:2]) assert point_mask is not None and list(point_mask.shape) == [
== [ bs,
point_seq_len, point_seq_len,
bs, ], (
] f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
), f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}" )
assert ( assert box_labels is not None and list(box_labels.shape) == [
point_mask is not None box_seq_len,
and list(point_mask.shape) bs,
== [ ], (
bs, f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
point_seq_len, )
] assert point_labels is not None and list(point_labels.shape) == [
), f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}" point_seq_len,
assert ( bs,
box_labels is not None ], (
and list(box_labels.shape) f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_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 ( assert (
# Allowed to be None, we leave it to the encoder to check for validity before encoding. # Allowed to be None, we leave it to the encoder to check for validity before encoding.
mask_embeddings is None mask_embeddings is None
@@ -203,41 +191,41 @@ class Prompt:
mask_seq_len, mask_seq_len,
bs, bs,
] ]
), f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}" ), (
assert ( f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
mask_mask is None )
or list(mask_mask.shape) assert mask_mask is None or list(mask_mask.shape) == [
== [ bs,
bs, mask_seq_len,
mask_seq_len, ], (
] f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
), f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}" )
# Device checks # Device checks
assert ( assert box_embeddings is not None and box_embeddings.device == device, (
box_embeddings is not None and box_embeddings.device == device f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
), f"Expected box embeddings to be on device {device}, got {box_embeddings.device}" )
assert ( assert box_mask is not None and box_mask.device == device, (
box_mask is not None and box_mask.device == device f"Expected box mask to be on device {device}, got {box_mask.device}"
), f"Expected box mask to be on device {device}, got {box_mask.device}" )
assert ( assert box_labels is not None and box_labels.device == device, (
box_labels is not None and box_labels.device == device f"Expected box labels to be on device {device}, got {box_labels.device}"
), f"Expected box labels to be on device {device}, got {box_labels.device}" )
assert ( assert point_embeddings is not None and point_embeddings.device == device, (
point_embeddings is not None and point_embeddings.device == device f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
), f"Expected point embeddings to be on device {device}, got {point_embeddings.device}" )
assert ( assert point_mask is not None and point_mask.device == device, (
point_mask is not None and point_mask.device == device f"Expected point mask to be on device {device}, got {point_mask.device}"
), f"Expected point mask to be on device {device}, got {point_mask.device}" )
assert ( assert point_labels is not None and point_labels.device == device, (
point_labels is not None and point_labels.device == device f"Expected point labels to be on device {device}, got {point_labels.device}"
), f"Expected point labels to be on device {device}, got {point_labels.device}" )
assert ( assert mask_embeddings is None or mask_embeddings.device == device, (
mask_embeddings is None or mask_embeddings.device == device f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
), f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}" )
assert ( assert mask_mask is None or mask_mask.device == device, (
mask_mask is None or mask_mask.device == device f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
), f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}" )
self.box_embeddings = box_embeddings self.box_embeddings = box_embeddings
self.point_embeddings = point_embeddings self.point_embeddings = point_embeddings
@@ -263,30 +251,30 @@ class Prompt:
if point_embeddings is not None: if point_embeddings is not None:
point_seq_len = point_embeddings.shape[0] point_seq_len = point_embeddings.shape[0]
if bs is not None: if bs is not None:
assert ( assert bs == point_embeddings.shape[1], (
bs == point_embeddings.shape[1] f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
), f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}." )
else: else:
bs = point_embeddings.shape[1] bs = point_embeddings.shape[1]
if device is not None: if device is not None:
assert ( assert device == point_embeddings.device, (
device == point_embeddings.device "Device mismatch between box and point embeddings"
), "Device mismatch between box and point embeddings" )
else: else:
device = point_embeddings.device device = point_embeddings.device
if mask_embeddings is not None: if mask_embeddings is not None:
mask_seq_len = mask_embeddings.shape[0] mask_seq_len = mask_embeddings.shape[0]
if bs is not None: if bs is not None:
assert ( assert bs == mask_embeddings.shape[1], (
bs == mask_embeddings.shape[1] f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
), f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}" )
else: else:
bs = mask_embeddings.shape[1] bs = mask_embeddings.shape[1]
if device is not None: if device is not None:
assert ( assert device == mask_embeddings.device, (
device == mask_embeddings.device "Device mismatch between box/point and mask embeddings."
), "Device mismatch between box/point and mask embeddings." )
else: else:
device = mask_embeddings.device device = mask_embeddings.device
@@ -538,9 +526,9 @@ class SequenceGeometryEncoder(nn.Module):
if add_cls: if add_cls:
self.cls_embed = torch.nn.Embedding(1, self.d_model) self.cls_embed = torch.nn.Embedding(1, self.d_model)
assert ( assert points_direct_project or points_pos_enc or points_pool, (
points_direct_project or points_pos_enc or points_pool "Error: need at least one way to encode points"
), "Error: need at least one way to encode points" )
assert ( assert (
encode_boxes_as_points encode_boxes_as_points
or boxes_direct_project or boxes_direct_project
@@ -582,16 +570,16 @@ class SequenceGeometryEncoder(nn.Module):
self.encode = None self.encode = None
if num_layers > 0: if num_layers > 0:
assert ( assert add_cls, (
add_cls "It's currently highly recommended to add a CLS when using a transformer"
), "It's currently highly recommended to add a CLS when using a transformer" )
self.encode = get_clones(layer, num_layers) self.encode = get_clones(layer, num_layers)
self.encode_norm = nn.LayerNorm(self.d_model) self.encode_norm = nn.LayerNorm(self.d_model)
if mask_encoder is not None: if mask_encoder is not None:
assert isinstance( assert isinstance(mask_encoder, MaskEncoder), (
mask_encoder, MaskEncoder f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
), f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}." )
if add_mask_label: if add_mask_label:
self.mask_label_embed = torch.nn.Embedding(2, self.d_model) self.mask_label_embed = torch.nn.Embedding(2, self.d_model)
self.add_mask_label = add_mask_label self.add_mask_label = add_mask_label
@@ -700,16 +688,15 @@ class SequenceGeometryEncoder(nn.Module):
img_feats: torch.Tensor = None, img_feats: torch.Tensor = None,
): ):
n_masks, bs = masks.shape[:2] n_masks, bs = masks.shape[:2]
assert ( assert n_masks == 1, (
n_masks == 1 "We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
), "We assume one mask per prompt for now. Code should still be functional if this assertion is removed." )
assert ( assert list(attn_mask.shape) == [
list(attn_mask.shape) bs,
== [ n_masks,
bs, ], (
n_masks, f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
] )
), f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
masks, pos = self.mask_encoder( masks, pos = self.mask_encoder(
masks=masks.flatten(0, 1).float(), masks=masks.flatten(0, 1).float(),
pix_feat=img_feats, pix_feat=img_feats,
+3 -1
View File
@@ -258,7 +258,9 @@ class UniversalSegmentationHead(SegmentationHead):
self.d_model = hidden_dim self.d_model = hidden_dim
if dot_product_scorer is not None: 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 self.presence_head = None
if presence_head: if presence_head:
+3 -3
View File
@@ -68,9 +68,9 @@ class SimpleMaskDownSampler(nn.Module):
self.multiplex_count = multiplex_count self.multiplex_count = multiplex_count
self.interpol_size = interpol_size self.interpol_size = interpol_size
if self.interpol_size is not None: if self.interpol_size is not None:
assert isinstance( assert isinstance(self.interpol_size, (list, tuple)), (
self.interpol_size, (list, tuple) f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
), f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple." )
self.interpol_size = list(interpol_size) self.interpol_size = list(interpol_size)
assert len(self.interpol_size) == 2 assert len(self.interpol_size) == 2
+65 -67
View File
@@ -182,45 +182,45 @@ def multi_head_attention_forward(
raise AssertionError( raise AssertionError(
"only bool and floating types of key_padding_mask are supported" "only bool and floating types of key_padding_mask are supported"
) )
assert ( assert embed_dim == embed_dim_to_check, (
embed_dim == embed_dim_to_check f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}" )
if isinstance(embed_dim, torch.Tensor): if isinstance(embed_dim, torch.Tensor):
head_dim = embed_dim.div(num_heads, rounding_mode="trunc") head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
else: else:
head_dim = embed_dim // num_heads head_dim = embed_dim // num_heads
assert ( assert head_dim * num_heads == embed_dim, (
head_dim * num_heads == embed_dim f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
), f"embed_dim {embed_dim} not divisible by num_heads {num_heads}" )
if use_separate_proj_weight: if use_separate_proj_weight:
assert ( assert key.shape[:2] == value.shape[:2], (
key.shape[:2] == value.shape[:2] f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
), f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}" )
else: else:
assert ( assert key.shape == value.shape, (
key.shape == value.shape f"key shape {key.shape} does not match value shape {value.shape}"
), f"key shape {key.shape} does not match value shape {value.shape}" )
# #
# compute in-projection # compute in-projection
# #
if not use_separate_proj_weight: if not use_separate_proj_weight:
assert ( assert in_proj_weight is not None, (
in_proj_weight is not None "use_separate_proj_weight is False but in_proj_weight is None"
), "use_separate_proj_weight is False but in_proj_weight is None" )
q, k, v = F._in_projection_packed( q, k, v = F._in_projection_packed(
query, key, value, in_proj_weight, in_proj_bias query, key, value, in_proj_weight, in_proj_bias
) )
else: else:
assert ( assert q_proj_weight is not None, (
q_proj_weight is not None "use_separate_proj_weight is True but q_proj_weight is None"
), "use_separate_proj_weight is True but q_proj_weight is None" )
assert ( assert k_proj_weight is not None, (
k_proj_weight is not None "use_separate_proj_weight is True but k_proj_weight is None"
), "use_separate_proj_weight is True but k_proj_weight is None" )
assert ( assert v_proj_weight is not None, (
v_proj_weight is not None "use_separate_proj_weight is True but v_proj_weight is None"
), "use_separate_proj_weight is True but v_proj_weight is None" )
if in_proj_bias is None: if in_proj_bias is None:
b_q = b_k = b_v = None b_q = b_k = b_v = None
else: else:
@@ -245,9 +245,9 @@ def multi_head_attention_forward(
) )
attn_mask = attn_mask.to(torch.bool) attn_mask = attn_mask.to(torch.bool)
else: else:
assert ( assert attn_mask.is_floating_point() or attn_mask.dtype == torch.bool, (
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}"
), f"Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}" )
# ensure attn_mask's dim is 3 # ensure attn_mask's dim is 3
if attn_mask.dim() == 2: if attn_mask.dim() == 2:
correct_2d_size = (tgt_len, src_len) correct_2d_size = (tgt_len, src_len)
@@ -288,22 +288,22 @@ def multi_head_attention_forward(
if static_k is None: if static_k is None:
k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1) k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else: else:
assert ( assert static_k.size(0) == bsz * num_heads, (
static_k.size(0) == bsz * num_heads f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
), f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}" )
assert ( assert static_k.size(2) == head_dim, (
static_k.size(2) == head_dim f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
), f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}" )
k = static_k k = static_k
if static_v is None: if static_v is None:
v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1) v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else: else:
assert ( assert static_v.size(0) == bsz * num_heads, (
static_v.size(0) == bsz * num_heads f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
), f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}" )
assert ( assert static_v.size(2) == head_dim, (
static_v.size(2) == head_dim f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
), f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}" )
v = static_v v = static_v
# add zero attention along batch dimension (now first) # add zero attention along batch dimension (now first)
@@ -325,13 +325,12 @@ def multi_head_attention_forward(
# merge key padding and attention masks # merge key padding and attention masks
if key_padding_mask is not None: if key_padding_mask is not None:
assert ( assert key_padding_mask.shape == (
key_padding_mask.shape bsz,
== ( src_len,
bsz, ), (
src_len, f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
) )
), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
key_padding_mask = ( key_padding_mask = (
key_padding_mask.view(bsz, 1, 1, src_len) key_padding_mask.view(bsz, 1, 1, src_len)
.expand(-1, num_heads, -1, -1) .expand(-1, num_heads, -1, -1)
@@ -365,15 +364,14 @@ def multi_head_attention_forward(
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len) attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
if attn_bias is not None: if attn_bias is not None:
assert ( assert attn_bias.shape == (
attn_bias.shape bsz,
== ( num_heads,
bsz, tgt_len,
num_heads, src_len,
tgt_len, ), (
src_len, f"expecting attn_bias shape of {(bsz, num_heads, tgt_len, src_len)}, but got {attn_bias.shape}"
) )
), f"expecting attn_bias shape of {(bsz, num_heads, tgt_len, src_len)}, but got {attn_bias.shape}"
if attn_mask is None: if attn_mask is None:
attn_mask = attn_bias attn_mask = attn_bias
else: else:
@@ -487,13 +485,13 @@ class MultiheadAttention(nn.Module):
self.batch_first = batch_first self.batch_first = batch_first
self.head_dim = embed_dim // num_heads self.head_dim = embed_dim // num_heads
self.use_act_checkpoint = use_act_checkpoint self.use_act_checkpoint = use_act_checkpoint
assert ( assert self.head_dim * num_heads == self.embed_dim, (
self.head_dim * num_heads == self.embed_dim "embed_dim must be divisible by num_heads"
), "embed_dim must be divisible by num_heads" )
assert ( assert attn_type == AttentionType.Sparse or sparsity == 0.0, (
attn_type == AttentionType.Sparse or sparsity == 0.0 "sparsity is only supported for sparse attention"
), "sparsity is only supported for sparse attention" )
if not self._qkv_same_embed_dim: if not self._qkv_same_embed_dim:
self.q_proj_weight = nn.Parameter( self.q_proj_weight = nn.Parameter(
@@ -1007,9 +1005,9 @@ class SAM3Output(list):
self.output = output self.output = output
else: else:
self.output = [] self.output = []
assert isinstance( assert isinstance(iter_mode, SAM3Output.IterMode), (
iter_mode, SAM3Output.IterMode f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
), f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}" )
self.iter_mode = iter_mode self.iter_mode = iter_mode
# We create a weak reference to self to be used in the lambda functions. # We create a weak reference to self to be used in the lambda functions.
@@ -1088,9 +1086,9 @@ class SAM3Output(list):
return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode) return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode)
def append(self, item: list): def append(self, item: list):
assert isinstance( assert isinstance(item, list), (
item, list f"Only list items are supported. Got {type(item)}"
), f"Only list items are supported. Got {type(item)}" )
self.output.append(item) self.output.append(item)
def __repr__(self): def __repr__(self):
+27 -27
View File
@@ -64,9 +64,9 @@ class MultiplexMaskDecoder(nn.Module):
) )
if self.decode_mask_with_shared_tokens: if self.decode_mask_with_shared_tokens:
assert ( assert multimask_outputs_only, (
multimask_outputs_only "multimask_outputs_only must be True if decode_mask_with_shared_tokens"
), "multimask_outputs_only must be True if decode_mask_with_shared_tokens" )
if self.multimask_outputs_only: if self.multimask_outputs_only:
self.num_mask_output_per_object = num_multimask_outputs self.num_mask_output_per_object = num_multimask_outputs
@@ -169,14 +169,14 @@ class MultiplexMaskDecoder(nn.Module):
""" """
if self.num_multimask_outputs <= 0: if self.num_multimask_outputs <= 0:
assert ( assert not multimask_output, (
not multimask_output f"multimask_output must be False with {self.num_multimask_outputs=}"
), f"multimask_output must be False with {self.num_multimask_outputs=}" )
if self.multimask_outputs_only: if self.multimask_outputs_only:
assert ( assert multimask_output, (
multimask_output f"multimask_output must be True with {self.multimask_outputs_only=}"
), f"multimask_output must be True with {self.multimask_outputs_only=}" )
out = self.predict_masks( out = self.predict_masks(
image_embeddings=image_embeddings, image_embeddings=image_embeddings,
@@ -223,19 +223,19 @@ class MultiplexMaskDecoder(nn.Module):
out["sam_tokens_out"] = sam_tokens_out out["sam_tokens_out"] = sam_tokens_out
if multimask_output: if multimask_output:
assert ( assert masks.shape[2] == self.num_mask_output_per_object, (
masks.shape[2] == self.num_mask_output_per_object f"{masks.shape=}, {self.num_mask_output_per_object=}"
), f"{masks.shape=}, {self.num_mask_output_per_object=}" )
assert ( assert iou_pred.shape[2] == self.num_mask_output_per_object, (
iou_pred.shape[2] == self.num_mask_output_per_object f"{iou_pred.shape=}, {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.use_multimask_token_for_obj_ptr:
if self.decode_mask_with_shared_tokens: if self.decode_mask_with_shared_tokens:
assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}" assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}"
else: else:
assert ( assert sam_tokens_out.shape[2] == self.num_mask_output_per_object, (
sam_tokens_out.shape[2] == self.num_mask_output_per_object f"{sam_tokens_out.shape=}, {self.num_mask_output_per_object=}"
), f"{sam_tokens_out.shape=}, {self.num_mask_output_per_object=}" )
else: else:
assert masks.shape[2] == 1, f"{masks.shape=}" assert masks.shape[2] == 1, f"{masks.shape=}"
assert iou_pred.shape[2] == 1, f"{iou_pred.shape=}" assert iou_pred.shape[2] == 1, f"{iou_pred.shape=}"
@@ -278,9 +278,9 @@ class MultiplexMaskDecoder(nn.Module):
src = image_embeddings src = image_embeddings
assert ( assert image_pe.size(0) == 1, (
image_pe.size(0) == 1 "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
), "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) pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
b, c, h, w = src.shape b, c, h, w = src.shape
@@ -289,9 +289,9 @@ class MultiplexMaskDecoder(nn.Module):
# Parse transformer outputs based on token sharing configuration # Parse transformer outputs based on token sharing configuration
if self.decode_mask_attribute_with_shared_tokens: if self.decode_mask_attribute_with_shared_tokens:
assert ( assert hs.shape[1] == self.num_mask_tokens, (
hs.shape[1] == self.num_mask_tokens f"{hs.shape=}, {self.num_mask_tokens=}"
), f"{hs.shape=}, {self.num_mask_tokens=}" )
iou_token_out = mask_tokens_out = hs[:, 0 : self.num_mask_tokens] iou_token_out = mask_tokens_out = hs[:, 0 : self.num_mask_tokens]
if self.pred_obj_scores: if self.pred_obj_scores:
obj_score_token_out = mask_tokens_out obj_score_token_out = mask_tokens_out
@@ -305,9 +305,9 @@ class MultiplexMaskDecoder(nn.Module):
iou_token_out = hs[:, s : s + self.multiplex_count, :] iou_token_out = hs[:, s : s + self.multiplex_count, :]
s += self.multiplex_count s += self.multiplex_count
mask_tokens_out = hs[:, s : s + self.num_mask_tokens, :] mask_tokens_out = hs[:, s : s + self.num_mask_tokens, :]
assert ( assert hs.shape[1] == s + self.num_mask_tokens, (
hs.shape[1] == s + self.num_mask_tokens f"{hs.shape=}, {s=}, {self.num_mask_tokens=}"
), f"{hs.shape=}, {s=}, {self.num_mask_tokens=}" )
# Upscale mask embeddings and predict masks using the mask tokens # Upscale mask embeddings and predict masks using the mask tokens
src = src.transpose(1, 2).view(b, c, h, w) src = src.transpose(1, 2).view(b, c, h, w)
+30 -30
View File
@@ -93,22 +93,22 @@ class MultiplexState:
# check the validity of the object IDs # check the validity of the object IDs
self.object_ids = object_ids self.object_ids = object_ids
if self.object_ids is not None: if self.object_ids is not None:
assert ( assert len(self.object_ids) == self.total_valid_entries, (
len(self.object_ids) == self.total_valid_entries "object_ids should map 1:1 to the valid entries"
), "object_ids should map 1:1 to the valid entries" )
# check the validity of the assignments # check the validity of the assignments
all_object_idxs = set() all_object_idxs = set()
for bucket in self.assignments: for bucket in self.assignments:
valid_entries_in_bucket = sum(1 for x in bucket if x != _PADDING_NUM) valid_entries_in_bucket = sum(1 for x in bucket if x != _PADDING_NUM)
assert ( assert valid_entries_in_bucket <= self.allowed_bucket_capacity, (
valid_entries_in_bucket <= self.allowed_bucket_capacity f"{valid_entries_in_bucket=} > {self.allowed_bucket_capacity=}"
), f"{valid_entries_in_bucket=} > {self.allowed_bucket_capacity=}" )
for obj_idx in bucket: for obj_idx in bucket:
if obj_idx >= 0: if obj_idx >= 0:
assert ( assert obj_idx < self.total_non_padding_entries, (
obj_idx < self.total_non_padding_entries f"object ID {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" assert obj_idx not in all_object_idxs, "object IDs must be unique"
all_object_idxs.add(obj_idx) all_object_idxs.add(obj_idx)
@@ -135,9 +135,9 @@ class MultiplexState:
# as the actual bucket allocation logic is in add_objects() # as the actual bucket allocation logic is in add_objects()
assert num_objects > 0, f"{num_objects=} must be positive" assert num_objects > 0, f"{num_objects=} must be positive"
if not allow_new_buckets: if not allow_new_buckets:
assert ( assert self.available_slots >= num_objects, (
self.available_slots >= num_objects f"not enough available slots {self.available_slots} < {num_objects}"
), f"not enough available slots {self.available_slots} < {num_objects}" )
return list( return list(
range( range(
@@ -167,14 +167,14 @@ class MultiplexState:
# we will modify this in-place # we will modify this in-place
object_indices = object_indices.copy() object_indices = object_indices.copy()
assert (object_ids is None) == ( assert (object_ids is None) == (self.object_ids is None), (
self.object_ids is None "object_ids must either be always given or always omitted"
), "object_ids must either be always given or always omitted" )
if object_ids is not None: if object_ids is not None:
assert len(object_ids) == len( assert len(object_ids) == len(object_indices), (
object_indices "object_ids must have the same length as object_indices"
), "object_ids must have the same length as object_indices" )
object_ids = object_ids.copy() object_ids = object_ids.copy()
num_new_objects = len(object_indices) num_new_objects = len(object_indices)
@@ -225,9 +225,9 @@ class MultiplexState:
# reinitialize all the settings # reinitialize all the settings
original_num_entries = self.total_valid_entries original_num_entries = self.total_valid_entries
self._initialize_assignments(self.assignments, object_ids=self.object_ids) self._initialize_assignments(self.assignments, object_ids=self.object_ids)
assert ( assert self.total_valid_entries == original_num_entries + num_new_objects, (
self.total_valid_entries == original_num_entries + num_new_objects f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}"
), f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}" )
logger.info( logger.info(
f"Filled {slots_filled} slots and created {buckets_created} new buckets" f"Filled {slots_filled} slots and created {buckets_created} new buckets"
@@ -258,9 +258,9 @@ class MultiplexState:
object_indices.remove(obj_id) object_indices.remove(obj_id)
if strict: if strict:
assert ( assert len(object_indices) == 0, (
len(object_indices) == 0 f"Failed to remove objects: {object_indices}"
), f"Failed to remove objects: {object_indices}" )
# Check which buckets should be completely removed (all objects removed/paddings) # Check which buckets should be completely removed (all objects removed/paddings)
# and which buckets we will keep # and which buckets we will keep
@@ -371,9 +371,9 @@ class MultiplexState:
with padding entries filled with 0 with padding entries filled with 0
""" """
num_valid_entries = x.shape[0] num_valid_entries = x.shape[0]
assert ( assert num_valid_entries == self.total_valid_entries, (
num_valid_entries == self.total_valid_entries f"{num_valid_entries=} != {self.total_valid_entries=}"
), f"{num_valid_entries=} != {self.total_valid_entries=}" )
output_shape = ( output_shape = (
self.num_buckets, self.num_buckets,
self.multiplex_count, self.multiplex_count,
@@ -396,9 +396,9 @@ class MultiplexState:
""" """
num_buckets, multiplex_count = x.shape[:2] num_buckets, multiplex_count = x.shape[:2]
assert num_buckets == self.num_buckets, f"{num_buckets=} != {self.num_buckets=}" assert num_buckets == self.num_buckets, f"{num_buckets=} != {self.num_buckets=}"
assert ( assert multiplex_count == self.multiplex_count, (
multiplex_count == self.multiplex_count f"{multiplex_count=} != {self.multiplex_count=}"
), f"{multiplex_count=} != {self.multiplex_count=}" )
output_shape = (self.total_valid_entries,) + x.shape[2:] output_shape = (self.total_valid_entries,) + x.shape[2:]
x_flat = x.reshape(num_buckets * multiplex_count, -1) x_flat = x.reshape(num_buckets * multiplex_count, -1)
+15 -15
View File
@@ -94,9 +94,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
input_image = self._transforms(image) input_image = self._transforms(image)
input_image = input_image[None, ...].to(self.device) input_image = input_image[None, ...].to(self.device)
assert ( assert len(input_image.shape) == 4 and input_image.shape[1] == 3, (
len(input_image.shape) == 4 and input_image.shape[1] == 3 f"input_image must be of size 1x3xHxW, got {input_image.shape}"
), f"input_image must be of size 1x3xHxW, got {input_image.shape}" )
logging.info("Computing image embeddings for the provided image...") logging.info("Computing image embeddings for the provided image...")
backbone_out = self.model.forward_image(input_image) backbone_out = self.model.forward_image(input_image)
( (
@@ -133,17 +133,17 @@ class SAM3InteractiveImagePredictor(nn.Module):
assert isinstance(image_list, list) assert isinstance(image_list, list)
self._orig_hw = [] self._orig_hw = []
for image in image_list: for image in image_list:
assert isinstance( assert isinstance(image, np.ndarray), (
image, np.ndarray "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
), "Images are expected to be an np.ndarray in RGB format, and of shape HWC" )
self._orig_hw.append(image.shape[:2]) self._orig_hw.append(image.shape[:2])
# Transform the image to the form expected by the model # Transform the image to the form expected by the model
img_batch = self._transforms.forward_batch(image_list) img_batch = self._transforms.forward_batch(image_list)
img_batch = img_batch.to(self.device) img_batch = img_batch.to(self.device)
batch_size = img_batch.shape[0] batch_size = img_batch.shape[0]
assert ( assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, (
len(img_batch.shape) == 4 and img_batch.shape[1] == 3 f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}" )
logging.info("Computing image embeddings for the provided images...") logging.info("Computing image embeddings for the provided images...")
backbone_out = self.model.forward_image(img_batch) 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 unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
if point_coords is not None: if point_coords is not None:
assert ( assert point_labels is not None, (
point_labels is not None "point_labels must be supplied if point_coords is supplied."
), "point_labels must be supplied if point_coords is supplied." )
point_coords = torch.as_tensor( point_coords = torch.as_tensor(
point_coords, dtype=torch.float, device=self.device point_coords, dtype=torch.float, device=self.device
) )
@@ -438,9 +438,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
raise RuntimeError( raise RuntimeError(
"An image must be set with .set_image(...) to generate an embedding." "An image must be set with .set_image(...) to generate an embedding."
) )
assert ( assert self._features is not None, (
self._features is not None "Features must exist if an image has been set."
), "Features must exist if an image has been set." )
return self._features["image_embed"] return self._features["image_embed"]
@property @property
+3 -3
View File
@@ -684,9 +684,9 @@ class Sam3Image(torch.nn.Module):
inference_state["original_heights"], inference_state["original_heights"],
inference_state["original_widths"], inference_state["original_widths"],
) )
assert ( assert batch_size == len(orig_heights) == len(orig_widths), (
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)}"
), f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}" )
feats = [ feats = [
feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
for feat, feat_size in zip( for feat, feat_size in zip(
+3 -3
View File
@@ -81,9 +81,9 @@ class Sam3Processor:
if not isinstance(images, list): if not isinstance(images, list):
raise ValueError("Images must be a list of PIL images or tensors") raise ValueError("Images must be a list of PIL images or tensors")
assert len(images) > 0, "Images list must not be empty" assert len(images) > 0, "Images list must not be empty"
assert isinstance( assert isinstance(images[0], PIL.Image.Image), (
images[0], PIL.Image.Image "Images must be a list of PIL images"
), "Images must be a list of PIL images" )
state["original_heights"] = [image.height for image in images] state["original_heights"] = [image.height for image in images]
state["original_widths"] = [image.width for image in images] state["original_widths"] = [image.width for image in images]
+21 -19
View File
@@ -281,7 +281,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
assert ( assert (
self.is_multiplex == self.tracker.is_multiplex == self.detector.is_multiplex self.is_multiplex == self.tracker.is_multiplex == self.detector.is_multiplex
), f"is_multiplex must be the same for all models: {self.is_multiplex=}, {self.tracker.is_multiplex=}, {self.detector.is_multiplex=}" ), (
f"is_multiplex must be the same for all models: {self.is_multiplex=}, {self.tracker.is_multiplex=}, {self.detector.is_multiplex=}"
)
# hotstart parameters # hotstart parameters
if hotstart_delay > 0: if hotstart_delay > 0:
@@ -356,9 +358,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
) )
if self.is_multiplex: if self.is_multiplex:
assert ( assert not self.tracker.multiplex_controller.training, (
not self.tracker.multiplex_controller.training "This model class should only be used for eval."
), "This model class should only be used for eval." )
self.bucket_capacity: int = ( self.bucket_capacity: int = (
self.tracker.multiplex_controller.allowed_bucket_capacity self.tracker.multiplex_controller.allowed_bucket_capacity
) )
@@ -1417,9 +1419,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0 binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
if batch_size > 0: if batch_size > 0:
assert ( assert len(obj_ids_global) == batch_size, (
len(obj_ids_global) == batch_size f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
), f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}" )
NEVER_OCCLUDED = -1 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 ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
@@ -1595,9 +1597,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
reverse: bool = False, reverse: bool = False,
): ):
# Suppress overlapping masks for objects that were most recently occluded # Suppress overlapping masks for objects that were most recently occluded
assert ( assert binary_low_res_masks.dtype == torch.bool, (
binary_low_res_masks.dtype == torch.bool f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
), f"Expected boolean tensor, got {binary_low_res_masks.dtype}" )
to_suppress = torch.zeros( to_suppress = torch.zeros(
binary_low_res_masks.size(0), binary_low_res_masks.size(0),
device=binary_low_res_masks.device, device=binary_low_res_masks.device,
@@ -1721,9 +1723,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
num_frames_propagated += 1 num_frames_propagated += 1
# only 1 frames should be propagated # only 1 frames should be propagated
assert ( assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
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}"
), f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}" )
assert isinstance(out_obj_ids, list) assert isinstance(out_obj_ids, list)
# Optionally filter to a subset of object ids (for partial propagation). # Optionally filter to a subset of object ids (for partial propagation).
# We also clamp indices to available rows to avoid CUDA index_select assertions. # We also clamp indices to available rows to avoid CUDA index_select assertions.
@@ -1867,9 +1869,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)" 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.is_floating_point(), "float tensor expected (do not binarize)"
assert ( assert trk_masks.size(0) == len(trk_obj_ids), (
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)}"
), 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: if trk_masks.size(0) == 0:
with torch.profiler.record_function("No tracklets"): with torch.profiler.record_function("No tracklets"):
num_trk = 0 num_trk = 0
@@ -2105,9 +2107,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
# New objects are added via extend_gpu_metadata_for_new_objects AFTER compaction, # New objects are added via extend_gpu_metadata_for_new_objects AFTER compaction,
# so prev_N_obj should already include objects detected on previous frame. # so prev_N_obj should already include objects detected on previous frame.
# N_obj should equal prev_N_obj (no new objects mid-planning-phase). # N_obj should equal prev_N_obj (no new objects mid-planning-phase).
assert ( assert N_obj == prev_N_obj, (
N_obj == prev_N_obj f"N_obj ({N_obj}) should equal prev_N_obj ({prev_N_obj}); new objects handled after compaction"
), f"N_obj ({N_obj}) should equal prev_N_obj ({prev_N_obj}); new objects handled after compaction" )
# Carry forward existing metadata (or initialize if first frame) # Carry forward existing metadata (or initialize if first frame)
NEVER_OCCLUDED = -1 NEVER_OCCLUDED = -1
+3 -3
View File
@@ -37,9 +37,9 @@ class Sam3MultiplexImageBase(Sam3Image):
input: BatchedDatapoint, input: BatchedDatapoint,
is_inference=False, # (a dummy parameter not used anymore) is_inference=False, # (a dummy parameter not used anymore)
): ):
assert ( assert not self.training, (
not self.training "Sam3MultiplexImageBase should only be used in eval mode."
), "Sam3MultiplexImageBase should only be used in eval mode." )
device = self.device device = self.device
backbone_out = {"img_batch_all_stages": input.img_batch} backbone_out = {"img_batch_all_stages": input.img_batch}
+25 -25
View File
@@ -1250,9 +1250,9 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
# Update with refined masks if provided # Update with refined masks if provided
if refined_obj_id_to_mask is not None: if refined_obj_id_to_mask is not None:
for obj_id, refined_mask in refined_obj_id_to_mask.items(): for obj_id, refined_mask in refined_obj_id_to_mask.items():
assert ( assert refined_mask is not None, (
refined_mask is not None f"Refined mask data must be provided for obj_id {obj_id}"
), f"Refined mask data must be provided for obj_id {obj_id}" )
obj_id_to_mask[obj_id] = refined_mask obj_id_to_mask[obj_id] = refined_mask
return obj_id_to_mask return obj_id_to_mask
@@ -1678,18 +1678,18 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
device = inference_state["device"] device = inference_state["device"]
num_frames = inference_state["num_frames"] num_frames = inference_state["num_frames"]
assert ( assert text_str is not None or points is not None or boxes_xywh is not None, (
text_str is not None or points is not None or boxes_xywh is not None "at least one type of prompt (text, points, boxes) must be provided"
), "at least one type of prompt (text, points, boxes) must be provided" )
assert ( assert 0 <= frame_idx < num_frames, (
0 <= frame_idx < num_frames f"{frame_idx=} is out of range for a total of {num_frames} frames"
), f"{frame_idx=} is out of range for a total of {num_frames} frames" )
assert clear_old_boxes, "clear old boxes must be True" assert clear_old_boxes, "clear old boxes must be True"
assert ( assert points is None and clear_old_points is True and point_labels is None, (
points is None and clear_old_points is True and point_labels is None "Point prompts not accepted"
), "Point prompts not accepted" )
# since it's a semantic prompt, we start over # since it's a semantic prompt, we start over
self.reset_state(inference_state) self.reset_state(inference_state)
@@ -2484,9 +2484,9 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
"propagation_fetch", "propagation_fetch",
"propagation_cancel", "propagation_cancel",
] ]
assert ( assert action_type in instance_actions + propagation_actions, (
action_type in instance_actions + propagation_actions f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
), f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}" )
action = { action = {
"type": action_type, "type": action_type,
"frame_idx": frame_idx, "frame_idx": frame_idx,
@@ -2518,7 +2518,7 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
): ):
# last action is cancel, we go back to the action before cancel # last action is cancel, we go back to the action before cancel
action_before_cancelation = inference_state["action_history"][-2] action_before_cancelation = inference_state["action_history"][-2]
# the action before cancelation can be a propagation_fetch from running both forward # the action before cancellation can be a propagation_fetch from running both forward
# and backward propagation as in webdemo interface, in that case we go back one more step # and backward propagation as in webdemo interface, in that case we go back one more step
if action_before_cancelation["type"] == "propagation_fetch": if action_before_cancelation["type"] == "propagation_fetch":
action_before_cancelation = inference_state["action_history"][-3] action_before_cancelation = inference_state["action_history"][-3]
@@ -2700,12 +2700,12 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
): ):
if points is not None: if points is not None:
# SAM2 instance prompts # SAM2 instance prompts
assert ( assert text_str is None and boxes_xywh is None, (
text_str is None and boxes_xywh is None "When points are provided, text_str and boxes_xywh must be None."
), "When points are provided, text_str and boxes_xywh must be None." )
assert ( assert obj_id is not None, (
obj_id is not None "When points are provided, obj_id must be provided."
), "When points are provided, obj_id must be provided." )
return self.add_sam2_new_points( return self.add_sam2_new_points(
inference_state, inference_state,
frame_idx, frame_idx,
@@ -2846,9 +2846,9 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
tracker_states = self._get_sam2_inference_states_by_obj_ids( tracker_states = self._get_sam2_inference_states_by_obj_ids(
inference_state, [obj_id] inference_state, [obj_id]
) )
assert ( assert len(tracker_states) == 1, (
len(tracker_states) == 1 f"[rank={self.rank}] Multiple SAM2 inference states found for the same object id."
), f"[rank={self.rank}] Multiple SAM2 inference states found for the same object id." )
sam2_state = tracker_states[0] sam2_state = tracker_states[0]
# log # log
+21 -19
View File
@@ -177,7 +177,9 @@ def _associate_det_trk_compilable(
else: else:
intersection_metric = mask_iou(det_masks_binary, trk_masks_binary) # (N, M) 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." assert not o2o_matching_masklets_enable, (
"Temporarily disabled support for o2o_matching_masklets_enable, due to optimizations."
)
if o2o_matching_masklets_enable: if o2o_matching_masklets_enable:
intersection_metric_np = intersection_metric.cpu().numpy() intersection_metric_np = intersection_metric.cpu().numpy()
@@ -830,9 +832,9 @@ class Sam3VideoBase(nn.Module):
num_obj_dropped_due_to_limit, num_obj_dropped_due_to_limit,
trk_id_to_max_iou_high_conf_det, trk_id_to_max_iou_high_conf_det,
] ]
assert ( assert len(update_plan) == NUM_BROADCAST_ITEMS, (
len(update_plan) == NUM_BROADCAST_ITEMS f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
), f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}" )
self.broadcast_python_obj_cpu(update_plan, src=0) self.broadcast_python_obj_cpu(update_plan, src=0)
elif self.rank > 0 and self.world_size > 1: elif self.rank > 0 and self.world_size > 1:
update_plan = [ update_plan = [
@@ -1052,9 +1054,9 @@ class Sam3VideoBase(nn.Module):
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0 binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
batch_size = tracker_low_res_masks_global.size(0) batch_size = tracker_low_res_masks_global.size(0)
if batch_size > 0: if batch_size > 0:
assert ( assert len(obj_ids_global) == batch_size, (
len(obj_ids_global) == batch_size f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
), f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}" )
NEVER_OCCLUDED = -1 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 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( last_occluded_prev = torch.cat(
@@ -1257,9 +1259,9 @@ class Sam3VideoBase(nn.Module):
reverse: bool = False, reverse: bool = False,
): ):
# Suppress overlapping masks for objects that were most recently occluded # Suppress overlapping masks for objects that were most recently occluded
assert ( assert binary_low_res_masks.dtype == torch.bool, (
binary_low_res_masks.dtype == torch.bool f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
), f"Expected boolean tensor, got {binary_low_res_masks.dtype}" )
to_suppress = torch.zeros( to_suppress = torch.zeros(
binary_low_res_masks.size(0), binary_low_res_masks.size(0),
device=binary_low_res_masks.device, device=binary_low_res_masks.device,
@@ -1364,9 +1366,9 @@ class Sam3VideoBase(nn.Module):
num_frames_propagated += 1 num_frames_propagated += 1
# only 1 frames should be propagated # only 1 frames should be propagated
assert ( assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
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}"
), f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}" )
assert isinstance(out_obj_ids, list) assert isinstance(out_obj_ids, list)
obj_ids_local.extend(out_obj_ids) obj_ids_local.extend(out_obj_ids)
low_res_masks_list.append(out_low_res_masks.squeeze(1)) low_res_masks_list.append(out_low_res_masks.squeeze(1))
@@ -1424,9 +1426,9 @@ class Sam3VideoBase(nn.Module):
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)" 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.is_floating_point(), "float tensor expected (do not binarize)"
assert ( assert trk_masks.size(0) == len(trk_obj_ids), (
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)}"
), 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: if trk_masks.size(0) == 0:
# all detections are new # all detections are new
new_det_fa_inds = np.arange(det_masks.size(0)) new_det_fa_inds = np.arange(det_masks.size(0))
@@ -1883,9 +1885,9 @@ class Sam3VideoBase(nn.Module):
# a) first, expand "confirmation_data" to include new masklets added in this frame # a) first, expand "confirmation_data" to include new masklets added in this frame
status_prev = confirmation_data["status"] status_prev = confirmation_data["status"]
consecutive_det_num_prev = confirmation_data["consecutive_det_num"] consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
assert ( assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
status_prev.shape == obj_ids_all_gpu_prev.shape f"Got {status_prev.shape} vs {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_to_updated_idx = {
obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated) obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
+24 -22
View File
@@ -554,7 +554,9 @@ class Sam3VideoInference(Sam3VideoBase):
assert ( assert (
"cached_frame_outputs" in inference_state "cached_frame_outputs" in inference_state
and frame_idx in inference_state["cached_frame_outputs"] 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] cached_outputs = inference_state["cached_frame_outputs"][frame_idx]
obj_id_to_mask = cached_outputs.copy() obj_id_to_mask = cached_outputs.copy()
@@ -562,9 +564,9 @@ class Sam3VideoInference(Sam3VideoBase):
# Update with refined masks if provided # Update with refined masks if provided
if refined_obj_id_to_mask is not None: if refined_obj_id_to_mask is not None:
for obj_id, refined_mask in refined_obj_id_to_mask.items(): for obj_id, refined_mask in refined_obj_id_to_mask.items():
assert ( assert refined_mask is not None, (
refined_mask is not None f"Refined mask data must be provided for obj_id {obj_id}"
), f"Refined mask data must be provided for obj_id {obj_id}" )
obj_id_to_mask[obj_id] = refined_mask obj_id_to_mask[obj_id] = refined_mask
return obj_id_to_mask return obj_id_to_mask
@@ -853,12 +855,12 @@ class Sam3VideoInference(Sam3VideoBase):
logger.debug("Running add_prompt on frame %d", frame_idx) logger.debug("Running add_prompt on frame %d", frame_idx)
num_frames = inference_state["num_frames"] num_frames = inference_state["num_frames"]
assert ( assert text_str is not None or boxes_xywh is not None, (
text_str is not None or boxes_xywh is not None "at least one type of prompt (text, boxes) must be provided"
), "at least one type of prompt (text, boxes) must be provided" )
assert ( assert 0 <= frame_idx < num_frames, (
0 <= frame_idx < num_frames f"{frame_idx=} is out of range for a total of {num_frames} frames"
), f"{frame_idx=} is out of range for a total of {num_frames} frames" )
# since it's a semantic prompt, we start over # since it's a semantic prompt, we start over
self.reset_state(inference_state) self.reset_state(inference_state)
@@ -1199,9 +1201,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
"propagation_partial", "propagation_partial",
"propagation_fetch", "propagation_fetch",
] ]
assert ( assert action_type in instance_actions + propagation_actions, (
action_type in instance_actions + propagation_actions f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
), f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}" )
action = { action = {
"type": action_type, "type": action_type,
"frame_idx": frame_idx, "frame_idx": frame_idx,
@@ -1369,12 +1371,12 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
): ):
if points is not None: if points is not None:
# Tracker instance prompts # Tracker instance prompts
assert ( assert text_str is None and boxes_xywh is None, (
text_str is None and boxes_xywh is None "When points are provided, text_str and boxes_xywh must be None."
), "When points are provided, text_str and boxes_xywh must be None." )
assert ( assert obj_id is not None, (
obj_id is not None "When points are provided, obj_id must be provided."
), "When points are provided, obj_id must be provided." )
return self.add_tracker_new_points( return self.add_tracker_new_points(
inference_state, inference_state,
frame_idx, frame_idx,
@@ -1490,9 +1492,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
tracker_states = self._get_tracker_inference_states_by_obj_ids( tracker_states = self._get_tracker_inference_states_by_obj_ids(
inference_state, [obj_id] inference_state, [obj_id]
) )
assert ( assert len(tracker_states) == 1, (
len(tracker_states) == 1 f"[rank={self.rank}] Multiple Tracker inference states found for the same object id."
), f"[rank={self.rank}] Multiple Tracker inference states found for the same object id." )
tracker_state = tracker_states[0] tracker_state = tracker_states[0]
# log # log
+3 -3
View File
@@ -318,9 +318,9 @@ class VETextEncoder(nn.Module):
# The text is already encoded, use as is. # The text is already encoded, use as is.
text_attention_mask, text_memory_resized, tokenized = text text_attention_mask, text_memory_resized, tokenized = text
inputs_embeds = tokenized["inputs_embeds"] inputs_embeds = tokenized["inputs_embeds"]
assert ( assert input_boxes is None or len(input_boxes) == 0, (
input_boxes is None or len(input_boxes) == 0 "Can't replace boxes in text if it's already encoded"
), "Can't replace boxes in text if it's already encoded" )
# Note that the input_embeds are returned in pytorch's convention (sequence first) # Note that the input_embeds are returned in pytorch's convention (sequence first)
return ( return (
+32 -31
View File
@@ -318,9 +318,9 @@ class VideoTrackingMultiplex(nn.Module):
): ):
# if there is compression of memories along channel dim # if there is compression of memories along channel dim
mem_dim = self.maskmem_backbone.out_proj.weight.shape[0] mem_dim = self.maskmem_backbone.out_proj.weight.shape[0]
assert ( assert mem_dim == self.hidden_dim, (
mem_dim == self.hidden_dim "there should be no compression of memory embeddings"
), "there should be no compression of memory embeddings" )
self.num_maskmem = num_maskmem # Number of memories accessible self.num_maskmem = num_maskmem # Number of memories accessible
# Temporal encoding of the memories # Temporal encoding of the memories
self.sincos_tpos_enc = sincos_tpos_enc self.sincos_tpos_enc = sincos_tpos_enc
@@ -396,9 +396,9 @@ class VideoTrackingMultiplex(nn.Module):
self.forward_backbone_per_frame_for_eval = forward_backbone_per_frame_for_eval self.forward_backbone_per_frame_for_eval = forward_backbone_per_frame_for_eval
self.offload_output_to_cpu_for_eval = offload_output_to_cpu_for_eval self.offload_output_to_cpu_for_eval = offload_output_to_cpu_for_eval
if trim_past_non_cond_mem_for_eval: if trim_past_non_cond_mem_for_eval:
assert ( assert num_frames_to_correct_for_eval <= 1, (
num_frames_to_correct_for_eval <= 1 "trim_past_non_cond_mem_for_eval=True requires that only the first frame receives prompts"
), "trim_past_non_cond_mem_for_eval=True requires that only the first frame receives prompts" )
self.trim_past_non_cond_mem_for_eval = trim_past_non_cond_mem_for_eval self.trim_past_non_cond_mem_for_eval = trim_past_non_cond_mem_for_eval
self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
self.interactive_sam_mask_decoder_extra_args = ( self.interactive_sam_mask_decoder_extra_args = (
@@ -940,9 +940,9 @@ class VideoTrackingMultiplex(nn.Module):
# Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
mask_inputs_float = mask_inputs.to(backbone_features.dtype) mask_inputs_float = mask_inputs.to(backbone_features.dtype)
assert mask_inputs.shape[0] == len( assert mask_inputs.shape[0] == len(objects_in_mask), (
objects_in_mask f"{mask_inputs.shape[0]} != {len(objects_in_mask)}"
), f"{mask_inputs.shape[0]} != {len(objects_in_mask)}" )
high_res_masks = mask_inputs_float * out_scale + out_bias high_res_masks = mask_inputs_float * out_scale + out_bias
low_res_masks = F.interpolate( low_res_masks = F.interpolate(
high_res_masks, high_res_masks,
@@ -1541,9 +1541,9 @@ class VideoTrackingMultiplex(nn.Module):
# expand to batch size # expand to batch size
obj_pos = obj_pos.unsqueeze(1).expand(-1, B, -1) obj_pos = obj_pos.unsqueeze(1).expand(-1, B, -1)
assert ( assert self.mem_dim == C, (
self.mem_dim == C f"obj_ptrs.shape = {obj_ptrs.shape}, C = {C}"
), f"obj_ptrs.shape = {obj_ptrs.shape}, C = {C}" )
# each frame has [bucket_size] pointers, except the first frame # each frame has [bucket_size] pointers, except the first frame
obj_pos = obj_pos.repeat_interleave( obj_pos = obj_pos.repeat_interleave(
@@ -1640,9 +1640,9 @@ class VideoTrackingMultiplex(nn.Module):
) )
if self.apply_sigmoid_to_mask_logits_for_mem_enc: if self.apply_sigmoid_to_mask_logits_for_mem_enc:
# scale the raw mask logits with a temperature before applying sigmoid # scale the raw mask logits with a temperature before applying sigmoid
assert ( assert not self.binarize_mask_from_pts_for_mem_enc, (
not self.binarize_mask_from_pts_for_mem_enc "haven't been trained this way; beware of hardcoded config override"
), "haven't been trained this way; beware of hardcoded config override" )
binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
if binarize and not self.training: if binarize and not self.training:
mask_for_mem = (pred_masks_high_res > 0).float() mask_for_mem = (pred_masks_high_res > 0).float()
@@ -1962,9 +1962,9 @@ class VideoTrackingMultiplex(nn.Module):
elif point_inputs is not None: elif point_inputs is not None:
# Case 3a: Refining existing predictions # Case 3a: Refining existing predictions
if prev_sam_mask_logits is not None: if prev_sam_mask_logits is not None:
assert ( assert objects_to_interact is not None, (
objects_to_interact is not None "objects_to_interact must be specified when refining with prev_sam_mask_logits"
), "objects_to_interact must be specified when refining with prev_sam_mask_logits" )
mode = "interaction_only" mode = "interaction_only"
# Case 3b: Initial conditioning frame # Case 3b: Initial conditioning frame
elif is_init_cond_frame: elif is_init_cond_frame:
@@ -2271,9 +2271,9 @@ class VideoTrackingMultiplex(nn.Module):
method="uniform" if self.training else self.pt_sampling_for_eval, method="uniform" if self.training else self.pt_sampling_for_eval,
) )
point_inputs = concat_points(point_inputs, new_points, new_labels) point_inputs = concat_points(point_inputs, new_points, new_labels)
assert low_res_masks.shape[0] > max( assert low_res_masks.shape[0] > max(objects_to_interact), (
objects_to_interact f"interacting {objects_to_interact} in {low_res_masks.shape}?"
), f"interacting {objects_to_interact} in {low_res_masks.shape}?" )
if self.iter_use_prev_mask_pred: if self.iter_use_prev_mask_pred:
# Feed the mask logits of the previous SAM outputs in the next SAM decoder step. # Feed the mask logits of the previous SAM outputs in the next SAM decoder step.
# For tracking, this means that when the user adds a correction click, we also feed # For tracking, this means that when the user adds a correction click, we also feed
@@ -2858,9 +2858,9 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
else: else:
# During evaluation, this should only happen for YouTubeVOS. # During evaluation, this should only happen for YouTubeVOS.
# We will skip the frames before the first conditional frame. # We will skip the frames before the first conditional frame.
assert ( assert self.is_dynamic_vos_evaluation, (
self.is_dynamic_vos_evaluation f"{visible_objects_per_frame=} invalid"
), f"{visible_objects_per_frame=} invalid" )
assert len(init_cond_frames) == 1 assert len(init_cond_frames) == 1
for stage_id in range(start_frame_idx, num_frames): for stage_id in range(start_frame_idx, num_frames):
if len(visible_objects_per_frame[stage_id]) > 0: if len(visible_objects_per_frame[stage_id]) > 0:
@@ -3525,13 +3525,14 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
new_object_idxs = new_idx_per_transition[stage_id] new_object_idxs = new_idx_per_transition[stage_id]
# Get the new object masks, ensure correct ordering # Get the new object masks, ensure correct ordering
assert sorted(new_object_idxs) == new_object_idxs assert sorted(new_object_idxs) == new_object_idxs
assert ( assert new_object_idxs[0] == len(
new_object_idxs[0] valid_objects_prior_to_each_transition[stage_id]
== len(valid_objects_prior_to_each_transition[stage_id]) ), (
), f"{new_object_idxs=}; {gt_masks.shape=}; {valid_objects_prior_to_each_transition[stage_id]=}" f"{new_object_idxs=}; {gt_masks.shape=}; {valid_objects_prior_to_each_transition[stage_id]=}"
assert new_object_idxs[-1] == ( )
len(gt_masks) - 1 assert new_object_idxs[-1] == (len(gt_masks) - 1), (
), f"{new_object_idxs=}; {gt_masks.shape=}" f"{new_object_idxs=}; {gt_masks.shape=}"
)
new_object_masks = gt_masks[new_object_idxs] new_object_masks = gt_masks[new_object_idxs]
# Remove the new objects from the gt masks # Remove the new objects from the gt masks
+3 -3
View File
@@ -838,9 +838,9 @@ class ViT(nn.Module):
self.retain_cls_token = retain_cls_token self.retain_cls_token = retain_cls_token
if self.retain_cls_token: if self.retain_cls_token:
assert pretrain_use_cls_token assert pretrain_use_cls_token
assert ( assert len(window_block_indexes) == 0, (
len(window_block_indexes) == 0 "windowing not supported with cls token"
), "windowing not supported with cls token" )
assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token" assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token"
+6 -6
View File
@@ -185,9 +185,9 @@ class SAM3VLBackboneTri(SAM3VLBackbone):
super().__init__( super().__init__(
visual=visual, text=text, compile_visual=compile_visual, scalp=scalp visual=visual, text=text, compile_visual=compile_visual, scalp=scalp
) )
assert isinstance( assert isinstance(self.vision_backbone, Sam3TriViTDetNeck), (
self.vision_backbone, Sam3TriViTDetNeck f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}" )
def forward_image( def forward_image(
self, self,
@@ -356,9 +356,9 @@ class TriHeadVisionOnly(VisionOnly):
compile_mode=compile_mode, compile_mode=compile_mode,
compile_extra_args=compile_extra_args, compile_extra_args=compile_extra_args,
) )
assert isinstance( assert isinstance(self.vision_backbone, Sam3TriViTDetNeck), (
self.vision_backbone, Sam3TriViTDetNeck f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}" )
def forward_image( def forward_image(
self, self,
+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: if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
input_tensor = input_tensor.squeeze(1) input_tensor = input_tensor.squeeze(1)
else: else:
assert ( assert input_tensor.dim() == 3, (
input_tensor.dim() == 3 "Input tensor must be (B, H, W) or (B, 1, H, W)."
), "Input tensor must be (B, H, W) or (B, 1, H, W)." )
batch_size = input_tensor.shape[0] batch_size = input_tensor.shape[0]
labels_list = [] labels_list = []
@@ -67,9 +67,9 @@ def connected_components(input_tensor: torch.Tensor):
if input_tensor.dim() == 3: if input_tensor.dim() == 3:
input_tensor = input_tensor.unsqueeze(1) input_tensor = input_tensor.unsqueeze(1)
assert ( assert input_tensor.dim() == 4 and input_tensor.shape[1] == 1, (
input_tensor.dim() == 4 and input_tensor.shape[1] == 1 "Input tensor must be (B, H, W) or (B, 1, H, W)."
), "Input tensor must be (B, H, W) or (B, 1, H, W)." )
if input_tensor.is_cuda: if input_tensor.is_cuda:
if HAS_CC_TORCH: if HAS_CC_TORCH:
+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 output tensor with dense labels. Background is 0.
- A BxHxW tensor with the size of the connected component for each pixel. - A BxHxW tensor with the size of the connected component for each pixel.
""" """
assert ( assert input_tensor.is_cuda and input_tensor.is_contiguous(), (
input_tensor.is_cuda and input_tensor.is_contiguous() "Input tensor must be a contiguous CUDA tensor."
), "Input tensor must be a contiguous CUDA tensor." )
out_shape = input_tensor.shape out_shape = input_tensor.shape
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1: if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
input_tensor = input_tensor.squeeze(1) input_tensor = input_tensor.squeeze(1)
else: else:
assert ( assert input_tensor.dim() == 3, (
input_tensor.dim() == 3 "Input tensor must be (B, H, W) or (B, 1, H, W)."
), "Input tensor must be (B, H, W) or (B, 1, H, W)." )
B, H, W = input_tensor.shape B, H, W = input_tensor.shape
numel = B * H * W numel = B * H * W
+3 -3
View File
@@ -202,9 +202,9 @@ class MaskDecoder(nn.Module):
assert image_embeddings.shape[0] == tokens.shape[0] assert image_embeddings.shape[0] == tokens.shape[0]
src = image_embeddings src = image_embeddings
src = src + dense_prompt_embeddings src = src + dense_prompt_embeddings
assert ( assert image_pe.size(0) == 1, (
image_pe.size(0) == 1 "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
), "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) pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
b, c, h, w = src.shape 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.internal_dim = embedding_dim // downsample_rate
self.num_heads = num_heads self.num_heads = num_heads
self.use_fa3 = use_fa3 self.use_fa3 = use_fa3
assert ( assert self.internal_dim % num_heads == 0, (
self.internal_dim % num_heads == 0 "num_heads must divide embedding_dim."
), "num_heads must divide embedding_dim." )
self.q_proj = nn.Linear(embedding_dim, self.internal_dim) self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim) self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
+3 -3
View File
@@ -216,9 +216,9 @@ def collate_fn_api(
text_batch.append(q.query_text) text_batch.append(q.query_text)
stages[stage_id].text_ids.append(text_batch.index(q.query_text)) stages[stage_id].text_ids.append(text_batch.index(q.query_text))
assert ( assert q.inference_metadata is not None, (
q.inference_metadata is not None "inference_metadata must be provided when FindQueryLoaded is created."
), "inference_metadata must be provided when FindQueryLoaded is created." )
for f in fields(q.inference_metadata): for f in fields(q.inference_metadata):
getattr(find_metadatas[stage_id], f.name).append( getattr(find_metadatas[stage_id], f.name).append(
getattr(q.inference_metadata, f.name) getattr(q.inference_metadata, f.name)
+6 -6
View File
@@ -233,9 +233,9 @@ class CustomCocoDetectionAPI(VisionDataset):
if self.coco is not None: if self.coco is not None:
return return
assert g_pathmgr.isfile( assert g_pathmgr.isfile(self.annFile), (
self.annFile f"please provide valid annotation file. Missing: {self.annFile}"
), f"please provide valid annotation file. Missing: {self.annFile}" )
annFile = g_pathmgr.get_local_path(self.annFile) annFile = g_pathmgr.get_local_path(self.annFile)
if self.coco is not None: if self.coco is not None:
@@ -325,9 +325,9 @@ class CustomCocoDetectionAPI(VisionDataset):
else: else:
num_queries_per_stage = stage2num_queries.most_common(1)[0][1] num_queries_per_stage = stage2num_queries.most_common(1)[0][1]
for stage, num_queries in stage2num_queries.items(): for stage, num_queries in stage2num_queries.items():
assert ( assert num_queries == num_queries_per_stage, (
num_queries == num_queries_per_stage f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}"
), f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}" )
for query in queries: for query in queries:
h, w = id2imsize[query["image_id"]] h, w = id2imsize[query["image_id"]]
+3 -4
View File
@@ -15,7 +15,6 @@ from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch import torch
import torchvision import torchvision
# from decord import cpu, VideoReader # from decord import cpu, VideoReader
from iopath.common.file_io import PathManager from iopath.common.file_io import PathManager
@@ -219,9 +218,9 @@ class VideoGroundingDataset(Sam3ImageDataset):
for query in filtered_queries: for query in filtered_queries:
ptr_x_is_empty = query["ptr_x_query_id"] in [None, -1] ptr_x_is_empty = query["ptr_x_query_id"] in [None, -1]
ptr_y_is_empty = query["ptr_y_query_id"] in [None, -1] ptr_y_is_empty = query["ptr_y_query_id"] in [None, -1]
assert ( assert ptr_x_is_empty and ptr_y_is_empty, (
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"
), "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"] = stage_id_old2new[
query["query_processing_order"] query["query_processing_order"]
] ]
+12 -6
View File
@@ -324,7 +324,9 @@ class IABCEMdetr(LossWithWeights):
if num_det_queries is not None: if num_det_queries is not None:
logging.warning("note: it's not needed to set num_det_queries anymore") logging.warning("note: it's not needed to set num_det_queries anymore")
if self.use_separate_loss_for_det_and_trk: 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_pos = det_exhaustive_loss_scale_pos
self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
@@ -339,7 +341,9 @@ class IABCEMdetr(LossWithWeights):
and det_non_exhaustive_loss_scale_neg == 1.0 and det_non_exhaustive_loss_scale_neg == 1.0
and trk_loss_scale_pos == 1.0 and trk_loss_scale_pos == 1.0
and trk_loss_scale_neg == 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): def get_loss(self, outputs, targets, indices, num_boxes):
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape" assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
@@ -440,7 +444,9 @@ class IABCEMdetr(LossWithWeights):
pass pass
if self.weak_loss: 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 # nullify the negative loss for the non-exhaustive classes
assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0] assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
@@ -494,9 +500,9 @@ class IABCEMdetr(LossWithWeights):
loss_bce = loss_bce.mean() loss_bce = loss_bce.mean()
else: else:
assert isinstance(self.pad_n_queries, int) assert isinstance(self.pad_n_queries, int)
assert ( assert loss_bce.size(1) < self.pad_n_queries, (
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."
), 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)) loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
bce_f1 = torchmetrics.functional.f1_score( bce_f1 = torchmetrics.functional.f1_score(
+3 -3
View File
@@ -119,9 +119,9 @@ def dilation(mask, kernel_size):
assert mask.ndim == 3 assert mask.ndim == 3
kernel_size = int(kernel_size) kernel_size = int(kernel_size)
assert ( assert kernel_size % 2 == 1, (
kernel_size % 2 == 1 f"Dilation expects a odd kernel size, got {kernel_size}"
), f"Dilation expects a odd kernel size, got {kernel_size}" )
if mask.is_cuda: if mask.is_cuda:
m = mask.unsqueeze(1).to(torch.float16) 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_bbox = cost_bbox
self.cost_giou = cost_giou self.cost_giou = cost_giou
self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1) self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
assert ( assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0 "all costs cant be 0"
), "all costs cant be 0" )
self.focal_loss = focal_loss self.focal_loss = focal_loss
self.focal_alpha = focal_alpha self.focal_alpha = focal_alpha
self.focal_gamma = focal_gamma self.focal_gamma = focal_gamma
@@ -196,9 +196,9 @@ class BinaryHungarianMatcher(nn.Module):
self.cost_bbox = cost_bbox self.cost_bbox = cost_bbox
self.cost_giou = cost_giou self.cost_giou = cost_giou
self.norm = nn.Sigmoid() self.norm = nn.Sigmoid()
assert ( assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0 "all costs cant be 0"
), "all costs cant be 0" )
@torch.no_grad() @torch.no_grad()
def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1): def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
@@ -321,9 +321,9 @@ class BinaryFocalHungarianMatcher(nn.Module):
self.alpha = alpha self.alpha = alpha
self.gamma = gamma self.gamma = gamma
self.stable = stable self.stable = stable
assert ( assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0 "all costs cant be 0"
), "all costs cant be 0" )
@torch.no_grad() @torch.no_grad()
def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1): 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_bbox = cost_bbox
self.cost_giou = cost_giou self.cost_giou = cost_giou
self.norm = nn.Sigmoid() self.norm = nn.Sigmoid()
assert ( assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
cost_class != 0 or cost_bbox != 0 or cost_giou != 0 "all costs cant be 0"
), "all costs cant be 0" )
self.focal = focal self.focal = focal
if focal: if focal:
self.alpha = alpha 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" "match any classes in the model"
) )
matching_parameters = module_cls_to_param_names[module_cls] matching_parameters = module_cls_to_param_names[module_cls]
assert ( assert len(matching_parameters) > 0, (
len(matching_parameters) > 0 f"module_cls_name {module_cls_name} does not contain any parameters in the model"
), f"module_cls_name {module_cls_name} does not contain any parameters in the model" )
logging.info( logging.info(
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} " 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 = [] allowed_parameter_names = []
for param_name in filter_param_names: for param_name in filter_param_names:
matching_parameters = set(fnmatch.filter(parameter_names, param_name)) matching_parameters = set(fnmatch.filter(parameter_names, param_name))
assert ( assert len(matching_parameters) >= 1, (
len(matching_parameters) >= 1 f"param_name {param_name} does not match any parameters in the model"
), f"param_name {param_name} does not match any parameters in the model" )
logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}") logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}")
allowed_parameter_names.append(matching_parameters) allowed_parameter_names.append(matching_parameters)
return set.union(*allowed_parameter_names) return set.union(*allowed_parameter_names)
+3 -3
View File
@@ -209,9 +209,9 @@ def main(args) -> None:
}, },
} }
if "include_nodes" in submitit_conf: if "include_nodes" in submitit_conf:
assert ( assert len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes, (
len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes "Not enough nodes"
), "Not enough nodes" )
job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join( job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
submitit_conf["include_nodes"] submitit_conf["include_nodes"]
) )
+3 -3
View File
@@ -276,9 +276,9 @@ class RandomSizeCrop:
max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1)) max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
) )
result_img, result_target = crop(img, target, [j, i, h, w]) result_img, result_target = crop(img, target, [j, i, h, w])
assert ( assert len(result_target["boxes"]) == init_boxes, (
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']}"
), 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 return result_img, result_target
else: else:
@@ -379,9 +379,9 @@ class FlexibleFilterFindGetQueries:
if len(new_find_queries) == 0: if len(new_find_queries) == 0:
start_with_zero_check = True start_with_zero_check = True
assert ( assert start_with_zero_check, (
start_with_zero_check "Invalid Find queries, they need to start at query_processing_order = 0"
), "Invalid Find queries, they need to start at query_processing_order = 0" )
datapoint.find_queries = new_find_queries datapoint.find_queries = new_find_queries
+3 -3
View File
@@ -249,9 +249,9 @@ class RandomGeometricInputsAPI:
def _get_target_object(self, datapoint, query): def _get_target_object(self, datapoint, query):
img = datapoint.images[query.image_id] img = datapoint.images[query.image_id]
targets = query.object_ids_output targets = query.object_ids_output
assert ( assert len(targets) == 1, (
len(targets) == 1 "Geometric queries only support a single target object."
), "Geometric queries only support a single target object." )
target_idx = targets[0] target_idx = targets[0]
return img.objects[target_idx] return img.objects[target_idx]
+3 -3
View File
@@ -36,9 +36,9 @@ def unix_pattern_to_parameter_names(
parameter_names = [] parameter_names = []
for param_name in constraints: for param_name in constraints:
matching_parameters = set(fnmatch.filter(all_parameter_names, param_name)) matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
assert ( assert len(matching_parameters) > 0, (
len(matching_parameters) > 0 f"param_names {param_name} don't match any param in the given names."
), f"param_names {param_name} don't match any param in the given names." )
parameter_names.append(matching_parameters) parameter_names.append(matching_parameters)
return set.union(*parameter_names) 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)) local_rank = int(os.environ.get("LOCAL_RANK", None))
distributed_rank = int(os.environ.get("RANK", None)) distributed_rank = int(os.environ.get("RANK", None))
assert ( assert local_rank is not None and distributed_rank is not None, (
local_rank is not None and distributed_rank is not None "Please the set the RANK and LOCAL_RANK environment variables."
), "Please the set the RANK and LOCAL_RANK environment variables." )
return local_rank, distributed_rank 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): def normalize_bbox(bbox_xywh, img_w, img_h):
# Assumes bbox_xywh is in XYWH format # Assumes bbox_xywh is in XYWH format
if isinstance(bbox_xywh, list): if isinstance(bbox_xywh, list):
assert ( assert len(bbox_xywh) == 4, (
len(bbox_xywh) == 4 "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
), "bbox_xywh list must have 4 elements. Batching not support except for torch tensors." )
normalized_bbox = bbox_xywh.copy() normalized_bbox = bbox_xywh.copy()
normalized_bbox[0] /= img_w normalized_bbox[0] /= img_w
normalized_bbox[1] /= img_h normalized_bbox[1] /= img_h
normalized_bbox[2] /= img_w normalized_bbox[2] /= img_w
normalized_bbox[3] /= img_h normalized_bbox[3] /= img_h
else: else:
assert isinstance( assert isinstance(bbox_xywh, torch.Tensor), (
bbox_xywh, torch.Tensor "Only torch tensors are supported for batching."
), "Only torch tensors are supported for batching." )
normalized_bbox = bbox_xywh.clone() normalized_bbox = bbox_xywh.clone()
assert ( assert normalized_bbox.size(-1) == 4, (
normalized_bbox.size(-1) == 4 "bbox_xywh tensor must have last dimension of size 4."
), "bbox_xywh tensor must have last dimension of size 4." )
normalized_bbox[..., 0] /= img_w normalized_bbox[..., 0] /= img_w
normalized_bbox[..., 1] /= img_h normalized_bbox[..., 1] /= img_h
normalized_bbox[..., 2] /= img_w normalized_bbox[..., 2] /= img_w
@@ -245,9 +245,9 @@ def visualize_formatted_frame_output(
num_outputs = len(outputs_list) num_outputs = len(outputs_list)
if titles is None: if titles is None:
titles = [f"Set {i + 1}" for i in range(num_outputs)] titles = [f"Set {i + 1}" for i in range(num_outputs)]
assert ( assert len(titles) == num_outputs, (
len(titles) == num_outputs "length of `titles` should match that of `outputs_list` if not None."
), "length of `titles` should match that of `outputs_list` if not None." )
_, axes = plt.subplots(1, num_outputs, figsize=figsize) _, axes = plt.subplots(1, num_outputs, figsize=figsize)
if num_outputs == 1: if num_outputs == 1:
@@ -703,9 +703,9 @@ def get_all_annotations_for_frame(
# Get the frame # Get the frame
video_df_current = video_df[video_df.id == video_id] video_df_current = video_df[video_df.id == video_id]
assert ( assert len(video_df_current) == 1, (
len(video_df_current) == 1 f"Expected 1 video row, got {len(video_df_current)}"
), f"Expected 1 video row, got {len(video_df_current)}" )
video_row = video_df_current.iloc[0] video_row = video_df_current.iloc[0]
file_name = video_row.file_names[frame_idx] file_name = video_row.file_names[frame_idx]
file_path = os.path.join( file_path = os.path.join(
+3 -3
View File
@@ -68,9 +68,9 @@ def process_image(args):
def main(): def main():
assert len(sys.argv) > 1, "You have to provide the name of the dataset" assert len(sys.argv) > 1, "You have to provide the name of the dataset"
dataset_name = sys.argv[1] dataset_name = sys.argv[1]
assert ( assert dataset_name in annotation_files, (
dataset_name in annotation_files f"The dataset can be one of {list(annotation_files.keys())}"
), f"The dataset can be one of {list(annotation_files.keys())}" )
all_outputs = [] all_outputs = []
for file in annotation_files[dataset_name]: for file in annotation_files[dataset_name]:
with open(os.path.join(config["path_annotations"], file), "r") as f: with open(os.path.join(config["path_annotations"], file), "r") as f:
@@ -58,9 +58,9 @@ class YtVideoPrep:
df = self.yt1b_start_end_time_df[ df = self.yt1b_start_end_time_df[
self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id
] ]
assert ( assert len(df) == 1, (
len(df) == 1 f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
), f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}" )
id_and_frame_map_row = df.iloc[0] id_and_frame_map_row = df.iloc[0]
yt_video_id = ( yt_video_id = (
@@ -82,9 +82,9 @@ class YtVideoPrep:
def download_youtube_video(self): def download_youtube_video(self):
video_url = f"https://youtube.com/watch?v={self.yt_video_id}" video_url = f"https://youtube.com/watch?v={self.yt_video_id}"
assert os.path.exists( assert os.path.exists(self.cookies_file), (
self.cookies_file f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
), f"Cookies file '{self.cookies_file}' not found. Must have it to download videos." )
outtmpl = self.raw_video_path outtmpl = self.raw_video_path