Enable Pyrefly for deeplearning/projects

Summary:
Enables Pyrefly for `deeplearning/projects` by setting `python.set_pyrefly(True)` in the subdirectory PACKAGE file and adding targeted `# pyrefly: ignore` annotations. Part of splitting D113608658 into a per-subdirectory stack; the final diff performs the directory-level flip.

#buildall

Reviewed By: shugurov

Differential Revision: D113962590

fbshipit-source-id: 2c69a82e5f862fa2fcdfbecba9668814df931026
This commit is contained in:
Chamath Wijesekera
2026-07-30 17:21:37 -07:00
committed by meta-codesync[bot]
parent 6dbb02bd38
commit 96914d2425
83 changed files with 595 additions and 583 deletions
+5
View File
@@ -252,6 +252,7 @@ def agent_inference(
# Add the text_prompt to the set of used prompts
USED_TEXT_PROMPTS.add(current_text_prompt)
LATEST_SAM3_TEXT_PROMPT = current_text_prompt
# pyrefly: ignore [missing-argument]
PATH_TO_LATEST_OUTPUT_JSON = call_sam_service(
image_path=img_path,
text_prompt=current_text_prompt,
@@ -296,6 +297,7 @@ def agent_inference(
assert LATEST_SAM3_TEXT_PROMPT != ""
# Make sure that the last message is a image
# pyrefly: ignore [bad-index]
assert messages[-1]["content"][1]["type"] == "image", (
"Second content element should be an image"
)
@@ -319,6 +321,7 @@ def agent_inference(
# MLLM check the mask one by one
for i in range(num_masks):
print(f"🔍 Checking mask {i + 1}/{num_masks}...")
# pyrefly: ignore [not-iterable]
image_w_mask_i, image_w_zoomed_in_mask_i = visualize(current_outputs, i)
image_w_zoomed_in_mask_i_path = os.path.join(
@@ -401,6 +404,7 @@ def agent_inference(
"/", "_"
),
)
# pyrefly: ignore [missing-attribute]
image_w_check_masks.save(image_w_check_masks_path)
# save the updated json outputs and append to message history
messages.append(
@@ -492,6 +496,7 @@ def agent_inference(
elif tool_call["name"] == "report_no_mask":
print("🔍 Calling report_no_mask tool...")
# pyrefly: ignore [missing-attribute]
height, width = cv2.imread(img_path).shape[:2]
final_outputs = {
"original_image_path": img_path,
+1 -1
View File
@@ -6,7 +6,7 @@ import base64
import os
from typing import Any, Optional
# pyre-fixme[21]: Could not find module `openai`.
# pyrefly: ignore [missing-import]
from openai import OpenAI
+1
View File
@@ -131,6 +131,7 @@ def call_sam_service(
print("🔍 Rendering visualizations on the image ...")
viz_image = visualize(serialized_response)
os.makedirs(os.path.dirname(output_image_path), exist_ok=True)
# pyrefly: ignore [missing-attribute]
viz_image.save(output_image_path)
print("✅ Saved visualization at:", output_image_path)
except Exception as e:
+1
View File
@@ -132,6 +132,7 @@ class BoxMode(IntEnum):
)
if single_box:
# pyrefly: ignore [bad-argument-type]
return original_type(arr.flatten().tolist())
if is_numpy:
return arr.numpy()
+2 -19
View File
@@ -39,19 +39,13 @@ 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:
@@ -69,9 +63,7 @@ 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]`.
# pyrefly: ignore [bad-return]
return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)
def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Keypoints":
@@ -89,11 +81,8 @@ class Keypoints:
subject to Pytorch's indexing semantics.
"""
if isinstance(item, int):
# pyrefly: ignore [bad-argument-type]
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:
@@ -117,9 +106,6 @@ 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
@@ -152,14 +138,11 @@ 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]
+8 -16
View File
@@ -149,8 +149,8 @@ class BitMasks:
return BitMasks(m)
@torch.jit.unused
# pyrefly: ignore [bad-return]
def __iter__(self) -> torch.Tensor:
# pyre-fixme[7]: Expected `Tensor` but got `Generator[Any, None, Any]`.
yield from self.tensor
@torch.jit.unused
@@ -198,7 +198,7 @@ class BitMasks:
roi_masks:
height, width (int):
"""
# pyre-fixme[20]: Argument `width` expected.
# pyrefly: ignore [bad-argument-type, missing-argument]
return roi_masks.to_bitmasks(height, width)
def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:
@@ -243,11 +243,7 @@ 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]
@@ -274,8 +270,6 @@ 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
@@ -329,6 +323,7 @@ class PolygonMasks:
raise ValueError(
f"Cannot create a polygon from {len(polygon)} coordinates."
)
# pyrefly: ignore [bad-return]
return polygons_per_instance
self.polygons: List[List[np.ndarray]] = [
@@ -403,9 +398,7 @@ 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.
# pyrefly: ignore [bad-argument-type]
return PolygonMasks(selected_polygons)
def __iter__(self) -> Iterator[List[np.ndarray]]:
@@ -491,8 +484,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list))
)
return cat_polymasks
@@ -556,7 +548,7 @@ class ROIMasks:
"""
Args: see documentation of :func:`paste_masks_in_image`.
"""
# pyre-fixme[21]: Could not find module `detectron2.layers.mask_ops`.
# pyrefly: ignore [missing-import]
from detectron2.layers.mask_ops import (
_paste_masks_tensor_shape,
paste_masks_in_image,
@@ -570,9 +562,9 @@ class ROIMasks:
else:
paste_func = retry_if_cuda_oom(paste_masks_in_image)
bitmasks = paste_func(
# pyre-fixme[16]: `Tensor` has no attribute `tensor`.
# pyrefly: ignore [missing-attribute]
self.tensor,
# pyre-fixme[16]: `Tensor` has no attribute `tensor`.
# pyrefly: ignore [missing-attribute]
boxes.tensor,
(height, width),
threshold=threshold,
+1 -3
View File
@@ -461,7 +461,6 @@ 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
@@ -472,7 +471,6 @@ 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
@@ -488,7 +486,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.
# pyrefly: ignore [bad-override]
def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes":
"""
Concatenates a list of RotatedBoxes into a single RotatedBoxes
+1 -1
View File
@@ -19,7 +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`.
# pyrefly: ignore [missing-import]
from tidecv import datasets, TIDE
HAS_TIDE = True
+1 -1
View File
@@ -121,7 +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.
# pyrefly: ignore [missing-argument]
raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}")
# Validate COCO format
+2
View File
@@ -513,6 +513,7 @@ class DemoEvaluator(CocoEvaluator):
self.use_self_evaluate = True
self.compute_JnF = compute_JnF
# pyrefly: ignore [bad-override]
def _lazy_init(self):
if self.initialized:
return
@@ -641,6 +642,7 @@ class DemoEvaluator(CocoEvaluator):
for coco_eval in self.coco_evals[0].values():
coco_eval.accumulate()
# pyrefly: ignore [bad-override]
def reset(self):
self.coco_evals = [{} for _ in range(len(self.coco_gts))]
for i, coco_gt in enumerate(self.coco_gts):
@@ -268,6 +268,7 @@ class HOTA(_BaseMetric):
res["HOTALocA(0)"] = res["HOTA(0)"] * res["LocA(0)"]
return res
# pyrefly: ignore [bad-override-param-name]
def plot_single_tracker_results(self, table_res, tracker, cls, output_folder):
"""Create plot of results"""
+19 -27
View File
@@ -88,7 +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`.
# pyrefly: ignore [missing-import]
from tensordict import TensorDict
except ImportError:
logging.info(
@@ -139,6 +139,7 @@ class PostProcessImage(nn.Module):
results.update(masks=out_masks)
if ret_tensordict:
# pyrefly: ignore [unbound-name]
results = TensorDict(results).auto_batch_size_()
if self.to_cpu:
results = results.cpu()
@@ -266,16 +267,16 @@ 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)
else torch.ones_like(
meta.original_size # pyrefly: ignore [bad-argument-type]
) # pyrefly: ignore [bad-argument-type]
)
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)
else torch.ones_like(
meta.original_size # pyrefly: ignore [bad-argument-type]
) # pyrefly: ignore [bad-argument-type]
)
detection_results = self(
outputs,
@@ -382,6 +383,7 @@ class PostProcessAPIVideo(PostProcessImage):
# Import tensordict here to avoid global dependency.
try:
# pyrefly: ignore [missing-import]
from tensordict import TensorDict
except ImportError as e:
logging.error(
@@ -406,7 +408,6 @@ 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.
@@ -421,8 +422,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
unique_vid_id = meta.original_image_id.unique()
assert unique_vid_id.size(0) == 1
if video_id == -1:
@@ -473,7 +473,7 @@ class PostProcessAPIVideo(PostProcessImage):
tracked_objs_outs_td.unsqueeze(1),
(
meta_td["original_size"]
if self.use_original_sizes
if self.use_original_sizes # pyrefly: ignore [not-callable]
else torch.ones_like(meta_td["original_size"])
),
forced_labels=(
@@ -499,7 +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`.
# pyrefly: ignore [bad-assignment]
vid_preds_packed = torch.cat(vid_preds_packed, dim=0)
############### Construct a padded representation of the predictions ###############
num_preds = len(tracked_objects_packed_idx)
@@ -511,7 +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`.
# pyrefly: ignore [missing-attribute]
for k, v in vid_preds_packed.items()
},
batch_size=[
@@ -531,17 +531,13 @@ 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]`.
# pyrefly: ignore [bad-index]
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.
# pyrefly: ignore [unbound-name]
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.
@@ -555,8 +551,7 @@ 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.
# pyrefly: ignore [unbound-name]
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"]
@@ -577,17 +572,14 @@ 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.
# pyrefly: ignore [bad-override]
def process_results(
self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs
):
# pyre-fixme[6]: For 1st argument expected
# `pyre_extensions.PyreReadOnly[Sized]` but got `BatchedInferenceMetadata`.
# pyrefly: ignore [bad-argument-type]
assert len(find_stages) == len(find_metadatas)
results = {}
# pyre-fixme[6]: For 2nd argument expected `Iterable[_T2]` but got
# `BatchedInferenceMetadata`.
# pyrefly: ignore [bad-argument-type]
for outputs, meta in zip(find_stages, find_metadatas):
if self.force_single_mask:
scores, labels = outputs["pred_logits"].max(-1)
+2 -4
View File
@@ -38,11 +38,9 @@ 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]`.
# pyrefly: ignore [no-matching-overload]
dataset_results.update(d_res)
# pyre-fixme[16]: Item `str` of `dict[Any, Any] | str` has no attribute
# `items`.
# pyrefly: ignore [missing-attribute]
for (video_id, category_id), res in v_np_res.items():
video_np_results[(video_id, category_id)].update(res)
+6 -10
View File
@@ -112,8 +112,7 @@ 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]]`.
# pyrefly: ignore [bad-return]
return results, video_np_level_results
@@ -149,7 +148,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`.
# pyrefly: ignore [bad-argument-type]
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
ytvisGT.dataset = gt
ytvisGT.createIndex()
@@ -183,8 +182,7 @@ 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]]`.
# pyrefly: ignore [bad-return]
return results, video_np_level_results
@@ -230,7 +228,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`.
# pyrefly: ignore [bad-argument-type]
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
ytvisGT.dataset = gt
ytvisGT.createIndex()
@@ -290,8 +288,7 @@ 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]]`.
# pyrefly: ignore [bad-return]
return results, video_np_level_results
def extract_video_np_level_results(self, demoF1Eval, video_np_level_results):
@@ -636,8 +633,7 @@ 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]]`.
# pyrefly: ignore [bad-return]
return out_dict, video_np_level_results
def _remap_gt_dt(self, gt, dt):
@@ -478,6 +478,7 @@ class COCO(_BaseDataset):
return data
# pyrefly: ignore [bad-override-param-name]
def _calculate_similarities(self, gt_dets_t, tk_dets_t):
"""Compute similarity scores."""
if self.use_mask:
@@ -489,6 +489,7 @@ class TAO(_BaseDataset):
return data
# pyrefly: ignore [bad-override-param-name]
def _calculate_similarities(self, gt_dets_t, tk_dets_t):
"""Compute similarity scores."""
if self.use_mask:
+1 -1
View File
@@ -19,7 +19,7 @@ class YTVIS(COCO):
"""
@override
# pyre-fixme[9]: annotation_file has type `str`; used as `None`.
# pyrefly: ignore [bad-function-definition]
def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True):
"""
Args:
+1 -2
View File
@@ -22,7 +22,7 @@ from sam3.train.utils import distributed as dist
from typing_extensions import override
try:
# pyre-fixme[21]: Could not find module `rapidjson`.
# pyrefly: ignore [missing-import]
import rapidjson as json
except ModuleNotFoundError:
import json
@@ -271,7 +271,6 @@ 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):
+1 -1
View File
@@ -59,11 +59,11 @@ from torch.utils import _pytree as pytree
pytree.register_pytree_node(
NestedTensor,
lambda x: ([x.tensors, x.mask], None),
# pyrefly: ignore [bad-index]
lambda values, _: NestedTensor(values[0], values[1]),
)
# pyre-fixme[10]: Name `Tensor` is used but not defined.
def interpolate(
input, size=None, scale_factor=None, mode="nearest", align_corners=None
):
+40 -10
View File
@@ -117,19 +117,25 @@ class TransformerDecoderLayer(nn.Module):
# 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
# pyrefly: ignore [missing-attribute]
num_o2o_queries = tgt.shape[0] // 2
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
tgt_o2o = tgt[:num_o2o_queries]
# pyrefly: ignore [unsupported-operation]
tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries]
# pyrefly: ignore [unsupported-operation]
tgt_o2m = tgt[num_o2o_queries:]
else:
tgt_o2o = tgt
tgt_query_pos_o2o = tgt_query_pos
if presence_token is not None:
# pyrefly: ignore [bad-argument-type]
tgt_o2o = torch.cat([presence_token, tgt_o2o], dim=0)
tgt_query_pos_o2o = torch.cat(
[torch.zeros_like(presence_token), tgt_query_pos_o2o], dim=0
# pyrefly: ignore [bad-argument-type]
[torch.zeros_like(presence_token), tgt_query_pos_o2o],
dim=0,
)
tgt_query_pos = torch.cat(
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
@@ -163,6 +169,7 @@ class TransformerDecoderLayer(nn.Module):
tgt = self.catext_norm(tgt)
if presence_token is not None:
# pyrefly: ignore [unsupported-operation]
presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :])
cross_attn_mask = torch.cat(
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
@@ -264,7 +271,9 @@ class TransformerDecoder(nn.Module):
self.instance_query_embed = nn.Embedding(num_instances, d_model)
self.box_refine = box_refine
if box_refine:
# pyrefly: ignore [bad-argument-type]
nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
# pyrefly: ignore [bad-argument-type]
nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
self.reference_points = nn.Embedding(num_queries, 4)
@@ -459,20 +468,29 @@ class TransformerDecoder(nn.Module):
apply_dac = apply_dac if apply_dac is not None else self.dac
if apply_dac:
assert (tgt.shape[0] == self.num_queries) or (
self.use_instance_query
and (tgt.shape[0] == self.instance_query_embed.num_embeddings)
assert (
(tgt.shape[0] == self.num_queries)
or (
self.use_instance_query
and (
tgt.shape[0]
== self.instance_query_embed.num_embeddings # pyrefly: ignore [missing-attribute]
) # pyrefly: ignore [missing-attribute]
)
)
tgt = tgt.repeat(2, 1, 1)
# note that we don't tile tgt_mask, since DAC doesn't
# use self-attention in o2m queries
if reference_boxes is not None:
assert (reference_boxes.shape[0] == self.num_queries) or (
self.use_instance_query
and (
reference_boxes.shape[0]
== self.instance_query_embed.num_embeddings
assert (
(reference_boxes.shape[0] == self.num_queries)
or (
self.use_instance_query
and (
reference_boxes.shape[0]
== self.instance_query_embed.num_embeddings # pyrefly: ignore [missing-attribute]
)
)
)
reference_boxes = reference_boxes.repeat(2, 1, 1)
@@ -513,6 +531,7 @@ class TransformerDecoder(nn.Module):
for layer_idx, layer in enumerate(self.layers):
reference_points_input = (
# pyrefly: ignore [unsupported-operation]
reference_boxes[:, :, None]
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
@@ -708,6 +727,7 @@ class TransformerEncoderCrossAttention(nn.Module):
# pyre-fixme[16]: `Optional` has no attribute `transpose`.
src_pos = src_pos.transpose(0, 1)
prompt = prompt.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
prompt_pos = prompt_pos.transpose(0, 1)
for layer in self.layers:
@@ -733,7 +753,9 @@ class TransformerEncoderCrossAttention(nn.Module):
if self.batch_first:
# Convert back to seq first
# pyrefly: ignore [unbound-name]
normed_output = normed_output.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
src_pos = src_pos.transpose(0, 1)
return {
@@ -1094,6 +1116,7 @@ class SimpleRoPEAttention(nn.Module):
w = h = math.sqrt(q.shape[-2])
self.freqs_cis = self.freqs_cis.to(q.device)
if self.freqs_cis.shape[0] != q.shape[-2]:
# pyrefly: ignore [bad-argument-type]
self.freqs_cis = self.compute_cis(end_x=w, end_y=h, device=q.device)
if self.use_rope_real:
self.freqs_cis_real = self.freqs_cis.real
@@ -1274,6 +1297,7 @@ class DecoupledTransformerDecoderLayerv2(nn.Module):
def forward(self, *args: Any, **kwds: Any) -> torch.Tensor:
if self.pre_norm:
# pyrefly: ignore [bad-return]
return self.forward_pre(*args, **kwds)
raise NotImplementedError
@@ -1336,8 +1360,10 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
src_pos = src_pos.transpose(0, 1)
image = image.transpose(0, 1)
memory = memory.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
memory_pos = memory_pos.transpose(0, 1)
memory_image = memory_image.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
memory_image_pos = memory_image_pos.transpose(0, 1)
if memory_image.shape[1] != memory.shape[1]:
@@ -1359,14 +1385,17 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
)
if memory_image_pos is not None:
assert (
memory_pos.shape[1] - memory_image_pos.shape[1]
memory_pos.shape[1] # pyrefly: ignore [missing-attribute]
- memory_image_pos.shape[1] # pyrefly: ignore [missing-attribute]
) == num_obj_ptr_tokens, (
# pyrefly: ignore [missing-attribute]
f"{memory_pos.shape[1]} - {memory_image_pos.shape[1]} != {num_obj_ptr_tokens}"
)
# tpos is the same in the batch anyway; note that memory_image always has a batch size of 1
memory_image_pos = torch.cat(
[
memory_image_pos,
# pyrefly: ignore [unsupported-operation]
memory_pos[0:1, -num_obj_ptr_tokens:],
],
dim=1,
@@ -1394,6 +1423,7 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
if self.batch_first:
# Convert back to seq first
normed_output = normed_output.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
src_pos = src_pos.transpose(0, 1)
return {
+2 -2
View File
@@ -153,7 +153,7 @@ def edt_triton(data: torch.Tensor):
parabola_inter,
H,
W,
# pyre-fixme[6]: For 7th argument expected `constexpr` but got `bool`.
# pyrefly: ignore [bad-argument-type]
horizontal=True,
)
@@ -170,7 +170,7 @@ def edt_triton(data: torch.Tensor):
parabola_inter,
H,
W,
# pyre-fixme[6]: For 7th argument expected `constexpr` but got `bool`.
# pyrefly: ignore [bad-argument-type]
horizontal=False,
)
# don't forget to take sqrt at the end
+12 -17
View File
@@ -112,8 +112,7 @@ class TransformerEncoderLayer(nn.Module):
Returns:
Processed tensor
"""
# pyre-fixme[58]: `+` is not supported for operand types `Tensor` and
# `Optional[Tensor]`.
# pyrefly: ignore [unsupported-operation]
q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
# Self attention
@@ -126,8 +125,6 @@ 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,
@@ -190,13 +187,11 @@ class TransformerEncoderLayer(nn.Module):
tgt = tgt + self.dropout1(tgt2)
if dac:
# Recombine
# pyre-fixme[61]: `other_tgt` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
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,
@@ -510,7 +505,6 @@ 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
)
@@ -520,8 +514,7 @@ class TransformerEncoderFusion(TransformerEncoder):
# Not needed here
return None
# pyre-fixme[14]: `forward` overrides method defined in `TransformerEncoder`
# inconsistently.
# pyrefly: ignore [bad-override]
def forward(
self,
src: List[Tensor],
@@ -538,17 +531,21 @@ class TransformerEncoderFusion(TransformerEncoder):
if feat_sizes is not None:
assert len(feat_sizes) == len(src)
if src_key_padding_mask is None:
# pyrefly: ignore [bad-assignment]
src_key_padding_mask = [None] * len(src)
# pyre-fixme[23]: Unable to unpack `int` into 2 values.
# pyrefly: ignore [not-iterable]
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__`.
# pyrefly: ignore [unsupported-operation]
src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
# pyrefly: ignore [unsupported-operation]
src_key_padding_mask[i] = (
# pyre-fixme[16]: `Optional` has no attribute `reshape`.
# pyrefly: ignore [unsupported-operation]
src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1)
if src_key_padding_mask[i] is not None
if src_key_padding_mask[ # pyrefly: ignore [unsupported-operation]
i
] # pyrefly: ignore [unsupported-operation]
is not None # pyrefly: ignore [unsupported-operation]
else None
)
else:
@@ -575,8 +572,6 @@ 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),
+14 -7
View File
@@ -441,12 +441,11 @@ class FusedMaskEncoder(MaskEncoder):
self.fuser = fuser
self.out_proj = nn.Identity()
if out_dim != in_dim:
# pyrefly: ignore [bad-assignment]
self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
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,
@@ -506,7 +505,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`.
# pyrefly: ignore [bad-function-definition]
mask_encoder: MaskEncoder = None,
add_mask_label: bool = False,
use_act_ckpt: bool = False,
@@ -569,6 +568,7 @@ class SequenceGeometryEncoder(nn.Module):
self.img_pre_norm = nn.Identity()
if self.points_pool_project is not None or self.boxes_pool_project is not None:
# pyrefly: ignore [bad-assignment]
self.img_pre_norm = nn.LayerNorm(self.d_model)
self.encode = None
@@ -688,7 +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`.
# pyrefly: ignore [bad-function-definition]
img_feats: torch.Tensor = None,
):
n_masks, bs = masks.shape[:2]
@@ -735,6 +735,7 @@ class SequenceGeometryEncoder(nn.Module):
else torch.zeros_like(seq_first_img_feats)
)
# pyrefly: ignore [not-callable]
if self.points_pool_project or self.boxes_pool_project:
assert len(img_feats) == len(img_sizes)
cur_img_feat = img_feats[-1]
@@ -760,21 +761,24 @@ class SequenceGeometryEncoder(nn.Module):
labels_br = geo_prompt.box_labels + 4
# Append to the existing points
# pyrefly: ignore [bad-unpacking]
points, _ = concat_padded_sequences(
points, points_mask, top_left, boxes_mask
)
# pyrefly: ignore [bad-unpacking]
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,
)
points_labels = points_labels.squeeze(-1)
# pyrefly: ignore [bad-unpacking]
points, _ = concat_padded_sequences(
points, points_mask, bottom_right, boxes_mask
)
# pyrefly: ignore [bad-unpacking]
points_labels, points_mask = concat_padded_sequences(
points_labels.unsqueeze(-1),
points_mask,
@@ -798,6 +802,7 @@ class SequenceGeometryEncoder(nn.Module):
img_feats=img_feats,
)
# pyrefly: ignore [bad-unpacking]
final_embeds, final_mask = concat_padded_sequences(
final_embeds, final_mask, boxes_embeds, boxes_mask
)
@@ -818,6 +823,7 @@ class SequenceGeometryEncoder(nn.Module):
cls_mask = torch.zeros(
bs, 1, dtype=final_mask.dtype, device=final_mask.device
)
# pyrefly: ignore [bad-unpacking]
final_embeds, final_mask = concat_padded_sequences(
final_embeds, final_mask, cls, cls_mask
)
@@ -837,11 +843,12 @@ class SequenceGeometryEncoder(nn.Module):
final_embeds = self.encode_norm(final_embeds)
# Finally, concat mask embeddings if any
if masks is not None and self.mask_encoder is not None:
# pyrefly: ignore [bad-unpacking]
final_embeds, final_mask = concat_padded_sequences(
# pyre-fixme[61]: `masks_embed` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
final_embeds,
final_mask,
# pyre-fixme[61]: `masks_embed` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
masks_embed,
masks_mask,
)
+26 -29
View File
@@ -42,9 +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.
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
# pyrefly: ignore [bad-assignment]
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
@@ -62,9 +62,9 @@ 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]`.
# pyrefly: ignore [unsupported-operation]
img -= img_mean
# pyrefly: ignore [unsupported-operation]
img /= img_std
images.append(img)
images = torch.stack(images)
@@ -107,17 +107,20 @@ 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.
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
# pyrefly: ignore [bad-assignment]
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`.
# pyrefly: ignore [missing-attribute]
img_mean = img_mean.cuda()
# pyrefly: ignore [missing-attribute]
img_std = img_std.cuda()
# normalize by mean and std
# pyrefly: ignore [unsupported-operation]
images -= img_mean
# pyrefly: ignore [unsupported-operation]
images /= img_std
return images, image_height, image_width
@@ -342,19 +345,22 @@ 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.
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1)
# pyre-fixme[9]: Unable to unpack `Tensor`, expected a tuple.
# pyrefly: ignore [bad-assignment]
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`.
# pyrefly: ignore [missing-attribute]
img_mean = img_mean.cuda()
# pyrefly: ignore [missing-attribute]
img_std = img_std.cuda()
# normalize by mean and std
# pyrefly: ignore [unsupported-operation]
video_tensor -= img_mean
# pyrefly: ignore [unsupported-operation]
video_tensor /= img_std
# pyre-fixme[7]: Expected `Tensor` but got `Tuple[Any, int, int]`.
# pyrefly: ignore [bad-return]
return video_tensor, original_height, original_width
@@ -378,10 +384,9 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
img = TF.resize(img, size=(image_size, image_size))
# pyre-fixme[6]: For 1st argument expected `Union[Image, ndarray]` but got `Tensor`.
# pyrefly: ignore [bad-argument-type]
img = TF.to_tensor(img)
return img, orig_height, orig_width
@@ -463,7 +468,7 @@ class TorchCodecDecoder:
device: str = "cpu",
num_threads: int = 1,
) -> None:
# pyre-fixme[21]: Could not find module `torchcodec`.
# pyrefly: ignore [missing-import]
from torchcodec import _core as core
self._source = source # hold a reference to the source to prevent it from GC
@@ -494,6 +499,7 @@ class TorchCodecDecoder:
return self._num_frames
def __getitem__(self, key: int) -> torch.Tensor:
# pyrefly: ignore [missing-import]
from torchcodec import _core as core
if key < 0:
@@ -588,26 +594,17 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
self.async_reader = TorchCodecDecoder(video_path, **decoder_option)
# `num_frames_from_content` is the true number of frames in the video content
@@ -772,14 +769,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`.
# pyrefly: ignore [bad-assignment]
reader._source = None
# pyre-fixme[8]: Attribute has type `TorchCodecDecoder`; used as `None`.
# pyrefly: ignore [bad-assignment]
self.async_reader = None
# pyre-fixme[16]: `AsyncVideoFileLoaderWithTorchCodec` has no attribute `pbar`.
self.pbar = None
self.thread = None
# pyrefly: ignore [bad-assignment]
self.rand_seek_idx_queue = None
# pyre-fixme[8]: Attribute has type `FIFOLock`; used as `nullcontext[None]`.
# pyrefly: ignore [bad-assignment]
self.torchcodec_access_lock = contextlib.nullcontext()
return self.__dict__.copy()
+3 -2
View File
@@ -18,6 +18,7 @@ class LinearPresenceHead(nn.Sequential):
# a hack to make `LinearPresenceHead` compatible with old checkpoints
super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1))
# pyrefly: ignore [bad-override]
def forward(self, hs, prompt, prompt_mask):
return super().forward(hs)
@@ -152,6 +153,7 @@ class SegmentationHead(nn.Module):
pixel_embed = pixel_embed.squeeze(0)
else:
pixel_embed = pixel_embed[image_ids, ...]
# pyrefly: ignore [bad-return]
return pixel_embed
def forward(
@@ -279,8 +281,7 @@ class UniversalSegmentationHead(SegmentationHead):
self.pixel_decoder.out_dim, self.d_model, kernel_size=1
)
# pyre-fixme[15]: `forward` overrides method defined in `SegmentationHead`
# inconsistently.
# pyrefly: ignore [bad-override]
def forward(
self,
backbone_feats: List[torch.Tensor],
+2 -1
View File
@@ -71,6 +71,7 @@ class SimpleMaskDownSampler(nn.Module):
assert isinstance(self.interpol_size, (list, tuple)), (
f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
)
# pyrefly: ignore [bad-argument-type]
self.interpol_size = list(interpol_size)
assert len(self.interpol_size) == 2
@@ -206,5 +207,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]`.
# pyrefly: ignore [bad-return]
return {"vision_features": x, "vision_pos_enc": [pos]}
+28 -4
View File
@@ -290,6 +290,7 @@ def multi_head_attention_forward(
#
q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
if static_k is None:
# pyrefly: ignore [bad-argument-type]
k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else:
assert static_k.size(0) == bsz * num_heads, (
@@ -300,6 +301,7 @@ def multi_head_attention_forward(
)
k = static_k
if static_v is None:
# pyrefly: ignore [bad-argument-type]
v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else:
assert static_v.size(0) == bsz * num_heads, (
@@ -314,10 +316,14 @@ def multi_head_attention_forward(
if add_zero_attn:
zero_attn_shape = (bsz * num_heads, 1, head_dim)
k = torch.cat(
[k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1
# pyrefly: ignore [no-matching-overload]
[k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)],
dim=1,
)
v = torch.cat(
[v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1
# pyrefly: ignore [no-matching-overload]
[v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)],
dim=1,
)
if attn_mask is not None:
attn_mask = F.pad(attn_mask, (0, 1))
@@ -382,7 +388,9 @@ def multi_head_attention_forward(
attn_mask = attn_mask + attn_bias
q = q.view(bsz, num_heads, tgt_len, head_dim)
# pyrefly: ignore [bad-argument-type]
k = k.view(bsz, num_heads, src_len, head_dim)
# pyrefly: ignore [bad-argument-type]
v = v.view(bsz, num_heads, src_len, head_dim)
if attn_type == AttentionType.Vanilla:
@@ -408,6 +416,7 @@ def multi_head_attention_forward(
elif attn_type == AttentionType.Xformer:
attn_output_weights = None
assert not need_weights, "need_weights is not supported in efficient mode"
# pyrefly: ignore [missing-attribute]
attn_output = xformers.ops.memory_efficient_attention(
q.transpose(1, 2),
k.transpose(1, 2),
@@ -421,11 +430,15 @@ def multi_head_attention_forward(
assert not need_weights, "need_weights is not supported in efficient mode"
# Need to collapse heads and batch dimensions
q = q.reshape(bsz * num_heads, tgt_len, head_dim).contiguous()
# pyrefly: ignore [bad-argument-type]
k = k.reshape(bsz * num_heads, src_len, head_dim).contiguous()
# pyrefly: ignore [bad-argument-type]
v = v.reshape(bsz * num_heads, src_len, head_dim).contiguous()
# pyrefly: ignore [missing-attribute]
row_offsets, column_indices = xformers.ops.find_locations_new(
q, k, attn_sparsity, True
)
# pyrefly: ignore [missing-attribute]
attn_output = xformers.ops.sparse_memory_efficient_attention(
q, k, v, row_offsets, column_indices, attn_bias=attn_mask
).reshape(bsz, num_heads, tgt_len, head_dim)
@@ -596,6 +609,7 @@ class MultiheadAttention(nn.Module):
if not self._qkv_same_embed_dim:
if self.use_act_checkpoint:
# pyrefly: ignore [not-iterable]
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward,
query,
@@ -657,6 +671,7 @@ class MultiheadAttention(nn.Module):
)
else:
if self.use_act_checkpoint:
# pyrefly: ignore [not-iterable]
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward,
query,
@@ -865,6 +880,7 @@ class MLP(nn.Module):
self.residual = residual
# whether to apply a normalization layer to the output
assert isinstance(out_norm, nn.Module) or out_norm is None
# pyrefly: ignore [not-callable]
self.out_norm = out_norm or nn.Identity()
def forward(self, x):
@@ -1020,12 +1036,20 @@ class SAM3Output(list):
# This is to avoid cyclic references and let SAM3Output be garabge collected.
self_ref = weakref.ref(self)
self._mode2iter = {
# pyrefly: ignore [missing-attribute]
SAM3Output.IterMode.ALL_STEPS_PER_STAGE: lambda: iter(self_ref().output),
SAM3Output.IterMode.LAST_STEP_PER_STAGE: lambda: (
inner_list[-1] for inner_list in self_ref().output
# pyrefly: ignore [missing-attribute]
inner_list[-1]
# pyrefly: ignore [missing-attribute]
for inner_list in self_ref().output
),
SAM3Output.IterMode.FLATTENED: lambda: (
element for inner_list in self_ref().output for element in inner_list
# pyrefly: ignore [missing-attribute]
element
# pyrefly: ignore [missing-attribute]
for inner_list in self_ref().output
for element in inner_list
),
}
self.loss_stages = loss_stages
+4 -6
View File
@@ -138,6 +138,7 @@ class MultiplexMaskDecoder(nn.Module):
if self.pred_obj_scores:
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
if pred_obj_scores_mlp:
# pyrefly: ignore [bad-assignment]
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
# When outputting a single mask, optionally we can dynamically fall back to the best
@@ -315,7 +316,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.
# pyrefly: ignore [not-iterable]
feat_s0, feat_s1 = high_res_features
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
@@ -346,7 +347,6 @@ 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)
@@ -363,15 +363,13 @@ 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.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
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
+20 -9
View File
@@ -197,6 +197,7 @@ class MultiplexState:
if not prefer_new_buckets:
# Fill empty slots in existing buckets first
# pyrefly: ignore [not-iterable]
for bucket in self.assignments:
for i in range(self.allowed_bucket_capacity):
if bucket[i] == _PADDING_NUM:
@@ -219,11 +220,13 @@ class MultiplexState:
if len(object_indices) == 0:
break
new_bucket[i] = _pop_next()
# pyrefly: ignore [missing-attribute]
self.assignments.append(new_bucket)
buckets_created += 1
# reinitialize all the settings
original_num_entries = self.total_valid_entries
# pyrefly: ignore [bad-argument-type]
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
assert self.total_valid_entries == original_num_entries + num_new_objects, (
f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}"
@@ -251,9 +254,11 @@ class MultiplexState:
object_indices = object_indices.copy()
# Mark objects as removed in assignments
# pyrefly: ignore [not-iterable]
for bucket_idx, bucket in enumerate(self.assignments):
for slot_idx, obj_id in enumerate(bucket):
if obj_id in object_indices:
# pyrefly: ignore [unsupported-operation]
self.assignments[bucket_idx][slot_idx] = _REMOVED_NUM
object_indices.remove(obj_id)
@@ -266,6 +271,7 @@ class MultiplexState:
# and which buckets we will keep
buckets_to_remove = []
buckets_to_keep = []
# pyrefly: ignore [not-iterable]
for bucket_idx, bucket in enumerate(self.assignments):
# Check if all objects in this bucket are removed or are paddings
all_removed = all(
@@ -281,10 +287,12 @@ class MultiplexState:
# Remove buckets in reverse order to maintain correct indices
for bucket_idx in reversed(buckets_to_remove):
# pyrefly: ignore [unsupported-operation]
del self.assignments[bucket_idx]
if len(buckets_to_keep) == 0:
logger.info(f"Removing all buckets: {buckets_to_remove}; state invalidated")
# pyrefly: ignore [bad-assignment]
self.assignments = None
if self.object_ids is not None:
self.object_ids = []
@@ -293,6 +301,7 @@ class MultiplexState:
# After removal, remap object IDs to be sequential
# Collect all unique positive object IDs and create a mapping to sequential IDs
all_positive_ids = set()
# pyrefly: ignore [not-iterable]
for bucket in self.assignments:
for obj_id in bucket:
if obj_id >= 0:
@@ -303,6 +312,7 @@ class MultiplexState:
id_mapping = {old_id: new_id for new_id, old_id in enumerate(sorted_ids)}
# Apply the mapping to assignments to make IDs sequential
# pyrefly: ignore [not-iterable]
for bucket in self.assignments:
for i, obj_id in enumerate(bucket):
if obj_id >= 0:
@@ -316,14 +326,15 @@ class MultiplexState:
# Map the original object_ids to their new positions
for old_idx, new_idx in id_mapping.items():
# pyrefly: ignore [unsupported-operation]
new_object_ids[new_idx] = self.object_ids[old_idx]
assert not any(obj_id is None for obj_id in new_object_ids)
# pyrefly: ignore [bad-assignment]
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]]`.
# pyrefly: ignore [bad-argument-type]
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
logger.info(f"Removed these buckets: {buckets_to_remove}")
@@ -340,8 +351,6 @@ 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,
@@ -350,7 +359,6 @@ 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,
@@ -362,6 +370,7 @@ class MultiplexState:
for i in range(self.num_buckets):
for j in range(self.multiplex_count):
bucket_idx = i * self.multiplex_count + j
# pyrefly: ignore [unsupported-operation]
object_idx = self.assignments[i][j]
if object_idx >= 0:
self.mux_matrix[bucket_idx, object_idx] = 1.0
@@ -388,7 +397,6 @@ 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)
@@ -411,7 +419,6 @@ 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)
@@ -421,7 +428,6 @@ 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)
@@ -434,7 +440,12 @@ class MultiplexState:
not the arbitrary object IDs that are passed in during initialization
"""
all_valid_objects = {
obj_idx for bucket in self.assignments for obj_idx in bucket if obj_idx >= 0
# pyrefly: ignore [not-iterable]
obj_idx
# pyrefly: ignore [not-iterable]
for bucket in self.assignments
for obj_idx in bucket
if obj_idx >= 0
}
return all_valid_objects
+8 -3
View File
@@ -37,7 +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...
# pyrefly: ignore [bad-assignment, bad-index]
dim: int = self.trunk.channel_list[-1]
for _, scale in enumerate(scale_factors):
@@ -123,8 +123,9 @@ 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`.
# pyrefly: ignore [missing-attribute]
sam2_out.append(sam2_x_out)
# pyrefly: ignore [missing-attribute]
sam2_pos.append(sam2_pos_out)
return sam3_out, sam3_pos, sam2_out, sam2_pos
@@ -148,7 +149,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...
# pyrefly: ignore [bad-index]
dim = self.trunk.channel_list[-1]
for _, scale in enumerate(scale_factors):
@@ -157,6 +158,7 @@ class Sam3TriViTDetNeck(nn.Module):
if scale == 4.0:
current.add_module(
"dconv_2x2_0",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
)
current.add_module(
@@ -165,12 +167,14 @@ class Sam3TriViTDetNeck(nn.Module):
)
current.add_module(
"dconv_2x2_1",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
)
out_dim = dim // 4
elif scale == 2.0:
current.add_module(
"dconv_2x2",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
)
out_dim = dim // 2
@@ -188,6 +192,7 @@ class Sam3TriViTDetNeck(nn.Module):
current.add_module(
"conv_1x1",
nn.Conv2d(
# pyrefly: ignore [bad-argument-type]
in_channels=out_dim,
out_channels=d_model,
kernel_size=1,
+7 -1
View File
@@ -186,6 +186,7 @@ class SAM3InteractiveImagePredictor(nn.Module):
raise RuntimeError(
"An image must be set with .set_image_batch(...) before mask prediction."
)
# pyrefly: ignore [unsupported-operation]
num_images = len(self._features["image_embed"])
all_masks = []
all_ious = []
@@ -412,9 +413,11 @@ class SAM3InteractiveImagePredictor(nn.Module):
) # multi object prediction
high_res_features = [
feat_level[img_idx].unsqueeze(0)
# pyrefly: ignore [unsupported-operation]
for feat_level in self._features["high_res_feats"]
]
low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
# pyrefly: ignore [unsupported-operation]
image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
sparse_prompt_embeddings=sparse_embeddings,
@@ -426,7 +429,10 @@ class SAM3InteractiveImagePredictor(nn.Module):
# Upscale the masks to the original image resolution
masks = self._transforms.postprocess_masks(
low_res_masks, self._orig_hw[img_idx]
# pyrefly: ignore [unsupported-operation]
low_res_masks,
# pyrefly: ignore [unsupported-operation]
self._orig_hw[img_idx],
)
low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
if not return_logits:
+1 -2
View File
@@ -404,8 +404,7 @@ 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]`.
# pyrefly: ignore [bad-assignment]
result["gpu_mem"] = gpu_mem
logger.info(f"removed session {session_id}")
return result
+9 -16
View File
@@ -55,8 +55,7 @@ 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`.
# pyrefly: ignore [bad-function-definition]
inst_interactive_predictor: SAM3InteractiveImagePredictor = None,
**kwargs,
):
@@ -529,8 +528,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
point_embeddings = find_input.input_points_before_embed.transpose(0, 1)
# they are stored as (x,y,label), so we unpack
@@ -573,7 +571,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`.
# pyrefly: ignore [missing-attribute]
if find_input.input_points is not None and find_input.input_points.numel() > 0:
print("Warning: Point prompts are ignored in PCS.")
@@ -589,8 +587,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
geometric_prompt, _ = self.interactive_prompt_sampler.sample(
geo_prompt=geometric_prompt,
find_target=find_target,
@@ -791,8 +788,7 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
multigpu_buffer.pop(frame_idx_rm, None)
@@ -897,16 +893,13 @@ 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.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
# pyre-fixme[61]: `vision_pos_enc` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None)
multigpu_buffer[frame_idx_to_save] = frame_buffer
+1 -2
View File
@@ -92,6 +92,7 @@ class Sam3Processor:
self.transform(v2.functional.to_image(image).to(self.device))
for image in images
]
# pyrefly: ignore [bad-argument-type, bad-assignment]
images = torch.stack(images, dim=0)
state["backbone_out"] = self.model.backbone.forward_image(images)
inst_interactivity_en = self.model.inst_interactive_predictor is not None
@@ -210,8 +211,6 @@ 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,
+49 -4
View File
@@ -277,6 +277,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
self.new_det_thresh = new_det_thresh
self.is_multiplex = is_multiplex
self.running_in_prod = running_in_prod
# pyrefly: ignore [bad-argument-type]
self.detector.running_in_prod = running_in_prod
assert (
@@ -587,6 +588,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
reverse=reverse,
det_out=det_out,
tracker_states_local=tracker_states_local,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=sam2_update_plan,
tracker_metadata_new=tracker_metadata_new,
orig_vid_height=orig_vid_height,
@@ -606,10 +608,12 @@ class Sam3MultiplexBase(Sam3VideoBase):
tracker_low_res_masks_global=tracker_low_res_masks_global,
tracker_obj_scores_global=tracker_obj_scores_global,
tracker_metadata_prev=tracker_metadata_prev,
# pyrefly: ignore [bad-argument-type]
sam2_update_plan=sam2_update_plan,
orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width,
reconditioned_obj_ids=reconditioned_obj_ids,
# pyrefly: ignore [bad-argument-type]
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
)
obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
@@ -654,6 +658,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# 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"]:
# pyrefly: ignore [missing-attribute]
text_outputs = self.detector.backbone.forward_text(
input_batch.find_text_batch, device=self.device
)
@@ -681,6 +686,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
"forward_video_grounding_batched_multigpu"
):
sam3_image_out, _ = (
# pyrefly: ignore [not-callable]
self.detector.forward_video_grounding_batched_multigpu(
backbone_out=backbone_out,
find_inputs=input_batch.find_inputs,
@@ -708,6 +714,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
feature_cache["multigpu_buffer"] = {}
with torch.profiler.record_function("forward_video_grounding_multigpu"):
# pyrefly: ignore [not-callable]
sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
backbone_out=backbone_out,
find_inputs=input_batch.find_inputs,
@@ -755,9 +762,11 @@ class Sam3MultiplexBase(Sam3VideoBase):
# TODO: We do not need the interaction features every frame so there are rooms for optimization
interaction_sam_mask_decoder = self.tracker.interactive_sam_mask_decoder
interaction_backbone_fpn = [
# pyrefly: ignore [missing-attribute]
interaction_sam_mask_decoder.conv_s0(
sam3_image_out["interactive_backbone_fpn_0"]
),
# pyrefly: ignore [missing-attribute]
interaction_sam_mask_decoder.conv_s1(
sam3_image_out["interactive_backbone_fpn_1"]
),
@@ -776,7 +785,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
backbone_cache["interactive"] = interaction_backbone_out
sam_mask_decoder = self.tracker.sam_mask_decoder
sam2_backbone_fpn = [
# pyrefly: ignore [missing-attribute]
sam_mask_decoder.conv_s0(sam3_image_out["sam2_backbone_fpn_0"]),
# pyrefly: ignore [missing-attribute]
sam_mask_decoder.conv_s1(sam3_image_out["sam2_backbone_fpn_1"]),
sam3_image_out["sam2_backbone_fpn_2"], # fpn_2 doesn't need additional conv
]
@@ -920,7 +931,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
new_masks_binary = (
F.interpolate(
new_masks.unsqueeze(1),
size=(input_mask_res, input_mask_res),
size=( # pyrefly: ignore [bad-argument-type]
input_mask_res,
input_mask_res,
), # pyrefly: ignore [bad-argument-type]
mode="bilinear",
align_corners=False,
).squeeze(1)
@@ -966,6 +980,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
with torch.profiler.record_function(
"_recodition_masklets.add_new_masks"
):
# pyrefly: ignore [not-callable]
self.tracker.add_new_masks(
inference_state=inference_state,
frame_idx=frame_idx,
@@ -979,6 +994,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for i, trk_obj_id in enumerate(valid_trk_obj_ids):
for inference_state in tracker_states_local:
if trk_obj_id in inference_state["obj_ids"]:
# pyrefly: ignore [not-callable]
self.tracker.add_new_mask(
inference_state=inference_state,
frame_idx=frame_idx,
@@ -1079,11 +1095,15 @@ class Sam3MultiplexBase(Sam3VideoBase):
)
if (
self.reconstruction_bbox_iou_thresh > 0
and len(adt_result.trk_id_to_max_iou_high_conf_det) > 0
and len(
adt_result.trk_id_to_max_iou_high_conf_det # pyrefly: ignore [missing-attribute]
) # pyrefly: ignore [missing-attribute]
> 0 # pyrefly: ignore [missing-attribute]
):
with torch.profiler.record_function(
"evaluate_reconstruction_bbox_iou_thresh"
):
# pyrefly: ignore [missing-attribute]
trk_obj_ids = adt_result.trk_id_to_max_iou_high_conf_det.keys()
sam2_obj_ids_all_gpu = list(tracker_metadata_prev["obj_ids_all_gpu"])
trk_ids = [
@@ -1091,6 +1111,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for trk_obj_id in trk_obj_ids
if trk_obj_id in sam2_obj_ids_all_gpu
]
# pyrefly: ignore [missing-attribute]
det_ids = list(adt_result.trk_id_to_max_iou_high_conf_det.values())
det_boxes_bbox_iou = det_out["bbox"][det_ids]
@@ -1120,7 +1141,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
should_recondition_periodic = (
self.recondition_every_nth_frame > 0
and frame_idx % self.recondition_every_nth_frame == 0
and len(adt_result.trk_id_to_max_iou_high_conf_det) > 0
and len(
adt_result.trk_id_to_max_iou_high_conf_det # pyrefly: ignore [missing-attribute]
) # pyrefly: ignore [missing-attribute]
> 0 # pyrefly: ignore [missing-attribute]
)
# Recondition if periodic or IoU condition met
@@ -1147,6 +1171,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
obj_id in reconditioned_obj_ids
for obj_id in state.get("obj_ids", [])
):
# pyrefly: ignore [not-callable]
self.tracker.propagate_in_video_preflight(
state, run_mem_encoder=True
)
@@ -1727,6 +1752,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# propagate one frame
num_frames_propagated = 0
with torch.profiler.record_function("sam2_predictor.propagate_in_video"):
# pyrefly: ignore [not-callable]
for out in self.tracker.propagate_in_video(
inference_state,
start_frame_idx=frame_idx,
@@ -1757,7 +1783,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
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:
# pyrefly: ignore [unbound-name]
max_mask_rows = out_low_res_masks.shape[0]
# pyrefly: ignore [unbound-name]
max_score_rows = out_obj_scores.shape[0]
# Special case: common single-object refinement path where SAM2 returns a single mask row
# but a longer out_obj_ids list for the state. Treat the lone row as the requested object.
@@ -1799,7 +1827,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
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)
# pyrefly: ignore [unbound-name]
low_res_masks_list.append(out_low_res_masks.squeeze(1))
# pyrefly: ignore [unbound-name]
obj_scores_list.append(out_obj_scores.squeeze(1))
# concatenate the output masklets from all local inference states
@@ -1823,6 +1853,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
)
low_res_masks_local = low_res_masks_local.squeeze(1)
else:
# pyrefly: ignore [bad-argument-type]
low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
obj_scores_local = torch.zeros(0, device=self.device)
@@ -2483,6 +2514,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
return
# Avoid an extra interpolation step by directly interpolating to `interpol_size`
high_res_H, high_res_W = (
# pyrefly: ignore [missing-attribute]
self.tracker.maskmem_backbone.mask_downsampler.interpol_size
)
# NOTE: inspect this part if we observe OOMs in the demo
@@ -2497,6 +2529,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
"sam2_predictor.propagate_in_video.apply_non_overlapping_constraints"
):
# TODO: try _apply_object_wise_non_overlapping_constraints instead
# pyrefly: ignore [not-callable]
high_res_masks = self.tracker._suppress_object_pw_area_shrinkage(
high_res_masks
)
@@ -2554,6 +2587,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
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
# pyrefly: ignore [not-callable]
encoded_mem = self.tracker._run_memory_encoder(
sam2_state,
frame_idx,
@@ -2612,7 +2646,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
newly_suppressed_objects = newly_suppressed_objects.float()
new_pointers = (
newly_suppressed_objects
* self.tracker.no_obj_ptr_linear(existing_pointers)
* self.tracker.no_obj_ptr_linear( # pyrefly: ignore [not-callable]
existing_pointers
) # pyrefly: ignore [not-callable]
+ (1 - newly_suppressed_objects) * existing_pointers
)
@@ -2626,6 +2662,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# for batched inference state, we also need to add per-object
# memory slides to support instance interactivity
# pyrefly: ignore [not-callable]
self.tracker.add_output_per_object(
inference_state=sam2_state,
frame_idx=frame_idx,
@@ -2676,6 +2713,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
new_sam2_state = best_state
else:
# Need to create a new state
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state(
cached_features=feature_cache,
video_height=orig_vid_height,
@@ -2696,6 +2734,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
if prev_sam2_state is not None:
new_sam2_state = prev_sam2_state
else:
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state(
cached_features=feature_cache,
video_height=orig_vid_height,
@@ -2707,6 +2746,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
else:
# batch objects that first appear on the same frame together
# Clear inference state. Keep the cached image features if available.
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state(
cached_features=feature_cache,
video_height=orig_vid_height,
@@ -2727,6 +2767,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
input_mask_res = self.tracker.input_mask_size
new_obj_masks = F.interpolate(
new_obj_masks.unsqueeze(1),
# pyrefly: ignore [bad-argument-type]
size=(input_mask_res, input_mask_res),
mode="bilinear",
align_corners=False,
@@ -2737,6 +2778,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# add all objects at once
# NOTE: In the current implementation, add_new_masks also runs the memory encoder
# the non-overlapping constraint is enforced
# pyrefly: ignore [not-callable]
self.tracker.add_new_masks(
inference_state=new_sam2_state,
frame_idx=frame_idx,
@@ -2747,6 +2789,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
else:
# add object one by one
for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
# pyrefly: ignore [not-callable]
self.tracker.add_new_mask(
inference_state=new_sam2_state,
frame_idx=frame_idx,
@@ -2755,6 +2798,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
add_mask_to_memory=True,
)
# NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
# pyrefly: ignore [not-callable]
self.tracker.propagate_in_video_preflight(new_sam2_state, run_mem_encoder=True)
return tracker_states_local
@@ -2772,6 +2816,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for sam2_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`
# pyrefly: ignore [not-callable]
new_obj_ids, _ = self.tracker.remove_objects(
sam2_inference_state, obj_ids, strict=False, need_output=False
)
+30 -57
View File
@@ -32,6 +32,7 @@ class Sam3MultiplexImageBase(Sam3Image):
self.offload_outputs_to_cpu_for_eval = offload_outputs_to_cpu_for_eval
self.trim_outputs_for_eval = True # dummy option -- it doesn't do anything
# pyrefly: ignore [bad-override]
def forward(
self,
input: BatchedDatapoint,
@@ -135,9 +136,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`.
# pyrefly: ignore [missing-attribute]
device = chunk_find_inputs[0].img_ids.device
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute `dtype`.
# pyrefly: ignore [missing-attribute]
dtype = chunk_find_inputs[0].img_ids.dtype
img_ids_list = [
torch.tensor([i], device=device, dtype=dtype)
@@ -151,15 +152,13 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_list, dim=0)
if input_boxes_list[0] is not None
else None
@@ -168,8 +167,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_mask_list, dim=0)
if input_boxes_mask_list[0] is not None
else None
@@ -178,8 +176,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_label_list, dim=0)
if input_boxes_label_list[0] is not None
else None
@@ -188,8 +185,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_list, dim=0)
if input_points_list[0] is not None
else None
@@ -198,8 +194,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_mask_list, dim=0)
if input_points_mask_list[0] is not None
else None
@@ -210,8 +205,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_before_embed_list, dim=0)
if input_boxes_before_embed_list[0] is not None
else None
@@ -221,8 +215,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_before_embed_list, dim=0)
if input_points_before_embed_list[0] is not None
else None
@@ -233,20 +226,15 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
input_boxes=batched_input_boxes,
# pyre-fixme[6]: For 5th argument expected `Union[List[Any], Tensor]`
# but got `Optional[Tensor]`.
# pyrefly: ignore [bad-argument-type]
input_boxes_mask=batched_input_boxes_mask,
# pyre-fixme[6]: For 6th argument expected `Union[List[Any], Tensor]`
# but got `Optional[Tensor]`.
# pyrefly: ignore [bad-argument-type]
input_boxes_label=batched_input_boxes_label,
# pyre-fixme[6]: For 7th argument expected `Union[List[Any], Tensor]`
# but got `Optional[Tensor]`.
# pyrefly: ignore [bad-argument-type]
input_points=batched_input_points,
# pyre-fixme[6]: For 8th argument expected `Union[List[Any], Tensor]`
# but got `Optional[Tensor]`.
# pyrefly: ignore [bad-argument-type]
input_points_mask=batched_input_points_mask,
ptrs=None, # Not batching pointers for now
ptrs_seg=None,
@@ -469,6 +457,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
else:
frame_idx_prev_b = frame_idx_prev_e = None
if frame_idx_prev_b is not None:
# pyrefly: ignore [bad-argument-type]
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
multigpu_buffer.pop(frame_idx_rm, None)
@@ -550,11 +539,7 @@ 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
@@ -628,45 +613,35 @@ 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.
# pyrefly: ignore [unbound-name]
inte_fpn0[rank],
# pyre-fixme[61]: `inte_fpn_handle0` is undefined, or not
# always defined.
# pyrefly: ignore [unbound-name]
inte_fpn_handle0,
)
frame_buffer["interactive_backbone_fpn_1"] = (
# pyre-fixme[61]: `inte_fpn1` is undefined, or not always
# defined.
# pyrefly: ignore [unbound-name]
inte_fpn1[rank],
# pyre-fixme[61]: `inte_fpn_handle1` is undefined, or not
# always defined.
# pyrefly: ignore [unbound-name]
inte_fpn_handle1,
)
frame_buffer["interactive_backbone_fpn_2"] = (
# pyre-fixme[61]: `inte_fpn2` is undefined, or not always
# defined.
# pyrefly: ignore [unbound-name]
inte_fpn2[rank],
# pyre-fixme[61]: `inte_fpn_handle2` is undefined, or not
# always defined.
# pyrefly: ignore [unbound-name]
inte_fpn_handle2,
)
frame_buffer["interactive_backbone_pos_enc"] = (
# pyre-fixme[61]: `inte_vision_pos_enc` is undefined, or not
# always defined.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
# pyre-fixme[61]: `vision_pos_enc` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None)
multigpu_buffer[frame_idx_to_save] = frame_buffer
@@ -865,11 +840,7 @@ 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
@@ -950,6 +921,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
out["sam2_backbone_fpn_2"] = sam2_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1
]
# pyrefly: ignore [unsupported-operation]
out["sam2_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in sam2_bb["vision_pos_enc"]
]
@@ -965,6 +937,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
out["interactive_backbone_fpn_2"] = inte_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1
]
# pyrefly: ignore [unsupported-operation]
out["interactive_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in inte_bb["vision_pos_enc"]
]
+1 -1
View File
@@ -7,7 +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`.
# pyrefly: ignore [missing-import]
from torch_generic_nms import generic_nms
GENERIC_NMS_AVAILABLE = True
+7 -4
View File
@@ -1758,7 +1758,9 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
# set the model to single GPU for benchmark evaluation (to be compatible with trainer)
orig_rank = self.rank
orig_world_size = self.world_size
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = 0
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = 1
# get data
@@ -1810,7 +1812,9 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels)
# revert the model to the original GPU and rank
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = orig_rank
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = orig_world_size
return {video_id: preds}
@@ -1866,6 +1870,7 @@ class Sam3MultiplexTrackingProd(Sam3MultiplexTracking):
}
@torch.inference_mode()
# pyrefly: ignore [bad-override]
def propagate_in_video(
self,
inference_state,
@@ -2287,8 +2292,7 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
)
@torch.inference_mode()
# pyre-fixme[14]: `propagate_in_video` overrides method defined in
# `Sam3MultiplexTracking` inconsistently.
# pyrefly: ignore [bad-override]
def propagate_in_video(
self,
inference_state,
@@ -2359,6 +2363,7 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
inference_state, obj_ids
)
for sam2_state in tracker_states_local:
# pyrefly: ignore [not-callable]
self.tracker.propagate_in_video_preflight(
sam2_state, run_mem_encoder=True
)
@@ -2369,8 +2374,6 @@ 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,
+2 -1
View File
@@ -36,6 +36,7 @@ def sample_box_points(
).repeat(B)
if noise > 0.0:
if not isinstance(noise_bound, torch.Tensor):
# pyrefly: ignore [bad-assignment]
noise_bound = torch.tensor(noise_bound, device=device)
bbox_w = box_coords[..., 2] - box_coords[..., 0]
bbox_h = box_coords[..., 3] - box_coords[..., 1]
@@ -52,7 +53,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]`.
# pyrefly: ignore [bad-return]
return box_coords, box_labels
+14
View File
@@ -38,11 +38,16 @@ class MaskletConfirmationStatus(Enum):
class RealizedAssociateDetTrkresult:
# pyre-fixme[11]: Annotation `array` is not defined as a type.
new_det_fa_inds: np.array
# pyrefly: ignore [not-a-type]
unmatched_trk_obj_ids: np.array
# pyrefly: ignore [not-a-type]
det_to_matched_trk_obj_ids: Dict[int, np.array]
trk_id_to_max_iou_high_conf_det: Dict[int, int]
# pyrefly: ignore [not-a-type]
empty_trk_obj_ids: np.array
# pyrefly: ignore [not-a-type]
new_det_obj_ids: Optional[np.array] = None
# pyrefly: ignore [not-a-type]
new_det_gpu_ids: Optional[np.array] = None
num_obj_dropped_due_to_limit: Optional[int] = None
@@ -467,6 +472,7 @@ class Sam3VideoBase(nn.Module):
reverse=reverse,
det_out=det_out,
tracker_states_local=tracker_states_local,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=tracker_update_plan,
orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width,
@@ -484,10 +490,13 @@ class Sam3VideoBase(nn.Module):
tracker_low_res_masks_global=tracker_low_res_masks_global,
tracker_obj_scores_global=tracker_obj_scores_global,
tracker_metadata_prev=tracker_metadata_prev,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=tracker_update_plan,
orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width,
# pyrefly: ignore [bad-argument-type]
reconditioned_obj_ids=reconditioned_obj_ids,
# pyrefly: ignore [bad-argument-type]
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
)
obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
@@ -928,6 +937,7 @@ class Sam3VideoBase(nn.Module):
# always defined.
and len(trk_id_to_max_iou_high_conf_det) > 0
):
# pyrefly: ignore [missing-attribute]
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
det_box = det_out["bbox"][det_idx]
det_score = det_out["scores"][det_idx]
@@ -1075,6 +1085,7 @@ class Sam3VideoBase(nn.Module):
)
# for removed objects, we set their scores to a very low value (-1e4) but still
# keep them in "obj_id_to_score" (it's easier to handle outputs this way)
# pyrefly: ignore [not-iterable]
for obj_id in obj_ids_newly_removed:
tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][
@@ -1357,6 +1368,7 @@ class Sam3VideoBase(nn.Module):
# pyre-fixme[16]: `List` has no attribute `unsqueeze`.
last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
# pyrefly: ignore [missing-attribute]
last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
# Suppress most recently occluded
cmp_op = torch.gt if not reverse else torch.lt
@@ -1455,7 +1467,9 @@ class Sam3VideoBase(nn.Module):
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)
# pyrefly: ignore [unbound-name]
low_res_masks_list.append(out_low_res_masks.squeeze(1))
# pyrefly: ignore [unbound-name]
obj_scores_list.append(out_obj_scores.squeeze(1))
# concatenate the output masklets from all local inference states
+4 -2
View File
@@ -911,9 +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`.
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = 0
# pyre-fixme[16]: `Module` has no attribute `world_size`.
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = 1
# get data
@@ -954,7 +954,9 @@ class Sam3VideoInference(Sam3VideoBase):
preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels)
# revert the model to the original GPU and rank
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = orig_rank
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = orig_world_size
return {video_id: preds}
+7 -9
View File
@@ -77,11 +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.
# pyrefly: ignore [not-callable]
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.
# pyrefly: ignore [not-callable]
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(
@@ -123,9 +123,6 @@ 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
)
@@ -143,6 +140,7 @@ class Transformer(nn.Module):
and not torch.jit.is_scripting()
and self.training
):
# pyrefly: ignore [bad-assignment]
x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False)
else:
x = r(
@@ -214,7 +212,6 @@ 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(
@@ -223,6 +220,7 @@ class TextTransformer(nn.Module):
if proj_bias:
self.text_projection = nn.Linear(width, output_dim)
else:
# pyrefly: ignore [bad-assignment]
self.text_projection = nn.Parameter(torch.empty(width, output_dim))
def build_causal_mask(self) -> torch.Tensor:
@@ -295,7 +293,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`.
# pyrefly: ignore [bad-function-definition]
device: torch.device = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if isinstance(text[0], str):
@@ -324,14 +322,14 @@ 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`.
# pyrefly: ignore [bad-index]
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"
)
# Note that the input_embeds are returned in pytorch's convention (sequence first)
# pyrefly: ignore [bad-return]
return (
text_attention_mask,
text_memory_resized,
+2 -3
View File
@@ -137,8 +137,7 @@ 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]`.
# pyrefly: ignore [no-matching-overload]
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")
@@ -254,5 +253,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`.
# pyrefly: ignore [bad-return]
return result
+2 -2
View File
@@ -48,15 +48,15 @@ def copy_data_to_device(data, device: torch.device, *args: Any, **kwargs: Any):
},
)
elif isinstance(data, Mapping):
# pyre-fixme[19]: Expected 0 positional arguments.
# pyrefly: ignore [bad-instantiation]
return type(data)(
# pyrefly: ignore [bad-argument-count]
{
k: copy_data_to_device(v, device, *args, **kwargs)
for k, v in data.items()
}
)
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(
+36 -2
View File
@@ -58,11 +58,13 @@ class SAMOutput(TypedDict, total=True):
low_res_masks: torch.Tensor
high_res_masks: torch.Tensor
object_score_logits: torch.Tensor
# pyrefly: ignore [invalid-annotation, not-a-type]
obj_ptr: NotRequired[torch.Tensor] # [num_objects, C], in data space
class StageOutput(TypedDict, total=False):
# metadata
# pyrefly: ignore [invalid-annotation, not-a-type]
conditioning_objects: Required[set[int]]
# The outputs from a single stage; could be used as memory
@@ -893,6 +895,7 @@ class VideoTrackingMultiplex(nn.Module):
obj_ptr = self.obj_ptr_proj(sam_output_token)
if self.pred_obj_scores and self.use_no_obj_ptr:
# pyrefly: ignore [unbound-name]
lambda_is_obj_appearing = is_obj_appearing.float()
if self.use_linear_no_obj_ptr:
obj_ptr = lambda_is_obj_appearing * obj_ptr + (
@@ -915,6 +918,7 @@ class VideoTrackingMultiplex(nn.Module):
obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr
)
# pyrefly: ignore [bad-typed-dict-key]
outputs: SAMOutput = {
"low_res_multimasks": low_res_multimasks,
"high_res_multimasks": high_res_multimasks,
@@ -1003,6 +1007,7 @@ class VideoTrackingMultiplex(nn.Module):
obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr
)
# pyrefly: ignore [bad-typed-dict-key]
outputs: SAMOutput = {
"low_res_multimasks": low_res_masks,
"high_res_multimasks": high_res_masks,
@@ -1462,7 +1467,9 @@ class VideoTrackingMultiplex(nn.Module):
# image features are in (HW)BC
image_feat = prev["image_features"].cuda()
image_pos_embed = prev["image_pos_enc"].cuda() + tpos_enc
# pyrefly: ignore [unbound-name]
to_cat_image_feat.append(image_feat)
# pyrefly: ignore [unbound-name]
to_cat_image_pos_embed.append(image_pos_embed)
to_cat_prompt_pos_embed.append(maskmem_enc)
@@ -1862,6 +1869,7 @@ class VideoTrackingMultiplex(nn.Module):
# Retrieve image features according to img_ids (if they are already computed).
current_image = input.img_batch.tensors[img_ids]
current_backbone_features = {}
# pyrefly: ignore [unbound-name]
for neck_k, neck_out in backbone_features.items():
current_backbone_features[neck_k] = {
"vision_feats": [
@@ -2069,7 +2077,10 @@ class VideoTrackingMultiplex(nn.Module):
# pix_feat = pix_feat.view(-1, self.hidden_dim, *interactive_feat_sizes[-1])
# use no_mem_embed here as well to better align first-frame mask input vs point input
interactive_pix_feat = self._get_interactive_pix_mem(
interactive_vision_feats, interactive_feat_sizes
# pyrefly: ignore [bad-argument-type]
interactive_vision_feats,
# pyrefly: ignore [bad-argument-type]
interactive_feat_sizes,
)
sam_outputs = self._use_mask_as_output(
backbone_features=interactive_pix_feat,
@@ -2351,6 +2362,7 @@ class VideoTrackingMultiplex(nn.Module):
high_res_multimasks = high_res_multimasks.clone()
ious = ious.clone()
object_score_logits = object_score_logits.clone()
# pyrefly: ignore [unbound-name]
obj_ptr = obj_ptr.clone() if self.use_obj_ptrs_in_encoder else None
# Update masks for the interacted objects
@@ -2470,10 +2482,13 @@ class VideoTrackingMultiplex(nn.Module):
multiplex_state=multiplex_state,
)
current_out["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
current_out["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features:
# pyrefly: ignore [unsupported-operation]
current_out["image_features"] = propagation_vision_feats[-1]
# pyrefly: ignore [unsupported-operation]
current_out["image_pos_enc"] = propagation_vision_pos_embeds[-1]
# this is to avoid recomputing some of these features for add_new_masks_to_existing_state
@@ -2481,11 +2496,17 @@ class VideoTrackingMultiplex(nn.Module):
if need_aux_output:
if interactive_pix_feat is None:
interactive_pix_feat = self._get_interactive_pix_mem(
interactive_vision_feats, interactive_feat_sizes
# pyrefly: ignore [bad-argument-type]
interactive_vision_feats,
# pyrefly: ignore [bad-argument-type]
interactive_feat_sizes,
)
aux_output["interactive_pix_feat"] = interactive_pix_feat
# pyrefly: ignore [unsupported-operation]
aux_output["interactive_high_res_features"] = interactive_high_res_features
# pyrefly: ignore [unsupported-operation]
aux_output["propagation_vision_feats"] = propagation_vision_feats
# pyrefly: ignore [unsupported-operation]
aux_output["propagation_feat_sizes"] = propagation_feat_sizes
return current_out, aux_output
@@ -3249,6 +3270,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
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.
# pyrefly: ignore [unbound-name]
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)
@@ -3275,6 +3297,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
multiplex_state=multiplex_state,
)
prev_output["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
prev_output["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features:
# They should already be in the state; no modification is needed
@@ -3377,6 +3400,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
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.
# pyrefly: ignore [unbound-name]
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
@@ -3404,6 +3428,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
multiplex_state=multiplex_state,
)
prev_output["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
prev_output["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features:
# They should already be in the state; no modification is needed
@@ -3492,6 +3517,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
return current_out
# pyrefly: ignore [bad-override]
def forward_tracking(
self,
backbone_out,
@@ -3552,6 +3578,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# Retrieve image features according to img_ids (if they are already computed).
current_image = input.img_batch.tensors[img_ids]
current_backbone_features = {}
# pyrefly: ignore [unbound-name]
for neck_k, neck_out in backbone_features.items():
current_backbone_features[neck_k] = {
"vision_feats": [
@@ -3695,8 +3722,11 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
last_mask = all_frame_outputs[-1]["pred_masks"]
# pyrefly: ignore [missing-attribute]
shape = last_mask.shape[1:]
# pyrefly: ignore [missing-attribute]
dtype = last_mask.dtype
# pyrefly: ignore [missing-attribute]
device = last_mask.device
for stage_i, frame_out in enumerate(all_frame_outputs):
if frame_out is None:
@@ -3708,14 +3738,18 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
continue
pred_mask = frame_out["pred_masks"]
# pyrefly: ignore [missing-attribute]
if pred_mask.shape[0] < num_objects:
# pyrefly: ignore [missing-attribute]
shape = pred_mask.shape[
1:
] # might have a different shape, e.g., input mask
frame_out["pred_masks"] = torch.cat(
# pyrefly: ignore [bad-argument-type]
[
pred_mask,
torch.zeros(
# pyrefly: ignore [missing-attribute]
(num_objects - pred_mask.shape[0], *shape),
device=device,
dtype=dtype,
+4 -4
View File
@@ -2734,8 +2734,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
obj_idxs_in_mask=new_obj_idxs,
obj_ids_in_mask=new_obj_ids,
prev_output=existing_out,
@@ -2770,12 +2769,12 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
propagation_vision_feats=propagation_vision_feats,
propagation_feat_sizes=propagation_feat_sizes,
new_masks=(
# pyrefly: ignore [bad-argument-type]
mask_inputs
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]]`.
# pyrefly: ignore [bad-argument-type]
obj_idxs_in_mask=new_obj_idxs,
obj_ids_in_mask=new_obj_ids,
prev_output=existing_out,
@@ -3221,6 +3220,7 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
class Sam3VideoTrackingMultiplexDemo(VideoTrackingMultiplexDemo):
@torch.inference_mode()
# pyrefly: ignore [bad-override-param-name]
def init_state(
self,
video_height,
+19 -36
View File
@@ -93,15 +93,11 @@ 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)
@@ -275,7 +271,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.
# pyrefly: ignore [unbound-name]
[cls_pos, new_abs_pos.permute(0, 2, 3, 1).reshape(1, h * w, -1)],
dim=1,
)
@@ -285,7 +281,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.
# pyrefly: ignore [unbound-name]
return torch.cat([cls_pos, abs_pos], dim=1)
@@ -400,7 +396,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`.
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla,
cls_token: bool = False,
use_rope: bool = False,
@@ -470,7 +466,6 @@ 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)
)
@@ -479,7 +474,6 @@ 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, :]
@@ -488,7 +482,6 @@ 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
@@ -499,10 +492,8 @@ 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],
)
@@ -569,7 +560,6 @@ 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
@@ -578,15 +568,11 @@ class Attention(nn.Module):
return apply_rotary_enc_real(
q,
k,
# pyre-fixme[6]: For 3rd argument expected `Tensor` but got
# `Union[Module, Tensor]`.
# pyrefly: ignore [bad-argument-type]
freqs_cis_imag=self.freqs_cis_imag,
# pyre-fixme[6]: For 4th argument expected `Tensor` but got
# `Union[Module, Tensor]`.
# pyrefly: ignore [bad-argument-type]
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:
@@ -613,26 +599,23 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
(H, W),
# pyre-fixme[6]: For 4th argument expected `Tuple[int, int]` but got
# `Size`.
# pyrefly: ignore [bad-argument-type]
x.shape[1:3],
# pyrefly: ignore [bad-argument-type]
self.rel_pos_h,
# pyrefly: ignore [bad-argument-type]
self.rel_pos_w,
rescale=True,
# pyre-fixme[6]: For 8th argument expected `Optional[Tensor]` but
# got `Union[Module, Tensor]`.
# pyrefly: ignore [bad-argument-type]
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`.
# pyrefly: ignore [bad-argument-type]
q = q.reshape(B, self.num_heads, H * W, -1)
# pyre-fixme[6]: For 3rd argument expected `Union[int, SymInt]` but got
# `float`.
# pyrefly: ignore [bad-argument-type]
k = k.reshape(B, self.num_heads, H * W, -1)
if self.attn_type == AttentionType.Vanilla:
@@ -649,8 +632,10 @@ class Attention(nn.Module):
if ndim == 4:
x = (
# pyrefly: ignore [bad-argument-type]
x.view(B, self.num_heads, H, W, -1)
.permute(0, 2, 3, 1, 4)
# pyrefly: ignore [bad-argument-type]
.reshape(B, H, W, -1)
)
else:
@@ -685,7 +670,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`.
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla,
use_fa3: bool = False,
use_rope_real: bool = False,
@@ -762,9 +747,7 @@ 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.
# pyrefly: ignore [unbound-name]
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
x = shortcut + self.dropout(self.drop_path(x))
@@ -811,7 +794,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`.
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla,
ln_pre: bool = False,
ln_post: bool = False,
@@ -866,8 +849,7 @@ 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__`.
# pyrefly: ignore [not-iterable]
for i in rel_pos_blocks:
self.rel_pos_blocks[i] = True
@@ -908,6 +890,7 @@ class ViT(nn.Module):
num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches
self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
else:
# pyrefly: ignore [bad-assignment]
self.pos_embed = None
# stochastic depth decay rule
+3 -4
View File
@@ -38,9 +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 = (
# pyrefly: ignore [bad-assignment]
torch.compile(visual) if compile_visual else visual
)
self.language_backbone = text
@@ -280,7 +279,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`.
# pyrefly: ignore [bad-function-definition]
compile_mode: str = None,
compile_extra_args: Optional[dict] = None,
):
@@ -346,7 +345,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`.
# pyrefly: ignore [bad-function-definition]
compile_mode: str = None,
compile_extra_args: Optional[dict] = None,
):
+1
View File
@@ -1127,6 +1127,7 @@ def build_sam3_multiplex_video_predictor(
strict_state_dict_loading=False,
)
del tracker_model.backbone
# pyrefly: ignore [bad-assignment]
tracker_model.backbone = None
sam2_predictor = Sam3MultiplexPredictorWrapper(
+1 -1
View File
@@ -6,7 +6,7 @@ import logging
import torch
try:
# pyre-fixme[21]: Could not find module `cc_torch`.
# pyrefly: ignore [missing-import]
from cc_torch import get_connected_components
HAS_CC_TORCH = True
+1 -1
View File
@@ -9,7 +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`.
# pyrefly: ignore [missing-import]
from flash_attn_interface import flash_attn_func as fa3
return fa3(q, k, v)
+1 -1
View File
@@ -10,7 +10,7 @@ from sam3.perflib.masks_ops import mask_iou
try:
# pyre-fixme[21]: Could not find module `torch_generic_nms`.
# pyrefly: ignore [missing-import]
from torch_generic_nms import generic_nms as generic_nms_cuda
GENERIC_NMS_AVAILABLE = True
+7 -8
View File
@@ -432,9 +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`.
# pyrefly: ignore [bad-argument-type]
numel,
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
# pyrefly: ignore [bad-argument-type]
BLOCK_SIZE=BLOCK_SIZE,
)
@@ -448,8 +448,7 @@ 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`.
# pyrefly: ignore [bad-argument-type]
_pointer_jump_kernel[grid_jump](labels, output, numel, BLOCK_SIZE=BLOCK_SIZE)
# --- Phase 4 ---
@@ -463,23 +462,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](
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
# pyrefly: ignore [bad-argument-type]
output,
sizes_histogram,
numel,
# pyre-fixme[6]: For 4th argument expected `constexpr` but got `int`.
# pyrefly: ignore [bad-argument-type]
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](
# pyre-fixme[6]: For 5th argument expected `constexpr` but got `int`.
# pyrefly: ignore [bad-argument-type]
output,
sizes_histogram,
component_sizes_out,
numel,
# pyre-fixme[6]: For 5th argument expected `constexpr` but got `int`.
# pyrefly: ignore [bad-argument-type]
BLOCK_SIZE=BLOCK_SIZE,
)
return output.view(out_shape) + 1, component_sizes_out.view(out_shape)
+2 -1
View File
@@ -27,9 +27,10 @@ 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.
# pyrefly: ignore [not-a-type]
num_boxes: tl.int32,
# Strides
# pyrefly: ignore [not-a-type]
iou_mask_stride: tl.int32,
# Constexprs
cxpr_block_size: tl.constexpr,
+5 -6
View File
@@ -98,6 +98,7 @@ class MaskDecoder(nn.Module):
if self.pred_obj_scores:
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
if pred_obj_scores_mlp:
# pyrefly: ignore [bad-assignment]
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
# When outputting a single mask, optionally we can dynamically fall back to the best
@@ -132,7 +133,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.
# pyrefly: ignore [bad-unpacking]
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
image_embeddings=image_embeddings,
image_pe=image_pe,
@@ -163,8 +164,7 @@ 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.
# pyrefly: ignore [bad-return]
return masks, iou_pred, sam_tokens_out, object_score_logits
def predict_masks(
@@ -222,7 +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.
# pyrefly: ignore [not-iterable]
feat_s0, feat_s1 = high_res_features
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
@@ -245,8 +245,7 @@ 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.
# pyrefly: ignore [bad-return]
return masks, iou_pred, mask_tokens_out, object_score_logits
def _get_stability_scores(self, mask_logits):
+8
View File
@@ -97,21 +97,25 @@ class PromptEncoder(nn.Module):
)
point_embedding = torch.where(
(labels == 0).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[0].weight,
point_embedding,
)
point_embedding = torch.where(
(labels == 1).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[1].weight,
point_embedding,
)
point_embedding = torch.where(
(labels == 2).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[2].weight,
point_embedding,
)
point_embedding = torch.where(
(labels == 3).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[3].weight,
point_embedding,
)
@@ -124,7 +128,9 @@ class PromptEncoder(nn.Module):
corner_embedding = self.pe_layer.forward_with_coords(
coords, self.input_image_size
)
# pyrefly: ignore [unsupported-operation]
corner_embedding[:, 0, :] += self.point_embeddings[2].weight
# pyrefly: ignore [unsupported-operation]
corner_embedding[:, 1, :] += self.point_embeddings[3].weight
return corner_embedding
@@ -152,6 +158,7 @@ class PromptEncoder(nn.Module):
return 1
def _get_device(self) -> torch.device:
# pyrefly: ignore [bad-return]
return self.point_embeddings[0].weight.device
def forward(
@@ -217,6 +224,7 @@ class PositionEmbeddingRandom(nn.Module):
"""Positionally encode points that are normalized to [0,1]."""
# assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
coords = 2 * coords - 1
# pyrefly: ignore [unsupported-operation]
coords = coords @ self.positional_encoding_gaussian_matrix
coords = 2 * np.pi * coords
# outputs d_1 x ... x d_n x C shape
+1 -5
View File
@@ -33,18 +33,14 @@ 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)
@@ -144,7 +140,6 @@ 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:
@@ -165,4 +160,5 @@ class VisionRotaryEmbeddingVE(nn.Module):
self.register_buffer("freqs_sin", freqs_sin)
def forward(self, t: torch.Tensor):
# pyrefly: ignore [unsupported-operation]
return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
+1 -1
View File
@@ -195,7 +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`.
# pyrefly: ignore [bad-function-definition]
kv_in_dim: int = None,
use_fa3: bool = False,
) -> None:
+30 -61
View File
@@ -211,13 +211,11 @@ 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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
stages[stage_id].text_ids.append(text_batch.index(q.query_text))
assert q.inference_metadata is not None, (
@@ -231,91 +229,70 @@ 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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes.append(torch.zeros(0, 4))
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no
# attribute `append`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].boxes.extend(current_out_boxes)
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
# `extend`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].repeated_boxes.extend(current_out_boxes)
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
# `append`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].num_boxes.append(len(current_out_boxes))
# pyre-fixme[16]: Item `Tensor` of `List[Any] | Tensor` has no attribute
# `append`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].is_exhaustive.append(q.is_exhaustive)
if with_seg_masks:
@@ -328,18 +305,15 @@ def collate_fn_api(
current_is_valid_segment.append(1)
else:
dummy_mask = torch.zeros(
# pyre-fixme[16]: Item `Image` of `Image | Tensor` has
# no attribute `shape`.
# pyrefly: ignore [missing-attribute]
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`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].segments.extend(current_seg_mask)
# pyre-fixme[16]: Item `None` of `None | List[Any] | Tensor` has no
# attribute `extend`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].is_valid_segment.extend(current_is_valid_segment)
else:
# We are not loading segmentation masks
@@ -347,8 +321,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].semantic_segments.append(q.semantic_target)
offset_img_id += len(data.images)
@@ -356,16 +329,14 @@ 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(
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
# `Union[List[Any], Tensor]`.
# pyrefly: ignore [bad-argument-type]
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(
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
# `Union[List[Any], Tensor]`.
# pyrefly: ignore [bad-argument-type]
stages[i].input_points_mask,
dim=0,
pad_val=1,
@@ -374,23 +345,20 @@ def collate_fn_api(
# Pad input boxes to equal sequence lengths
for i in range(len(stages)):
stages[i].input_boxes = pad_tensor_list_to_longest(
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
# `Union[List[Any], Tensor]`.
# pyrefly: ignore [bad-argument-type]
stages[i].input_boxes,
dim=0,
pad_val=0,
)
stages[i].input_boxes_label = pad_tensor_list_to_longest(
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
# `Union[List[Any], Tensor]`.
# pyrefly: ignore [bad-argument-type]
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(
# pyre-fixme[6]: For 1st argument expected `List[Tensor]` but got
# `Union[List[Any], Tensor]`.
# pyrefly: ignore [bad-argument-type]
stages[i].input_boxes_mask,
dim=0,
pad_val=1,
@@ -403,8 +371,7 @@ 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(
# pyre-fixme[16]: Item `List` of `List[Any] | Tensor` has no attribute
# `view`.
# pyrefly: ignore [missing-attribute]
find_targets[i].boxes.view(-1, 4),
find_targets[i].num_boxes,
)
@@ -415,7 +382,9 @@ def collate_fn_api(
# Finalize the image batch
# check sizes
for img in img_batch[1:]:
# pyrefly: ignore [missing-attribute]
assert img.shape == img_batch[0].shape, "All images must have the same size"
# pyrefly: ignore [bad-argument-type]
image_batch = torch.stack(img_batch)
if load_image_in_fp16:
# Optionally, cast the image tensors to fp16, which helps save GPU memory on
+6 -4
View File
@@ -157,7 +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`.
# pyrefly: ignore [bad-function-definition]
limit_ids: int = None,
) -> None:
super().__init__(root)
@@ -183,6 +183,7 @@ class CustomCocoDetectionAPI(VisionDataset):
) -> Tuple[List[Tuple[int, PILImage.Image]], List[Dict[str, Any]]]:
all_images = []
all_img_metadata = []
# pyrefly: ignore [missing-attribute]
for current_meta in self.coco.loadImagesFromDatapoint(datapoint_id):
img_id = current_meta["id"]
if img_ids_to_load is not None and img_id not in img_ids_to_load:
@@ -192,8 +193,6 @@ 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:
@@ -259,7 +258,9 @@ class CustomCocoDetectionAPI(VisionDataset):
def _load_datapoint(self, index: int) -> Datapoint:
"""A separate method for easy overriding in subclasses."""
id = self.ids[index].item()
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id)
# pyrefly: ignore [missing-attribute]
queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id)
return self.load_queries(pil_images, annotations, queries, img_metadata)
@@ -457,7 +458,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`.
# pyrefly: ignore [bad-function-definition]
limit_ids: int = None,
):
super(Sam3ImageDataset, self).__init__(
@@ -487,6 +488,7 @@ class Sam3ImageDataset(CustomCocoDetectionAPI):
self._MAX_RETRIES = 100
# pyrefly: ignore [bad-override-param-name]
def __getitem__(self, idx):
return self.__orig_getitem__(idx)
+8 -9
View File
@@ -91,6 +91,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
def _load_datapoint(self, index: int) -> Datapoint:
id = self.ids[index].item()
# pyrefly: ignore [missing-attribute]
queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id)
# we subsample the video frames during training
@@ -114,6 +115,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
remap_stage_id=True,
reverse_time_axis=reverse_time_axis,
)
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id, kept_img_ids)
if reverse_time_axis:
# reverse the temporal ordering of the images and their metadata
@@ -121,6 +123,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
pil_images = pil_images[::-1]
img_metadata = img_metadata[::-1]
else:
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id)
# check that all the images have the same image size (they are expected
@@ -251,9 +254,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
if datapoint.raw_images is not None:
assert len(datapoint.raw_images) == 1, "Expected only one single image"
tiled_raw_images = [
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
datapoint.raw_images[0].copy()
for _ in range(num_stages_sample)
datapoint.raw_images[0].copy() for _ in range(num_stages_sample)
]
# tile `find_queries: List[FindQueryLoaded]`
@@ -263,10 +264,9 @@ 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`.
# pyrefly: ignore [missing-attribute]
assert query.ptr_x is None and query.ptr_y is None
# pyre-fixme[16]: `FindQueryLoaded` has no attribute `ptr_mem`.
# pyrefly: ignore [missing-attribute]
assert query.ptr_mem is None
# assert query.wkdata_qid is None
# assert query.other_positive_qids is None
@@ -295,11 +295,11 @@ 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,
find_queries=tiled_find_queries,
# pyrefly: ignore [unexpected-keyword]
get_queries=tiled_get_queries,
)
@@ -324,11 +324,10 @@ 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`.
# pyrefly: ignore [missing-attribute, unexpected-keyword]
get_queries=datapoint.get_queries,
)
+2 -2
View File
@@ -32,16 +32,16 @@ class TorchDataset:
if enable_distributed_sampler:
self.sampler = DistributedSampler(self.dataset, shuffle=self.shuffle)
else:
# pyrefly: ignore [bad-assignment]
self.sampler = None
def get_loader(self, epoch) -> Iterable:
if self.sampler:
self.sampler.set_epoch(epoch)
if hasattr(self.dataset, "epoch"):
# pyre-fixme[16]: `Dataset` has no attribute `epoch`.
# pyrefly: ignore [missing-attribute]
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(
+6
View File
@@ -345,6 +345,7 @@ class IABCEMdetr(LossWithWeights):
"If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
)
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes):
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
assert outputs["pred_logits"].shape[-1] == 1, "Incorrect predicted logits shape"
@@ -533,6 +534,7 @@ class Boxes(LossWithWeights):
)
self.target_keys.extend(["boxes", "boxes_xyxy"])
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
@@ -638,6 +640,7 @@ class Masks(LossWithWeights):
return losses
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the masks: the focal loss and the dice loss.
targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
@@ -1025,6 +1028,7 @@ class SemanticSegCriterion(LossWithWeights):
self.presence_head = presence_head
self.presence_loss = presence_loss
# pyrefly: ignore [bad-override]
def get_loss(self, out_dict, targets):
outputs = out_dict["semantic_seg"]
presence_logit = out_dict["presence_logit"]
@@ -1170,6 +1174,7 @@ class Det2TrkAssoc(LossWithWeights):
if self.use_fp_loss:
self.target_keys.append("is_exhaustive")
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes):
det2trk_assoc_logits = outputs["det2trk_assoc_logits"]
device = det2trk_assoc_logits.device
@@ -1237,6 +1242,7 @@ class TrackingByDetectionAssoc(LossWithWeights):
assert "loss_det2trk_assoc" in self.weight_dict
assert "loss_trk2det_assoc" in self.weight_dict
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes):
# Part A: gather object id matching between detection and tracking
det2trk_assoc_logits = outputs["det2trk_assoc_logits"] # (B, Q_det+1, Q_trk+1)
+2
View File
@@ -231,6 +231,7 @@ class SigmoidFocalLoss(torch.autograd.Function):
return loss.view(input_shape)
@staticmethod
# pyrefly: ignore [bad-override]
def backward(ctx, grad_output):
inputs, targets = ctx.saved_tensors
alpha = ctx.alpha
@@ -294,6 +295,7 @@ class SigmoidFocalLossReduced(torch.autograd.Function):
return loss.sum()
@staticmethod
# pyrefly: ignore [bad-override]
def backward(ctx, grad_output):
inputs, targets = ctx.saved_tensors
alpha = ctx.alpha
+4 -2
View File
@@ -9,7 +9,7 @@ import numpy as np
# Check if Numba is available
HAS_NUMBA = False
try:
# pyre-fixme[21]: Could not find module `numba`.
# pyrefly: ignore [missing-import]
import numba as nb
HAS_NUMBA = True
@@ -71,6 +71,7 @@ def process_track_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
# Suppress non-kept tracks
for idx, track in enumerate(track_detections):
if idx not in keep:
# pyrefly: ignore [bad-argument-type]
tracks[track["track_idx"]]["bboxes"] = [None] * len(track["bboxes"])
return video_groups
@@ -104,6 +105,7 @@ def process_frame_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
# Apply NMS
if frame_detections:
# pyrefly: ignore [bad-argument-type]
bboxes = np.stack([d["bbox"] for d in frame_detections])
scores = np.array(
[d["score"] for d in frame_detections], dtype=np.float32
@@ -156,7 +158,7 @@ def compute_track_iou_matrix(
if HAS_NUMBA:
# pyrefly: ignore [unbound-name]
@nb.jit(nopython=True, parallel=True)
def _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas):
"""Numba-optimized IoU matrix computation for track-level NMS"""
+16 -20
View File
@@ -103,8 +103,7 @@ 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]]`.
# pyrefly: ignore [bad-argument-type]
scheduler_cfgs.append({"parameter_names": default_params})
@@ -124,7 +123,7 @@ def name_constraints_to_parameters(
param_constraints.
"""
matching_names = set.intersection(*param_constraints)
# pyre-fixme[7]: Expected `List[Parameter]` but got `List[Tensor]`.
# pyrefly: ignore [bad-return]
return [value for name, value in named_parameters.items() if name in matching_names]
@@ -221,6 +220,7 @@ def unix_module_cls_pattern_to_parameter_names(
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
)
allowed_parameter_names.append(matching_parameters)
# pyrefly: ignore [bad-argument-type]
return set.union(*allowed_parameter_names)
@@ -263,13 +263,11 @@ 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`.
# pyrefly: ignore [missing-attribute]
return unix_param_pattern_to_parameter_names(
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
# `Set[str]`.
# pyrefly: ignore [bad-argument-type]
scheduler_cfg.get("param_names"),
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
# `Set[str]`.
# pyrefly: ignore [bad-argument-type]
parameter_names,
).union(
unix_module_cls_pattern_to_parameter_names(
@@ -279,9 +277,9 @@ def _unix_pattern_to_parameter_names(
def get_module_cls_to_param_names(
# pyre-fixme[9]: param_allowlist has type `Set[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
model: nn.Module,
# pyre-fixme[9]: param_allowlist has type `Set[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
param_allowlist: Set[str] = None,
) -> Dict[Type, str]:
"""Produce a mapping from all the modules classes to the names of parames they own.
@@ -302,16 +300,16 @@ def get_module_cls_to_param_names(
full_param_name = get_full_parameter_name(module_name, param_name)
if param_allowlist is None or full_param_name in param_allowlist:
module_cls_to_params[module_cls].add(full_param_name)
# pyrefly: ignore [bad-return]
return module_cls_to_params
def construct_optimizer(
model: torch.nn.Module,
optimizer_conf: Any,
# pyre-fixme[9]: options_conf has type `Mapping[str, List[Any]]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
options_conf: Mapping[str, List] = None,
# pyre-fixme[9]: param_group_modifiers_conf has type `List[(...) -> Any]`; used
# as `None`.
# pyrefly: ignore [bad-function-definition]
param_group_modifiers_conf: List[Callable] = None,
param_allowlist: Optional[Set[str]] = None,
validate_param_groups=True,
@@ -375,11 +373,9 @@ def construct_optimizer(
scheduler_cfgs=all_scheduler_cfgs, model=model
)
schedulers, param_groups = map_scheduler_cfgs_to_param_groups(
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
# `Dict[str, Parameter]`.
# pyrefly: ignore [bad-argument-type]
all_scheduler_cfgs,
# pyre-fixme[6]: For 2nd argument expected `Dict[str, Tensor]` but got
# `Dict[str, Parameter]`.
# pyrefly: ignore [bad-argument-type]
named_parameters,
)
if validate_param_groups:
@@ -423,7 +419,7 @@ class ValueScaler:
return val * self.mult_val
# pyre-fixme[9]: rattrs has type `str`; used as `None`.
# pyrefly: ignore [bad-function-definition]
def rgetattr(obj, rattrs: str = None):
"""
Like getattr(), but supports dotted notation for nested objects.
@@ -443,7 +439,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[]`.
# pyrefly: ignore [bad-function-definition]
overrides: List[Dict] = (),
) -> List[List[Dict]]:
"""
@@ -465,7 +461,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]`.
# pyrefly: ignore [bad-argument-type]
model = rgetattr(model, apply_to)
num_layers = model.get_num_layers() + 1
layer_decays = [
+1 -2
View File
@@ -10,7 +10,7 @@ import traceback
from argparse import ArgumentParser
from copy import deepcopy
# pyre-fixme[21]: Could not find module `submitit`.
# pyrefly: ignore [missing-import]
import submitit
import torch
from hydra import compose, initialize_config_module
@@ -83,7 +83,6 @@ 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."""
+1 -1
View File
@@ -284,7 +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`.
# pyrefly: ignore [bad-argument-type]
region = T.RandomCrop.get_params(img, (h, w))
result_img, result_target = crop(img, target, region)
return result_img, result_target
+37 -76
View File
@@ -871,14 +871,12 @@ 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`.
# pyrefly: ignore [missing-attribute]
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]`.
# pyrefly: ignore [bad-argument-type]
img.data = F.to_tensor(img.data)
return datapoint
@@ -892,18 +890,14 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
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]`.
# pyrefly: ignore [bad-argument-type]
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(
@@ -914,8 +908,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
boxes = box_xyxy_to_cxcywh(boxes)
boxes = boxes / torch.tensor(
@@ -924,8 +917,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
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
@@ -1012,35 +1004,23 @@ class ColorJitter:
) = T.ColorJitter.get_params(
self.brightness, self.contrast, self.saturation, self.hue
)
# pyrefly: ignore [unbound-name]
for fn_id in fn_idx:
# pyre-fixme[61]: `brightness_factor` is undefined, or not always
# defined.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_brightness(img.data, brightness_factor)
# pyre-fixme[61]: `contrast_factor` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_contrast(img.data, contrast_factor)
# pyre-fixme[61]: `saturation_factor` is undefined, or not always
# defined.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_saturation(img.data, saturation_factor)
# pyre-fixme[61]: `hue_factor` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
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.
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_hue(img.data, hue_factor)
return datapoint
@@ -1093,8 +1073,7 @@ class RandomAffine:
return datapoint
def transform_datapoint(self, datapoint: Datapoint):
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Union[Image,
# Tensor]`.
# pyrefly: ignore [bad-argument-type]
_, height, width = F.get_dimensions(datapoint.images[0].data)
img_size = [width, height]
@@ -1110,8 +1089,7 @@ 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`.
# pyrefly: ignore [missing-attribute]
obj.segment.unsqueeze(0) if obj.segment is not None else None
for obj in img.objects
]
@@ -1132,18 +1110,13 @@ 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(
# pyrefly: ignore [bad-argument-type]
this_masks[i],
# pyre-fixme[61]: `affine_params` is undefined, or not
# always defined.
# pyrefly: ignore [bad-argument-type, unbound-name]
*affine_params,
interpolation=InterpolationMode.NEAREST,
# pyre-fixme[6]: For 7th argument expected
# `Optional[List[float]]` but got `float`.
# pyrefly: ignore [bad-argument-type]
fill=0.0,
)
if img_idx == 0 and transformed_mask.max() == 0:
@@ -1158,15 +1131,10 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
img.data,
# pyre-fixme[61]: `affine_params` is undefined, or not always defined.
# pyrefly: ignore [bad-argument-type, unbound-name]
*affine_params,
interpolation=self.image_interpolation,
fill=self.fill_img,
@@ -1228,8 +1196,7 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
img=datapoint.images[0].data,
scale=self.scale,
ratio=ratio,
@@ -1239,16 +1206,14 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
img=img.data,
scale=self.scale,
ratio=ratio,
)
this_masks = [
# pyre-fixme[16]: Item `dict` of `dict[Any, Any] | Tensor` has no
# attribute `unsqueeze`.
# pyrefly: ignore [missing-attribute]
obj.segment.unsqueeze(0) if obj.segment is not None else None
for obj in img.objects
]
@@ -1261,9 +1226,9 @@ class RandomResizedCrop:
transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
else:
transformed_mask = F.resized_crop(
# pyrefly: ignore [bad-argument-type]
this_masks[i],
# pyre-fixme[61]: `crop_params` is undefined, or not always
# defined.
# pyrefly: ignore [unbound-name]
*crop_params,
size=self.size,
interpolation=InterpolationMode.NEAREST,
@@ -1282,10 +1247,9 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
img.data,
# pyre-fixme[61]: `crop_params` is undefined, or not always defined.
# pyrefly: ignore [unbound-name]
*crop_params,
size=self.size,
interpolation=InterpolationMode.BILINEAR,
@@ -1302,8 +1266,7 @@ 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]`.
# pyrefly: ignore [bad-argument-type]
_, height, width = F.get_dimensions(datapoint.images[0].data)
if height <= self.max_size and width <= self.max_size:
@@ -1319,15 +1282,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]`.
# pyrefly: ignore [bad-argument-type]
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__`.
# pyrefly: ignore [unsupported-operation]
obj.segment[None, None],
# pyrefly: ignore [bad-argument-type]
size,
interpolation=InterpolationMode.NEAREST,
).squeeze()
@@ -1373,7 +1335,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.
# pyrefly: ignore [unbound-name]
img.data = self._apply_motion_blur(img.data, kernel)
return datapoint
@@ -1436,8 +1398,7 @@ 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`.
# pyrefly: ignore [bad-argument-type]
torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
).item()
@@ -1447,12 +1408,12 @@ 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`.
# pyrefly: ignore [bad-argument-type]
torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
).item()
# Compute the dimensions of the jittered crop
# pyrefly: ignore [not-iterable]
original_width, original_height = img.data.size
target_area = original_width * original_height * scale_factor
crop_width = int(round((target_area * aspect_ratio) ** 0.5))
@@ -12,11 +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`.
# pyrefly: ignore [bad-assignment]
find_ids_to_filter: set = None
# pyre-fixme[8]: Attribute has type `Set[Any]`; used as `None`.
# pyrefly: ignore [bad-assignment]
get_ids_to_filter: set = None
# pyre-fixme[8]: Attribute has type `Set[Any]`; used as `None`.
# pyrefly: ignore [bad-assignment]
obj_ids_to_filter: set = None # stored as pairs (img_id, obj_id)
def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
@@ -37,12 +37,11 @@ class FilterQueryWithText(FilterDataPointQueries):
"""
def __init__(
# 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`.
# pyrefly: ignore [bad-function-definition]
self,
# pyre-fixme[9]: exclude_find_keys has type `List[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
exclude_find_keys: List[str] = None,
# pyre-fixme[9]: exclude_get_keys has type `List[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
exclude_get_keys: List[str] = None,
):
self.find_filter_keys = exclude_find_keys if exclude_find_keys else []
@@ -228,11 +227,7 @@ 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
+4 -1
View File
@@ -161,7 +161,10 @@ class DecodeRle:
warning_shown = True
query.semantic_target = F.resize(
query.semantic_target[None], imgId2size[query.image_id]
# pyrefly: ignore [bad-argument-type]
query.semantic_target[None],
# pyrefly: ignore [bad-argument-type]
imgId2size[query.image_id],
).squeeze(0)
assert tuple(query.semantic_target.shape) == imgId2size[query.image_id]
+14 -23
View File
@@ -61,7 +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__`.
# pyrefly: ignore [not-iterable]
return {k: state_dict[k] for k in included_keys}
@@ -83,8 +83,7 @@ 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]]`.
# pyrefly: ignore [not-iterable]
return {k: v for k, v in state_dict.items() if k not in excluded_keys}
@@ -183,15 +182,12 @@ class CkptExcludeKernel:
if len(self.key_pattern) == 0:
return state_dict
exclude_keys = unix_pattern_to_parameter_names(
# pyre-fixme[6]: For 2nd argument expected `Sequence[str]` but got
# `dict_keys[Any, Any]`.
# pyrefly: ignore [bad-argument-type]
self.key_pattern,
# pyre-fixme[6]: For 2nd argument expected `Sequence[str]` but got
# `dict_keys[Any, Any]`.
# pyrefly: ignore [bad-argument-type]
state_dict.keys(),
)
# pyre-fixme[58]: `not in` is not supported for right operand type
# `Optional[Set[str]]`.
# pyrefly: ignore [not-iterable]
return {k: v for k, v in state_dict.items() if k not in exclude_keys}
@@ -223,11 +219,9 @@ 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:
@@ -257,7 +251,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`.
# pyrefly: ignore [bad-function-definition]
checkpoint_kernels: List[Callable] = None,
ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
map_location: str = "cpu",
@@ -310,17 +304,16 @@ 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`.
# pyrefly: ignore [bad-function-definition]
ignore_missing_keys: List[str] = None,
# pyre-fixme[9]: ignore_unexpected_keys has type `List[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
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]]`.
# pyrefly: ignore [not-iterable]
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:
@@ -328,12 +321,10 @@ def check_load_state_dict_errors(
ignore_unexpected_keys, unexpected_keys
)
unexpected_keys = [
# pyre-fixme[58]: `not in` is not supported for right operand type
# `Optional[Set[str]]`.
# pyrefly: ignore [not-iterable]
key
for key in unexpected_keys
# pyre-fixme[58]: `not in` is not supported for right operand type
# `Optional[Set[str]]`.
# pyrefly: ignore [not-iterable]
if key not in ignored_unexpected_keys
]
@@ -353,11 +344,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`.
# pyrefly: ignore [bad-function-definition]
ignore_missing_keys: List[str] = None,
# pyre-fixme[9]: ignore_unexpected_keys has type `List[str]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
ignore_unexpected_keys: List[str] = None,
# pyre-fixme[9]: checkpoint_kernels has type `List[(...) -> Any]`; used as `None`.
# pyrefly: ignore [bad-function-definition]
checkpoint_kernels: List[Callable] = None,
):
"""
+4 -3
View File
@@ -271,7 +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`.
# pyrefly: ignore [bad-function-definition]
after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
) -> torch.Tensor:
"""
@@ -437,12 +437,12 @@ 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]]`.
# pyrefly: ignore [no-matching-overload]
data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
data_tensor = broadcast(data_tensor, src=src)
if use_disk:
with tempfile.TemporaryFile("r+b") as f:
# pyrefly: ignore [bad-argument-type]
f.write(data_tensor.numpy())
# remove reference to the data tensor and hope that Python garbage
# collects it
@@ -450,6 +450,7 @@ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True)
f.seek(0)
obj = torch.load(f, weights_only=False)
else:
# pyrefly: ignore [bad-argument-type]
buffer = io.BytesIO(data_tensor.numpy())
obj = torch.load(buffer, weights_only=False)
return obj
+1 -1
View File
@@ -36,7 +36,7 @@ class TensorBoardWriterWrapper:
self,
path: str,
*args: Any,
# pyre-fixme[9]: filename_suffix has type `str`; used as `None`.
# pyrefly: ignore [bad-function-definition]
filename_suffix: str = None,
summary_writer_method: Any = SummaryWriter,
**kwargs: Any,
+1 -1
View File
@@ -636,7 +636,6 @@ 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,
@@ -713,6 +712,7 @@ def get_all_annotations_for_frame(
get_media_dir(media_dir=media_dir, dataset=dataset), file_name
)
frame = cv2.imread(file_path)
# pyrefly: ignore [no-matching-overload]
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Get the masks and noun phrases annotated in this video in this frame
+1 -1
View File
@@ -9,7 +9,7 @@ from pathlib import Path
import requests
# pyre-fixme[21]: Could not find module `fathomnet.api`.
# pyrefly: ignore [missing-import]
from fathomnet.api import images
from tqdm import tqdm
@@ -11,7 +11,7 @@ import numpy as np
import pandas as pd
import requests
# pyre-fixme[21]: Could not find module `utils`.
# pyrefly: ignore [missing-import]
import utils
from PIL import Image
from tqdm import tqdm
+2 -2
View File
@@ -10,10 +10,10 @@ import sys
from concurrent.futures import as_completed, ThreadPoolExecutor
from pathlib import Path
# pyre-fixme[21]: Could not find module `yt_dlp`.
# pyrefly: ignore [missing-source-for-stubs]
import yt_dlp
# pyre-fixme[21]: Could not find module `utils`.
# pyrefly: ignore [missing-import]
from utils import (
annotation_files,
config,
+1 -1
View File
@@ -17,7 +17,7 @@ from multiprocessing import Pool
from PIL import Image
from tqdm import tqdm
# pyre-fixme[21]: Could not find module `utils`.
# pyrefly: ignore [missing-import]
from utils import (
annotation_files,
config,
@@ -7,7 +7,7 @@ from pathlib import Path
import pandas as pd
# pyre-fixme[21]: Could not find module `utils`.
# pyrefly: ignore [missing-import]
import utils
from tqdm import tqdm
+1 -1
View File
@@ -9,7 +9,7 @@ from functools import partial
import pandas as pd
# pyre-fixme[21]: Could not find module `saco_yt1b_frame_prep_util`.
# pyrefly: ignore [missing-import]
from saco_yt1b_frame_prep_util import YtVideoPrep
from tqdm import tqdm
@@ -8,7 +8,7 @@ import subprocess
import pandas as pd
# pyre-fixme[21]: Could not find module `yt_dlp`.
# pyrefly: ignore [missing-source-for-stubs]
import yt_dlp
logger = logging.getLogger(__name__)
+3 -8
View File
@@ -153,11 +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`.
# pyrefly: ignore [bad-function-definition]
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`.
# pyrefly: ignore [bad-function-definition]
checkpoint_path: str = None,
) -> float:
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
@@ -185,14 +185,9 @@ 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`.
# pyrefly: ignore [bad-assignment]
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