Suppress type errors for Pyre upgrade
Summary: This diff was automatically generated by the Pyre per-target upgrade tool. It adds `# pyre-fixme` or `pyrefly: ignore` comments to suppress type errors that will be introduced by an upcoming Pyre or Pyrefly release. These suppressions allow the upgrade to proceed without breaking existing code. Upgrading to new pyrefly Version. Without landing this diff your type checking tests may break. If assigned as a reviewer please help us get these diffs across the finish line. Thank you! #pyreupgrade Differential Revision: D113834959 fbshipit-source-id: 63169c3df9d594b58d39a33ab51c8866629dd1fa
This commit is contained in:
committed by
meta-codesync[bot]
parent
46957e4780
commit
6dbb02bd38
@@ -6,6 +6,7 @@ import base64
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
# pyre-fixme[21]: Could not find module `openai`.
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
|
||||
@@ -73,6 +73,8 @@ class BoxMode(IntEnum):
|
||||
if is_numpy:
|
||||
arr = torch.from_numpy(np.asarray(box)).clone()
|
||||
else:
|
||||
# pyre-fixme[16]: Item `List` of `List[float] | ndarray | Tensor |
|
||||
# tuple[float, ...]` has no attribute `clone`.
|
||||
arr = box.clone()
|
||||
|
||||
assert to_mode not in [
|
||||
@@ -113,6 +115,7 @@ class BoxMode(IntEnum):
|
||||
arr[:, 0] += arr[:, 2] / 2.0
|
||||
arr[:, 1] += arr[:, 3] / 2.0
|
||||
angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)
|
||||
# pyre-fixme[28]: Unexpected keyword argument `axis`.
|
||||
arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)
|
||||
else:
|
||||
if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:
|
||||
@@ -336,9 +339,17 @@ def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
|
||||
Returns:
|
||||
Tensor: intersection, sized [N,M].
|
||||
"""
|
||||
# pyre-fixme[9]: boxes1 has type `Boxes`; used as `Tensor`.
|
||||
# pyre-fixme[9]: boxes2 has type `Boxes`; used as `Tensor`.
|
||||
boxes1, boxes2 = boxes1.tensor, boxes2.tensor
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Boxes`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
|
||||
width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(
|
||||
boxes1[:, None, :2], boxes2[:, :2]
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Boxes`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
|
||||
boxes1[:, None, :2],
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
|
||||
boxes2[:, :2],
|
||||
) # [N,M,2]
|
||||
|
||||
width_height.clamp_(min=0) # [N,M,2]
|
||||
|
||||
@@ -39,13 +39,19 @@ class Keypoints:
|
||||
self.tensor = keypoints
|
||||
|
||||
def __len__(self) -> int:
|
||||
# pyre-fixme[16]: Item `List` of `List[List[float]] | ndarray | Tensor` has
|
||||
# no attribute `size`.
|
||||
return self.tensor.size(0)
|
||||
|
||||
def to(self, *args: Any, **kwargs: Any) -> "Keypoints":
|
||||
# pyre-fixme[16]: Item `List` of `List[List[float]] | ndarray | Tensor` has
|
||||
# no attribute `to`.
|
||||
return type(self)(self.tensor.to(*args, **kwargs))
|
||||
|
||||
@property
|
||||
def device(self) -> torch.device:
|
||||
# pyre-fixme[16]: Item `List` of `List[List[float]] | ndarray | Tensor` has
|
||||
# no attribute `device`.
|
||||
return self.tensor.device
|
||||
|
||||
def to_heatmap(self, boxes: torch.Tensor, heatmap_size: int) -> torch.Tensor:
|
||||
@@ -63,6 +69,9 @@ class Keypoints:
|
||||
valid:
|
||||
A tensor of shape (N, K) containing whether each keypoint is in the roi or not.
|
||||
"""
|
||||
# pyre-fixme[7]: Expected `Tensor` but got `Tuple[Tensor, Tensor]`.
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[List[List[float]], ndarray, Tensor]`.
|
||||
return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)
|
||||
|
||||
def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Keypoints":
|
||||
@@ -81,6 +90,10 @@ class Keypoints:
|
||||
"""
|
||||
if isinstance(item, int):
|
||||
return Keypoints([self.tensor[item]])
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[List[float]],
|
||||
# ndarray, Tensor]` but got `List[float]`.
|
||||
# pyre-fixme[6]: For 1st argument expected `SupportsIndex` but got
|
||||
# `Union[slice[Any, Any, Any], BoolTensor]`.
|
||||
return Keypoints(self.tensor[item])
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -104,6 +117,9 @@ class Keypoints:
|
||||
assert all(isinstance(keypoints, Keypoints) for keypoints in keypoints_list)
|
||||
|
||||
cat_kpts = type(keypoints_list[0])(
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[List[float]], ndarray,
|
||||
# Tensor]]`.
|
||||
torch.cat([kpts.tensor for kpts in keypoints_list], dim=0)
|
||||
)
|
||||
return cat_kpts
|
||||
@@ -136,11 +152,14 @@ def _keypoints_to_heatmap(
|
||||
return rois.new().long(), rois.new().long()
|
||||
offset_x = rois[:, 0]
|
||||
offset_y = rois[:, 1]
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `int` and `Tensor`.
|
||||
scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `int` and `Tensor`.
|
||||
scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
|
||||
|
||||
offset_x = offset_x[:, None]
|
||||
offset_y = offset_y[:, None]
|
||||
# pyre-fixme[16]: `float` has no attribute `__getitem__`.
|
||||
scale_x = scale_x[:, None]
|
||||
scale_y = scale_y[:, None]
|
||||
|
||||
|
||||
@@ -150,6 +150,7 @@ class BitMasks:
|
||||
|
||||
@torch.jit.unused
|
||||
def __iter__(self) -> torch.Tensor:
|
||||
# pyre-fixme[7]: Expected `Tensor` but got `Generator[Any, None, Any]`.
|
||||
yield from self.tensor
|
||||
|
||||
@torch.jit.unused
|
||||
@@ -197,6 +198,7 @@ class BitMasks:
|
||||
roi_masks:
|
||||
height, width (int):
|
||||
"""
|
||||
# pyre-fixme[20]: Argument `width` expected.
|
||||
return roi_masks.to_bitmasks(height, width)
|
||||
|
||||
def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:
|
||||
@@ -241,7 +243,11 @@ class BitMasks:
|
||||
If a mask is empty, it's bounding box will be all zero.
|
||||
"""
|
||||
boxes = torch.zeros(self.tensor.shape[0], 4, dtype=torch.float32)
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Union[ndarray,
|
||||
# Tensor]`.
|
||||
x_any = torch.any(self.tensor, dim=1)
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Union[ndarray,
|
||||
# Tensor]`.
|
||||
y_any = torch.any(self.tensor, dim=2)
|
||||
for idx in range(self.tensor.shape[0]):
|
||||
x = torch.where(x_any[idx, :])[0]
|
||||
@@ -268,6 +274,8 @@ class BitMasks:
|
||||
assert all(isinstance(bitmask, BitMasks) for bitmask in bitmasks_list)
|
||||
|
||||
cat_bitmasks = type(bitmasks_list[0])(
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[ndarray, Tensor]]`.
|
||||
torch.cat([bm.tensor for bm in bitmasks_list], dim=0)
|
||||
)
|
||||
return cat_bitmasks
|
||||
@@ -395,6 +403,9 @@ class PolygonMasks:
|
||||
"Unsupported tensor dtype={} for indexing!".format(item.dtype)
|
||||
)
|
||||
selected_polygons = [self.polygons[i] for i in item]
|
||||
# pyre-fixme[6]: For 1st argument expected `List[List[Union[ndarray,
|
||||
# Tensor]]]` but got `List[List[ndarray]]`.
|
||||
# pyre-fixme[61]: `selected_polygons` is undefined, or not always defined.
|
||||
return PolygonMasks(selected_polygons)
|
||||
|
||||
def __iter__(self) -> Iterator[List[np.ndarray]]:
|
||||
@@ -480,6 +491,8 @@ class PolygonMasks:
|
||||
assert all(isinstance(polymask, PolygonMasks) for polymask in polymasks_list)
|
||||
|
||||
cat_polymasks = type(polymasks_list[0])(
|
||||
# pyre-fixme[6]: For 1st argument expected `List[List[Union[ndarray,
|
||||
# Tensor]]]` but got `List[List[ndarray]]`.
|
||||
list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list))
|
||||
)
|
||||
return cat_polymasks
|
||||
@@ -543,6 +556,7 @@ class ROIMasks:
|
||||
"""
|
||||
Args: see documentation of :func:`paste_masks_in_image`.
|
||||
"""
|
||||
# pyre-fixme[21]: Could not find module `detectron2.layers.mask_ops`.
|
||||
from detectron2.layers.mask_ops import (
|
||||
_paste_masks_tensor_shape,
|
||||
paste_masks_in_image,
|
||||
@@ -556,6 +570,11 @@ class ROIMasks:
|
||||
else:
|
||||
paste_func = retry_if_cuda_oom(paste_masks_in_image)
|
||||
bitmasks = paste_func(
|
||||
self.tensor, boxes.tensor, (height, width), threshold=threshold
|
||||
# pyre-fixme[16]: `Tensor` has no attribute `tensor`.
|
||||
self.tensor,
|
||||
# pyre-fixme[16]: `Tensor` has no attribute `tensor`.
|
||||
boxes.tensor,
|
||||
(height, width),
|
||||
threshold=threshold,
|
||||
)
|
||||
return BitMasks(bitmasks)
|
||||
|
||||
@@ -461,6 +461,7 @@ class RotatedBoxes(Boxes):
|
||||
# For example,
|
||||
# when angle = 0 or 180, |c| = 1, s = 0, scale_factor_w == scale_factor_x;
|
||||
# when |angle| = 90, c = 0, |s| = 1, scale_factor_w == scale_factor_y
|
||||
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
|
||||
self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2)
|
||||
|
||||
# h(new) = |F(new) - O| * 2
|
||||
@@ -471,6 +472,7 @@ class RotatedBoxes(Boxes):
|
||||
# For example,
|
||||
# when angle = 0 or 180, |c| = 1, s = 0, scale_factor_h == scale_factor_y;
|
||||
# when |angle| = 90, c = 0, |s| = 1, scale_factor_h == scale_factor_x
|
||||
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
|
||||
self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2)
|
||||
|
||||
# The angle is the rotation angle from y-axis in image space to the height
|
||||
@@ -486,6 +488,7 @@ class RotatedBoxes(Boxes):
|
||||
self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi
|
||||
|
||||
@classmethod
|
||||
# pyre-fixme[14]: `cat` overrides method defined in `Boxes` inconsistently.
|
||||
def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes":
|
||||
"""
|
||||
Concatenates a list of RotatedBoxes into a single RotatedBoxes
|
||||
|
||||
@@ -674,6 +674,7 @@ class Visualizer:
|
||||
with PathManager.open(dic["pan_seg_file_name"], "rb") as f:
|
||||
pan_seg = Image.open(f)
|
||||
pan_seg = np.asarray(pan_seg)
|
||||
# pyre-fixme[21]: Could not find module `panopticapi.utils`.
|
||||
from panopticapi.utils import rgb2id
|
||||
|
||||
pan_seg = rgb2id(pan_seg)
|
||||
|
||||
@@ -155,6 +155,7 @@ class CocoEvaluator:
|
||||
print(f"{k}: {len(v)}")
|
||||
|
||||
def set_sync_device(self, device: torch.device) -> Any:
|
||||
# pyre-fixme[16]: `CocoEvaluator` has no attribute `_sync_device`.
|
||||
self._sync_device = device
|
||||
|
||||
def _evaluate(self, *args, **kwargs):
|
||||
|
||||
@@ -19,6 +19,7 @@ from pycocotools.cocoeval import COCOeval
|
||||
from sam3.train.utils.distributed import is_main_process
|
||||
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `tidecv`.
|
||||
from tidecv import datasets, TIDE
|
||||
|
||||
HAS_TIDE = True
|
||||
|
||||
@@ -121,6 +121,7 @@ def reindex_coco_to_temp(input_json_path: str) -> Optional[str]:
|
||||
with open(input_json_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
# pyre-fixme[20]: Argument `doc` expected.
|
||||
raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}")
|
||||
|
||||
# Validate COCO format
|
||||
|
||||
@@ -88,6 +88,7 @@ class PostProcessImage(nn.Module):
|
||||
) # NOTE: It's possible but we don't support it.
|
||||
assert self.detection_threshold <= 0.0, "TODO: implement?"
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `tensordict`.
|
||||
from tensordict import TensorDict
|
||||
except ImportError:
|
||||
logging.info(
|
||||
@@ -265,11 +266,15 @@ class PostProcessImage(nn.Module):
|
||||
img_size_for_boxes = (
|
||||
meta.original_size
|
||||
if self.use_original_sizes_box
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
else torch.ones_like(meta.original_size)
|
||||
)
|
||||
img_size_for_masks = (
|
||||
meta.original_size
|
||||
if self.use_original_sizes_mask
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
else torch.ones_like(meta.original_size)
|
||||
)
|
||||
detection_results = self(
|
||||
@@ -401,6 +406,7 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
tracked_objects_frame_idx = defaultdict(list)
|
||||
total_num_preds = 0
|
||||
# This will hold the packed representation of predictions.
|
||||
# pyre-fixme[11]: Annotation `TensorDict` is not defined as a type.
|
||||
vid_preds_packed: List[TensorDict] = []
|
||||
vid_masklets_rle_packed: List[Optional[Dict]] = []
|
||||
video_id = -1 # We assume single video postprocessing, this ID should be unique in the datapoint.
|
||||
@@ -415,6 +421,8 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
meta_td = TensorDict(
|
||||
dataclasses.asdict(meta)
|
||||
).auto_batch_size_() # Shape is [P,...]
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute
|
||||
# `unique`.
|
||||
unique_vid_id = meta.original_image_id.unique()
|
||||
assert unique_vid_id.size(0) == 1
|
||||
if video_id == -1:
|
||||
@@ -491,6 +499,7 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
logging.debug(f"Video {video_id} has no predictions")
|
||||
return {video_id: []}
|
||||
|
||||
# pyre-fixme[9]: vid_preds_packed has type `List[_T]`; used as `Tensor`.
|
||||
vid_preds_packed = torch.cat(vid_preds_packed, dim=0)
|
||||
############### Construct a padded representation of the predictions ###############
|
||||
num_preds = len(tracked_objects_packed_idx)
|
||||
@@ -502,6 +511,7 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
k: torch.zeros(
|
||||
num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype
|
||||
)
|
||||
# pyre-fixme[16]: `List` has no attribute `items`.
|
||||
for k, v in vid_preds_packed.items()
|
||||
},
|
||||
batch_size=[
|
||||
@@ -521,11 +531,17 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
for o_idx, oid in enumerate(tracked_objects_packed_idx):
|
||||
oid2packed_idx = tracked_objects_packed_idx[oid]
|
||||
oid2padded_idx = tracked_objects_frame_idx[oid]
|
||||
# pyre-fixme[6]: For 1st argument expected `SupportsIndex` but got
|
||||
# `List[Any]`.
|
||||
obj_packed_results = vid_preds_packed[oid2packed_idx]
|
||||
padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results
|
||||
if self.convert_mask_to_rle_for_video:
|
||||
for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx):
|
||||
# pyre-fixme[61]: `vid_masklets_rle_padded` is undefined, or not
|
||||
# always defined.
|
||||
vid_masklets_rle_padded[o_idx][padded_idx] = (
|
||||
# pyre-fixme[6]: For 2nd argument expected `None` but got
|
||||
# `Optional[Dict[Any, Any]]`.
|
||||
vid_masklets_rle_packed[packed_idx]
|
||||
)
|
||||
# NOTE: We need a single confidence score per tracklet for the mAP metric.
|
||||
@@ -539,6 +555,8 @@ class PostProcessAPIVideo(PostProcessImage):
|
||||
results["scores"] = torch.stack(tracklet_scores, dim=0)
|
||||
results["labels"] = torch.stack(tracklet_labels, dim=0)
|
||||
if self.convert_mask_to_rle_for_video:
|
||||
# pyre-fixme[61]: `vid_masklets_rle_padded` is undefined, or not always
|
||||
# defined.
|
||||
results["masks_rle"] = vid_masklets_rle_padded
|
||||
# we keep the frame-level scores since it's needed by some evaluation scripts
|
||||
results["per_frame_scores"] = padded_frames_results["scores"]
|
||||
@@ -559,11 +577,17 @@ class PostProcessTracking(PostProcessImage):
|
||||
super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs)
|
||||
self.force_single_mask = force_single_mask
|
||||
|
||||
# pyre-fixme[14]: `process_results` overrides method defined in
|
||||
# `PostProcessImage` inconsistently.
|
||||
def process_results(
|
||||
self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs
|
||||
):
|
||||
# pyre-fixme[6]: For 1st argument expected
|
||||
# `pyre_extensions.PyreReadOnly[Sized]` but got `BatchedInferenceMetadata`.
|
||||
assert len(find_stages) == len(find_metadatas)
|
||||
results = {}
|
||||
# pyre-fixme[6]: For 2nd argument expected `Iterable[_T2]` but got
|
||||
# `BatchedInferenceMetadata`.
|
||||
for outputs, meta in zip(find_stages, find_metadatas):
|
||||
if self.force_single_mask:
|
||||
scores, labels = outputs["pred_logits"].max(-1)
|
||||
|
||||
@@ -38,7 +38,11 @@ class VEvalEvaluator:
|
||||
video_np_results = defaultdict(dict)
|
||||
for evaluator in self.evaluators:
|
||||
d_res, v_np_res = evaluator.evaluate(pred_file)
|
||||
# pyre-fixme[6]: For 1st argument expected `SupportsKeysAndGetItem[Any,
|
||||
# Any]` but got `Union[Dict[Any, Any], str]`.
|
||||
dataset_results.update(d_res)
|
||||
# pyre-fixme[16]: Item `str` of `dict[Any, Any] | str` has no attribute
|
||||
# `items`.
|
||||
for (video_id, category_id), res in v_np_res.items():
|
||||
video_np_results[(video_id, category_id)].update(res)
|
||||
|
||||
|
||||
@@ -112,6 +112,8 @@ class YTVISPredFileEvaluator(BasePredFileEvaluator):
|
||||
|
||||
# video-NP level results not supported for `YTVISPredFileEvaluator` yet
|
||||
video_np_level_results = {}
|
||||
# pyre-fixme[7]: Expected `Dict[str, float]` but got `Tuple[Dict[Any, Any],
|
||||
# Dict[Any, Any]]`.
|
||||
return results, video_np_level_results
|
||||
|
||||
|
||||
@@ -147,6 +149,7 @@ class VideoPhraseApEvaluator(BasePredFileEvaluator):
|
||||
|
||||
results = {}
|
||||
use_cats = False # Phrase AP evaluation does not use categories
|
||||
# pyre-fixme[6]: For 1st argument expected `str` but got `None`.
|
||||
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
|
||||
ytvisGT.dataset = gt
|
||||
ytvisGT.createIndex()
|
||||
@@ -180,6 +183,8 @@ class VideoPhraseApEvaluator(BasePredFileEvaluator):
|
||||
|
||||
# video-NP level results not supported for `VideoPhraseApEvaluator` yet
|
||||
video_np_level_results = {}
|
||||
# pyre-fixme[7]: Expected `Dict[str, float]` but got `Tuple[Dict[Any, Any],
|
||||
# Dict[Any, Any]]`.
|
||||
return results, video_np_level_results
|
||||
|
||||
|
||||
@@ -225,6 +230,7 @@ class VideoCGF1Evaluator(BasePredFileEvaluator):
|
||||
|
||||
results = {}
|
||||
use_cats = False # Demo F1 evaluation does not use categories
|
||||
# pyre-fixme[6]: For 1st argument expected `str` but got `None`.
|
||||
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
|
||||
ytvisGT.dataset = gt
|
||||
ytvisGT.createIndex()
|
||||
@@ -284,6 +290,8 @@ class VideoCGF1Evaluator(BasePredFileEvaluator):
|
||||
|
||||
self.extract_video_np_level_results(demoF1Eval, video_np_level_results)
|
||||
|
||||
# pyre-fixme[7]: Expected `Dict[str, float]` but got `Tuple[Dict[Any, Any],
|
||||
# Dict[Any, Any]]`.
|
||||
return results, video_np_level_results
|
||||
|
||||
def extract_video_np_level_results(self, demoF1Eval, video_np_level_results):
|
||||
@@ -628,6 +636,8 @@ class VideoPhraseHotaEvaluator(BasePredFileEvaluator):
|
||||
)
|
||||
|
||||
# video-NP level results not supported for `VideoPhraseHotaEvaluator` yet
|
||||
# pyre-fixme[7]: Expected `Dict[str, float]` but got `Tuple[Dict[Any, Any],
|
||||
# Dict[Any, Any]]`.
|
||||
return out_dict, video_np_level_results
|
||||
|
||||
def _remap_gt_dt(self, gt, dt):
|
||||
|
||||
@@ -19,6 +19,7 @@ class YTVIS(COCO):
|
||||
"""
|
||||
|
||||
@override
|
||||
# pyre-fixme[9]: annotation_file has type `str`; used as `None`.
|
||||
def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True):
|
||||
"""
|
||||
Args:
|
||||
|
||||
@@ -22,6 +22,7 @@ from sam3.train.utils import distributed as dist
|
||||
from typing_extensions import override
|
||||
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `rapidjson`.
|
||||
import rapidjson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
@@ -270,6 +271,7 @@ class YTVISResultsWriter:
|
||||
return ytvis_results
|
||||
|
||||
def set_sync_device(self, device: torch.device):
|
||||
# pyre-fixme[16]: `YTVISResultsWriter` has no attribute `_sync_device`.
|
||||
self._sync_device = device
|
||||
|
||||
def update(self, *args, **kwargs):
|
||||
|
||||
@@ -63,6 +63,7 @@ pytree.register_pytree_node(
|
||||
)
|
||||
|
||||
|
||||
# pyre-fixme[10]: Name `Tensor` is used but not defined.
|
||||
def interpolate(
|
||||
input, size=None, scale_factor=None, mode="nearest", align_corners=None
|
||||
):
|
||||
|
||||
+29
-2
@@ -115,8 +115,10 @@ class TransformerDecoderLayer(nn.Module):
|
||||
if self.self_attn is not None:
|
||||
if dac:
|
||||
# we only apply self attention to the first half of the queries
|
||||
# pyre-fixme[16]: `Optional` has no attribute `shape`.
|
||||
assert tgt.shape[0] % 2 == 0
|
||||
num_o2o_queries = tgt.shape[0] // 2
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
tgt_o2o = tgt[:num_o2o_queries]
|
||||
tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries]
|
||||
tgt_o2m = tgt[num_o2o_queries:]
|
||||
@@ -130,7 +132,10 @@ class TransformerDecoderLayer(nn.Module):
|
||||
[torch.zeros_like(presence_token), tgt_query_pos_o2o], dim=0
|
||||
)
|
||||
tgt_query_pos = torch.cat(
|
||||
[torch.zeros_like(presence_token), tgt_query_pos], dim=0
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
|
||||
[torch.zeros_like(presence_token), tgt_query_pos],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
q = k = self.with_pos_embed(tgt_o2o, tgt_query_pos_o2o)
|
||||
@@ -139,6 +144,7 @@ class TransformerDecoderLayer(nn.Module):
|
||||
if dac:
|
||||
if not dac_use_selfatt_ln:
|
||||
tgt_o2o = self.norm2(tgt_o2o)
|
||||
# pyre-fixme[61]: `tgt_o2m` is undefined, or not always defined.
|
||||
tgt = torch.cat((tgt_o2o, tgt_o2m), dim=0) # Recombine
|
||||
if dac_use_selfatt_ln:
|
||||
tgt = self.norm2(tgt)
|
||||
@@ -159,7 +165,10 @@ class TransformerDecoderLayer(nn.Module):
|
||||
if presence_token is not None:
|
||||
presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :])
|
||||
cross_attn_mask = torch.cat(
|
||||
[presence_token_mask, cross_attn_mask], dim=1
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
|
||||
[presence_token_mask, cross_attn_mask],
|
||||
dim=1,
|
||||
) # (bs*nheads, 1+nq, hw)
|
||||
|
||||
# Cross attention to image
|
||||
@@ -505,6 +514,8 @@ class TransformerDecoder(nn.Module):
|
||||
for layer_idx, layer in enumerate(self.layers):
|
||||
reference_points_input = (
|
||||
reference_boxes[:, :, None]
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
|
||||
* torch.cat([valid_ratios, valid_ratios], -1)[None, :]
|
||||
) # nq, bs, nlevel, 4
|
||||
|
||||
@@ -516,11 +527,13 @@ class TransformerDecoder(nn.Module):
|
||||
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
|
||||
|
||||
if self.boxRPB != "none" and reference_boxes is not None:
|
||||
# pyre-fixme[16]: `Optional` has no attribute `shape`.
|
||||
assert spatial_shapes.shape[0] == 1, (
|
||||
"only single scale support implemented"
|
||||
)
|
||||
memory_mask = self._get_rpb_matrix(
|
||||
reference_boxes,
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
(spatial_shapes[0, 0], spatial_shapes[0, 1]),
|
||||
)
|
||||
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
|
||||
@@ -564,6 +577,7 @@ class TransformerDecoder(nn.Module):
|
||||
delta_unsig = box_head(out_norm(output))
|
||||
else:
|
||||
# box_head_trk use a separate box head for tracking queries
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
Q_det = decoder_extra_kwargs["Q_det"]
|
||||
assert output.size(0) >= Q_det
|
||||
delta_unsig_det = self.bbox_embed(output[:Q_det])
|
||||
@@ -574,6 +588,7 @@ class TransformerDecoder(nn.Module):
|
||||
|
||||
reference_boxes = new_reference_points.detach()
|
||||
if layer_idx != self.num_layers - 1:
|
||||
# pyre-fixme[16]: `Optional` has no attribute `append`.
|
||||
intermediate_ref_boxes.append(new_reference_points)
|
||||
else:
|
||||
raise NotImplementedError("not implemented yet")
|
||||
@@ -603,6 +618,8 @@ class TransformerDecoder(nn.Module):
|
||||
|
||||
return (
|
||||
torch.stack(intermediate),
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `Optional[List[Any]]`.
|
||||
torch.stack(intermediate_ref_boxes),
|
||||
(
|
||||
torch.stack(intermediate_presence_logits)
|
||||
@@ -688,6 +705,7 @@ class TransformerEncoderCrossAttention(nn.Module):
|
||||
if self.batch_first:
|
||||
# Convert to batch first
|
||||
output = output.transpose(0, 1)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `transpose`.
|
||||
src_pos = src_pos.transpose(0, 1)
|
||||
prompt = prompt.transpose(0, 1)
|
||||
prompt_pos = prompt_pos.transpose(0, 1)
|
||||
@@ -719,6 +737,7 @@ class TransformerEncoderCrossAttention(nn.Module):
|
||||
src_pos = src_pos.transpose(0, 1)
|
||||
|
||||
return {
|
||||
# pyre-fixme[61]: `normed_output` is undefined, or not always defined.
|
||||
"memory": normed_output,
|
||||
"pos_embed": src_pos,
|
||||
"padding_mask": src_key_padding_mask,
|
||||
@@ -839,6 +858,7 @@ class TransformerDecoderLayerv1(nn.Module):
|
||||
tgt = tgt + self.dropout1(tgt2)
|
||||
if dac:
|
||||
# Recombine
|
||||
# pyre-fixme[61]: `other_tgt` is undefined, or not always defined.
|
||||
tgt = torch.cat((tgt, other_tgt), dim=0)
|
||||
tgt2 = self.norm2(tgt)
|
||||
tgt2 = self.cross_attn_image(
|
||||
@@ -918,6 +938,8 @@ class TransformerDecoderLayerv2(TransformerDecoderLayerv1):
|
||||
tgt = tgt + self.dropout2(tgt2)
|
||||
return tgt
|
||||
|
||||
# pyre-fixme[14]: `forward_pre` overrides method defined in
|
||||
# `TransformerDecoderLayerv1` inconsistently.
|
||||
def forward_pre(
|
||||
self,
|
||||
tgt,
|
||||
@@ -993,7 +1015,11 @@ def functional_attention(
|
||||
q, k[:, :, :num_k_rope] = apply_rotary_enc_real(
|
||||
q,
|
||||
k[:, :, :num_k_rope],
|
||||
# pyre-fixme[6]: For 3rd argument expected `Tensor` but got
|
||||
# `Optional[Tensor]`.
|
||||
freqs_cis_real=freqs_cis_real,
|
||||
# pyre-fixme[6]: For 4th argument expected `Tensor` but got
|
||||
# `Optional[Tensor]`.
|
||||
freqs_cis_imag=freqs_cis_imag,
|
||||
repeat_freqs_k=rope_k_repeat,
|
||||
)
|
||||
@@ -1306,6 +1332,7 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
|
||||
if self.batch_first:
|
||||
# Convert to batch first
|
||||
output = output.transpose(0, 1)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `transpose`.
|
||||
src_pos = src_pos.transpose(0, 1)
|
||||
image = image.transpose(0, 1)
|
||||
memory = memory.transpose(0, 1)
|
||||
|
||||
@@ -153,6 +153,7 @@ def edt_triton(data: torch.Tensor):
|
||||
parabola_inter,
|
||||
H,
|
||||
W,
|
||||
# pyre-fixme[6]: For 7th argument expected `constexpr` but got `bool`.
|
||||
horizontal=True,
|
||||
)
|
||||
|
||||
@@ -169,6 +170,7 @@ def edt_triton(data: torch.Tensor):
|
||||
parabola_inter,
|
||||
H,
|
||||
W,
|
||||
# pyre-fixme[6]: For 7th argument expected `constexpr` but got `bool`.
|
||||
horizontal=False,
|
||||
)
|
||||
# don't forget to take sqrt at the end
|
||||
|
||||
@@ -112,6 +112,8 @@ class TransformerEncoderLayer(nn.Module):
|
||||
Returns:
|
||||
Processed tensor
|
||||
"""
|
||||
# pyre-fixme[58]: `+` is not supported for operand types `Tensor` and
|
||||
# `Optional[Tensor]`.
|
||||
q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
|
||||
|
||||
# Self attention
|
||||
@@ -124,6 +126,8 @@ class TransformerEncoderLayer(nn.Module):
|
||||
# Cross attention to image
|
||||
tgt2 = self.cross_attn_image(
|
||||
query=tgt + query_pos if self.pos_enc_at_cross_attn_queries else tgt,
|
||||
# pyre-fixme[58]: `+` is not supported for operand types `Tensor` and
|
||||
# `Optional[Tensor]`.
|
||||
key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
|
||||
value=memory,
|
||||
attn_mask=memory_mask,
|
||||
@@ -186,10 +190,13 @@ class TransformerEncoderLayer(nn.Module):
|
||||
tgt = tgt + self.dropout1(tgt2)
|
||||
if dac:
|
||||
# Recombine
|
||||
# pyre-fixme[61]: `other_tgt` is undefined, or not always defined.
|
||||
tgt = torch.cat((tgt, other_tgt), dim=0)
|
||||
tgt2 = self.norm2(tgt)
|
||||
tgt2 = self.cross_attn_image(
|
||||
query=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
|
||||
# pyre-fixme[58]: `+` is not supported for operand types `Tensor` and
|
||||
# `Optional[Tensor]`.
|
||||
key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
|
||||
value=memory,
|
||||
attn_mask=memory_mask,
|
||||
@@ -503,6 +510,7 @@ class TransformerEncoderFusion(TransformerEncoder):
|
||||
self.text_pooling_proj = nn.Linear(d_model, d_model)
|
||||
self.pool_text_with_mask = pool_text_with_mask
|
||||
if compile_mode is not None:
|
||||
# pyre-fixme[8]: Attribute has type `(self: TransformerEncoderFusion, src...
|
||||
self.forward = torch.compile(
|
||||
self.forward, mode=compile_mode, fullgraph=True
|
||||
)
|
||||
@@ -512,6 +520,8 @@ class TransformerEncoderFusion(TransformerEncoder):
|
||||
# Not needed here
|
||||
return None
|
||||
|
||||
# pyre-fixme[14]: `forward` overrides method defined in `TransformerEncoder`
|
||||
# inconsistently.
|
||||
def forward(
|
||||
self,
|
||||
src: List[Tensor],
|
||||
@@ -529,10 +539,14 @@ class TransformerEncoderFusion(TransformerEncoder):
|
||||
assert len(feat_sizes) == len(src)
|
||||
if src_key_padding_mask is None:
|
||||
src_key_padding_mask = [None] * len(src)
|
||||
# pyre-fixme[23]: Unable to unpack `int` into 2 values.
|
||||
for i, (h, w) in enumerate(feat_sizes):
|
||||
src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__setitem__`.
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
|
||||
src_key_padding_mask[i] = (
|
||||
# pyre-fixme[16]: `Optional` has no attribute `reshape`.
|
||||
src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1)
|
||||
if src_key_padding_mask[i] is not None
|
||||
else None
|
||||
@@ -561,6 +575,8 @@ class TransformerEncoderFusion(TransformerEncoder):
|
||||
valid_ratios,
|
||||
) = super().forward(
|
||||
src,
|
||||
# pyre-fixme[6]: For 2nd argument expected `Optional[List[Tensor]]` but
|
||||
# got `Union[None, List[None], List[Tensor]]`.
|
||||
src_key_padding_masks=src_key_padding_mask,
|
||||
pos=src_pos,
|
||||
prompt=prompt.transpose(0, 1),
|
||||
|
||||
@@ -445,6 +445,8 @@ class FusedMaskEncoder(MaskEncoder):
|
||||
self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
|
||||
|
||||
@override
|
||||
# pyre-fixme[14]: `forward` overrides method defined in `MaskEncoder`
|
||||
# inconsistently.
|
||||
def forward(
|
||||
self,
|
||||
masks: torch.Tensor,
|
||||
@@ -504,6 +506,7 @@ class SequenceGeometryEncoder(nn.Module):
|
||||
roi_size: int = 7, # for boxes pool
|
||||
add_cls: bool = True,
|
||||
add_post_encode_proj: bool = True,
|
||||
# pyre-fixme[9]: mask_encoder has type `MaskEncoder`; used as `None`.
|
||||
mask_encoder: MaskEncoder = None,
|
||||
add_mask_label: bool = False,
|
||||
use_act_ckpt: bool = False,
|
||||
@@ -685,6 +688,7 @@ class SequenceGeometryEncoder(nn.Module):
|
||||
masks: torch.Tensor,
|
||||
attn_mask: torch.Tensor,
|
||||
mask_labels: torch.Tensor,
|
||||
# pyre-fixme[9]: img_feats has type `Tensor`; used as `None`.
|
||||
img_feats: torch.Tensor = None,
|
||||
):
|
||||
n_masks, bs = masks.shape[:2]
|
||||
@@ -762,6 +766,7 @@ class SequenceGeometryEncoder(nn.Module):
|
||||
points_labels, points_mask = concat_padded_sequences(
|
||||
points_labels.unsqueeze(-1),
|
||||
points_mask,
|
||||
# pyre-fixme[16]: `int` has no attribute `unsqueeze`.
|
||||
labels_tl.unsqueeze(-1),
|
||||
boxes_mask,
|
||||
)
|
||||
@@ -833,6 +838,11 @@ class SequenceGeometryEncoder(nn.Module):
|
||||
# Finally, concat mask embeddings if any
|
||||
if masks is not None and self.mask_encoder is not None:
|
||||
final_embeds, final_mask = concat_padded_sequences(
|
||||
final_embeds, final_mask, masks_embed, masks_mask
|
||||
# pyre-fixme[61]: `masks_embed` is undefined, or not always defined.
|
||||
final_embeds,
|
||||
final_mask,
|
||||
# pyre-fixme[61]: `masks_embed` is undefined, or not always defined.
|
||||
masks_embed,
|
||||
masks_mask,
|
||||
)
|
||||
return final_embeds, final_mask
|
||||
|
||||
@@ -42,7 +42,9 @@ def load_resource_as_video_frames(
|
||||
Alternatively, if input is a list of PIL images, convert its format
|
||||
"""
|
||||
if isinstance(resource_path, list):
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
||||
assert all(isinstance(img_pil, Image.Image) for img_pil in resource_path)
|
||||
assert len(resource_path) is not None
|
||||
@@ -60,6 +62,8 @@ def load_resource_as_video_frames(
|
||||
# float16 precision should be sufficient for image tensor storage
|
||||
img = img.to(dtype=torch.float16)
|
||||
# normalize by mean and std
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[bool, complex, float,
|
||||
# int, Tensor]` but got `Tuple[float, float, float]`.
|
||||
img -= img_mean
|
||||
img /= img_std
|
||||
images.append(img)
|
||||
@@ -103,10 +107,13 @@ def load_image_as_single_frame_video(
|
||||
images, image_height, image_width = _load_img_as_tensor(image_path, image_size)
|
||||
images = images.unsqueeze(0).half()
|
||||
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
||||
if not offload_video_to_cpu:
|
||||
images = images.cuda()
|
||||
# pyre-fixme[16]: `Tuple` has no attribute `cuda`.
|
||||
img_mean = img_mean.cuda()
|
||||
img_std = img_std.cuda()
|
||||
# normalize by mean and std
|
||||
@@ -335,15 +342,19 @@ def load_video_frames_from_video_file_using_cv2(
|
||||
frames_np = np.stack(frames, axis=0).astype(np.float32) # (T, H, W, C)
|
||||
video_tensor = torch.from_numpy(frames_np).permute(0, 3, 1, 2) # (T, C, H, W)
|
||||
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1)
|
||||
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
|
||||
img_std = torch.tensor(img_std, dtype=torch.float16).view(1, 3, 1, 1)
|
||||
if not offload_video_to_cpu:
|
||||
video_tensor = video_tensor.cuda()
|
||||
# pyre-fixme[16]: `tuple` has no attribute `cuda`.
|
||||
img_mean = img_mean.cuda()
|
||||
img_std = img_std.cuda()
|
||||
# normalize by mean and std
|
||||
video_tensor -= img_mean
|
||||
video_tensor /= img_std
|
||||
# pyre-fixme[7]: Expected `Tensor` but got `Tuple[Any, int, int]`.
|
||||
return video_tensor, original_height, original_width
|
||||
|
||||
|
||||
@@ -367,7 +378,10 @@ def _load_img_as_tensor(
|
||||
"""Load and resize an image and convert it into a PyTorch tensor."""
|
||||
img = Image.open(img_path).convert("RGB")
|
||||
orig_width, orig_height = img.width, img.height
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Image`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[int]` but got `Tuple[int, int]`.
|
||||
img = TF.resize(img, size=(image_size, image_size))
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[Image, ndarray]` but got `Tensor`.
|
||||
img = TF.to_tensor(img)
|
||||
return img, orig_height, orig_width
|
||||
|
||||
@@ -449,6 +463,7 @@ class TorchCodecDecoder:
|
||||
device: str = "cpu",
|
||||
num_threads: int = 1,
|
||||
) -> None:
|
||||
# pyre-fixme[21]: Could not find module `torchcodec`.
|
||||
from torchcodec import _core as core
|
||||
|
||||
self._source = source # hold a reference to the source to prevent it from GC
|
||||
@@ -573,16 +588,26 @@ class AsyncVideoFileLoaderWithTorchCodec:
|
||||
self.img_std = img_std
|
||||
|
||||
if gpu_acceleration:
|
||||
# pyre-fixme[16]: Item `Tuple` of `Tensor | Tuple[float, float, float]`
|
||||
# has no attribute `to`.
|
||||
self.img_mean = self.img_mean.to(f"cuda:{self.gpu_id}")
|
||||
# pyre-fixme[16]: Item `Tuple` of `Tensor | Tuple[float, float, float]`
|
||||
# has no attribute `to`.
|
||||
self.img_std = self.img_std.to(f"cuda:{self.gpu_id}")
|
||||
decoder_option = {"device": f"cuda:{self.gpu_id}"}
|
||||
else:
|
||||
# pyre-fixme[16]: Item `Tuple` of `Tensor | Tuple[float, float, float]`
|
||||
# has no attribute `cpu`.
|
||||
self.img_mean = self.img_mean.cpu()
|
||||
# pyre-fixme[16]: Item `Tuple` of `Tensor | Tuple[float, float, float]`
|
||||
# has no attribute `cpu`.
|
||||
self.img_std = self.img_std.cpu()
|
||||
decoder_option = {"num_threads": 1} # use a single thread to save memory
|
||||
|
||||
self.rank = int(os.environ.get("RANK", "0"))
|
||||
self.world_size = int(os.environ.get("WORLD_SIZE", "1"))
|
||||
# pyre-fixme[6]: For 2nd argument expected `int` but got `Union[int, str]`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `str` but got `Union[int, str]`.
|
||||
self.async_reader = TorchCodecDecoder(video_path, **decoder_option)
|
||||
|
||||
# `num_frames_from_content` is the true number of frames in the video content
|
||||
@@ -747,10 +772,14 @@ class AsyncVideoFileLoaderWithTorchCodec:
|
||||
# release a few objects that cannot be pickled
|
||||
reader = self.async_reader
|
||||
if reader is not None:
|
||||
# pyre-fixme[8]: Attribute has type `Union[bytes, str]`; used as `None`.
|
||||
reader._source = None
|
||||
# pyre-fixme[8]: Attribute has type `TorchCodecDecoder`; used as `None`.
|
||||
self.async_reader = None
|
||||
# pyre-fixme[16]: `AsyncVideoFileLoaderWithTorchCodec` has no attribute `pbar`.
|
||||
self.pbar = None
|
||||
self.thread = None
|
||||
self.rand_seek_idx_queue = None
|
||||
# pyre-fixme[8]: Attribute has type `FIFOLock`; used as `nullcontext[None]`.
|
||||
self.torchcodec_access_lock = contextlib.nullcontext()
|
||||
return self.__dict__.copy()
|
||||
|
||||
@@ -279,6 +279,8 @@ class UniversalSegmentationHead(SegmentationHead):
|
||||
self.pixel_decoder.out_dim, self.d_model, kernel_size=1
|
||||
)
|
||||
|
||||
# pyre-fixme[15]: `forward` overrides method defined in `SegmentationHead`
|
||||
# inconsistently.
|
||||
def forward(
|
||||
self,
|
||||
backbone_feats: List[torch.Tensor],
|
||||
|
||||
@@ -206,4 +206,5 @@ class SimpleMaskEncoder(nn.Module):
|
||||
|
||||
pos = self.position_encoding(x).to(x.dtype)
|
||||
|
||||
# pyre-fixme[7]: Expected `Tuple[Tensor, Tensor]` but got `Dict[str, Any]`.
|
||||
return {"vision_features": x, "vision_pos_enc": [pos]}
|
||||
|
||||
@@ -21,6 +21,7 @@ from torch.overrides import handle_torch_function, has_torch_function
|
||||
from typing_extensions import override
|
||||
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `xformers`.
|
||||
import xformers
|
||||
except ImportError:
|
||||
xformers = None
|
||||
@@ -112,6 +113,7 @@ def multi_head_attention_forward(
|
||||
static_v: Optional[Tensor] = None,
|
||||
average_attn_weights: bool = True,
|
||||
is_causal: bool = False,
|
||||
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
|
||||
attn_type: AttentionType = AttentionType.Vanilla,
|
||||
attn_sparsity: float = 0.0,
|
||||
attn_bias: Optional[Tensor] = None,
|
||||
@@ -208,6 +210,7 @@ def multi_head_attention_forward(
|
||||
assert in_proj_weight is not None, (
|
||||
"use_separate_proj_weight is False but in_proj_weight is None"
|
||||
)
|
||||
# pyre-fixme[16]: Module `functional` has no attribute `_in_projection_packed`.
|
||||
q, k, v = F._in_projection_packed(
|
||||
query, key, value, in_proj_weight, in_proj_bias
|
||||
)
|
||||
@@ -225,6 +228,7 @@ def multi_head_attention_forward(
|
||||
b_q = b_k = b_v = None
|
||||
else:
|
||||
b_q, b_k, b_v = in_proj_bias.chunk(3)
|
||||
# pyre-fixme[16]: Module `functional` has no attribute `_in_projection`.
|
||||
q, k, v = F._in_projection(
|
||||
query,
|
||||
key,
|
||||
@@ -468,6 +472,7 @@ class MultiheadAttention(nn.Module):
|
||||
batch_first=False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
|
||||
attn_type: AttentionType = AttentionType.Vanilla,
|
||||
sparsity: float = 0.0,
|
||||
use_act_checkpoint: bool = False,
|
||||
@@ -992,6 +997,7 @@ class SAM3Output(list):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
# pyre-fixme[9]: output has type `List[List[Dict[Any, Any]]]`; used as `None`.
|
||||
output: List[List[Dict]] = None,
|
||||
iter_mode: IterMode = IterMode.ALL_STEPS_PER_STAGE,
|
||||
loss_stages: Optional[List[int]] = None,
|
||||
@@ -1025,6 +1031,7 @@ class SAM3Output(list):
|
||||
self.loss_stages = loss_stages
|
||||
|
||||
@override
|
||||
# pyre-fixme[14]: `__iter__` overrides method defined in `list` inconsistently.
|
||||
def __iter__(self) -> Iterator:
|
||||
return self._mode2iter[self.iter_mode]()
|
||||
|
||||
|
||||
@@ -315,6 +315,7 @@ class MultiplexMaskDecoder(nn.Module):
|
||||
upscaled_embedding = self.output_upscaling(src)
|
||||
else:
|
||||
dc1, ln1, act1, dc2, act2 = self.output_upscaling
|
||||
# pyre-fixme[23]: Unable to unpack `list[Tensor] | None` into 2 values.
|
||||
feat_s0, feat_s1 = high_res_features
|
||||
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
|
||||
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
|
||||
@@ -345,6 +346,7 @@ class MultiplexMaskDecoder(nn.Module):
|
||||
|
||||
# generate the masks
|
||||
b, c, h, w = upscaled_embedding.shape
|
||||
# pyre-fixme[19]: Expected 1 positional argument.
|
||||
masks = torch.bmm(
|
||||
hyper_in.flatten(1, 2), upscaled_embedding.view(b, c, h * w)
|
||||
).view(b, self.multiplex_count, self.num_mask_output_per_object, h, w)
|
||||
@@ -361,11 +363,15 @@ class MultiplexMaskDecoder(nn.Module):
|
||||
and not self.decode_mask_with_shared_tokens
|
||||
):
|
||||
object_score_logits = (
|
||||
# pyre-fixme[61]: `obj_score_token_out` is undefined, or not
|
||||
# always defined.
|
||||
self.pred_obj_score_head(obj_score_token_out)
|
||||
.view(b, self.multiplex_count, self.num_mask_output_per_object)
|
||||
.sum(-1, keepdim=True)
|
||||
)
|
||||
else:
|
||||
# pyre-fixme[61]: `obj_score_token_out` is undefined, or not always
|
||||
# defined.
|
||||
object_score_logits = self.pred_obj_score_head(obj_score_token_out)
|
||||
else:
|
||||
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
|
||||
|
||||
@@ -322,6 +322,8 @@ class MultiplexState:
|
||||
self.object_ids = new_object_ids
|
||||
|
||||
# Reinitialize the state to update all internal structures
|
||||
# pyre-fixme[6]: For 2nd argument expected `Optional[List[int]]` but got
|
||||
# `Optional[List[None]]`.
|
||||
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
|
||||
|
||||
logger.info(f"Removed these buckets: {buckets_to_remove}")
|
||||
@@ -338,6 +340,8 @@ class MultiplexState:
|
||||
Note that these should be partial permutation matrices.
|
||||
"""
|
||||
# Create a transition matrix for muxing
|
||||
# pyre-fixme[16]: `MultiplexState` has no attribute `mux_matrix`.
|
||||
# pyre-fixme[19]: Expected 1 positional argument.
|
||||
self.mux_matrix = torch.zeros(
|
||||
self.num_buckets * self.multiplex_count,
|
||||
self.total_valid_entries,
|
||||
@@ -346,6 +350,7 @@ class MultiplexState:
|
||||
)
|
||||
|
||||
# Create a transition matrix for demuxing
|
||||
# pyre-fixme[16]: `MultiplexState` has no attribute `demux_matrix`.
|
||||
self.demux_matrix = torch.zeros(
|
||||
self.total_valid_entries,
|
||||
self.num_buckets * self.multiplex_count,
|
||||
@@ -383,6 +388,7 @@ class MultiplexState:
|
||||
|
||||
# Apply mux matrix: (num_buckets * multiplex_count, batch_size) @ (batch_size, features)
|
||||
# Result: (num_buckets * multiplex_count, features)
|
||||
# pyre-fixme[16]: `MultiplexState` has no attribute `mux_matrix`.
|
||||
result_flat = self.mux_matrix @ x_flat
|
||||
|
||||
result = result_flat.view(output_shape)
|
||||
@@ -405,6 +411,7 @@ class MultiplexState:
|
||||
|
||||
# Apply demux matrix: (total_valid_entries, num_buckets*multiplex_count) @ (num_buckets*multiplex_count, features)
|
||||
# Result: (total_valid_entries, features)
|
||||
# pyre-fixme[16]: `MultiplexState` has no attribute `demux_matrix`.
|
||||
result_flat = self.demux_matrix @ x_flat
|
||||
|
||||
result = result_flat.view(output_shape)
|
||||
@@ -414,6 +421,7 @@ class MultiplexState:
|
||||
"""
|
||||
Returns a (num_buckets, multiplex_count) tensor with 1 for valid entries and 0 for padding entries
|
||||
"""
|
||||
# pyre-fixme[16]: `MultiplexState` has no attribute `mux_matrix`.
|
||||
valid_mask = self.mux_matrix.sum(dim=1) > 0
|
||||
valid_mask = valid_mask.reshape(self.num_buckets, self.multiplex_count)
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ class Sam3DualViTDetNeck(nn.Module):
|
||||
|
||||
self.scale_factors = scale_factors
|
||||
use_bias = True
|
||||
# pyre-fixme[29]: `Union[(TensorBase, Union[None, slice[Any, Any, Any], _Nest...
|
||||
dim: int = self.trunk.channel_list[-1]
|
||||
|
||||
for _, scale in enumerate(scale_factors):
|
||||
@@ -122,6 +123,7 @@ class Sam3DualViTDetNeck(nn.Module):
|
||||
if self.sam2_convs is not None:
|
||||
sam2_x_out = self.sam2_convs[i](x)
|
||||
sam2_pos_out = self.position_encoding(sam2_x_out).to(sam2_x_out.dtype)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `append`.
|
||||
sam2_out.append(sam2_x_out)
|
||||
sam2_pos.append(sam2_pos_out)
|
||||
return sam3_out, sam3_pos, sam2_out, sam2_pos
|
||||
@@ -146,6 +148,7 @@ class Sam3TriViTDetNeck(nn.Module):
|
||||
|
||||
self.scale_factors = scale_factors
|
||||
use_bias = neck_norm is None
|
||||
# pyre-fixme[29]: `Union[(TensorBase, Union[None, slice[Any, Any, Any], _Nest...
|
||||
dim = self.trunk.channel_list[-1]
|
||||
|
||||
for _, scale in enumerate(scale_factors):
|
||||
|
||||
@@ -166,9 +166,13 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
||||
|
||||
def predict_batch(
|
||||
self,
|
||||
# pyre-fixme[9]: point_coords_batch has type `List[ndarray]`; used as `None`.
|
||||
point_coords_batch: List[np.ndarray] = None,
|
||||
# pyre-fixme[9]: point_labels_batch has type `List[ndarray]`; used as `None`.
|
||||
point_labels_batch: List[np.ndarray] = None,
|
||||
# pyre-fixme[9]: box_batch has type `List[ndarray]`; used as `None`.
|
||||
box_batch: List[np.ndarray] = None,
|
||||
# pyre-fixme[9]: mask_input_batch has type `List[ndarray]`; used as `None`.
|
||||
mask_input_batch: List[np.ndarray] = None,
|
||||
multimask_output: bool = True,
|
||||
return_logits: bool = False,
|
||||
@@ -389,6 +393,8 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
||||
# boxes are added at the beginning) to sam_prompt_encoder
|
||||
if concat_points is not None:
|
||||
concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
|
||||
concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
|
||||
concat_points = (concat_coords, concat_labels)
|
||||
else:
|
||||
|
||||
@@ -404,6 +404,8 @@ class Sam3BasePredictor:
|
||||
f"{post_gpu_mem['reserved_bytes']} bytes)"
|
||||
)
|
||||
gpu_mem = post_gpu_mem
|
||||
# pyre-fixme[6]: For 2nd argument expected `bool` but got `Dict[Any,
|
||||
# Any]`.
|
||||
result["gpu_mem"] = gpu_mem
|
||||
logger.info(f"removed session {session_id}")
|
||||
return result
|
||||
|
||||
@@ -55,6 +55,8 @@ class Sam3Image(torch.nn.Module):
|
||||
detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score
|
||||
separate_scorer_for_instance: bool = False,
|
||||
num_interactive_steps_val: int = 0,
|
||||
# pyre-fixme[9]: inst_interactive_predictor has type
|
||||
# `SAM3InteractiveImagePredictor`; used as `None`.
|
||||
inst_interactive_predictor: SAM3InteractiveImagePredictor = None,
|
||||
**kwargs,
|
||||
):
|
||||
@@ -527,6 +529,8 @@ class Sam3Image(torch.nn.Module):
|
||||
point_embeddings, point_mask, point_labels = None, None, None
|
||||
if find_input.input_points_before_embed is not None:
|
||||
# Point embeddings are batch first, switch to seq first
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute
|
||||
# `transpose`.
|
||||
point_embeddings = find_input.input_points_before_embed.transpose(0, 1)
|
||||
|
||||
# they are stored as (x,y,label), so we unpack
|
||||
@@ -569,6 +573,7 @@ class Sam3Image(torch.nn.Module):
|
||||
find_input = input.find_inputs[0]
|
||||
find_target = input.find_targets[0]
|
||||
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute `numel`.
|
||||
if find_input.input_points is not None and find_input.input_points.numel() > 0:
|
||||
print("Warning: Point prompts are ignored in PCS.")
|
||||
|
||||
@@ -584,6 +589,8 @@ class Sam3Image(torch.nn.Module):
|
||||
for cur_step in range(num_interactive_steps + 1):
|
||||
if cur_step > 0:
|
||||
# We sample interactive geometric prompts (boxes, points)
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no
|
||||
# attribute `sample`.
|
||||
geometric_prompt, _ = self.interactive_prompt_sampler.sample(
|
||||
geo_prompt=geometric_prompt,
|
||||
find_target=find_target,
|
||||
@@ -784,6 +791,8 @@ class Sam3ImageOnVideoMultiGPU(Sam3Image):
|
||||
else:
|
||||
frame_idx_prev_b = frame_idx_prev_e = None
|
||||
if frame_idx_prev_b is not None:
|
||||
# pyre-fixme[6]: For 2nd argument expected `SupportsIndex` but got
|
||||
# `Optional[int]`.
|
||||
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
|
||||
multigpu_buffer.pop(frame_idx_rm, None)
|
||||
|
||||
@@ -888,9 +897,16 @@ class Sam3ImageOnVideoMultiGPU(Sam3Image):
|
||||
}
|
||||
if self.gather_backbone_out:
|
||||
# also add gathered SAM 2 backbone features to frame_buffer
|
||||
# pyre-fixme[61]: `fpn0` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle0` is undefined, or not always defined.
|
||||
frame_buffer["tracker_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
|
||||
# pyre-fixme[61]: `fpn1` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle1` is undefined, or not always defined.
|
||||
frame_buffer["tracker_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
|
||||
# pyre-fixme[61]: `fpn2` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle2` is undefined, or not always defined.
|
||||
frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
|
||||
# pyre-fixme[61]: `vision_pos_enc` is undefined, or not always defined.
|
||||
frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None)
|
||||
|
||||
multigpu_buffer[frame_idx_to_save] = frame_buffer
|
||||
|
||||
@@ -210,6 +210,8 @@ class Sam3Processor:
|
||||
|
||||
out_masks = interpolate(
|
||||
out_masks.unsqueeze(1),
|
||||
# pyre-fixme[6]: For 2nd argument expected `Optional[List[int]]` but got
|
||||
# `Tuple[Any, Any]`.
|
||||
(img_h, img_w),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
|
||||
@@ -427,6 +427,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
self._profiling_enabled = False
|
||||
os.environ["ENABLE_PROFILING"] = "0"
|
||||
|
||||
# pyre-fixme[14]: `_det_track_one_frame` overrides method defined in
|
||||
# `Sam3VideoBase` inconsistently.
|
||||
def _det_track_one_frame(
|
||||
self,
|
||||
frame_idx: int,
|
||||
@@ -636,6 +638,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
tracker_obj_scores_global, # a dict: obj_id --> sam2 frame-level scores
|
||||
)
|
||||
|
||||
# pyre-fixme[14]: `run_backbone_and_detection` overrides method defined in
|
||||
# `Sam3VideoBase` inconsistently.
|
||||
def run_backbone_and_detection(
|
||||
self,
|
||||
frame_idx: int,
|
||||
@@ -786,6 +790,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
|
||||
with torch.profiler.record_function("run_backbone_and_detection.feature_cache"):
|
||||
feature_cache[frame_idx] = (
|
||||
# pyre-fixme[16]: `Tensor` has no attribute `tensors`.
|
||||
input_batch.img_batch.tensors[frame_idx],
|
||||
backbone_cache,
|
||||
)
|
||||
@@ -847,6 +852,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
obj_scores_global = obj_scores_local
|
||||
return low_res_masks_global, obj_scores_global
|
||||
|
||||
# pyre-fixme[14]: `_recondition_masklets` overrides method defined in
|
||||
# `Sam3VideoBase` inconsistently.
|
||||
def _recondition_masklets(
|
||||
self,
|
||||
frame_idx,
|
||||
@@ -991,6 +998,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
return x
|
||||
return deepcopy(x)
|
||||
|
||||
# pyre-fixme[14]: `run_tracker_update_planning_phase` overrides method defined
|
||||
# in `Sam3VideoBase` inconsistently.
|
||||
def run_tracker_update_planning_phase(
|
||||
self,
|
||||
frame_idx: int,
|
||||
@@ -1041,6 +1050,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
reverse=reverse,
|
||||
adt_result=adt_result, # Still lazy - no sync!
|
||||
tracker_metadata_prev=tracker_metadata_prev,
|
||||
# pyre-fixme[6]: For 5th argument expected `Dict[str,
|
||||
# Tensor]` but got `ndarray`.
|
||||
gpu_metadata_prev=tracker_metadata_prev["gpu_metadata"],
|
||||
)
|
||||
)
|
||||
@@ -1384,6 +1395,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
}
|
||||
return sam2_update_plan, tracker_metadata_new
|
||||
|
||||
# pyre-fixme[14]: `_suppress_overlapping_based_on_recent_occlusion` overrides
|
||||
# method defined in `Sam3VideoBase` inconsistently.
|
||||
def _suppress_overlapping_based_on_recent_occlusion(
|
||||
self,
|
||||
frame_idx: int,
|
||||
@@ -1502,6 +1515,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
total_buckets += state["multiplex_state"].num_buckets
|
||||
return total_buckets
|
||||
|
||||
# pyre-fixme[14]: `build_outputs` overrides method defined in `Sam3VideoBase`
|
||||
# inconsistently.
|
||||
def build_outputs(
|
||||
self,
|
||||
frame_idx: int,
|
||||
@@ -1516,7 +1531,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
sam2_update_plan: Dict[str, np.ndarray],
|
||||
orig_vid_height: int,
|
||||
orig_vid_width: int,
|
||||
# pyre-fixme[9]: reconditioned_obj_ids has type `Set[Any]`; used as `None`.
|
||||
reconditioned_obj_ids: set = None,
|
||||
# pyre-fixme[9]: det_to_matched_trk_obj_ids has type `Dict[Any, Any]`; used
|
||||
# as `None`.
|
||||
det_to_matched_trk_obj_ids: dict = None,
|
||||
):
|
||||
new_det_fa_inds: np.ndarray = sam2_update_plan["new_det_fa_inds"]
|
||||
@@ -1588,11 +1606,14 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
|
||||
return obj_id_to_mask
|
||||
|
||||
# pyre-fixme[14]: `_get_objects_to_suppress_based_on_most_recently_occluded`
|
||||
# overrides method defined in `Sam3VideoBase` inconsistently.
|
||||
def _get_objects_to_suppress_based_on_most_recently_occluded(
|
||||
self,
|
||||
binary_low_res_masks: Tensor,
|
||||
last_occluded: Tensor, # GPU tensor (N_obj,) with frame indices
|
||||
obj_ids: np.ndarray, # numpy array of object IDs
|
||||
# pyre-fixme[9]: frame_idx has type `int`; used as `None`.
|
||||
frame_idx: int = None,
|
||||
reverse: bool = False,
|
||||
):
|
||||
@@ -1659,6 +1680,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
):
|
||||
suppress_i_mask = suppress_i_mask.cpu().numpy()
|
||||
suppress_j_mask = suppress_j_mask.cpu().numpy()
|
||||
# pyre-fixme[9]: last_occluded has type `Tensor`; used as `ndarray`.
|
||||
last_occluded = last_occluded.cpu().numpy()
|
||||
|
||||
# Find all suppression pairs without using torch.where
|
||||
@@ -1723,13 +1745,17 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
num_frames_propagated += 1
|
||||
|
||||
# only 1 frames should be propagated
|
||||
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
|
||||
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
|
||||
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
|
||||
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
|
||||
)
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
assert isinstance(out_obj_ids, list)
|
||||
# Optionally filter to a subset of object ids (for partial propagation).
|
||||
# We also clamp indices to available rows to avoid CUDA index_select assertions.
|
||||
if filter_obj_ids is not None:
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
if len(out_obj_ids) > 0:
|
||||
max_mask_rows = out_low_res_masks.shape[0]
|
||||
max_score_rows = out_obj_scores.shape[0]
|
||||
@@ -1745,6 +1771,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
else:
|
||||
keep_indices = [
|
||||
i
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not
|
||||
# always defined.
|
||||
for i, oid in enumerate(out_obj_ids)
|
||||
if oid in filter_obj_ids
|
||||
and i < max_mask_rows
|
||||
@@ -1767,7 +1795,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
# no selected objects in this local state; skip appending
|
||||
out_obj_ids = []
|
||||
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
if len(out_obj_ids) > 0:
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
obj_ids_local.extend(out_obj_ids)
|
||||
low_res_masks_list.append(out_low_res_masks.squeeze(1))
|
||||
obj_scores_list.append(out_obj_scores.squeeze(1))
|
||||
@@ -1833,6 +1863,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
|
||||
return obj_ids_local, low_res_masks_local, obj_scores_local
|
||||
|
||||
# pyre-fixme[14]: `_associate_det_trk` overrides method defined in
|
||||
# `Sam3VideoBase` inconsistently.
|
||||
def _associate_det_trk(
|
||||
self,
|
||||
det_masks: Tensor,
|
||||
@@ -2058,6 +2090,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
if isinstance(adt_result, RealizedAssociateDetTrkresult):
|
||||
# No tracks exist, so no objects to remove/suppress
|
||||
empty_mask = torch.zeros(0, dtype=torch.bool, device=self.device)
|
||||
# pyre-fixme[7]: Expected `Tuple[Tensor, Tensor, Dict[str, Tensor]]` but
|
||||
# got `Tuple[Tensor, Tensor, Dict[str, int]]`.
|
||||
return empty_mask, empty_mask, {"N_obj": 0}
|
||||
|
||||
device = adt_result.trk_is_unmatched.device
|
||||
@@ -2432,6 +2466,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
removed_obj_ids.update(obj_ids_newly_removed)
|
||||
return obj_ids_newly_removed, rank0_metadata
|
||||
|
||||
# pyre-fixme[14]: `_tracker_update_memories` overrides method defined in
|
||||
# `Sam3VideoBase` inconsistently.
|
||||
def _tracker_update_memories(
|
||||
self,
|
||||
sam2_inference_states: List[Any],
|
||||
@@ -2501,6 +2537,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
# Get the local high-res masks and object score logits for this inference state
|
||||
if self.is_multiplex and self.tracker.is_multiplex_dynamic:
|
||||
local_idx = (
|
||||
# pyre-fixme[61]: `object_idx_assignment` is undefined, or not
|
||||
# always defined.
|
||||
torch.tensor(object_idx_assignment[state_i])
|
||||
.pin_memory()
|
||||
.to(device=high_res_masks.device, non_blocking=True)
|
||||
@@ -2547,9 +2585,13 @@ class Sam3MultiplexBase(Sam3VideoBase):
|
||||
]
|
||||
if self.is_multiplex:
|
||||
output_dict[storage_key][frame_idx]["image_features"] = (
|
||||
# pyre-fixme[61]: `local_image_features` is undefined, or
|
||||
# not always defined.
|
||||
local_image_features
|
||||
)
|
||||
output_dict[storage_key][frame_idx]["image_pos_enc"] = (
|
||||
# pyre-fixme[61]: `local_image_pos_enc` is undefined, or not
|
||||
# always defined.
|
||||
local_image_pos_enc
|
||||
)
|
||||
|
||||
|
||||
@@ -135,7 +135,9 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
# Generate img_ids based on chunk frame indices
|
||||
# Each frame in the chunk gets its corresponding frame index
|
||||
# The modulo for circular buffer access is handled in _get_img_feats
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute `device`.
|
||||
device = chunk_find_inputs[0].img_ids.device
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute `dtype`.
|
||||
dtype = chunk_find_inputs[0].img_ids.dtype
|
||||
img_ids_list = [
|
||||
torch.tensor([i], device=device, dtype=dtype)
|
||||
@@ -149,11 +151,15 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
|
||||
# Concatenate text_ids
|
||||
text_ids_list = [fi.text_ids for fi in chunk_find_inputs]
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
batched_text_ids = torch.cat(text_ids_list, dim=0)
|
||||
|
||||
# Concatenate input_boxes
|
||||
input_boxes_list = [fi.input_boxes for fi in chunk_find_inputs]
|
||||
batched_input_boxes = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
torch.cat(input_boxes_list, dim=0)
|
||||
if input_boxes_list[0] is not None
|
||||
else None
|
||||
@@ -162,6 +168,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
# Concatenate input_boxes_mask
|
||||
input_boxes_mask_list = [fi.input_boxes_mask for fi in chunk_find_inputs]
|
||||
batched_input_boxes_mask = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
torch.cat(input_boxes_mask_list, dim=0)
|
||||
if input_boxes_mask_list[0] is not None
|
||||
else None
|
||||
@@ -170,6 +178,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
# Concatenate input_boxes_label
|
||||
input_boxes_label_list = [fi.input_boxes_label for fi in chunk_find_inputs]
|
||||
batched_input_boxes_label = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
torch.cat(input_boxes_label_list, dim=0)
|
||||
if input_boxes_label_list[0] is not None
|
||||
else None
|
||||
@@ -178,6 +188,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
# Concatenate input_points
|
||||
input_points_list = [fi.input_points for fi in chunk_find_inputs]
|
||||
batched_input_points = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
torch.cat(input_points_list, dim=0)
|
||||
if input_points_list[0] is not None
|
||||
else None
|
||||
@@ -186,6 +198,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
# Concatenate input_points_mask
|
||||
input_points_mask_list = [fi.input_points_mask for fi in chunk_find_inputs]
|
||||
batched_input_points_mask = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[List[Any], Tensor]]`.
|
||||
torch.cat(input_points_mask_list, dim=0)
|
||||
if input_points_mask_list[0] is not None
|
||||
else None
|
||||
@@ -196,6 +210,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
fi.input_boxes_before_embed for fi in chunk_find_inputs
|
||||
]
|
||||
batched_input_boxes_before_embed = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[None, List[Any], Tensor]]`.
|
||||
torch.cat(input_boxes_before_embed_list, dim=0)
|
||||
if input_boxes_before_embed_list[0] is not None
|
||||
else None
|
||||
@@ -205,6 +221,8 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
fi.input_points_before_embed for fi in chunk_find_inputs
|
||||
]
|
||||
batched_input_points_before_embed = (
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[None, List[Any], Tensor]]`.
|
||||
torch.cat(input_points_before_embed_list, dim=0)
|
||||
if input_points_before_embed_list[0] is not None
|
||||
else None
|
||||
@@ -215,10 +233,20 @@ class Sam3MultiplexImageBase(Sam3Image):
|
||||
img_ids=batched_img_ids,
|
||||
img_ids_np=batched_img_ids_np,
|
||||
text_ids=batched_text_ids,
|
||||
# pyre-fixme[6]: For 4th argument expected `Union[List[Any], Tensor]`
|
||||
# but got `Optional[Tensor]`.
|
||||
input_boxes=batched_input_boxes,
|
||||
# pyre-fixme[6]: For 5th argument expected `Union[List[Any], Tensor]`
|
||||
# but got `Optional[Tensor]`.
|
||||
input_boxes_mask=batched_input_boxes_mask,
|
||||
# pyre-fixme[6]: For 6th argument expected `Union[List[Any], Tensor]`
|
||||
# but got `Optional[Tensor]`.
|
||||
input_boxes_label=batched_input_boxes_label,
|
||||
# pyre-fixme[6]: For 7th argument expected `Union[List[Any], Tensor]`
|
||||
# but got `Optional[Tensor]`.
|
||||
input_points=batched_input_points,
|
||||
# pyre-fixme[6]: For 8th argument expected `Union[List[Any], Tensor]`
|
||||
# but got `Optional[Tensor]`.
|
||||
input_points_mask=batched_input_points_mask,
|
||||
ptrs=None, # Not batching pointers for now
|
||||
ptrs_seg=None,
|
||||
@@ -522,7 +550,11 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
|
||||
prob_threshold=nms_prob_thresh,
|
||||
iou_threshold=nms_iou_thresh,
|
||||
nms_use_iom=nms_use_iom,
|
||||
# pyre-fixme[6]: For 6th argument expected `bool` but got
|
||||
# `Union[Tensor, Module]`.
|
||||
do_compile=getattr(self, "compile_model", False),
|
||||
# pyre-fixme[6]: For 7th argument expected `bool` but got
|
||||
# `Union[Tensor, Module]`.
|
||||
running_in_prod=getattr(self, "running_in_prod", False),
|
||||
)
|
||||
# set a very low threshold for those detections removed by NMS
|
||||
@@ -596,24 +628,45 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
|
||||
# also add gathered SAM 2 backbone features to frame_buffer
|
||||
if self.is_multiplex:
|
||||
frame_buffer["interactive_backbone_fpn_0"] = (
|
||||
# pyre-fixme[61]: `inte_fpn0` is undefined, or not always
|
||||
# defined.
|
||||
inte_fpn0[rank],
|
||||
# pyre-fixme[61]: `inte_fpn_handle0` is undefined, or not
|
||||
# always defined.
|
||||
inte_fpn_handle0,
|
||||
)
|
||||
frame_buffer["interactive_backbone_fpn_1"] = (
|
||||
# pyre-fixme[61]: `inte_fpn1` is undefined, or not always
|
||||
# defined.
|
||||
inte_fpn1[rank],
|
||||
# pyre-fixme[61]: `inte_fpn_handle1` is undefined, or not
|
||||
# always defined.
|
||||
inte_fpn_handle1,
|
||||
)
|
||||
frame_buffer["interactive_backbone_fpn_2"] = (
|
||||
# pyre-fixme[61]: `inte_fpn2` is undefined, or not always
|
||||
# defined.
|
||||
inte_fpn2[rank],
|
||||
# pyre-fixme[61]: `inte_fpn_handle2` is undefined, or not
|
||||
# always defined.
|
||||
inte_fpn_handle2,
|
||||
)
|
||||
frame_buffer["interactive_backbone_pos_enc"] = (
|
||||
# pyre-fixme[61]: `inte_vision_pos_enc` is undefined, or not
|
||||
# always defined.
|
||||
inte_vision_pos_enc,
|
||||
None,
|
||||
)
|
||||
# pyre-fixme[61]: `fpn0` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle0` is undefined, or not always defined.
|
||||
frame_buffer["sam2_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
|
||||
# pyre-fixme[61]: `fpn1` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle1` is undefined, or not always defined.
|
||||
frame_buffer["sam2_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
|
||||
# pyre-fixme[61]: `fpn2` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `fpn_handle2` is undefined, or not always defined.
|
||||
frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
|
||||
# pyre-fixme[61]: `vision_pos_enc` is undefined, or not always defined.
|
||||
frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None)
|
||||
|
||||
multigpu_buffer[frame_idx_to_save] = frame_buffer
|
||||
@@ -812,7 +865,11 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
|
||||
prob_threshold=nms_prob_thresh,
|
||||
iou_threshold=nms_iou_thresh,
|
||||
nms_use_iom=nms_use_iom,
|
||||
# pyre-fixme[6]: For 6th argument expected `bool` but got
|
||||
# `Union[Tensor, Module]`.
|
||||
do_compile=getattr(self, "compile_model", False),
|
||||
# pyre-fixme[6]: For 7th argument expected `bool` but got
|
||||
# `Union[Tensor, Module]`.
|
||||
running_in_prod=getattr(self, "running_in_prod", False),
|
||||
)
|
||||
# Set a very low threshold for detections removed by NMS
|
||||
|
||||
@@ -7,6 +7,7 @@ from sam3 import perflib
|
||||
try:
|
||||
# Ronghang's generic GPU NMS implementation; install via
|
||||
# pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms
|
||||
# pyre-fixme[21]: Could not find module `torch_generic_nms`.
|
||||
from torch_generic_nms import generic_nms
|
||||
|
||||
GENERIC_NMS_AVAILABLE = True
|
||||
|
||||
@@ -2287,6 +2287,8 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
# pyre-fixme[14]: `propagate_in_video` overrides method defined in
|
||||
# `Sam3MultiplexTracking` inconsistently.
|
||||
def propagate_in_video(
|
||||
self,
|
||||
inference_state,
|
||||
@@ -2367,6 +2369,8 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
|
||||
self._prepare_backbone_feats(inference_state, frame_idx, reverse)
|
||||
obj_ids_local, low_res_masks_local, sam2_scores_local = (
|
||||
self._propogate_tracker_one_frame_local_gpu(
|
||||
# pyre-fixme[61]: `tracker_states_local` is undefined, or
|
||||
# not always defined.
|
||||
tracker_states_local,
|
||||
frame_idx=frame_idx,
|
||||
reverse=reverse,
|
||||
|
||||
@@ -52,6 +52,7 @@ def sample_box_points(
|
||||
|
||||
box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
|
||||
box_labels = box_labels.reshape(-1, 2)
|
||||
# pyre-fixme[7]: Expected `Tuple[ndarray, ndarray]` but got `Tuple[Any, Tensor]`.
|
||||
return box_coords, box_labels
|
||||
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ class MaskletConfirmationStatus(Enum):
|
||||
|
||||
@dataclass
|
||||
class RealizedAssociateDetTrkresult:
|
||||
# pyre-fixme[11]: Annotation `array` is not defined as a type.
|
||||
new_det_fa_inds: np.array
|
||||
unmatched_trk_obj_ids: np.array
|
||||
det_to_matched_trk_obj_ids: Dict[int, np.array]
|
||||
@@ -546,6 +547,8 @@ class Sam3VideoBase(nn.Module):
|
||||
# Step 1: if text feature is not cached in `feature_cache`, compute and cache it
|
||||
text_batch_key = tuple(input_batch.find_text_batch)
|
||||
if "text" not in feature_cache or text_batch_key not in feature_cache["text"]:
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
|
||||
# `forward_text`.
|
||||
text_outputs = self.detector.backbone.forward_text(
|
||||
input_batch.find_text_batch, device=self.device
|
||||
)
|
||||
@@ -565,6 +568,7 @@ class Sam3VideoBase(nn.Module):
|
||||
max_frame_num_to_track = tracking_bounds.get("max_frame_num_to_track")
|
||||
start_frame_idx = tracking_bounds.get("propagate_in_video_start_frame_idx")
|
||||
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
|
||||
backbone_out={
|
||||
"img_batch_all_stages": input_batch.img_batch,
|
||||
@@ -604,7 +608,11 @@ class Sam3VideoBase(nn.Module):
|
||||
backbone_cache = {}
|
||||
sam_mask_decoder = self.tracker.sam_mask_decoder
|
||||
tracker_backbone_fpn = [
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
|
||||
# `conv_s0`.
|
||||
sam_mask_decoder.conv_s0(sam3_image_out["tracker_backbone_fpn_0"]),
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
|
||||
# `conv_s1`.
|
||||
sam_mask_decoder.conv_s1(sam3_image_out["tracker_backbone_fpn_1"]),
|
||||
sam3_image_out["tracker_backbone_fpn_2"], # fpn_2 doesn't need conv
|
||||
]
|
||||
@@ -684,12 +692,16 @@ class Sam3VideoBase(nn.Module):
|
||||
tracker_obj_scores_global: Tensor,
|
||||
):
|
||||
# Recondition the masklets based on the new detections
|
||||
# pyre-fixme[16]: `List` has no attribute `items`.
|
||||
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
|
||||
new_mask = det_out["mask"][det_idx : det_idx + 1]
|
||||
input_mask_res = self.tracker.input_mask_size
|
||||
new_mask_binary = (
|
||||
F.interpolate(
|
||||
new_mask.unsqueeze(1),
|
||||
# pyre-fixme[6]: For 2nd argument expected `Union[None,
|
||||
# Sequence[int], int]` but got `Tuple[Union[Module, Tensor],
|
||||
# Union[Module, Tensor]]`.
|
||||
size=(input_mask_res, input_mask_res),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
@@ -712,6 +724,7 @@ class Sam3VideoBase(nn.Module):
|
||||
logger.debug(
|
||||
f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
|
||||
)
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.tracker.add_new_mask(
|
||||
inference_state=inference_state,
|
||||
frame_idx=frame_idx,
|
||||
@@ -721,6 +734,7 @@ class Sam3VideoBase(nn.Module):
|
||||
reconditioned_states_idx.add(state_idx)
|
||||
|
||||
for idx in reconditioned_states_idx:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.tracker.propagate_in_video_preflight(
|
||||
tracker_states_local[idx], run_mem_encoder=True
|
||||
)
|
||||
@@ -807,6 +821,8 @@ class Sam3VideoBase(nn.Module):
|
||||
new_det_obj_ids=new_det_obj_ids,
|
||||
empty_trk_obj_ids=empty_trk_obj_ids,
|
||||
unmatched_trk_obj_ids=unmatched_trk_obj_ids,
|
||||
# pyre-fixme[6]: For 8th argument expected `Dict[str, Any]` but
|
||||
# got `ndarray`.
|
||||
rank0_metadata=rank0_metadata_new,
|
||||
tracker_metadata=tracker_metadata_prev,
|
||||
)
|
||||
@@ -822,14 +838,27 @@ class Sam3VideoBase(nn.Module):
|
||||
# (it's a small array with length==self.world_size, so broadcasting it is cheap)
|
||||
num_obj_per_gpu_on_rank0 = tracker_metadata_prev["num_obj_per_gpu"]
|
||||
update_plan = [
|
||||
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
|
||||
new_det_fa_inds,
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
new_det_obj_ids,
|
||||
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
|
||||
new_det_gpu_ids,
|
||||
num_obj_per_gpu_on_rank0,
|
||||
# pyre-fixme[61]: `unmatched_trk_obj_ids` is undefined, or not
|
||||
# always defined.
|
||||
unmatched_trk_obj_ids,
|
||||
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
|
||||
# always defined.
|
||||
det_to_matched_trk_obj_ids,
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
|
||||
# always defined.
|
||||
obj_ids_newly_removed,
|
||||
# pyre-fixme[61]: `num_obj_dropped_due_to_limit` is undefined, or
|
||||
# not always defined.
|
||||
num_obj_dropped_due_to_limit,
|
||||
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or
|
||||
# not always defined.
|
||||
trk_id_to_max_iou_high_conf_det,
|
||||
]
|
||||
assert len(update_plan) == NUM_BROADCAST_ITEMS, (
|
||||
@@ -864,13 +893,26 @@ class Sam3VideoBase(nn.Module):
|
||||
|
||||
# `tracker_update_plan` should be identical on all GPUs after broadcasting
|
||||
tracker_update_plan = {
|
||||
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
|
||||
"new_det_fa_inds": new_det_fa_inds, # npt.NDArray
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
"new_det_obj_ids": new_det_obj_ids, # npt.NDArray
|
||||
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
|
||||
"new_det_gpu_ids": new_det_gpu_ids, # npt.NDArray
|
||||
# pyre-fixme[61]: `unmatched_trk_obj_ids` is undefined, or not always
|
||||
# defined.
|
||||
"unmatched_trk_obj_ids": unmatched_trk_obj_ids, # npt.NDArray
|
||||
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
|
||||
# always defined.
|
||||
"det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not always
|
||||
# defined.
|
||||
"obj_ids_newly_removed": obj_ids_newly_removed, # set
|
||||
# pyre-fixme[61]: `num_obj_dropped_due_to_limit` is undefined, or not
|
||||
# always defined.
|
||||
"num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
|
||||
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
|
||||
# always defined.
|
||||
"trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
|
||||
"reconditioned_obj_ids": reconditioned_obj_ids, # set
|
||||
}
|
||||
@@ -882,6 +924,8 @@ class Sam3VideoBase(nn.Module):
|
||||
# Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
|
||||
if (
|
||||
self.reconstruction_bbox_iou_thresh > 0
|
||||
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
|
||||
# always defined.
|
||||
and len(trk_id_to_max_iou_high_conf_det) > 0
|
||||
):
|
||||
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
|
||||
@@ -934,6 +978,8 @@ class Sam3VideoBase(nn.Module):
|
||||
should_recondition_periodic = (
|
||||
self.recondition_every_nth_frame > 0
|
||||
and frame_idx % self.recondition_every_nth_frame == 0
|
||||
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
|
||||
# always defined.
|
||||
and len(trk_id_to_max_iou_high_conf_det) > 0
|
||||
)
|
||||
|
||||
@@ -942,6 +988,8 @@ class Sam3VideoBase(nn.Module):
|
||||
self._recondition_masklets(
|
||||
frame_idx,
|
||||
det_out,
|
||||
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or
|
||||
# not always defined.
|
||||
trk_id_to_max_iou_high_conf_det,
|
||||
tracker_states_local,
|
||||
tracker_metadata_prev,
|
||||
@@ -961,6 +1009,8 @@ class Sam3VideoBase(nn.Module):
|
||||
tracker_low_res_masks_global,
|
||||
tracker_metadata_prev,
|
||||
tracker_metadata_new,
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined,
|
||||
# or not always defined.
|
||||
obj_ids_newly_removed,
|
||||
reverse,
|
||||
)
|
||||
@@ -977,15 +1027,24 @@ class Sam3VideoBase(nn.Module):
|
||||
# note: except for "rank0_metadata" (that is only available on GPU 0),
|
||||
# the updated `tracker_metadata_new` should be identical on all GPUs
|
||||
for rank in range(self.world_size):
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
|
||||
new_det_obj_ids_this_gpu = new_det_obj_ids[new_det_gpu_ids == rank]
|
||||
updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids_per_gpu"][rank]
|
||||
if len(new_det_obj_ids_this_gpu) > 0:
|
||||
updated_obj_ids_this_gpu = np.concatenate(
|
||||
[updated_obj_ids_this_gpu, new_det_obj_ids_this_gpu]
|
||||
)
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not always
|
||||
# defined.
|
||||
if len(obj_ids_newly_removed) > 0:
|
||||
is_removed = np.isin(
|
||||
updated_obj_ids_this_gpu, list(obj_ids_newly_removed)
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
|
||||
# always defined.
|
||||
updated_obj_ids_this_gpu,
|
||||
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
|
||||
# always defined.
|
||||
list(obj_ids_newly_removed),
|
||||
)
|
||||
updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
|
||||
tracker_metadata_new["obj_ids_per_gpu"][rank] = updated_obj_ids_this_gpu
|
||||
@@ -996,16 +1055,22 @@ class Sam3VideoBase(nn.Module):
|
||||
tracker_metadata_new["obj_ids_per_gpu"]
|
||||
)
|
||||
# update object scores and the maximum object ID assigned so far
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
if len(new_det_obj_ids) > 0:
|
||||
tracker_metadata_new["obj_id_to_score"].update(
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
|
||||
zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
|
||||
)
|
||||
# tracker scores are not available for new objects, use det score instead.
|
||||
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
|
||||
frame_idx
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
|
||||
].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
|
||||
tracker_metadata_new["max_obj_id"] = max(
|
||||
tracker_metadata_new["max_obj_id"],
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
np.max(new_det_obj_ids),
|
||||
)
|
||||
# for removed objects, we set their scores to a very low value (-1e4) but still
|
||||
@@ -1023,7 +1088,10 @@ class Sam3VideoBase(nn.Module):
|
||||
rank0_metadata=tracker_metadata_new["rank0_metadata"],
|
||||
obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids_all_gpu"],
|
||||
obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids_all_gpu"],
|
||||
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
|
||||
# always defined.
|
||||
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
|
||||
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
|
||||
new_det_obj_ids=new_det_obj_ids,
|
||||
)
|
||||
tracker_metadata_new["rank0_metadata"] = rank0_metadata
|
||||
@@ -1080,6 +1148,7 @@ class Sam3VideoBase(nn.Module):
|
||||
)
|
||||
to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
|
||||
binary_tracker_low_res_masks_global,
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[int]` but got `Tensor`.
|
||||
last_occluded_prev,
|
||||
obj_ids_global,
|
||||
frame_idx,
|
||||
@@ -1123,6 +1192,7 @@ class Sam3VideoBase(nn.Module):
|
||||
is_on_this_gpu: npt.NDArray = new_det_gpu_ids == self.rank
|
||||
new_det_obj_ids_local: npt.NDArray = new_det_obj_ids[is_on_this_gpu]
|
||||
new_det_fa_inds_local: npt.NDArray = new_det_fa_inds[is_on_this_gpu]
|
||||
# pyre-fixme[9]: obj_ids_newly_removed has type `Set[int]`; used as `ndarray`.
|
||||
obj_ids_newly_removed: Set[int] = tracker_update_plan["obj_ids_newly_removed"]
|
||||
|
||||
# Step 1: add new objects from the detector to SAM2 inference states
|
||||
@@ -1133,6 +1203,8 @@ class Sam3VideoBase(nn.Module):
|
||||
tracker_states_local = self._tracker_add_new_objects(
|
||||
frame_idx=frame_idx,
|
||||
num_frames=num_frames,
|
||||
# pyre-fixme[6]: For 3rd argument expected `List[int]` but got
|
||||
# `ndarray`.
|
||||
new_obj_ids=new_det_obj_ids_local,
|
||||
new_obj_masks=new_det_masks,
|
||||
tracker_states_local=tracker_states_local,
|
||||
@@ -1143,6 +1215,7 @@ class Sam3VideoBase(nn.Module):
|
||||
|
||||
# Step 2: remove from SAM2 inference states those objects removed by heuristics
|
||||
if len(obj_ids_newly_removed) > 0:
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[int]` but got `Set[int]`.
|
||||
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
|
||||
|
||||
self._post_execution_phase_hook(tracker_states_local, tracker_metadata_new)
|
||||
@@ -1182,7 +1255,10 @@ class Sam3VideoBase(nn.Module):
|
||||
tracker_update_plan: Dict[str, npt.NDArray],
|
||||
orig_vid_height: int,
|
||||
orig_vid_width: int,
|
||||
# pyre-fixme[9]: reconditioned_obj_ids has type `Set[Any]`; used as `None`.
|
||||
reconditioned_obj_ids: set = None,
|
||||
# pyre-fixme[9]: det_to_matched_trk_obj_ids has type `Dict[Any, Any]`; used
|
||||
# as `None`.
|
||||
det_to_matched_trk_obj_ids: dict = None,
|
||||
):
|
||||
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
|
||||
@@ -1255,6 +1331,7 @@ class Sam3VideoBase(nn.Module):
|
||||
binary_low_res_masks: Tensor,
|
||||
last_occluded: List[int],
|
||||
obj_ids: List[int],
|
||||
# pyre-fixme[9]: frame_idx has type `int`; used as `None`.
|
||||
frame_idx: int = None,
|
||||
reverse: bool = False,
|
||||
):
|
||||
@@ -1278,6 +1355,7 @@ class Sam3VideoBase(nn.Module):
|
||||
)
|
||||
overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
|
||||
|
||||
# pyre-fixme[16]: `List` has no attribute `unsqueeze`.
|
||||
last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
|
||||
last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
|
||||
# Suppress most recently occluded
|
||||
@@ -1309,6 +1387,7 @@ class Sam3VideoBase(nn.Module):
|
||||
):
|
||||
suppress_i_mask = suppress_i_mask.cpu().numpy()
|
||||
suppress_j_mask = suppress_j_mask.cpu().numpy()
|
||||
# pyre-fixme[16]: `List` has no attribute `cpu`.
|
||||
last_occluded = last_occluded.cpu().numpy()
|
||||
|
||||
# Find all suppression pairs without using torch.where
|
||||
@@ -1352,6 +1431,7 @@ class Sam3VideoBase(nn.Module):
|
||||
|
||||
# propagate one frame
|
||||
num_frames_propagated = 0
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
for out in self.tracker.propagate_in_video(
|
||||
inference_state,
|
||||
start_frame_idx=frame_idx,
|
||||
@@ -1366,10 +1446,14 @@ class Sam3VideoBase(nn.Module):
|
||||
num_frames_propagated += 1
|
||||
|
||||
# only 1 frames should be propagated
|
||||
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
|
||||
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
|
||||
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
|
||||
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
|
||||
)
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
assert isinstance(out_obj_ids, list)
|
||||
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
|
||||
obj_ids_local.extend(out_obj_ids)
|
||||
low_res_masks_list.append(out_low_res_masks.squeeze(1))
|
||||
obj_scores_list.append(out_obj_scores.squeeze(1))
|
||||
@@ -1390,6 +1474,10 @@ class Sam3VideoBase(nn.Module):
|
||||
)
|
||||
low_res_masks_local = low_res_masks_local.squeeze(1)
|
||||
else:
|
||||
# pyre-fixme[6]: For 2nd argument expected `Union[int, SymInt]` but got
|
||||
# `Union[Module, Tensor]`.
|
||||
# pyre-fixme[6]: For 3rd argument expected `Union[int, SymInt]` but got
|
||||
# `Union[Module, Tensor]`.
|
||||
low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
|
||||
obj_scores_local = torch.zeros(0, device=self.device)
|
||||
|
||||
@@ -1666,6 +1754,8 @@ class Sam3VideoBase(nn.Module):
|
||||
return
|
||||
# Avoid an extra interpolation step by directly interpolating to `interpol_size`
|
||||
high_res_H, high_res_W = (
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
|
||||
# `mask_downsampler`.
|
||||
self.tracker.maskmem_backbone.mask_downsampler.interpol_size
|
||||
)
|
||||
# NOTE: inspect this part if we observe OOMs in the demo
|
||||
@@ -1677,6 +1767,7 @@ class Sam3VideoBase(nn.Module):
|
||||
)
|
||||
# We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
|
||||
if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
high_res_masks = self.tracker._suppress_object_pw_area_shrinkage(
|
||||
high_res_masks
|
||||
)
|
||||
@@ -1701,6 +1792,7 @@ class Sam3VideoBase(nn.Module):
|
||||
local_batch_size = local_high_res_masks.size(0)
|
||||
# Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
|
||||
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
encoded_mem = self.tracker._run_memory_encoder(
|
||||
tracker_state,
|
||||
frame_idx,
|
||||
@@ -1723,6 +1815,7 @@ class Sam3VideoBase(nn.Module):
|
||||
]
|
||||
# for batched inference state, we also need to add per-object
|
||||
# memory slides to support instance interactivity
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.tracker._add_output_per_object(
|
||||
inference_state=tracker_state,
|
||||
frame_idx=frame_idx,
|
||||
@@ -1750,6 +1843,7 @@ class Sam3VideoBase(nn.Module):
|
||||
# prepare inference_state
|
||||
# batch objects that first appear on the same frame together
|
||||
# Clear inference state. Keep the cached image features if available.
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
new_tracker_state = self.tracker.init_state(
|
||||
cached_features=feature_cache,
|
||||
video_height=orig_vid_height,
|
||||
@@ -1767,6 +1861,8 @@ class Sam3VideoBase(nn.Module):
|
||||
input_mask_res = self.tracker.input_mask_size
|
||||
new_obj_masks = F.interpolate(
|
||||
new_obj_masks.unsqueeze(1),
|
||||
# pyre-fixme[6]: For 2nd argument expected `Union[None, Sequence[int],
|
||||
# int]` but got `Tuple[Union[Module, Tensor], Union[Module, Tensor]]`.
|
||||
size=(input_mask_res, input_mask_res),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
@@ -1775,6 +1871,7 @@ class Sam3VideoBase(nn.Module):
|
||||
|
||||
# add object one by one
|
||||
for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.tracker.add_new_mask(
|
||||
inference_state=new_tracker_state,
|
||||
frame_idx=frame_idx,
|
||||
@@ -1783,6 +1880,7 @@ class Sam3VideoBase(nn.Module):
|
||||
add_mask_to_memory=True,
|
||||
)
|
||||
# NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.tracker.propagate_in_video_preflight(
|
||||
new_tracker_state, run_mem_encoder=True
|
||||
)
|
||||
@@ -1799,6 +1897,7 @@ class Sam3VideoBase(nn.Module):
|
||||
for tracker_inference_state in tracker_states_local_before_removal:
|
||||
# we try to remove `obj_id` on every inference state with `strict=False`
|
||||
# it will not do anything if an inference state doesn't contain `obj_id`
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
new_obj_ids, _ = self.tracker.remove_object(
|
||||
tracker_inference_state, obj_id, strict=False, need_output=False
|
||||
)
|
||||
|
||||
@@ -911,7 +911,9 @@ class Sam3VideoInference(Sam3VideoBase):
|
||||
# set the model to single GPU for benchmark evaluation (to be compatible with trainer)
|
||||
orig_rank = self.rank
|
||||
orig_world_size = self.world_size
|
||||
# pyre-fixme[16]: `Module` has no attribute `rank`.
|
||||
self.rank = self.detector.rank = 0
|
||||
# pyre-fixme[16]: `Module` has no attribute `world_size`.
|
||||
self.world_size = self.detector.world_size = 1
|
||||
|
||||
# get data
|
||||
|
||||
@@ -77,9 +77,11 @@ class ResidualAttentionBlock(nn.Module):
|
||||
attn_mask: Optional[torch.Tensor] = None,
|
||||
) -> torch.Tensor:
|
||||
k_x = (
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
|
||||
)
|
||||
v_x = (
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
|
||||
)
|
||||
x = q_x + self.ls_1(
|
||||
@@ -121,6 +123,9 @@ class Transformer(nn.Module):
|
||||
)
|
||||
|
||||
if compile_mode is not None:
|
||||
# pyre-fixme[8]: Attribute has type `(self: Transformer, x: Tensor,
|
||||
# attn_mask: Optional[Tensor] = ...) -> Tensor`; used as `(x: Tensor,
|
||||
# attn_mask: Optional[Tensor] = ...) -> Tensor`.
|
||||
self.forward = torch.compile(
|
||||
self.forward, mode=compile_mode, fullgraph=True
|
||||
)
|
||||
@@ -209,6 +214,7 @@ class TextTransformer(nn.Module):
|
||||
)
|
||||
self.ln_final = norm_layer(width) if use_ln_post else nn.Identity()
|
||||
if no_causal_mask:
|
||||
# pyre-fixme[8]: Attribute has type `Tensor`; used as `None`.
|
||||
self.attn_mask = None
|
||||
else:
|
||||
self.register_buffer(
|
||||
@@ -289,6 +295,7 @@ class VETextEncoder(nn.Module):
|
||||
self,
|
||||
text: Union[List[str], Tuple[torch.Tensor, torch.Tensor, dict]],
|
||||
input_boxes: Optional[List] = None,
|
||||
# pyre-fixme[9]: device has type `device`; used as `None`.
|
||||
device: torch.device = None,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
if isinstance(text[0], str):
|
||||
@@ -317,6 +324,8 @@ class VETextEncoder(nn.Module):
|
||||
else:
|
||||
# The text is already encoded, use as is.
|
||||
text_attention_mask, text_memory_resized, tokenized = text
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[slice[Any, Any, Any],
|
||||
# SupportsIndex]` but got `str`.
|
||||
inputs_embeds = tokenized["inputs_embeds"]
|
||||
assert input_boxes is None or len(input_boxes) == 0, (
|
||||
"Can't replace boxes in text if it's already encoded"
|
||||
|
||||
@@ -137,6 +137,8 @@ class SimpleTokenizer(object):
|
||||
):
|
||||
self.byte_encoder = bytes_to_unicode()
|
||||
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
||||
# pyre-fixme[6]: For 1st argument expected `str` but got
|
||||
# `Union[PathLike[Any], str]`.
|
||||
with g_pathmgr.open(bpe_path, "rb") as fh:
|
||||
bpe_bytes = io.BytesIO(fh.read())
|
||||
merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
|
||||
@@ -252,4 +254,5 @@ class SimpleTokenizer(object):
|
||||
tokens = tokens[:context_length] # Truncate
|
||||
tokens[-1] = self.eot_token_id
|
||||
result[i, : len(tokens)] = torch.tensor(tokens)
|
||||
# pyre-fixme[7]: Expected `LongTensor` but got `Tensor`.
|
||||
return result
|
||||
|
||||
@@ -48,6 +48,7 @@ def copy_data_to_device(data, device: torch.device, *args: Any, **kwargs: Any):
|
||||
},
|
||||
)
|
||||
elif isinstance(data, Mapping):
|
||||
# pyre-fixme[19]: Expected 0 positional arguments.
|
||||
return type(data)(
|
||||
{
|
||||
k: copy_data_to_device(v, device, *args, **kwargs)
|
||||
@@ -55,6 +56,7 @@ def copy_data_to_device(data, device: torch.device, *args: Any, **kwargs: Any):
|
||||
}
|
||||
)
|
||||
elif is_dataclass(data) and not isinstance(data, type):
|
||||
# pyre-fixme[45]: Cannot instantiate protocol `DataclassInstance`.
|
||||
new_data_class = type(data)(
|
||||
**{
|
||||
field.name: copy_data_to_device(
|
||||
|
||||
@@ -308,6 +308,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
# with memories from past frames
|
||||
assert transformer.decoder is None, "transformer should be encoder-only"
|
||||
self.transformer = transformer
|
||||
# pyre-fixme[8]: Attribute has type `int`; used as `Union[Module, Tensor]`.
|
||||
self.hidden_dim: int = transformer.d_model
|
||||
|
||||
# Part 3: memory encoder for the previous frame's outputs
|
||||
@@ -317,6 +318,8 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
self.maskmem_backbone.out_proj, "weight"
|
||||
):
|
||||
# if there is compression of memories along channel dim
|
||||
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
|
||||
# `weight`.
|
||||
mem_dim = self.maskmem_backbone.out_proj.weight.shape[0]
|
||||
assert mem_dim == self.hidden_dim, (
|
||||
"there should be no compression of memory embeddings"
|
||||
@@ -883,8 +886,10 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
# Extract object pointer from the SAM output token
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
if is_interactive:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
obj_ptr = self.interactive_obj_ptr_proj(sam_output_token)
|
||||
else:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
obj_ptr = self.obj_ptr_proj(sam_output_token)
|
||||
|
||||
if self.pred_obj_scores and self.use_no_obj_ptr:
|
||||
@@ -919,6 +924,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
"object_score_logits": object_score_logits,
|
||||
}
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
|
||||
outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space
|
||||
return outputs
|
||||
|
||||
@@ -1003,9 +1009,11 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
"ious": ious,
|
||||
"low_res_masks": low_res_masks,
|
||||
"high_res_masks": high_res_masks,
|
||||
# pyre-fixme[61]: `object_score_logits` is undefined, or not always defined.
|
||||
"object_score_logits": object_score_logits,
|
||||
}
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
|
||||
outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space
|
||||
return outputs
|
||||
|
||||
@@ -1037,6 +1045,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
need_propagation_out = need_interactive_out or need_propagation_out
|
||||
need_interactive_out = False
|
||||
# this also means that convs for backbone_fpn are shared
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
backbone_out = self.backbone.forward_image(
|
||||
img_batch,
|
||||
need_sam3_out=need_sam3_out,
|
||||
@@ -1044,6 +1053,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
)
|
||||
backbone_out["interactive"] = backbone_out["sam2_backbone_out"]
|
||||
else:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
backbone_out = self.backbone.forward_image(
|
||||
img_batch,
|
||||
need_sam3_out=need_sam3_out,
|
||||
@@ -1360,8 +1370,12 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
for t_pos in range(1, self.num_maskmem):
|
||||
t_rel = self.num_maskmem - t_pos # how many frames before current frame
|
||||
if self.use_memory_selection:
|
||||
# pyre-fixme[61]: `valid_indices` is undefined, or not always
|
||||
# defined.
|
||||
if t_rel > len(valid_indices):
|
||||
continue
|
||||
# pyre-fixme[61]: `valid_indices` is undefined, or not always
|
||||
# defined.
|
||||
prev_frame_idx = valid_indices[-t_rel]
|
||||
else:
|
||||
if t_rel == 1:
|
||||
@@ -1491,8 +1505,12 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
if t < 0 or (num_frames is not None and t >= num_frames):
|
||||
break
|
||||
else:
|
||||
# pyre-fixme[61]: `valid_indices` is undefined, or not
|
||||
# always defined.
|
||||
if -t_diff <= -len(valid_indices):
|
||||
break
|
||||
# pyre-fixme[61]: `valid_indices` is undefined, or not
|
||||
# always defined.
|
||||
t = valid_indices[-t_diff]
|
||||
|
||||
out = output_dict["non_cond_frame_outputs"].get(
|
||||
@@ -1580,13 +1598,20 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
if self.save_image_features:
|
||||
assert prompt_mask is None
|
||||
assert vision_mask is None
|
||||
# pyre-fixme[61]: `to_cat_image_feat` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `to_cat_image_pos_embed` is undefined, or not always
|
||||
# defined.
|
||||
if len(to_cat_image_feat) == 0 or len(to_cat_image_pos_embed) == 0:
|
||||
# Memory image features were cleared; fall back to current-frame features.
|
||||
pix_feat = vision_feat.permute(1, 2, 0).view(B, C, H, W)
|
||||
return pix_feat
|
||||
# pyre-fixme[61]: `to_cat_image_feat` is undefined, or not always defined.
|
||||
image_feat = torch.cat(to_cat_image_feat, dim=0)
|
||||
# pyre-fixme[61]: `to_cat_image_pos_embed` is undefined, or not always
|
||||
# defined.
|
||||
image_pos_embed = torch.cat(to_cat_image_pos_embed, dim=0)
|
||||
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
encoder_out = self.transformer.encoder(
|
||||
image=current_vision_feats[-1],
|
||||
src=vision_feat,
|
||||
@@ -1599,6 +1624,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
num_obj_ptr_tokens=num_obj_ptr_tokens,
|
||||
)
|
||||
else:
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
encoder_out = self.transformer.encoder(
|
||||
src=vision_feat,
|
||||
src_key_padding_mask=vision_mask,
|
||||
@@ -1684,7 +1710,10 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
device=mask_for_mem.device,
|
||||
dtype=mask_for_mem.dtype,
|
||||
)
|
||||
# pyre-fixme[6]: For 1st argument expected
|
||||
# `pyre_extensions.PyreReadOnly[Sized]` but got `Optional[Iterable[Any]]`.
|
||||
if len(conditioning_objects) > 0:
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[None, slice[Any, An...
|
||||
cond_values[conditioning_objects] = self.condition_as_mask_input_fg
|
||||
# Broadcast to full spatial dimensions: [N] -> [N, 1, H, W]
|
||||
embedded_conditions = cond_values.view(-1, 1, 1, 1).expand_as(mask_for_mem)
|
||||
@@ -1752,7 +1781,11 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
obj_non_cond_embed = multiplex_state.demux(obj_non_cond_embed)
|
||||
if self.training:
|
||||
obj_merged_embed = obj_merged_embed.clone()
|
||||
# pyre-fixme[61]: `unconditioning_objects` is undefined, or not
|
||||
# always defined.
|
||||
obj_merged_embed[unconditioning_objects] = obj_non_cond_embed[
|
||||
# pyre-fixme[61]: `unconditioning_objects` is undefined, or not
|
||||
# always defined.
|
||||
unconditioning_objects
|
||||
]
|
||||
|
||||
@@ -1888,6 +1921,8 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
else:
|
||||
output_dict["non_cond_frame_outputs"][stage_id] = current_out
|
||||
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[int, StageOutput]` but got
|
||||
# `MultiplexState`.
|
||||
output_dict["multiplex_state"] = multiplex_state
|
||||
|
||||
if return_dict:
|
||||
@@ -2038,6 +2073,8 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
)
|
||||
sam_outputs = self._use_mask_as_output(
|
||||
backbone_features=interactive_pix_feat,
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[Tensor]` but got
|
||||
# `Optional[List[Any]]`.
|
||||
high_res_features=interactive_high_res_features,
|
||||
mask_inputs=mask_inputs,
|
||||
multiplex_state=multiplex_state,
|
||||
@@ -2156,12 +2193,15 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
"obj_ptr",
|
||||
]
|
||||
for k in keys_to_merge:
|
||||
# pyre-fixme[26]: TypedDict key must be a string literal.
|
||||
src = interaction_out[k]
|
||||
# pyre-fixme[26]: TypedDict key must be a string literal.
|
||||
dst = propagation_out[k]
|
||||
# Align dtype for floating tensors before indexed assignment
|
||||
if torch.is_tensor(src) and torch.is_tensor(dst):
|
||||
if torch.is_floating_point(src) and src.dtype != dst.dtype:
|
||||
src = src.to(dtype=dst.dtype)
|
||||
# pyre-fixme[26]: TypedDict key must be a string literal.
|
||||
propagation_out[k][objects_to_interact] = src
|
||||
sam_outputs = propagation_out
|
||||
|
||||
@@ -2361,6 +2401,9 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
)
|
||||
object_score_logits[objects_to_interact] = interact_object_score_logits
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `interact_obj_ptr` is undefined, or not always
|
||||
# defined.
|
||||
obj_ptr[objects_to_interact] = interact_obj_ptr
|
||||
|
||||
all_pred_masks.append(low_res_masks)
|
||||
@@ -2398,6 +2441,7 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
current_out["pred_masks_high_res"] = high_res_masks
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# similar to spatial memory, the object pointers are stored with multiplex
|
||||
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
|
||||
current_out["obj_ptr"] = multiplex_state.mux(obj_ptr)
|
||||
if self.use_memory_selection:
|
||||
current_out["object_score_logits"] = object_score_logits
|
||||
@@ -2505,9 +2549,13 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
if past_out is not None:
|
||||
if (
|
||||
self.use_memory_selection
|
||||
# pyre-fixme[58]: `<` is not supported for operand types
|
||||
# `Union[int, Tensor]` and `float`.
|
||||
and past_out.get("eff_iou_score", 0) < self.mf_threshold
|
||||
) or not self.use_memory_selection:
|
||||
output_dict["non_cond_frame_outputs"][past_frame_idx] = (
|
||||
# pyre-fixme[6]: For 2nd argument expected `StageOutput` but
|
||||
# got `Optional[StageOutput]`.
|
||||
_trim_past_out(past_out, current_out)
|
||||
)
|
||||
|
||||
@@ -2520,6 +2568,8 @@ class VideoTrackingMultiplex(nn.Module):
|
||||
)
|
||||
if past_out is not None:
|
||||
output_dict["non_cond_frame_outputs"][far_old_frame_idx] = (
|
||||
# pyre-fixme[6]: For 2nd argument expected `StageOutput` but
|
||||
# got `Optional[StageOutput]`.
|
||||
_trim_past_out(past_out, current_out)
|
||||
)
|
||||
|
||||
@@ -2742,6 +2792,9 @@ def _append(
|
||||
if k1 not in d1:
|
||||
return
|
||||
|
||||
# pyre-fixme[26]: TypedDict key must be a string literal.
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor], tuple[Tensor,
|
||||
# ...]]` but got `List[Union[Set[int], Tensor]]`.
|
||||
d1[k1] = torch.cat([d1[k1], d2[k2]], dim=dim)
|
||||
|
||||
|
||||
@@ -2758,6 +2811,9 @@ def _merge(
|
||||
else:
|
||||
if k1 not in d1:
|
||||
return
|
||||
# pyre-fixme[16]: `set` has no attribute `__setitem__`.
|
||||
# pyre-fixme[26]: TypedDict key must be a string literal.
|
||||
# pyre-fixme[16]: `set` has no attribute `dtype`.
|
||||
d1[k1][d2_idx] = d2[k2].to(dtype=d1[k1].dtype)
|
||||
|
||||
|
||||
@@ -3181,14 +3237,20 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
|
||||
|
||||
# Merge the input masks
|
||||
if "input_masks" in prev_output:
|
||||
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
|
||||
prev_output["input_masks"] = torch.cat(
|
||||
[prev_output["input_masks"], new_masks], dim=0
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
|
||||
# tuple[Tensor, ...]]` but got `List[Union[Set[int], Tensor]]`.
|
||||
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
|
||||
[prev_output["input_masks"], new_masks],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# Merge the object pointers. Note that the pointers in SAMOutput are in the data space,
|
||||
# while those in StageOutput are in the mux space.
|
||||
new_pointers = mask_output["obj_ptr"].to(existing_pointers.dtype)
|
||||
# pyre-fixme[61]: `existing_pointers` is undefined, or not always defined.
|
||||
combined_pointers = torch.cat([existing_pointers, new_pointers], dim=0)
|
||||
prev_output["obj_ptr"] = multiplex_state.mux(combined_pointers)
|
||||
|
||||
@@ -3308,13 +3370,17 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
|
||||
|
||||
# Merge the input masks
|
||||
if "input_masks" in prev_output:
|
||||
# pyre-fixme[16]: `set` has no attribute `__setitem__`.
|
||||
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
|
||||
prev_output["input_masks"][obj_idxs_in_mask] = new_masks
|
||||
|
||||
if self.use_obj_ptrs_in_encoder:
|
||||
# Merge the object pointers. Note that the pointers in SAMOutput are in the data space,
|
||||
# while those in StageOutput are in the mux space.
|
||||
new_pointers = mask_output["obj_ptr"].to(existing_pointers.dtype)
|
||||
# pyre-fixme[61]: `existing_pointers` is undefined, or not always defined.
|
||||
existing_pointers[obj_idxs_in_mask] = new_pointers
|
||||
# pyre-fixme[61]: `existing_pointers` is undefined, or not always defined.
|
||||
prev_output["obj_ptr"] = multiplex_state.mux(existing_pointers)
|
||||
|
||||
# Step 3: Update the set of conditioning objects at this frame
|
||||
@@ -3581,6 +3647,8 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
|
||||
else:
|
||||
output_dict["non_cond_frame_outputs"][stage_id] = current_out
|
||||
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[int, StageOutput]` but got
|
||||
# `MultiplexState`.
|
||||
output_dict["multiplex_state"] = multiplex_state
|
||||
|
||||
if return_dict:
|
||||
@@ -3606,6 +3674,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
|
||||
# since we have remapped the object appearance order, we would need to map it back here
|
||||
inverse_object_appearance_order = [None for _ in object_appearance_order]
|
||||
for idx, obj_id in enumerate(object_appearance_order):
|
||||
# pyre-fixme[6]: For 2nd argument expected `None` but got `int`.
|
||||
inverse_object_appearance_order[obj_id] = idx
|
||||
assert all(i is not None for i in inverse_object_appearance_order)
|
||||
|
||||
@@ -3617,10 +3686,13 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
|
||||
# This only happens if we evaluate on the new (fully annotated) YouTubeVOS set.
|
||||
if len(inverse_object_appearance_order) < num_objects:
|
||||
inverse_object_appearance_order.extend(
|
||||
# pyre-fixme[6]: For 1st argument expected `Iterable[None]` but
|
||||
# got `List[int]`.
|
||||
list(range(len(inverse_object_appearance_order), num_objects))
|
||||
)
|
||||
|
||||
# we need to pad the outputs with zeros (for the frames before the object appears)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
last_mask = all_frame_outputs[-1]["pred_masks"]
|
||||
|
||||
shape = last_mask.shape[1:]
|
||||
|
||||
@@ -2734,6 +2734,8 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
|
||||
propagation_vision_feats=propagation_vision_feats,
|
||||
propagation_feat_sizes=propagation_feat_sizes,
|
||||
new_masks=mask_inputs,
|
||||
# pyre-fixme[6]: For 6th argument expected `List[int]` but
|
||||
# got `Optional[List[int]]`.
|
||||
obj_idxs_in_mask=new_obj_idxs,
|
||||
obj_ids_in_mask=new_obj_ids,
|
||||
prev_output=existing_out,
|
||||
@@ -2772,6 +2774,8 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
|
||||
if mask_inputs is not None
|
||||
else new_masks_from_points
|
||||
),
|
||||
# pyre-fixme[6]: For 6th argument expected `List[int]` but
|
||||
# got `Optional[List[int]]`.
|
||||
obj_idxs_in_mask=new_obj_idxs,
|
||||
obj_ids_in_mask=new_obj_ids,
|
||||
prev_output=existing_out,
|
||||
|
||||
@@ -93,11 +93,15 @@ def compute_axial_cis(
|
||||
scale_pos: float = 1.0,
|
||||
offset: int = 0,
|
||||
) -> torch.Tensor:
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
||||
freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
||||
freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
|
||||
|
||||
t_x, t_y = init_t_xy(end_x, end_y, scale_pos, offset)
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `float`.
|
||||
freqs_x = torch.outer(t_x, freqs_x)
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `float`.
|
||||
freqs_y = torch.outer(t_y, freqs_y)
|
||||
freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
|
||||
freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
|
||||
@@ -271,6 +275,7 @@ def get_abs_pos(
|
||||
# add cls_token back, flatten spatial dims
|
||||
assert has_cls_token
|
||||
return torch.cat(
|
||||
# pyre-fixme[61]: `cls_pos` is undefined, or not always defined.
|
||||
[cls_pos, new_abs_pos.permute(0, 2, 3, 1).reshape(1, h * w, -1)],
|
||||
dim=1,
|
||||
)
|
||||
@@ -280,6 +285,7 @@ def get_abs_pos(
|
||||
return abs_pos.reshape(1, h, w, -1)
|
||||
else:
|
||||
assert has_cls_token
|
||||
# pyre-fixme[61]: `cls_pos` is undefined, or not always defined.
|
||||
return torch.cat([cls_pos, abs_pos], dim=1)
|
||||
|
||||
|
||||
@@ -394,6 +400,7 @@ class Attention(nn.Module):
|
||||
use_rel_pos: bool = False,
|
||||
rel_pos_zero_init: bool = True,
|
||||
input_size: Optional[Tuple[int, int]] = None,
|
||||
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
|
||||
attn_type: AttentionType = AttentionType.Vanilla,
|
||||
cls_token: bool = False,
|
||||
use_rope: bool = False,
|
||||
@@ -463,6 +470,7 @@ class Attention(nn.Module):
|
||||
torch.zeros(2 * self.input_size[0] - 1, self.head_dim)
|
||||
)
|
||||
self.rel_pos_w = nn.Parameter(
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
torch.zeros(2 * self.input_size[1] - 1, self.head_dim)
|
||||
)
|
||||
|
||||
@@ -471,6 +479,7 @@ class Attention(nn.Module):
|
||||
trunc_normal_(self.rel_pos_w, std=0.02)
|
||||
|
||||
# Precompute the relative coords
|
||||
# pyre-fixme[23]: Unable to unpack `tuple[int, int] | None` into 2 values.
|
||||
H, W = self.input_size
|
||||
q_coords = torch.arange(H)[:, None]
|
||||
k_coords = torch.arange(W)[None, :]
|
||||
@@ -479,6 +488,7 @@ class Attention(nn.Module):
|
||||
|
||||
def _setup_rope_freqs(self) -> None:
|
||||
if not self.use_rope:
|
||||
# pyre-fixme[16]: `Attention` has no attribute `freqs_cis`.
|
||||
self.freqs_cis = None
|
||||
return
|
||||
|
||||
@@ -489,8 +499,10 @@ class Attention(nn.Module):
|
||||
|
||||
if self.use_ve_rope:
|
||||
assert not self.rope_tiled, "not supported"
|
||||
# pyre-fixme[16]: `Attention` has no attribute `rope`.
|
||||
self.rope = VisionRotaryEmbeddingVE(
|
||||
dim=self.head_dim // 2,
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
seq_len=self.input_size[0],
|
||||
pt_seq_len=self.rope_pt_size[0],
|
||||
)
|
||||
@@ -557,6 +569,7 @@ class Attention(nn.Module):
|
||||
|
||||
if self.use_ve_rope:
|
||||
dtype = q.dtype
|
||||
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
|
||||
return self.rope(q).to(dtype), self.rope(k).to(dtype)
|
||||
|
||||
assert self.freqs_cis is not None
|
||||
@@ -565,9 +578,15 @@ class Attention(nn.Module):
|
||||
return apply_rotary_enc_real(
|
||||
q,
|
||||
k,
|
||||
# pyre-fixme[6]: For 3rd argument expected `Tensor` but got
|
||||
# `Union[Module, Tensor]`.
|
||||
freqs_cis_imag=self.freqs_cis_imag,
|
||||
# pyre-fixme[6]: For 4th argument expected `Tensor` but got
|
||||
# `Union[Module, Tensor]`.
|
||||
freqs_cis_real=self.freqs_cis_real,
|
||||
)
|
||||
# pyre-fixme[6]: For 3rd argument expected `Tensor` but got `Union[Module,
|
||||
# Tensor]`.
|
||||
return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis)
|
||||
|
||||
def forward(self, x: Tensor) -> Tensor:
|
||||
@@ -594,16 +613,26 @@ class Attention(nn.Module):
|
||||
q, k = concat_rel_pos(
|
||||
q.flatten(0, 1),
|
||||
k.flatten(0, 1),
|
||||
# pyre-fixme[6]: For 3rd argument expected `Tuple[int, int]` but got
|
||||
# `Tuple[float, float]`.
|
||||
(H, W),
|
||||
# pyre-fixme[6]: For 4th argument expected `Tuple[int, int]` but got
|
||||
# `Size`.
|
||||
x.shape[1:3],
|
||||
self.rel_pos_h,
|
||||
self.rel_pos_w,
|
||||
rescale=True,
|
||||
# pyre-fixme[6]: For 8th argument expected `Optional[Tensor]` but
|
||||
# got `Union[Module, Tensor]`.
|
||||
relative_coords=self.relative_coords,
|
||||
)
|
||||
|
||||
# sdpa expects [B, nheads, H*W, C] so we transpose back
|
||||
# pyre-fixme[6]: For 3rd argument expected `Union[int, SymInt]` but got
|
||||
# `float`.
|
||||
q = q.reshape(B, self.num_heads, H * W, -1)
|
||||
# pyre-fixme[6]: For 3rd argument expected `Union[int, SymInt]` but got
|
||||
# `float`.
|
||||
k = k.reshape(B, self.num_heads, H * W, -1)
|
||||
|
||||
if self.attn_type == AttentionType.Vanilla:
|
||||
@@ -656,6 +685,7 @@ class Block(nn.Module):
|
||||
cls_token: bool = False,
|
||||
dropout: float = 0.0,
|
||||
init_values: Optional[float] = None,
|
||||
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
|
||||
attn_type: AttentionType = AttentionType.Vanilla,
|
||||
use_fa3: bool = False,
|
||||
use_rope_real: bool = False,
|
||||
@@ -732,6 +762,9 @@ class Block(nn.Module):
|
||||
x = self.ls1(self.attn(x))
|
||||
# Reverse window partition
|
||||
if self.window_size > 0:
|
||||
# pyre-fixme[61]: `pad_hw` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `H` is undefined, or not always defined.
|
||||
# pyre-fixme[61]: `W` is undefined, or not always defined.
|
||||
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
|
||||
|
||||
x = shortcut + self.dropout(self.drop_path(x))
|
||||
@@ -778,6 +811,7 @@ class ViT(nn.Module):
|
||||
dropout: float = 0.0,
|
||||
return_interm_layers: bool = False,
|
||||
init_values: Optional[float] = None, # for layerscale
|
||||
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
|
||||
attn_type: AttentionType = AttentionType.Vanilla,
|
||||
ln_pre: bool = False,
|
||||
ln_post: bool = False,
|
||||
@@ -832,6 +866,8 @@ class ViT(nn.Module):
|
||||
if isinstance(rel_pos_blocks, bool) and rel_pos_blocks:
|
||||
self.rel_pos_blocks = [True] * depth
|
||||
else:
|
||||
# pyre-fixme[16]: Item `bool` of `Literal[False] | tuple[int, ...]` has
|
||||
# no attribute `__iter__`.
|
||||
for i in rel_pos_blocks:
|
||||
self.rel_pos_blocks[i] = True
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ class SAM3VLBackbone(nn.Module):
|
||||
:param text: The text encoder to use
|
||||
"""
|
||||
super().__init__()
|
||||
# pyre-fixme[8]: Attribute has type `Sam3DualViTDetNeck`; used as `(...) ->
|
||||
# Any`.
|
||||
self.vision_backbone: Sam3DualViTDetNeck = (
|
||||
torch.compile(visual) if compile_visual else visual
|
||||
)
|
||||
@@ -278,6 +280,7 @@ class VisionOnly(nn.Module):
|
||||
eval_chunk_size=4,
|
||||
eval_cast_to_cpu=False,
|
||||
scalp=0,
|
||||
# pyre-fixme[9]: compile_mode has type `str`; used as `None`.
|
||||
compile_mode: str = None,
|
||||
compile_extra_args: Optional[dict] = None,
|
||||
):
|
||||
@@ -343,6 +346,7 @@ class TriHeadVisionOnly(VisionOnly):
|
||||
eval_chunk_size=4,
|
||||
eval_cast_to_cpu=False,
|
||||
scalp=0,
|
||||
# pyre-fixme[9]: compile_mode has type `str`; used as `None`.
|
||||
compile_mode: str = None,
|
||||
compile_extra_args: Optional[dict] = None,
|
||||
):
|
||||
|
||||
@@ -6,6 +6,7 @@ import logging
|
||||
import torch
|
||||
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `cc_torch`.
|
||||
from cc_torch import get_connected_components
|
||||
|
||||
HAS_CC_TORCH = True
|
||||
|
||||
@@ -9,6 +9,7 @@ import torch
|
||||
def flash_attn_func_op(
|
||||
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
# pyre-fixme[21]: Could not find module `flash_attn_interface`.
|
||||
from flash_attn_interface import flash_attn_func as fa3
|
||||
|
||||
return fa3(q, k, v)
|
||||
|
||||
@@ -10,6 +10,7 @@ from sam3.perflib.masks_ops import mask_iou
|
||||
|
||||
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `torch_generic_nms`.
|
||||
from torch_generic_nms import generic_nms as generic_nms_cuda
|
||||
|
||||
GENERIC_NMS_AVAILABLE = True
|
||||
|
||||
@@ -432,7 +432,9 @@ def connected_components_triton(input_tensor: torch.Tensor):
|
||||
_init_labels_kernel[grid_init](
|
||||
input_tensor,
|
||||
labels,
|
||||
# pyre-fixme[6]: For 3rd argument expected `constexpr` but got `int`.
|
||||
numel,
|
||||
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
)
|
||||
|
||||
@@ -446,6 +448,8 @@ def connected_components_triton(input_tensor: torch.Tensor):
|
||||
# --- Phase 3 ---
|
||||
BLOCK_SIZE = 256
|
||||
grid_jump = lambda meta: (triton.cdiv(numel, meta["BLOCK_SIZE"]),)
|
||||
# pyre-fixme[6]: For 3rd argument expected `constexpr` but got `int`.
|
||||
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
|
||||
_pointer_jump_kernel[grid_jump](labels, output, numel, BLOCK_SIZE=BLOCK_SIZE)
|
||||
|
||||
# --- Phase 4 ---
|
||||
@@ -459,12 +463,23 @@ def connected_components_triton(input_tensor: torch.Tensor):
|
||||
# 4.1: Count the occurrences of each label
|
||||
grid_count = (triton.cdiv(numel, BLOCK_SIZE),)
|
||||
_count_labels_kernel[grid_count](
|
||||
output, sizes_histogram, numel, BLOCK_SIZE=BLOCK_SIZE
|
||||
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
|
||||
output,
|
||||
sizes_histogram,
|
||||
numel,
|
||||
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
)
|
||||
|
||||
# 2.2: Broadcast the counts to the final output tensor
|
||||
grid_broadcast = (triton.cdiv(numel, BLOCK_SIZE),)
|
||||
_broadcast_sizes_kernel[grid_broadcast](
|
||||
output, sizes_histogram, component_sizes_out, numel, BLOCK_SIZE=BLOCK_SIZE
|
||||
# pyre-fixme[6]: For 5th argument expected `constexpr` but got `int`.
|
||||
output,
|
||||
sizes_histogram,
|
||||
component_sizes_out,
|
||||
numel,
|
||||
# pyre-fixme[6]: For 5th argument expected `constexpr` but got `int`.
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
)
|
||||
return output.view(out_shape) + 1, component_sizes_out.view(out_shape)
|
||||
|
||||
@@ -27,6 +27,7 @@ def _nms_suppression_kernel(
|
||||
iou_mask_ptr: tl.tensor, # [N, N]
|
||||
keep_mask_ptr: tl.tensor, # [N]
|
||||
# Scalars
|
||||
# pyre-fixme[11]: Annotation `int32` is not defined as a type.
|
||||
num_boxes: tl.int32,
|
||||
# Strides
|
||||
iou_mask_stride: tl.int32,
|
||||
|
||||
@@ -132,6 +132,7 @@ class MaskDecoder(nn.Module):
|
||||
torch.Tensor: batched predictions of mask quality
|
||||
torch.Tensor: batched SAM token for mask output
|
||||
"""
|
||||
# pyre-fixme[23]: Unable to unpack 2 values, 4 were expected.
|
||||
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
|
||||
image_embeddings=image_embeddings,
|
||||
image_pe=image_pe,
|
||||
@@ -162,6 +163,8 @@ class MaskDecoder(nn.Module):
|
||||
sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
|
||||
|
||||
# Prepare output
|
||||
# pyre-fixme[7]: Expected `Tuple[Tensor, Tensor]` but got `Tuple[Any, Any,
|
||||
# Any, Any]`. Expected has length 2, but actual has length 4.
|
||||
return masks, iou_pred, sam_tokens_out, object_score_logits
|
||||
|
||||
def predict_masks(
|
||||
@@ -219,6 +222,7 @@ class MaskDecoder(nn.Module):
|
||||
upscaled_embedding = self.output_upscaling(src)
|
||||
else:
|
||||
dc1, ln1, act1, dc2, act2 = self.output_upscaling
|
||||
# pyre-fixme[23]: Unable to unpack `list[Tensor] | None` into 2 values.
|
||||
feat_s0, feat_s1 = high_res_features
|
||||
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
|
||||
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
|
||||
@@ -241,6 +245,8 @@ class MaskDecoder(nn.Module):
|
||||
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
|
||||
object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
|
||||
|
||||
# pyre-fixme[7]: Expected `Tuple[Tensor, Tensor]` but got `Tuple[Tensor,
|
||||
# Any, Any, Any]`. Expected has length 2, but actual has length 4.
|
||||
return masks, iou_pred, mask_tokens_out, object_score_logits
|
||||
|
||||
def _get_stability_scores(self, mask_logits):
|
||||
|
||||
@@ -33,14 +33,18 @@ def compute_axial_cis(
|
||||
device=None,
|
||||
):
|
||||
freqs_x = 1.0 / (
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
||||
theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim)
|
||||
)
|
||||
freqs_y = 1.0 / (
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
||||
theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim)
|
||||
)
|
||||
|
||||
t_x, t_y = init_t_xy(end_x, end_y, scale_pos, offset, device=device)
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `float`.
|
||||
freqs_x = torch.outer(t_x, freqs_x)
|
||||
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `float`.
|
||||
freqs_y = torch.outer(t_y, freqs_y)
|
||||
freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
|
||||
freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
|
||||
@@ -140,6 +144,7 @@ class VisionRotaryEmbeddingVE(nn.Module):
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
|
||||
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
||||
scale = 1.0
|
||||
if pt_seq_len is not None:
|
||||
|
||||
@@ -195,6 +195,7 @@ class Attention(nn.Module):
|
||||
num_heads: int,
|
||||
downsample_rate: int = 1,
|
||||
dropout: float = 0.0,
|
||||
# pyre-fixme[9]: kv_in_dim has type `int`; used as `None`.
|
||||
kv_in_dim: int = None,
|
||||
use_fa3: bool = False,
|
||||
) -> None:
|
||||
|
||||
@@ -211,9 +211,13 @@ def collate_fn_api(
|
||||
|
||||
for q in data.find_queries:
|
||||
stage_id = q.query_processing_order
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `append`.
|
||||
stages[stage_id].img_ids.append(q.image_id + offset_img_id)
|
||||
if q.query_text not in text_batch:
|
||||
text_batch.append(q.query_text)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `append`.
|
||||
stages[stage_id].text_ids.append(text_batch.index(q.query_text))
|
||||
|
||||
assert q.inference_metadata is not None, (
|
||||
@@ -227,54 +231,91 @@ def collate_fn_api(
|
||||
if q.input_bbox is not None:
|
||||
assert q.input_bbox.numel() % 4 == 0
|
||||
assert q.input_bbox_label is not None
|
||||
# pyre-fixme[16]: Optional type has no attribute `numel`.
|
||||
nb_boxes = q.input_bbox.numel() // 4
|
||||
# pyre-fixme[6]: For 1st argument expected
|
||||
# `pyre_extensions.PyreReadOnly[Sized]` but got `Optional[Tensor]`.
|
||||
assert len(q.input_bbox_label) == nb_boxes
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
# pyre-fixme[16]: Optional type has no attribute `view`.
|
||||
stages[stage_id].input_boxes.append(q.input_bbox.view(nb_boxes, 4))
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_boxes_label.append(
|
||||
q.input_bbox_label.view(nb_boxes)
|
||||
)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_boxes_mask.append(
|
||||
torch.zeros(nb_boxes, dtype=torch.bool)
|
||||
)
|
||||
else:
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_boxes.append(torch.zeros(0, 4))
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_boxes_label.append(
|
||||
torch.zeros(0, dtype=torch.bool)
|
||||
)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_boxes_mask.append(
|
||||
torch.ones(0, dtype=torch.bool)
|
||||
)
|
||||
|
||||
if q.input_points is not None:
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_points.append(
|
||||
# pyre-fixme[16]: Optional type has no attribute `squeeze`.
|
||||
q.input_points.squeeze(0) # Strip a trivial batch index
|
||||
)
|
||||
# All masks will be padded up to the longest length
|
||||
# with 1s before final conversion to batchd tensors
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_points_mask.append(
|
||||
# pyre-fixme[16]: Optional type has no attribute `shape`.
|
||||
torch.zeros(q.input_points.shape[1])
|
||||
)
|
||||
else:
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_points.append(
|
||||
torch.empty(0, input_points_embedding_dim)
|
||||
)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
stages[stage_id].input_points_mask.append(torch.empty(0))
|
||||
|
||||
current_out_boxes = []
|
||||
current_out_object_ids = []
|
||||
# Set the object ids referred to by this query
|
||||
# pyre-fixme[16]: Optional type has no attribute `append`.
|
||||
stages[stage_id].object_ids.append(q.object_ids_output)
|
||||
for object_id in q.object_ids_output:
|
||||
current_out_boxes.append(
|
||||
data.images[q.image_id].objects[object_id].bbox
|
||||
)
|
||||
current_out_object_ids.append(object_id)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `extend`.
|
||||
find_targets[stage_id].boxes.extend(current_out_boxes)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `extend`.
|
||||
find_targets[stage_id].object_ids.extend(current_out_object_ids)
|
||||
if repeats > 0:
|
||||
for _ in range(repeats):
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
|
||||
# attribute `extend`.
|
||||
find_targets[stage_id].repeated_boxes.extend(current_out_boxes)
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `append`.
|
||||
find_targets[stage_id].num_boxes.append(len(current_out_boxes))
|
||||
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
|
||||
# `append`.
|
||||
find_targets[stage_id].is_exhaustive.append(q.is_exhaustive)
|
||||
|
||||
if with_seg_masks:
|
||||
@@ -287,11 +328,18 @@ def collate_fn_api(
|
||||
current_is_valid_segment.append(1)
|
||||
else:
|
||||
dummy_mask = torch.zeros(
|
||||
data.images[q.image_id].data.shape[-2:], dtype=torch.bool
|
||||
# pyre-fixme[16]: Item `Image` of `Image | Tensor` has
|
||||
# no attribute `shape`.
|
||||
data.images[q.image_id].data.shape[-2:],
|
||||
dtype=torch.bool,
|
||||
)
|
||||
current_seg_mask.append(dummy_mask)
|
||||
current_is_valid_segment.append(0)
|
||||
# pyre-fixme[16]: Item `None` of `None | List[Any] | Tensor` has no
|
||||
# attribute `extend`.
|
||||
find_targets[stage_id].segments.extend(current_seg_mask)
|
||||
# pyre-fixme[16]: Item `None` of `None | List[Any] | Tensor` has no
|
||||
# attribute `extend`.
|
||||
find_targets[stage_id].is_valid_segment.extend(current_is_valid_segment)
|
||||
else:
|
||||
# We are not loading segmentation masks
|
||||
@@ -299,6 +347,8 @@ def collate_fn_api(
|
||||
find_targets[stage_id].is_valid_segment = None
|
||||
|
||||
if q.semantic_target is not None:
|
||||
# pyre-fixme[16]: Item `None` of `None | List[Any] | Tensor` has no
|
||||
# attribute `append`.
|
||||
find_targets[stage_id].semantic_segments.append(q.semantic_target)
|
||||
|
||||
offset_img_id += len(data.images)
|
||||
@@ -306,24 +356,44 @@ def collate_fn_api(
|
||||
# Pad input points to equal sequence lengths
|
||||
for i in range(len(stages)):
|
||||
stages[i].input_points = pad_tensor_list_to_longest(
|
||||
stages[i].input_points, dim=0, pad_val=0
|
||||
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
stages[i].input_points,
|
||||
dim=0,
|
||||
pad_val=0,
|
||||
)
|
||||
# Masked-out regions indicated by 1s.
|
||||
stages[i].input_points_mask = pad_tensor_list_to_longest(
|
||||
stages[i].input_points_mask, dim=0, pad_val=1
|
||||
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
stages[i].input_points_mask,
|
||||
dim=0,
|
||||
pad_val=1,
|
||||
)
|
||||
|
||||
# Pad input boxes to equal sequence lengths
|
||||
for i in range(len(stages)):
|
||||
stages[i].input_boxes = pad_tensor_list_to_longest(
|
||||
stages[i].input_boxes, dim=0, pad_val=0
|
||||
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
stages[i].input_boxes,
|
||||
dim=0,
|
||||
pad_val=0,
|
||||
)
|
||||
stages[i].input_boxes_label = pad_tensor_list_to_longest(
|
||||
stages[i].input_boxes_label, dim=0, pad_val=0
|
||||
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
stages[i].input_boxes_label,
|
||||
dim=0,
|
||||
pad_val=0,
|
||||
)
|
||||
# Masked-out regions indicated by 1s.
|
||||
stages[i].input_boxes_mask = pad_tensor_list_to_longest(
|
||||
stages[i].input_boxes_mask, dim=0, pad_val=1
|
||||
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
|
||||
# `Union[List[Any], Tensor]`.
|
||||
stages[i].input_boxes_mask,
|
||||
dim=0,
|
||||
pad_val=1,
|
||||
)
|
||||
|
||||
# Convert to tensors
|
||||
@@ -333,7 +403,10 @@ def collate_fn_api(
|
||||
find_metadatas[i] = convert_my_tensors(find_metadatas[i])
|
||||
# get padded representation for the boxes
|
||||
find_targets[i].boxes_padded = packed_to_padded_naive(
|
||||
find_targets[i].boxes.view(-1, 4), find_targets[i].num_boxes
|
||||
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute
|
||||
# `view`.
|
||||
find_targets[i].boxes.view(-1, 4),
|
||||
find_targets[i].num_boxes,
|
||||
)
|
||||
find_targets[i].object_ids_padded = packed_to_padded_naive(
|
||||
find_targets[i].object_ids, find_targets[i].num_boxes, fill_value=-1
|
||||
|
||||
@@ -157,6 +157,7 @@ class CustomCocoDetectionAPI(VisionDataset):
|
||||
zstd_dict_path=None,
|
||||
filter_query=None,
|
||||
coco_json_loader: Callable = COCO_FROM_JSON,
|
||||
# pyre-fixme[9]: limit_ids has type `int`; used as `None`.
|
||||
limit_ids: int = None,
|
||||
) -> None:
|
||||
super().__init__(root)
|
||||
@@ -191,6 +192,8 @@ class CustomCocoDetectionAPI(VisionDataset):
|
||||
path = current_meta["file_name"]
|
||||
if self.blurring_masks_path is not None:
|
||||
mask_fname = os.path.basename(path).replace(".jpg", "-mask.json")
|
||||
# pyre-fixme[6]: For 1st argument expected `LiteralString` but got
|
||||
# `Optional[str]`.
|
||||
mask_path = os.path.join(self.blurring_masks_path, mask_fname)
|
||||
if os.path.exists(mask_path):
|
||||
with open(mask_path, "r") as fopen:
|
||||
@@ -454,6 +457,7 @@ class Sam3ImageDataset(CustomCocoDetectionAPI):
|
||||
zstd_dict_path=None,
|
||||
filter_query=None,
|
||||
coco_json_loader: Callable = COCO_FROM_JSON,
|
||||
# pyre-fixme[9]: limit_ids has type `int`; used as `None`.
|
||||
limit_ids: int = None,
|
||||
):
|
||||
super(Sam3ImageDataset, self).__init__(
|
||||
|
||||
@@ -251,7 +251,9 @@ class VideoGroundingDataset(Sam3ImageDataset):
|
||||
if datapoint.raw_images is not None:
|
||||
assert len(datapoint.raw_images) == 1, "Expected only one single image"
|
||||
tiled_raw_images = [
|
||||
datapoint.raw_images[0].copy() for _ in range(num_stages_sample)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
|
||||
datapoint.raw_images[0].copy()
|
||||
for _ in range(num_stages_sample)
|
||||
]
|
||||
|
||||
# tile `find_queries: List[FindQueryLoaded]`
|
||||
@@ -261,7 +263,10 @@ class VideoGroundingDataset(Sam3ImageDataset):
|
||||
assert query.query_processing_order == 0
|
||||
# check and make sure that a query doesn't contain pointers or references
|
||||
# to other queries (that cannot be tiled)
|
||||
# pyre-fixme[16]: `FindQueryLoaded` has no attribute `ptr_x`.
|
||||
# pyre-fixme[16]: `FindQueryLoaded` has no attribute `ptr_y`.
|
||||
assert query.ptr_x is None and query.ptr_y is None
|
||||
# pyre-fixme[16]: `FindQueryLoaded` has no attribute `ptr_mem`.
|
||||
assert query.ptr_mem is None
|
||||
# assert query.wkdata_qid is None
|
||||
# assert query.other_positive_qids is None
|
||||
@@ -290,6 +295,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
|
||||
else:
|
||||
tiled_get_queries = []
|
||||
|
||||
# pyre-fixme[28]: Unexpected keyword argument `get_queries`.
|
||||
return Datapoint(
|
||||
images=tiled_images,
|
||||
raw_images=tiled_raw_images,
|
||||
@@ -318,9 +324,11 @@ class VideoGroundingDataset(Sam3ImageDataset):
|
||||
[queries[idx] for idx in sampled_inds] for queries in find_queries_per_stage
|
||||
]
|
||||
sampled_find_queries = sum(sampled_find_queries_per_stage, [])
|
||||
# pyre-fixme[28]: Unexpected keyword argument `get_queries`.
|
||||
return Datapoint(
|
||||
images=datapoint.images,
|
||||
raw_images=datapoint.raw_images,
|
||||
find_queries=sampled_find_queries,
|
||||
# pyre-fixme[16]: `Datapoint` has no attribute `get_queries`.
|
||||
get_queries=datapoint.get_queries,
|
||||
)
|
||||
|
||||
@@ -38,8 +38,10 @@ class TorchDataset:
|
||||
if self.sampler:
|
||||
self.sampler.set_epoch(epoch)
|
||||
if hasattr(self.dataset, "epoch"):
|
||||
# pyre-fixme[16]: `Dataset` has no attribute `epoch`.
|
||||
self.dataset.epoch = epoch
|
||||
if hasattr(self.dataset, "set_epoch"):
|
||||
# pyre-fixme[16]: `Dataset` has no attribute `set_epoch`.
|
||||
self.dataset.set_epoch(epoch)
|
||||
|
||||
return DataLoader(
|
||||
|
||||
@@ -9,6 +9,7 @@ import numpy as np
|
||||
# Check if Numba is available
|
||||
HAS_NUMBA = False
|
||||
try:
|
||||
# pyre-fixme[21]: Could not find module `numba`.
|
||||
import numba as nb
|
||||
|
||||
HAS_NUMBA = True
|
||||
|
||||
@@ -103,6 +103,8 @@ def set_default_parameters(
|
||||
if default_count == 0:
|
||||
# No default scheduler specified, add a default, but without any scheduler
|
||||
# for that option
|
||||
# pyre-fixme[6]: For 1st argument expected `DictConfig` but got `Dict[str,
|
||||
# Set[str]]`.
|
||||
scheduler_cfgs.append({"parameter_names": default_params})
|
||||
|
||||
|
||||
@@ -122,6 +124,7 @@ def name_constraints_to_parameters(
|
||||
param_constraints.
|
||||
"""
|
||||
matching_names = set.intersection(*param_constraints)
|
||||
# pyre-fixme[7]: Expected `List[Parameter]` but got `List[Tensor]`.
|
||||
return [value for name, value in named_parameters.items() if name in matching_names]
|
||||
|
||||
|
||||
@@ -260,8 +263,14 @@ def _unix_pattern_to_parameter_names(
|
||||
"""
|
||||
if "param_names" not in scheduler_cfg and "module_cls_names" not in scheduler_cfg:
|
||||
return None
|
||||
# pyre-fixme[16]: `Optional` has no attribute `union`.
|
||||
return unix_param_pattern_to_parameter_names(
|
||||
scheduler_cfg.get("param_names"), parameter_names
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
|
||||
# `Set[str]`.
|
||||
scheduler_cfg.get("param_names"),
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
|
||||
# `Set[str]`.
|
||||
parameter_names,
|
||||
).union(
|
||||
unix_module_cls_pattern_to_parameter_names(
|
||||
scheduler_cfg.get("module_cls_names"), module_cls_to_param_names
|
||||
@@ -270,7 +279,10 @@ def _unix_pattern_to_parameter_names(
|
||||
|
||||
|
||||
def get_module_cls_to_param_names(
|
||||
model: nn.Module, param_allowlist: Set[str] = None
|
||||
# pyre-fixme[9]: param_allowlist has type `Set[str]`; used as `None`.
|
||||
model: nn.Module,
|
||||
# pyre-fixme[9]: param_allowlist has type `Set[str]`; used as `None`.
|
||||
param_allowlist: Set[str] = None,
|
||||
) -> Dict[Type, str]:
|
||||
"""Produce a mapping from all the modules classes to the names of parames they own.
|
||||
|
||||
@@ -296,7 +308,10 @@ def get_module_cls_to_param_names(
|
||||
def construct_optimizer(
|
||||
model: torch.nn.Module,
|
||||
optimizer_conf: Any,
|
||||
# pyre-fixme[9]: options_conf has type `Mapping[str, List[Any]]`; used as `None`.
|
||||
options_conf: Mapping[str, List] = None,
|
||||
# pyre-fixme[9]: param_group_modifiers_conf has type `List[(...) -> Any]`; used
|
||||
# as `None`.
|
||||
param_group_modifiers_conf: List[Callable] = None,
|
||||
param_allowlist: Optional[Set[str]] = None,
|
||||
validate_param_groups=True,
|
||||
@@ -360,7 +375,12 @@ def construct_optimizer(
|
||||
scheduler_cfgs=all_scheduler_cfgs, model=model
|
||||
)
|
||||
schedulers, param_groups = map_scheduler_cfgs_to_param_groups(
|
||||
all_scheduler_cfgs, named_parameters
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
|
||||
# `Dict[str, Parameter]`.
|
||||
all_scheduler_cfgs,
|
||||
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
|
||||
# `Dict[str, Parameter]`.
|
||||
named_parameters,
|
||||
)
|
||||
if validate_param_groups:
|
||||
validate_param_group_params(param_groups, model)
|
||||
@@ -403,6 +423,7 @@ class ValueScaler:
|
||||
return val * self.mult_val
|
||||
|
||||
|
||||
# pyre-fixme[9]: rattrs has type `str`; used as `None`.
|
||||
def rgetattr(obj, rattrs: str = None):
|
||||
"""
|
||||
Like getattr(), but supports dotted notation for nested objects.
|
||||
@@ -422,6 +443,7 @@ def layer_decay_param_modifier(
|
||||
layer_decay_value: float,
|
||||
layer_decay_min: Optional[float] = None,
|
||||
apply_to: Optional[str] = None,
|
||||
# pyre-fixme[9]: overrides has type `List[Dict[Any, Any]]`; used as `Tuple[]`.
|
||||
overrides: List[Dict] = (),
|
||||
) -> List[List[Dict]]:
|
||||
"""
|
||||
@@ -443,6 +465,7 @@ def layer_decay_param_modifier(
|
||||
Returns
|
||||
- scheduler_configs: same structure as the input, elements can be modified
|
||||
"""
|
||||
# pyre-fixme[6]: For 2nd argument expected `str` but got `Optional[str]`.
|
||||
model = rgetattr(model, apply_to)
|
||||
num_layers = model.get_num_layers() + 1
|
||||
layer_decays = [
|
||||
|
||||
@@ -10,6 +10,7 @@ import traceback
|
||||
from argparse import ArgumentParser
|
||||
from copy import deepcopy
|
||||
|
||||
# pyre-fixme[21]: Could not find module `submitit`.
|
||||
import submitit
|
||||
import torch
|
||||
from hydra import compose, initialize_config_module
|
||||
@@ -82,6 +83,7 @@ def format_exception(e: Exception, limit=20):
|
||||
return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
|
||||
|
||||
|
||||
# pyre-fixme[11]: Annotation `Checkpointable` is not defined as a type.
|
||||
class SubmititRunner(submitit.helpers.Checkpointable):
|
||||
"""A callable which is passed to submitit to launch the jobs."""
|
||||
|
||||
|
||||
+24
-1
@@ -68,6 +68,7 @@ class OptimAMPConf:
|
||||
|
||||
@dataclass
|
||||
class OptimConf:
|
||||
# pyre-fixme[8]: Attribute has type `Optimizer`; used as `None`.
|
||||
optimizer: torch.optim.Optimizer = None
|
||||
options: Optional[Dict[str, Any]] = None
|
||||
param_group_modifiers: Optional[List] = None
|
||||
@@ -111,6 +112,7 @@ class CheckpointConf:
|
||||
save_freq: int
|
||||
save_list: List[int] = field(default_factory=list)
|
||||
model_weight_initializer: Any = None
|
||||
# pyre-fixme[8]: Attribute has type `List[str]`; used as `None`.
|
||||
save_best_meters: List[str] = None
|
||||
skip_saving_parameters: List[str] = field(default_factory=list)
|
||||
initialize_after_preemption: Optional[bool] = None
|
||||
@@ -157,7 +159,9 @@ class Trainer:
|
||||
accelerator: str = "cuda",
|
||||
seed_value: int = 123,
|
||||
val_epoch_freq: int = 1,
|
||||
# pyre-fixme[9]: distributed has type `Dict[str, bool]`; used as `None`.
|
||||
distributed: Dict[str, bool] = None,
|
||||
# pyre-fixme[9]: cuda has type `Dict[str, bool]`; used as `None`.
|
||||
cuda: Dict[str, bool] = None,
|
||||
env_variables: Optional[Dict[str, Any]] = None,
|
||||
optim: Optional[Dict[str, Any]] = None,
|
||||
@@ -183,7 +187,12 @@ class Trainer:
|
||||
self.meters_conf = meters
|
||||
self.loss_conf = loss
|
||||
self.gradient_accumulation_steps = gradient_accumulation_steps
|
||||
# pyre-fixme[9]: distributed has type `Dict[str, bool]`; used as
|
||||
# `DistributedConf`.
|
||||
# pyre-fixme[6]: For 1st argument expected `Optional[str]` but got
|
||||
# `Union[bool, _VT]`.
|
||||
distributed = DistributedConf(**distributed or {})
|
||||
# pyre-fixme[9]: cuda has type `Dict[str, bool]`; used as `CudaConf`.
|
||||
cuda = CudaConf(**cuda or {})
|
||||
self.where = 0.0
|
||||
|
||||
@@ -218,6 +227,7 @@ class Trainer:
|
||||
self._construct_optimizers()
|
||||
self._setup_dataloaders()
|
||||
|
||||
# pyre-fixme[16]: `Trainer` has no attribute `device`.
|
||||
self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
|
||||
|
||||
if self.checkpoint_conf.resume_from is not None:
|
||||
@@ -450,6 +460,7 @@ class Trainer:
|
||||
self.steps = checkpoint["steps"]
|
||||
self.ckpt_time_elapsed = checkpoint.get("time_elapsed")
|
||||
|
||||
# pyre-fixme[16]: `Optional` has no attribute `enabled`.
|
||||
if self.optim_conf.amp.enabled and "scaler" in checkpoint:
|
||||
self.scaler.load_state_dict(checkpoint["scaler"])
|
||||
|
||||
@@ -491,7 +502,9 @@ class Trainer:
|
||||
model: nn.Module,
|
||||
phase: str,
|
||||
):
|
||||
# pyre-fixme[16]: `BatchedDatapoint` has no attribute `popitem`.
|
||||
key, batch = batch.popitem()
|
||||
# pyre-fixme[16]: `Trainer` has no attribute `device`.
|
||||
batch = copy_data_to_device(batch, self.device, non_blocking=True)
|
||||
|
||||
find_stages = model(batch)
|
||||
@@ -925,8 +938,12 @@ class Trainer:
|
||||
accum_steps = len(batch)
|
||||
else:
|
||||
accum_steps = 1
|
||||
# pyre-fixme[9]: batch has type `BatchedDatapoint`; used as
|
||||
# `List[BatchedDatapoint]`.
|
||||
batch = [batch]
|
||||
|
||||
# pyre-fixme[6]: For 1st argument expected `Iterable[_T]` but got
|
||||
# `BatchedDatapoint`.
|
||||
for i, chunked_batch in enumerate(batch):
|
||||
ddp_context = (
|
||||
self.model.no_sync()
|
||||
@@ -936,7 +953,9 @@ class Trainer:
|
||||
with ddp_context:
|
||||
with torch.amp.autocast(
|
||||
device_type="cuda",
|
||||
# pyre-fixme[16]: `Optional` has no attribute `enabled`.
|
||||
enabled=self.optim_conf.amp.enabled,
|
||||
# pyre-fixme[16]: `Optional` has no attribute `amp_dtype`.
|
||||
dtype=get_amp_type(self.optim_conf.amp.amp_dtype),
|
||||
):
|
||||
loss_dict, batch_size, extra_losses = self._step(
|
||||
@@ -961,7 +980,11 @@ class Trainer:
|
||||
for extra_loss_key, extra_loss in extra_losses.items():
|
||||
if extra_loss_key not in extra_loss_mts:
|
||||
extra_loss_mts[extra_loss_key] = AverageMeter(
|
||||
extra_loss_key, self.device, ":.2e"
|
||||
# pyre-fixme[16]: `Trainer` has no attribute `device`.
|
||||
extra_loss_key,
|
||||
# pyre-fixme[16]: `Trainer` has no attribute `device`.
|
||||
self.device,
|
||||
":.2e",
|
||||
)
|
||||
extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size)
|
||||
|
||||
|
||||
@@ -284,6 +284,7 @@ class RandomSizeCrop:
|
||||
else:
|
||||
w = random.randint(self.min_size, min(img.width, self.max_size))
|
||||
h = random.randint(self.min_size, min(img.height, self.max_size))
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Image`.
|
||||
region = T.RandomCrop.get_params(img, (h, w))
|
||||
result_img, result_target = crop(img, target, region)
|
||||
return result_img, result_target
|
||||
|
||||
@@ -871,10 +871,14 @@ class ToTensorAPI:
|
||||
def __call__(self, datapoint: Datapoint, **kwargs):
|
||||
for img in datapoint.images:
|
||||
if self.v2:
|
||||
# pyre-fixme[16]: Module `functional` has no attribute
|
||||
# `to_image_tensor`.
|
||||
img.data = Fv2.to_image_tensor(img.data)
|
||||
# img.data = Fv2.to_dtype(img.data, torch.uint8, scale=True)
|
||||
# img.data = Fv2.convert_image_dtype(img.data, torch.uint8)
|
||||
else:
|
||||
# pyre-fixme[6]: For 1st argument expected `Union[Image, ndarray]`
|
||||
# but got `Union[Image, Tensor]`.
|
||||
img.data = F.to_tensor(img.data)
|
||||
return datapoint
|
||||
|
||||
@@ -888,12 +892,18 @@ class NormalizeAPI:
|
||||
def __call__(self, datapoint: Datapoint, **kwargs):
|
||||
for img in datapoint.images:
|
||||
if self.v2:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img.data = Fv2.convert_image_dtype(img.data, torch.float32)
|
||||
img.data = Fv2.normalize(img.data, mean=self.mean, std=self.std)
|
||||
else:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img.data = F.normalize(img.data, mean=self.mean, std=self.std)
|
||||
for obj in img.objects:
|
||||
boxes = obj.bbox
|
||||
# pyre-fixme[16]: Item `Image` of `Image | Tensor` has no attribute
|
||||
# `shape`.
|
||||
cur_h, cur_w = img.data.shape[-2:]
|
||||
boxes = box_xyxy_to_cxcywh(boxes)
|
||||
boxes = boxes / torch.tensor(
|
||||
@@ -904,6 +914,8 @@ class NormalizeAPI:
|
||||
for query in datapoint.find_queries:
|
||||
if query.input_bbox is not None:
|
||||
boxes = query.input_bbox
|
||||
# pyre-fixme[16]: Item `Image` of `Image | Tensor` has no attribute
|
||||
# `shape`.
|
||||
cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
|
||||
boxes = box_xyxy_to_cxcywh(boxes)
|
||||
boxes = boxes / torch.tensor(
|
||||
@@ -912,6 +924,8 @@ class NormalizeAPI:
|
||||
query.input_bbox = boxes
|
||||
if query.input_points is not None:
|
||||
points = query.input_points
|
||||
# pyre-fixme[16]: Item `Image` of `Image | Tensor` has no attribute
|
||||
# `shape`.
|
||||
cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
|
||||
points = points / torch.tensor([cur_w, cur_h, 1.0], dtype=torch.float32)
|
||||
query.input_points = points
|
||||
@@ -999,13 +1013,34 @@ class ColorJitter:
|
||||
self.brightness, self.contrast, self.saturation, self.hue
|
||||
)
|
||||
for fn_id in fn_idx:
|
||||
# pyre-fixme[61]: `brightness_factor` is undefined, or not always
|
||||
# defined.
|
||||
if fn_id == 0 and brightness_factor is not None:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
# pyre-fixme[61]: `brightness_factor` is undefined, or not
|
||||
# always defined.
|
||||
img.data = F.adjust_brightness(img.data, brightness_factor)
|
||||
# pyre-fixme[61]: `contrast_factor` is undefined, or not always defined.
|
||||
elif fn_id == 1 and contrast_factor is not None:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
# pyre-fixme[61]: `contrast_factor` is undefined, or not always
|
||||
# defined.
|
||||
img.data = F.adjust_contrast(img.data, contrast_factor)
|
||||
# pyre-fixme[61]: `saturation_factor` is undefined, or not always
|
||||
# defined.
|
||||
elif fn_id == 2 and saturation_factor is not None:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
# pyre-fixme[61]: `saturation_factor` is undefined, or not
|
||||
# always defined.
|
||||
img.data = F.adjust_saturation(img.data, saturation_factor)
|
||||
# pyre-fixme[61]: `hue_factor` is undefined, or not always defined.
|
||||
elif fn_id == 3 and hue_factor is not None:
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
# pyre-fixme[61]: `hue_factor` is undefined, or not always defined.
|
||||
img.data = F.adjust_hue(img.data, hue_factor)
|
||||
return datapoint
|
||||
|
||||
@@ -1058,6 +1093,8 @@ class RandomAffine:
|
||||
return datapoint
|
||||
|
||||
def transform_datapoint(self, datapoint: Datapoint):
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Union[Image,
|
||||
# Tensor]`.
|
||||
_, height, width = F.get_dimensions(datapoint.images[0].data)
|
||||
img_size = [width, height]
|
||||
|
||||
@@ -1073,6 +1110,8 @@ class RandomAffine:
|
||||
|
||||
for img_idx, img in enumerate(datapoint.images):
|
||||
this_masks = [
|
||||
# pyre-fixme[16]: Item `dict` of `dict[Any, Any] | Tensor` has no
|
||||
# attribute `unsqueeze`.
|
||||
obj.segment.unsqueeze(0) if obj.segment is not None else None
|
||||
for obj in img.objects
|
||||
]
|
||||
@@ -1093,10 +1132,18 @@ class RandomAffine:
|
||||
# Dummy bbox for a dummy target
|
||||
transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
|
||||
else:
|
||||
# pyre-fixme[6]: For 3rd argument expected `List[int]` but got
|
||||
# `Tuple[int, int]`.
|
||||
# pyre-fixme[6]: For 5th argument expected `List[float]` but got
|
||||
# `Tuple[float, float]`.
|
||||
transformed_mask = F.affine(
|
||||
this_masks[i],
|
||||
# pyre-fixme[61]: `affine_params` is undefined, or not
|
||||
# always defined.
|
||||
*affine_params,
|
||||
interpolation=InterpolationMode.NEAREST,
|
||||
# pyre-fixme[6]: For 7th argument expected
|
||||
# `Optional[List[float]]` but got `float`.
|
||||
fill=0.0,
|
||||
)
|
||||
if img_idx == 0 and transformed_mask.max() == 0:
|
||||
@@ -1111,8 +1158,15 @@ class RandomAffine:
|
||||
img.objects[i].bbox = transformed_bboxes[i]
|
||||
img.objects[i].segment = transformed_masks[i]
|
||||
|
||||
# pyre-fixme[6]: For 3rd argument expected `List[int]` but got
|
||||
# `Tuple[int, int]`.
|
||||
# pyre-fixme[6]: For 5th argument expected `List[float]` but got
|
||||
# `Tuple[float, float]`.
|
||||
img.data = F.affine(
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img.data,
|
||||
# pyre-fixme[61]: `affine_params` is undefined, or not always defined.
|
||||
*affine_params,
|
||||
interpolation=self.image_interpolation,
|
||||
fill=self.fill_img,
|
||||
@@ -1174,6 +1228,8 @@ class RandomResizedCrop:
|
||||
if self.consistent_transform:
|
||||
# Create a random crop transformation
|
||||
crop_params = T.RandomResizedCrop.get_params(
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img=datapoint.images[0].data,
|
||||
scale=self.scale,
|
||||
ratio=ratio,
|
||||
@@ -1183,12 +1239,16 @@ class RandomResizedCrop:
|
||||
if not self.consistent_transform:
|
||||
# Create a random crop transformation
|
||||
crop_params = T.RandomResizedCrop.get_params(
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img=img.data,
|
||||
scale=self.scale,
|
||||
ratio=ratio,
|
||||
)
|
||||
|
||||
this_masks = [
|
||||
# pyre-fixme[16]: Item `dict` of `dict[Any, Any] | Tensor` has no
|
||||
# attribute `unsqueeze`.
|
||||
obj.segment.unsqueeze(0) if obj.segment is not None else None
|
||||
for obj in img.objects
|
||||
]
|
||||
@@ -1202,6 +1262,8 @@ class RandomResizedCrop:
|
||||
else:
|
||||
transformed_mask = F.resized_crop(
|
||||
this_masks[i],
|
||||
# pyre-fixme[61]: `crop_params` is undefined, or not always
|
||||
# defined.
|
||||
*crop_params,
|
||||
size=self.size,
|
||||
interpolation=InterpolationMode.NEAREST,
|
||||
@@ -1220,7 +1282,10 @@ class RandomResizedCrop:
|
||||
img.objects[i].segment = transformed_masks[i]
|
||||
|
||||
img.data = F.resized_crop(
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
img.data,
|
||||
# pyre-fixme[61]: `crop_params` is undefined, or not always defined.
|
||||
*crop_params,
|
||||
size=self.size,
|
||||
interpolation=InterpolationMode.BILINEAR,
|
||||
@@ -1237,6 +1302,8 @@ class ResizeToMaxIfAbove:
|
||||
self.max_size = max_size
|
||||
|
||||
def __call__(self, datapoint: Datapoint, **kwargs):
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Union[Image,
|
||||
# Tensor]`.
|
||||
_, height, width = F.get_dimensions(datapoint.images[0].data)
|
||||
|
||||
if height <= self.max_size and width <= self.max_size:
|
||||
@@ -1252,10 +1319,14 @@ class ResizeToMaxIfAbove:
|
||||
size = new_height, new_width
|
||||
|
||||
for index in range(len(datapoint.images)):
|
||||
# pyre-fixme[6]: For 1st argument expected `Tensor` but got
|
||||
# `Union[Image, Tensor]`.
|
||||
datapoint.images[index].data = F.resize(datapoint.images[index].data, size)
|
||||
|
||||
for obj in datapoint.images[index].objects:
|
||||
obj.segment = F.resize(
|
||||
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any] |
|
||||
# Tensor` has no attribute `__getitem__`.
|
||||
obj.segment[None, None],
|
||||
size,
|
||||
interpolation=InterpolationMode.NEAREST,
|
||||
@@ -1302,6 +1373,7 @@ class MotionBlur:
|
||||
if not self.consistent_transform:
|
||||
# Generate a new motion blur kernel for each image
|
||||
kernel = self._generate_motion_blur_kernel()
|
||||
# pyre-fixme[61]: `kernel` is undefined, or not always defined.
|
||||
img.data = self._apply_motion_blur(img.data, kernel)
|
||||
|
||||
return datapoint
|
||||
@@ -1364,6 +1436,8 @@ class LargeScaleJitter:
|
||||
log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
|
||||
scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
|
||||
aspect_ratio = torch.exp(
|
||||
# pyre-fixme[6]: For 1st argument expected `float` but got `Tensor`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `float` but got `Tensor`.
|
||||
torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
|
||||
).item()
|
||||
|
||||
@@ -1373,6 +1447,8 @@ class LargeScaleJitter:
|
||||
log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
|
||||
scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
|
||||
aspect_ratio = torch.exp(
|
||||
# pyre-fixme[6]: For 1st argument expected `float` but got `Tensor`.
|
||||
# pyre-fixme[6]: For 2nd argument expected `float` but got `Tensor`.
|
||||
torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
|
||||
).item()
|
||||
|
||||
|
||||
@@ -12,8 +12,11 @@ from sam3.train.data.sam3_image_dataset import Datapoint, FindQuery, Object
|
||||
|
||||
|
||||
class FilterDataPointQueries:
|
||||
# pyre-fixme[8]: Attribute has type `Set[Any]`; used as `None`.
|
||||
find_ids_to_filter: set = None
|
||||
# pyre-fixme[8]: Attribute has type `Set[Any]`; used as `None`.
|
||||
get_ids_to_filter: set = None
|
||||
# pyre-fixme[8]: Attribute has type `Set[Any]`; used as `None`.
|
||||
obj_ids_to_filter: set = None # stored as pairs (img_id, obj_id)
|
||||
|
||||
def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
|
||||
@@ -34,7 +37,13 @@ class FilterQueryWithText(FilterDataPointQueries):
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, exclude_find_keys: List[str] = None, exclude_get_keys: List[str] = None
|
||||
# pyre-fixme[9]: exclude_find_keys has type `List[str]`; used as `None`.
|
||||
# pyre-fixme[9]: exclude_get_keys has type `List[str]`; used as `None`.
|
||||
self,
|
||||
# pyre-fixme[9]: exclude_find_keys has type `List[str]`; used as `None`.
|
||||
exclude_find_keys: List[str] = None,
|
||||
# pyre-fixme[9]: exclude_get_keys has type `List[str]`; used as `None`.
|
||||
exclude_get_keys: List[str] = None,
|
||||
):
|
||||
self.find_filter_keys = exclude_find_keys if exclude_find_keys else []
|
||||
self.get_filter_keys = exclude_get_keys if exclude_get_keys else []
|
||||
@@ -219,7 +228,11 @@ class FilterZeroBoxQueries(FilterDataPointQueries):
|
||||
def _is_zero_area_object(obj: Object):
|
||||
# Check if height or width of bounding box is zero
|
||||
bbox = obj.bbox # Assume in XYXY format
|
||||
# pyre-fixme[6]: For 1st argument expected `int` but got `Union[bool, float,
|
||||
# int]`.
|
||||
height = bbox[..., 3].item() - bbox[..., 1].item()
|
||||
# pyre-fixme[6]: For 1st argument expected `int` but got `Union[bool, float,
|
||||
# int]`.
|
||||
width = bbox[..., 2].item() - bbox[..., 0].item()
|
||||
|
||||
return height == 0 or width == 0
|
||||
|
||||
@@ -334,8 +334,11 @@ class RandomizeInputBbox:
|
||||
assert isinstance(img, torch.Tensor)
|
||||
h, w = img.shape[-2:]
|
||||
|
||||
# pyre-fixme[16]: Optional type has no attribute `shape`.
|
||||
for box_id in range(query.input_bbox.shape[0]):
|
||||
# pyre-fixme[16]: Optional type has no attribute `__setitem__`.
|
||||
query.input_bbox[box_id, :] = noise_box(
|
||||
# pyre-fixme[16]: Optional type has no attribute `__getitem__`.
|
||||
query.input_bbox[box_id, :].view(4),
|
||||
(h, w),
|
||||
box_noise_std=self.box_noise_std,
|
||||
|
||||
@@ -31,8 +31,12 @@ class InstanceToSemantic(object):
|
||||
# we need to double check that all rles are the correct size
|
||||
# Otherwise cocotools will fail silently to an empty [0,0] mask
|
||||
for seg in all_segs:
|
||||
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any] |
|
||||
# Tensor` has no attribute `__getitem__`.
|
||||
assert seg["size"] == all_segs[0]["size"], (
|
||||
"Instance segments have inconsistent sizes. "
|
||||
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any]
|
||||
# | Tensor` has no attribute `__getitem__`.
|
||||
f"Found sizes {seg['size']} and {all_segs[0]['size']}"
|
||||
)
|
||||
fquery.semantic_target = mask_utils.merge(all_segs)
|
||||
@@ -54,6 +58,7 @@ class InstanceToSemantic(object):
|
||||
isinstance(segment, torch.Tensor)
|
||||
and segment.dtype == torch.uint8
|
||||
)
|
||||
# pyre-fixme[16]: Optional type has no attribute `__ior__`.
|
||||
fquery.semantic_target |= segment
|
||||
|
||||
if self.delete_instance:
|
||||
@@ -74,6 +79,8 @@ class RecomputeBoxesFromMasks:
|
||||
# Note: if the mask is empty, the bounding box will be undefined
|
||||
# The empty targets should be subsequently filtered
|
||||
obj.bbox = masks_to_boxes(obj.segment)
|
||||
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any] | Tensor`
|
||||
# has no attribute `sum`.
|
||||
obj.area = obj.segment.sum().item()
|
||||
|
||||
return datapoint
|
||||
@@ -114,6 +121,7 @@ class DecodeRle:
|
||||
# segment is uint8 and remains uint8 throughout the transforms
|
||||
obj.segment = torch.tensor(obj.segment).to(torch.uint8)
|
||||
|
||||
# pyre-fixme[16]: `dict` has no attribute `shape`.
|
||||
if list(obj.segment.shape) != [img_h, img_w]:
|
||||
# Should not happen often, but adding for security
|
||||
if not warning_shown:
|
||||
@@ -124,7 +132,12 @@ class DecodeRle:
|
||||
warning_shown = True
|
||||
|
||||
obj.segment = F.resize(
|
||||
obj.segment[None], (img_h, img_w)
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[int]`
|
||||
# but got `Tuple[int, int]`.
|
||||
obj.segment[None],
|
||||
# pyre-fixme[6]: For 2nd argument expected `List[int]`
|
||||
# but got `Tuple[int, int]`.
|
||||
(img_h, img_w),
|
||||
).squeeze(0)
|
||||
|
||||
assert list(obj.segment.shape) == [img_h, img_w]
|
||||
|
||||
@@ -61,6 +61,7 @@ def filter_params_matching_unix_pattern(
|
||||
|
||||
all_keys = list(state_dict.keys())
|
||||
included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
|
||||
# pyre-fixme[16]: `Optional` has no attribute `__iter__`.
|
||||
return {k: state_dict[k] for k in included_keys}
|
||||
|
||||
|
||||
@@ -82,6 +83,8 @@ def exclude_params_matching_unix_pattern(
|
||||
|
||||
all_keys = list(state_dict.keys())
|
||||
excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
|
||||
# pyre-fixme[58]: `not in` is not supported for right operand type
|
||||
# `Optional[Set[str]]`.
|
||||
return {k: v for k, v in state_dict.items() if k not in excluded_keys}
|
||||
|
||||
|
||||
@@ -180,8 +183,15 @@ class CkptExcludeKernel:
|
||||
if len(self.key_pattern) == 0:
|
||||
return state_dict
|
||||
exclude_keys = unix_pattern_to_parameter_names(
|
||||
self.key_pattern, state_dict.keys()
|
||||
# pyre-fixme[6]: For 2nd argument expected `Sequence[str]` but got
|
||||
# `dict_keys[Any, Any]`.
|
||||
self.key_pattern,
|
||||
# pyre-fixme[6]: For 2nd argument expected `Sequence[str]` but got
|
||||
# `dict_keys[Any, Any]`.
|
||||
state_dict.keys(),
|
||||
)
|
||||
# pyre-fixme[58]: `not in` is not supported for right operand type
|
||||
# `Optional[Set[str]]`.
|
||||
return {k: v for k, v in state_dict.items() if k not in exclude_keys}
|
||||
|
||||
|
||||
@@ -213,9 +223,11 @@ def load_checkpoint(
|
||||
if not path_exists:
|
||||
raise ValueError(f"No path exists in {path_list}")
|
||||
|
||||
# pyre-fixme[61]: `path` is undefined, or not always defined.
|
||||
with g_pathmgr.open(path, "rb") as f:
|
||||
checkpoint = torch.load(f, map_location=map_location)
|
||||
|
||||
# pyre-fixme[61]: `path` is undefined, or not always defined.
|
||||
logging.info(f"Loaded checkpoint from {path}")
|
||||
if pick_recursive_keys is not None:
|
||||
for key in pick_recursive_keys:
|
||||
@@ -245,6 +257,7 @@ def get_state_dict(checkpoint, ckpt_state_dict_keys):
|
||||
|
||||
def load_checkpoint_and_apply_kernels(
|
||||
checkpoint_path: str,
|
||||
# pyre-fixme[9]: checkpoint_kernels has type `List[(...) -> Any]`; used as `None`.
|
||||
checkpoint_kernels: List[Callable] = None,
|
||||
ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
|
||||
map_location: str = "cpu",
|
||||
@@ -297,13 +310,17 @@ def check_load_state_dict_errors(
|
||||
missing_keys,
|
||||
unexpected_keys,
|
||||
strict: bool,
|
||||
# pyre-fixme[9]: ignore_missing_keys has type `List[str]`; used as `None`.
|
||||
ignore_missing_keys: List[str] = None,
|
||||
# pyre-fixme[9]: ignore_unexpected_keys has type `List[str]`; used as `None`.
|
||||
ignore_unexpected_keys: List[str] = None,
|
||||
):
|
||||
if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
|
||||
ignored_keys = unix_pattern_to_parameter_names(
|
||||
ignore_missing_keys, missing_keys
|
||||
)
|
||||
# pyre-fixme[58]: `not in` is not supported for right operand type
|
||||
# `Optional[Set[str]]`.
|
||||
missing_keys = [key for key in missing_keys if key not in ignored_keys]
|
||||
|
||||
if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
|
||||
@@ -311,7 +328,13 @@ def check_load_state_dict_errors(
|
||||
ignore_unexpected_keys, unexpected_keys
|
||||
)
|
||||
unexpected_keys = [
|
||||
key for key in unexpected_keys if key not in ignored_unexpected_keys
|
||||
# pyre-fixme[58]: `not in` is not supported for right operand type
|
||||
# `Optional[Set[str]]`.
|
||||
key
|
||||
for key in unexpected_keys
|
||||
# pyre-fixme[58]: `not in` is not supported for right operand type
|
||||
# `Optional[Set[str]]`.
|
||||
if key not in ignored_unexpected_keys
|
||||
]
|
||||
|
||||
err = "State key mismatch."
|
||||
@@ -330,8 +353,11 @@ def load_state_dict_into_model(
|
||||
state_dict: Dict,
|
||||
model: nn.Module,
|
||||
strict: bool = True,
|
||||
# pyre-fixme[9]: ignore_missing_keys has type `List[str]`; used as `None`.
|
||||
ignore_missing_keys: List[str] = None,
|
||||
# pyre-fixme[9]: ignore_unexpected_keys has type `List[str]`; used as `None`.
|
||||
ignore_unexpected_keys: List[str] = None,
|
||||
# pyre-fixme[9]: checkpoint_kernels has type `List[(...) -> Any]`; used as `None`.
|
||||
checkpoint_kernels: List[Callable] = None,
|
||||
):
|
||||
"""
|
||||
|
||||
@@ -271,6 +271,7 @@ def all_reduce_max(tensor: torch.Tensor) -> torch.Tensor:
|
||||
def all_reduce_op(
|
||||
tensor: torch.Tensor,
|
||||
op: torch.distributed.ReduceOp,
|
||||
# pyre-fixme[9]: after_op_func has type `(Tensor) -> Tensor`; used as `None`.
|
||||
after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
@@ -436,6 +437,8 @@ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True)
|
||||
# Fetch from the source
|
||||
length_tensor = torch.LongTensor([0])
|
||||
length_tensor = broadcast(length_tensor, src=src)
|
||||
# pyre-fixme[6]: For 1st argument expected `Sequence[Union[int, SymInt]]`
|
||||
# but got `Sequence[Union[bool, float, int]]`.
|
||||
data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
|
||||
data_tensor = broadcast(data_tensor, src=src)
|
||||
if use_disk:
|
||||
|
||||
@@ -36,6 +36,7 @@ class TensorBoardWriterWrapper:
|
||||
self,
|
||||
path: str,
|
||||
*args: Any,
|
||||
# pyre-fixme[9]: filename_suffix has type `str`; used as `None`.
|
||||
filename_suffix: str = None,
|
||||
summary_writer_method: Any = SummaryWriter,
|
||||
**kwargs: Any,
|
||||
|
||||
@@ -636,6 +636,7 @@ def draw_masks_to_frame(
|
||||
cv2.CHAIN_APPROX_NONE,
|
||||
)
|
||||
else:
|
||||
# pyre-fixme[23]: Unable to unpack 2 values, 3 were expected.
|
||||
_, contours, _ = cv2.findContours(
|
||||
np.array(mask, dtype=np.uint8).copy(),
|
||||
cv2.RETR_TREE,
|
||||
|
||||
@@ -8,6 +8,8 @@ from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
# pyre-fixme[21]: Could not find module `fathomnet.api`.
|
||||
from fathomnet.api import images
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import requests
|
||||
|
||||
# pyre-fixme[21]: Could not find module `utils`.
|
||||
import utils
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
|
||||
@@ -10,7 +10,10 @@ import sys
|
||||
from concurrent.futures import as_completed, ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
# pyre-fixme[21]: Could not find module `yt_dlp`.
|
||||
import yt_dlp
|
||||
|
||||
# pyre-fixme[21]: Could not find module `utils`.
|
||||
from utils import (
|
||||
annotation_files,
|
||||
config,
|
||||
|
||||
@@ -16,6 +16,8 @@ from multiprocessing import Pool
|
||||
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
|
||||
# pyre-fixme[21]: Could not find module `utils`.
|
||||
from utils import (
|
||||
annotation_files,
|
||||
config,
|
||||
|
||||
@@ -6,6 +6,8 @@ from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# pyre-fixme[21]: Could not find module `utils`.
|
||||
import utils
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import os
|
||||
from functools import partial
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# pyre-fixme[21]: Could not find module `saco_yt1b_frame_prep_util`.
|
||||
from saco_yt1b_frame_prep_util import YtVideoPrep
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import os
|
||||
import subprocess
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# pyre-fixme[21]: Could not find module `yt_dlp`.
|
||||
import yt_dlp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -153,9 +153,11 @@ def run_test(
|
||||
height: int,
|
||||
n_frames: int,
|
||||
synthesize_data: bool = True,
|
||||
# pyre-fixme[9]: profile_save_dir has type `str`; used as `None`.
|
||||
profile_save_dir: str = None,
|
||||
profile_end_frame: int = -1,
|
||||
do_compile: bool = True,
|
||||
# pyre-fixme[9]: checkpoint_path has type `str`; used as `None`.
|
||||
checkpoint_path: str = None,
|
||||
) -> float:
|
||||
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
|
||||
@@ -183,8 +185,14 @@ def run_test(
|
||||
build_kwargs["checkpoint_path"] = checkpoint_path
|
||||
if version == "sam3.1":
|
||||
build_kwargs["warm_up"] = do_compile
|
||||
# pyre-fixme[6]: For 2nd argument expected `Union[bool, str]` but got `int`.
|
||||
build_kwargs["max_num_objects"] = num_objects
|
||||
|
||||
# pyre-fixme[6]: For 1st argument expected `Optional[str]` but got `Union[bool,
|
||||
# str]`.
|
||||
# pyre-fixme[6]: For 1st argument expected `bool` but got `Union[bool, str]`.
|
||||
# pyre-fixme[6]: For 1st argument expected `int` but got `Union[bool, str]`.
|
||||
# pyre-fixme[6]: For 1st argument expected `str` but got `Union[bool, str]`.
|
||||
model_wrapper = build_sam3_predictor(**build_kwargs)
|
||||
|
||||
# Initialize session
|
||||
|
||||
Reference in New Issue
Block a user