Compare commits

...
10 Commits
Author SHA1 Message Date
Marco Dal Farra 8f0b7f4d4e Restore autocast state on video predictor shutdown
Summary:
During development of an end2end test I encountered this bug.

SAM3's tracker enters a long-lived bfloat16 autocast context during model construction. Exit and clear that context when the owning video predictor shuts down so subsequent work in the same thread is not silently autocast.

___

Differential Revision: D115565123

fbshipit-source-id: 87dd514e974345d41b22a89569dd0ea3200bc53a
2026-08-13 22:33:07 -07:00
Chamath Wijesekera 96914d2425 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
2026-07-30 17:21:37 -07:00
generatedunixname89002005307016 6dbb02bd38 Suppress type errors for Pyre upgrade
Summary:
This diff was automatically generated by the Pyre per-target upgrade tool.

It adds `# pyre-fixme` or `pyrefly: ignore` comments to suppress type errors that will be introduced by an upcoming Pyre or Pyrefly release. These suppressions allow the upgrade to proceed without breaking existing code.

Upgrading to new pyrefly Version. Without landing this diff your type checking tests may break. If assigned as a reviewer please help us get these diffs across the finish line. Thank you!

#pyreupgrade

Differential Revision: D113834959

fbshipit-source-id: 63169c3df9d594b58d39a33ab51c8866629dd1fa
2026-07-27 19:25:12 -07:00
Jaime Rodriguez Sanchez 46957e4780 SAM3: production-faithful torch.compile A/B benchmark
Summary:
scripts/bench_compile.py + :bench_compile target. Builds Sam3VideoPredictorMultiGPU with the exact scene_service constructor args + sam3_v4.pt, toggling compile, and measures the real per-frame served sequence (start_session on a single image + K add_prompt, mirroring Sam3Client.getMasksStream) plus optional propagate. --native-warmup mirrors prod Sam3DenseTrackingModel.warmup (_compile_model() direct + single-image warm) to verify 0 serve-time recompiles under TORCH_LOGS=recompiles.

Needs -c fbcode.enable_gpu_sections=true (else cudaErrorInvalidKernelImage on H100). Reuses measure_speed.py synth+timing helpers.

Reviewed By: flanggut

Differential Revision: D111922692

fbshipit-source-id: b2c96da965ce67e76e5e8837d3b08e020d138eea
2026-07-15 04:05:53 -07:00
generatedunixname2333890303787380 5dd401d1c5 Remove F401 unused imports in fbcode//deeplearning/projects/sam3_release:_sam3
Reviewed By: brittanyrey

Differential Revision: D108589523

fbshipit-source-id: 6e56192d205566bd3cc393839b15a3e921849fa8
2026-06-15 12:12:38 -07:00
generatedunixname1401739305002972 8e451d5eb4 Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/sam3_image.py
Differential Revision: D105340230

fbshipit-source-id: ecb32f6146dcff7e16dd184f2e54c57897923bc3
2026-05-23 08:49:56 -07:00
generatedunixname1401739305002972 2814fa6194 Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D104793065

fbshipit-source-id: 1e6d98ee42fb51acfa4b0ce4b9bbe1251363b3e0
2026-05-16 01:56:52 -07:00
generatedunixname2094418054467506 32f5f81ab9 Fix python_unnecessary_generator_set_comprehension issues in deeplearning/.../silver/extract_frames.py
Differential Revision: D105295334

fbshipit-source-id: 3166b2df09bd7af1cea4dbd8dd7ba525a25bf9dd
2026-05-15 04:42:36 -07:00
generatedunixname2094418054467506 f66a2514df Fix python_unnecessary_generator_set_comprehension issues in deeplearning/.../transforms/filter_query_transforms.py
Differential Revision: D104956511

fbshipit-source-id: f15651e5407d543887ddff7e6bb0d5b494936443
2026-05-13 03:17:47 -07:00
generatedunixname1401739305002972 4cbac146c1 Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D104644929

fbshipit-source-id: 53867910385982e0620979b9a46049fe4d02224d
2026-05-11 07:06:53 -07:00
90 changed files with 1275 additions and 77 deletions
+5
View File
@@ -252,6 +252,7 @@ def agent_inference(
# Add the text_prompt to the set of used prompts # Add the text_prompt to the set of used prompts
USED_TEXT_PROMPTS.add(current_text_prompt) USED_TEXT_PROMPTS.add(current_text_prompt)
LATEST_SAM3_TEXT_PROMPT = current_text_prompt LATEST_SAM3_TEXT_PROMPT = current_text_prompt
# pyrefly: ignore [missing-argument]
PATH_TO_LATEST_OUTPUT_JSON = call_sam_service( PATH_TO_LATEST_OUTPUT_JSON = call_sam_service(
image_path=img_path, image_path=img_path,
text_prompt=current_text_prompt, text_prompt=current_text_prompt,
@@ -296,6 +297,7 @@ def agent_inference(
assert LATEST_SAM3_TEXT_PROMPT != "" assert LATEST_SAM3_TEXT_PROMPT != ""
# Make sure that the last message is a image # Make sure that the last message is a image
# pyrefly: ignore [bad-index]
assert messages[-1]["content"][1]["type"] == "image", ( assert messages[-1]["content"][1]["type"] == "image", (
"Second content element should be an image" "Second content element should be an image"
) )
@@ -319,6 +321,7 @@ def agent_inference(
# MLLM check the mask one by one # MLLM check the mask one by one
for i in range(num_masks): for i in range(num_masks):
print(f"🔍 Checking mask {i + 1}/{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_mask_i, image_w_zoomed_in_mask_i = visualize(current_outputs, i)
image_w_zoomed_in_mask_i_path = os.path.join( 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) image_w_check_masks.save(image_w_check_masks_path)
# save the updated json outputs and append to message history # save the updated json outputs and append to message history
messages.append( messages.append(
@@ -492,6 +496,7 @@ def agent_inference(
elif tool_call["name"] == "report_no_mask": elif tool_call["name"] == "report_no_mask":
print("🔍 Calling report_no_mask tool...") print("🔍 Calling report_no_mask tool...")
# pyrefly: ignore [missing-attribute]
height, width = cv2.imread(img_path).shape[:2] height, width = cv2.imread(img_path).shape[:2]
final_outputs = { final_outputs = {
"original_image_path": img_path, "original_image_path": img_path,
+1
View File
@@ -6,6 +6,7 @@ import base64
import os import os
from typing import Any, Optional from typing import Any, Optional
# pyrefly: ignore [missing-import]
from openai import OpenAI from openai import OpenAI
+1
View File
@@ -131,6 +131,7 @@ def call_sam_service(
print("🔍 Rendering visualizations on the image ...") print("🔍 Rendering visualizations on the image ...")
viz_image = visualize(serialized_response) viz_image = visualize(serialized_response)
os.makedirs(os.path.dirname(output_image_path), exist_ok=True) os.makedirs(os.path.dirname(output_image_path), exist_ok=True)
# pyrefly: ignore [missing-attribute]
viz_image.save(output_image_path) viz_image.save(output_image_path)
print("✅ Saved visualization at:", output_image_path) print("✅ Saved visualization at:", output_image_path)
except Exception as e: except Exception as e:
+13 -1
View File
@@ -73,6 +73,8 @@ class BoxMode(IntEnum):
if is_numpy: if is_numpy:
arr = torch.from_numpy(np.asarray(box)).clone() arr = torch.from_numpy(np.asarray(box)).clone()
else: else:
# pyre-fixme[16]: Item `List` of `List[float] | ndarray | Tensor |
# tuple[float, ...]` has no attribute `clone`.
arr = box.clone() arr = box.clone()
assert to_mode not in [ assert to_mode not in [
@@ -113,6 +115,7 @@ class BoxMode(IntEnum):
arr[:, 0] += arr[:, 2] / 2.0 arr[:, 0] += arr[:, 2] / 2.0
arr[:, 1] += arr[:, 3] / 2.0 arr[:, 1] += arr[:, 3] / 2.0
angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype) angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)
# pyre-fixme[28]: Unexpected keyword argument `axis`.
arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype) arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)
else: else:
if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS: if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:
@@ -129,6 +132,7 @@ class BoxMode(IntEnum):
) )
if single_box: if single_box:
# pyrefly: ignore [bad-argument-type]
return original_type(arr.flatten().tolist()) return original_type(arr.flatten().tolist())
if is_numpy: if is_numpy:
return arr.numpy() return arr.numpy()
@@ -336,9 +340,17 @@ def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
Returns: Returns:
Tensor: intersection, sized [N,M]. Tensor: intersection, sized [N,M].
""" """
# pyre-fixme[9]: boxes1 has type `Boxes`; used as `Tensor`.
# pyre-fixme[9]: boxes2 has type `Boxes`; used as `Tensor`.
boxes1, boxes2 = boxes1.tensor, boxes2.tensor boxes1, boxes2 = boxes1.tensor, boxes2.tensor
# pyre-fixme[6]: For 1st argument expected `Tensor` but got `Boxes`.
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max( width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(
boxes1[:, None, :2], boxes2[:, :2] # pyre-fixme[6]: For 1st argument expected `Tensor` but got `Boxes`.
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
boxes1[:, None, :2],
# pyre-fixme[6]: For 2nd argument expected `Tensor` but got `Boxes`.
boxes2[:, :2],
) # [N,M,2] ) # [N,M,2]
width_height.clamp_(min=0) # [N,M,2] width_height.clamp_(min=0) # [N,M,2]
+2
View File
@@ -63,6 +63,7 @@ class Keypoints:
valid: valid:
A tensor of shape (N, K) containing whether each keypoint is in the roi or not. A tensor of shape (N, K) containing whether each keypoint is in the roi or not.
""" """
# pyrefly: ignore [bad-return]
return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size) return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)
def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Keypoints": def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> "Keypoints":
@@ -80,6 +81,7 @@ class Keypoints:
subject to Pytorch's indexing semantics. subject to Pytorch's indexing semantics.
""" """
if isinstance(item, int): if isinstance(item, int):
# pyrefly: ignore [bad-argument-type]
return Keypoints([self.tensor[item]]) return Keypoints([self.tensor[item]])
return Keypoints(self.tensor[item]) return Keypoints(self.tensor[item])
+12 -1
View File
@@ -149,6 +149,7 @@ class BitMasks:
return BitMasks(m) return BitMasks(m)
@torch.jit.unused @torch.jit.unused
# pyrefly: ignore [bad-return]
def __iter__(self) -> torch.Tensor: def __iter__(self) -> torch.Tensor:
yield from self.tensor yield from self.tensor
@@ -197,6 +198,7 @@ class BitMasks:
roi_masks: roi_masks:
height, width (int): height, width (int):
""" """
# pyrefly: ignore [bad-argument-type, missing-argument]
return roi_masks.to_bitmasks(height, width) return roi_masks.to_bitmasks(height, width)
def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor: def crop_and_resize(self, boxes: torch.Tensor, mask_size: int) -> torch.Tensor:
@@ -321,6 +323,7 @@ class PolygonMasks:
raise ValueError( raise ValueError(
f"Cannot create a polygon from {len(polygon)} coordinates." f"Cannot create a polygon from {len(polygon)} coordinates."
) )
# pyrefly: ignore [bad-return]
return polygons_per_instance return polygons_per_instance
self.polygons: List[List[np.ndarray]] = [ self.polygons: List[List[np.ndarray]] = [
@@ -395,6 +398,7 @@ class PolygonMasks:
"Unsupported tensor dtype={} for indexing!".format(item.dtype) "Unsupported tensor dtype={} for indexing!".format(item.dtype)
) )
selected_polygons = [self.polygons[i] for i in item] selected_polygons = [self.polygons[i] for i in item]
# pyrefly: ignore [bad-argument-type]
return PolygonMasks(selected_polygons) return PolygonMasks(selected_polygons)
def __iter__(self) -> Iterator[List[np.ndarray]]: def __iter__(self) -> Iterator[List[np.ndarray]]:
@@ -480,6 +484,7 @@ class PolygonMasks:
assert all(isinstance(polymask, PolygonMasks) for polymask in polymasks_list) assert all(isinstance(polymask, PolygonMasks) for polymask in polymasks_list)
cat_polymasks = type(polymasks_list[0])( cat_polymasks = type(polymasks_list[0])(
# pyrefly: ignore [bad-argument-type]
list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list)) list(itertools.chain.from_iterable(pm.polygons for pm in polymasks_list))
) )
return cat_polymasks return cat_polymasks
@@ -543,6 +548,7 @@ class ROIMasks:
""" """
Args: see documentation of :func:`paste_masks_in_image`. Args: see documentation of :func:`paste_masks_in_image`.
""" """
# pyrefly: ignore [missing-import]
from detectron2.layers.mask_ops import ( from detectron2.layers.mask_ops import (
_paste_masks_tensor_shape, _paste_masks_tensor_shape,
paste_masks_in_image, paste_masks_in_image,
@@ -556,6 +562,11 @@ class ROIMasks:
else: else:
paste_func = retry_if_cuda_oom(paste_masks_in_image) paste_func = retry_if_cuda_oom(paste_masks_in_image)
bitmasks = paste_func( bitmasks = paste_func(
self.tensor, boxes.tensor, (height, width), threshold=threshold # pyrefly: ignore [missing-attribute]
self.tensor,
# pyrefly: ignore [missing-attribute]
boxes.tensor,
(height, width),
threshold=threshold,
) )
return BitMasks(bitmasks) return BitMasks(bitmasks)
+1
View File
@@ -486,6 +486,7 @@ class RotatedBoxes(Boxes):
self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi
@classmethod @classmethod
# pyrefly: ignore [bad-override]
def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes": def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes":
""" """
Concatenates a list of RotatedBoxes into a single RotatedBoxes Concatenates a list of RotatedBoxes into a single RotatedBoxes
+1
View File
@@ -674,6 +674,7 @@ class Visualizer:
with PathManager.open(dic["pan_seg_file_name"], "rb") as f: with PathManager.open(dic["pan_seg_file_name"], "rb") as f:
pan_seg = Image.open(f) pan_seg = Image.open(f)
pan_seg = np.asarray(pan_seg) pan_seg = np.asarray(pan_seg)
# pyre-fixme[21]: Could not find module `panopticapi.utils`.
from panopticapi.utils import rgb2id from panopticapi.utils import rgb2id
pan_seg = rgb2id(pan_seg) pan_seg = rgb2id(pan_seg)
+1
View File
@@ -155,6 +155,7 @@ class CocoEvaluator:
print(f"{k}: {len(v)}") print(f"{k}: {len(v)}")
def set_sync_device(self, device: torch.device) -> Any: def set_sync_device(self, device: torch.device) -> Any:
# pyre-fixme[16]: `CocoEvaluator` has no attribute `_sync_device`.
self._sync_device = device self._sync_device = device
def _evaluate(self, *args, **kwargs): def _evaluate(self, *args, **kwargs):
+1
View File
@@ -19,6 +19,7 @@ from pycocotools.cocoeval import COCOeval
from sam3.train.utils.distributed import is_main_process from sam3.train.utils.distributed import is_main_process
try: try:
# pyrefly: ignore [missing-import]
from tidecv import datasets, TIDE from tidecv import datasets, TIDE
HAS_TIDE = True HAS_TIDE = True
+1
View File
@@ -121,6 +121,7 @@ def reindex_coco_to_temp(input_json_path: str) -> Optional[str]:
with open(input_json_path, "r", encoding="utf-8") as f: with open(input_json_path, "r", encoding="utf-8") as f:
data = json.load(f) data = json.load(f)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
# pyrefly: ignore [missing-argument]
raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}") raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}")
# Validate COCO format # Validate COCO format
+2
View File
@@ -513,6 +513,7 @@ class DemoEvaluator(CocoEvaluator):
self.use_self_evaluate = True self.use_self_evaluate = True
self.compute_JnF = compute_JnF self.compute_JnF = compute_JnF
# pyrefly: ignore [bad-override]
def _lazy_init(self): def _lazy_init(self):
if self.initialized: if self.initialized:
return return
@@ -641,6 +642,7 @@ class DemoEvaluator(CocoEvaluator):
for coco_eval in self.coco_evals[0].values(): for coco_eval in self.coco_evals[0].values():
coco_eval.accumulate() coco_eval.accumulate()
# pyrefly: ignore [bad-override]
def reset(self): def reset(self):
self.coco_evals = [{} for _ in range(len(self.coco_gts))] self.coco_evals = [{} for _ in range(len(self.coco_gts))]
for i, coco_gt in enumerate(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)"] res["HOTALocA(0)"] = res["HOTA(0)"] * res["LocA(0)"]
return res return res
# pyrefly: ignore [bad-override-param-name]
def plot_single_tracker_results(self, table_res, tracker, cls, output_folder): def plot_single_tracker_results(self, table_res, tracker, cls, output_folder):
"""Create plot of results""" """Create plot of results"""
+19 -3
View File
@@ -88,6 +88,7 @@ class PostProcessImage(nn.Module):
) # NOTE: It's possible but we don't support it. ) # NOTE: It's possible but we don't support it.
assert self.detection_threshold <= 0.0, "TODO: implement?" assert self.detection_threshold <= 0.0, "TODO: implement?"
try: try:
# pyrefly: ignore [missing-import]
from tensordict import TensorDict from tensordict import TensorDict
except ImportError: except ImportError:
logging.info( logging.info(
@@ -138,6 +139,7 @@ class PostProcessImage(nn.Module):
results.update(masks=out_masks) results.update(masks=out_masks)
if ret_tensordict: if ret_tensordict:
# pyrefly: ignore [unbound-name]
results = TensorDict(results).auto_batch_size_() results = TensorDict(results).auto_batch_size_()
if self.to_cpu: if self.to_cpu:
results = results.cpu() results = results.cpu()
@@ -265,12 +267,16 @@ class PostProcessImage(nn.Module):
img_size_for_boxes = ( img_size_for_boxes = (
meta.original_size meta.original_size
if self.use_original_sizes_box if self.use_original_sizes_box
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 = ( img_size_for_masks = (
meta.original_size meta.original_size
if self.use_original_sizes_mask if self.use_original_sizes_mask
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( detection_results = self(
outputs, outputs,
@@ -377,6 +383,7 @@ class PostProcessAPIVideo(PostProcessImage):
# Import tensordict here to avoid global dependency. # Import tensordict here to avoid global dependency.
try: try:
# pyrefly: ignore [missing-import]
from tensordict import TensorDict from tensordict import TensorDict
except ImportError as e: except ImportError as e:
logging.error( logging.error(
@@ -415,6 +422,7 @@ class PostProcessAPIVideo(PostProcessImage):
meta_td = TensorDict( meta_td = TensorDict(
dataclasses.asdict(meta) dataclasses.asdict(meta)
).auto_batch_size_() # Shape is [P,...] ).auto_batch_size_() # Shape is [P,...]
# pyrefly: ignore [missing-attribute]
unique_vid_id = meta.original_image_id.unique() unique_vid_id = meta.original_image_id.unique()
assert unique_vid_id.size(0) == 1 assert unique_vid_id.size(0) == 1
if video_id == -1: if video_id == -1:
@@ -465,7 +473,7 @@ class PostProcessAPIVideo(PostProcessImage):
tracked_objs_outs_td.unsqueeze(1), tracked_objs_outs_td.unsqueeze(1),
( (
meta_td["original_size"] 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"]) else torch.ones_like(meta_td["original_size"])
), ),
forced_labels=( forced_labels=(
@@ -491,6 +499,7 @@ class PostProcessAPIVideo(PostProcessImage):
logging.debug(f"Video {video_id} has no predictions") logging.debug(f"Video {video_id} has no predictions")
return {video_id: []} return {video_id: []}
# pyrefly: ignore [bad-assignment]
vid_preds_packed = torch.cat(vid_preds_packed, dim=0) vid_preds_packed = torch.cat(vid_preds_packed, dim=0)
############### Construct a padded representation of the predictions ############### ############### Construct a padded representation of the predictions ###############
num_preds = len(tracked_objects_packed_idx) num_preds = len(tracked_objects_packed_idx)
@@ -502,6 +511,7 @@ class PostProcessAPIVideo(PostProcessImage):
k: torch.zeros( k: torch.zeros(
num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype
) )
# pyrefly: ignore [missing-attribute]
for k, v in vid_preds_packed.items() for k, v in vid_preds_packed.items()
}, },
batch_size=[ batch_size=[
@@ -521,10 +531,12 @@ class PostProcessAPIVideo(PostProcessImage):
for o_idx, oid in enumerate(tracked_objects_packed_idx): for o_idx, oid in enumerate(tracked_objects_packed_idx):
oid2packed_idx = tracked_objects_packed_idx[oid] oid2packed_idx = tracked_objects_packed_idx[oid]
oid2padded_idx = tracked_objects_frame_idx[oid] oid2padded_idx = tracked_objects_frame_idx[oid]
# pyrefly: ignore [bad-index]
obj_packed_results = vid_preds_packed[oid2packed_idx] obj_packed_results = vid_preds_packed[oid2packed_idx]
padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results
if self.convert_mask_to_rle_for_video: if self.convert_mask_to_rle_for_video:
for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx): for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx):
# pyrefly: ignore [unbound-name]
vid_masklets_rle_padded[o_idx][padded_idx] = ( vid_masklets_rle_padded[o_idx][padded_idx] = (
vid_masklets_rle_packed[packed_idx] vid_masklets_rle_packed[packed_idx]
) )
@@ -539,6 +551,7 @@ class PostProcessAPIVideo(PostProcessImage):
results["scores"] = torch.stack(tracklet_scores, dim=0) results["scores"] = torch.stack(tracklet_scores, dim=0)
results["labels"] = torch.stack(tracklet_labels, dim=0) results["labels"] = torch.stack(tracklet_labels, dim=0)
if self.convert_mask_to_rle_for_video: if self.convert_mask_to_rle_for_video:
# pyrefly: ignore [unbound-name]
results["masks_rle"] = vid_masklets_rle_padded results["masks_rle"] = vid_masklets_rle_padded
# we keep the frame-level scores since it's needed by some evaluation scripts # we keep the frame-level scores since it's needed by some evaluation scripts
results["per_frame_scores"] = padded_frames_results["scores"] results["per_frame_scores"] = padded_frames_results["scores"]
@@ -559,11 +572,14 @@ class PostProcessTracking(PostProcessImage):
super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs) super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs)
self.force_single_mask = force_single_mask self.force_single_mask = force_single_mask
# pyrefly: ignore [bad-override]
def process_results( def process_results(
self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs
): ):
# pyrefly: ignore [bad-argument-type]
assert len(find_stages) == len(find_metadatas) assert len(find_stages) == len(find_metadatas)
results = {} results = {}
# pyrefly: ignore [bad-argument-type]
for outputs, meta in zip(find_stages, find_metadatas): for outputs, meta in zip(find_stages, find_metadatas):
if self.force_single_mask: if self.force_single_mask:
scores, labels = outputs["pred_logits"].max(-1) scores, labels = outputs["pred_logits"].max(-1)
+2
View File
@@ -38,7 +38,9 @@ class VEvalEvaluator:
video_np_results = defaultdict(dict) video_np_results = defaultdict(dict)
for evaluator in self.evaluators: for evaluator in self.evaluators:
d_res, v_np_res = evaluator.evaluate(pred_file) d_res, v_np_res = evaluator.evaluate(pred_file)
# pyrefly: ignore [no-matching-overload]
dataset_results.update(d_res) dataset_results.update(d_res)
# pyrefly: ignore [missing-attribute]
for (video_id, category_id), res in v_np_res.items(): for (video_id, category_id), res in v_np_res.items():
video_np_results[(video_id, category_id)].update(res) video_np_results[(video_id, category_id)].update(res)
+6
View File
@@ -112,6 +112,7 @@ class YTVISPredFileEvaluator(BasePredFileEvaluator):
# video-NP level results not supported for `YTVISPredFileEvaluator` yet # video-NP level results not supported for `YTVISPredFileEvaluator` yet
video_np_level_results = {} video_np_level_results = {}
# pyrefly: ignore [bad-return]
return results, video_np_level_results return results, video_np_level_results
@@ -147,6 +148,7 @@ class VideoPhraseApEvaluator(BasePredFileEvaluator):
results = {} results = {}
use_cats = False # Phrase AP evaluation does not use categories use_cats = False # Phrase AP evaluation does not use categories
# pyrefly: ignore [bad-argument-type]
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats) ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
ytvisGT.dataset = gt ytvisGT.dataset = gt
ytvisGT.createIndex() ytvisGT.createIndex()
@@ -180,6 +182,7 @@ class VideoPhraseApEvaluator(BasePredFileEvaluator):
# video-NP level results not supported for `VideoPhraseApEvaluator` yet # video-NP level results not supported for `VideoPhraseApEvaluator` yet
video_np_level_results = {} video_np_level_results = {}
# pyrefly: ignore [bad-return]
return results, video_np_level_results return results, video_np_level_results
@@ -225,6 +228,7 @@ class VideoCGF1Evaluator(BasePredFileEvaluator):
results = {} results = {}
use_cats = False # Demo F1 evaluation does not use categories use_cats = False # Demo F1 evaluation does not use categories
# pyrefly: ignore [bad-argument-type]
ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats) ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
ytvisGT.dataset = gt ytvisGT.dataset = gt
ytvisGT.createIndex() ytvisGT.createIndex()
@@ -284,6 +288,7 @@ class VideoCGF1Evaluator(BasePredFileEvaluator):
self.extract_video_np_level_results(demoF1Eval, video_np_level_results) self.extract_video_np_level_results(demoF1Eval, video_np_level_results)
# pyrefly: ignore [bad-return]
return results, video_np_level_results return results, video_np_level_results
def extract_video_np_level_results(self, demoF1Eval, video_np_level_results): def extract_video_np_level_results(self, demoF1Eval, video_np_level_results):
@@ -628,6 +633,7 @@ class VideoPhraseHotaEvaluator(BasePredFileEvaluator):
) )
# video-NP level results not supported for `VideoPhraseHotaEvaluator` yet # video-NP level results not supported for `VideoPhraseHotaEvaluator` yet
# pyrefly: ignore [bad-return]
return out_dict, video_np_level_results return out_dict, video_np_level_results
def _remap_gt_dt(self, gt, dt): def _remap_gt_dt(self, gt, dt):
@@ -478,6 +478,7 @@ class COCO(_BaseDataset):
return data return data
# pyrefly: ignore [bad-override-param-name]
def _calculate_similarities(self, gt_dets_t, tk_dets_t): def _calculate_similarities(self, gt_dets_t, tk_dets_t):
"""Compute similarity scores.""" """Compute similarity scores."""
if self.use_mask: if self.use_mask:
@@ -489,6 +489,7 @@ class TAO(_BaseDataset):
return data return data
# pyrefly: ignore [bad-override-param-name]
def _calculate_similarities(self, gt_dets_t, tk_dets_t): def _calculate_similarities(self, gt_dets_t, tk_dets_t):
"""Compute similarity scores.""" """Compute similarity scores."""
if self.use_mask: if self.use_mask:
+1
View File
@@ -19,6 +19,7 @@ class YTVIS(COCO):
""" """
@override @override
# pyrefly: ignore [bad-function-definition]
def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True): def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True):
""" """
Args: Args:
+1
View File
@@ -22,6 +22,7 @@ from sam3.train.utils import distributed as dist
from typing_extensions import override from typing_extensions import override
try: try:
# pyrefly: ignore [missing-import]
import rapidjson as json import rapidjson as json
except ModuleNotFoundError: except ModuleNotFoundError:
import json import json
+1
View File
@@ -59,6 +59,7 @@ from torch.utils import _pytree as pytree
pytree.register_pytree_node( pytree.register_pytree_node(
NestedTensor, NestedTensor,
lambda x: ([x.tensors, x.mask], None), lambda x: ([x.tensors, x.mask], None),
# pyrefly: ignore [bad-index]
lambda values, _: NestedTensor(values[0], values[1]), lambda values, _: NestedTensor(values[0], values[1]),
) )
+65 -8
View File
@@ -115,22 +115,33 @@ class TransformerDecoderLayer(nn.Module):
if self.self_attn is not None: if self.self_attn is not None:
if dac: if dac:
# we only apply self attention to the first half of the queries # 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 assert tgt.shape[0] % 2 == 0
# pyrefly: ignore [missing-attribute]
num_o2o_queries = tgt.shape[0] // 2 num_o2o_queries = tgt.shape[0] // 2
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
tgt_o2o = tgt[:num_o2o_queries] tgt_o2o = tgt[:num_o2o_queries]
# pyrefly: ignore [unsupported-operation]
tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries] tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries]
# pyrefly: ignore [unsupported-operation]
tgt_o2m = tgt[num_o2o_queries:] tgt_o2m = tgt[num_o2o_queries:]
else: else:
tgt_o2o = tgt tgt_o2o = tgt
tgt_query_pos_o2o = tgt_query_pos tgt_query_pos_o2o = tgt_query_pos
if presence_token is not None: if presence_token is not None:
# pyrefly: ignore [bad-argument-type]
tgt_o2o = torch.cat([presence_token, tgt_o2o], dim=0) tgt_o2o = torch.cat([presence_token, tgt_o2o], dim=0)
tgt_query_pos_o2o = torch.cat( 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( tgt_query_pos = torch.cat(
[torch.zeros_like(presence_token), tgt_query_pos], dim=0 # pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
[torch.zeros_like(presence_token), tgt_query_pos],
dim=0,
) )
q = k = self.with_pos_embed(tgt_o2o, tgt_query_pos_o2o) q = k = self.with_pos_embed(tgt_o2o, tgt_query_pos_o2o)
@@ -139,6 +150,7 @@ class TransformerDecoderLayer(nn.Module):
if dac: if dac:
if not dac_use_selfatt_ln: if not dac_use_selfatt_ln:
tgt_o2o = self.norm2(tgt_o2o) tgt_o2o = self.norm2(tgt_o2o)
# pyre-fixme[61]: `tgt_o2m` is undefined, or not always defined.
tgt = torch.cat((tgt_o2o, tgt_o2m), dim=0) # Recombine tgt = torch.cat((tgt_o2o, tgt_o2m), dim=0) # Recombine
if dac_use_selfatt_ln: if dac_use_selfatt_ln:
tgt = self.norm2(tgt) tgt = self.norm2(tgt)
@@ -157,9 +169,13 @@ class TransformerDecoderLayer(nn.Module):
tgt = self.catext_norm(tgt) tgt = self.catext_norm(tgt)
if presence_token is not None: if presence_token is not None:
# pyrefly: ignore [unsupported-operation]
presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :]) presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :])
cross_attn_mask = torch.cat( cross_attn_mask = torch.cat(
[presence_token_mask, cross_attn_mask], dim=1 # pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
[presence_token_mask, cross_attn_mask],
dim=1,
) # (bs*nheads, 1+nq, hw) ) # (bs*nheads, 1+nq, hw)
# Cross attention to image # Cross attention to image
@@ -255,7 +271,9 @@ class TransformerDecoder(nn.Module):
self.instance_query_embed = nn.Embedding(num_instances, d_model) self.instance_query_embed = nn.Embedding(num_instances, d_model)
self.box_refine = box_refine self.box_refine = box_refine
if box_refine: if box_refine:
# pyrefly: ignore [bad-argument-type]
nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0) 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) nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
self.reference_points = nn.Embedding(num_queries, 4) self.reference_points = nn.Embedding(num_queries, 4)
@@ -450,20 +468,29 @@ class TransformerDecoder(nn.Module):
apply_dac = apply_dac if apply_dac is not None else self.dac apply_dac = apply_dac if apply_dac is not None else self.dac
if apply_dac: if apply_dac:
assert (tgt.shape[0] == self.num_queries) or ( assert (
(tgt.shape[0] == self.num_queries)
or (
self.use_instance_query self.use_instance_query
and (tgt.shape[0] == self.instance_query_embed.num_embeddings) and (
tgt.shape[0]
== self.instance_query_embed.num_embeddings # pyrefly: ignore [missing-attribute]
) # pyrefly: ignore [missing-attribute]
)
) )
tgt = tgt.repeat(2, 1, 1) tgt = tgt.repeat(2, 1, 1)
# note that we don't tile tgt_mask, since DAC doesn't # note that we don't tile tgt_mask, since DAC doesn't
# use self-attention in o2m queries # use self-attention in o2m queries
if reference_boxes is not None: if reference_boxes is not None:
assert (reference_boxes.shape[0] == self.num_queries) or ( assert (
(reference_boxes.shape[0] == self.num_queries)
or (
self.use_instance_query self.use_instance_query
and ( and (
reference_boxes.shape[0] reference_boxes.shape[0]
== self.instance_query_embed.num_embeddings == self.instance_query_embed.num_embeddings # pyrefly: ignore [missing-attribute]
)
) )
) )
reference_boxes = reference_boxes.repeat(2, 1, 1) reference_boxes = reference_boxes.repeat(2, 1, 1)
@@ -504,7 +531,10 @@ class TransformerDecoder(nn.Module):
for layer_idx, layer in enumerate(self.layers): for layer_idx, layer in enumerate(self.layers):
reference_points_input = ( reference_points_input = (
# pyrefly: ignore [unsupported-operation]
reference_boxes[:, :, None] reference_boxes[:, :, None]
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
* torch.cat([valid_ratios, valid_ratios], -1)[None, :] * torch.cat([valid_ratios, valid_ratios], -1)[None, :]
) # nq, bs, nlevel, 4 ) # nq, bs, nlevel, 4
@@ -516,11 +546,13 @@ class TransformerDecoder(nn.Module):
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
if self.boxRPB != "none" and reference_boxes is not None: if self.boxRPB != "none" and reference_boxes is not None:
# pyre-fixme[16]: `Optional` has no attribute `shape`.
assert spatial_shapes.shape[0] == 1, ( assert spatial_shapes.shape[0] == 1, (
"only single scale support implemented" "only single scale support implemented"
) )
memory_mask = self._get_rpb_matrix( memory_mask = self._get_rpb_matrix(
reference_boxes, reference_boxes,
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
(spatial_shapes[0, 0], spatial_shapes[0, 1]), (spatial_shapes[0, 0], spatial_shapes[0, 1]),
) )
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W) memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
@@ -564,6 +596,7 @@ class TransformerDecoder(nn.Module):
delta_unsig = box_head(out_norm(output)) delta_unsig = box_head(out_norm(output))
else: else:
# box_head_trk use a separate box head for tracking queries # box_head_trk use a separate box head for tracking queries
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
Q_det = decoder_extra_kwargs["Q_det"] Q_det = decoder_extra_kwargs["Q_det"]
assert output.size(0) >= Q_det assert output.size(0) >= Q_det
delta_unsig_det = self.bbox_embed(output[:Q_det]) delta_unsig_det = self.bbox_embed(output[:Q_det])
@@ -574,6 +607,7 @@ class TransformerDecoder(nn.Module):
reference_boxes = new_reference_points.detach() reference_boxes = new_reference_points.detach()
if layer_idx != self.num_layers - 1: if layer_idx != self.num_layers - 1:
# pyre-fixme[16]: `Optional` has no attribute `append`.
intermediate_ref_boxes.append(new_reference_points) intermediate_ref_boxes.append(new_reference_points)
else: else:
raise NotImplementedError("not implemented yet") raise NotImplementedError("not implemented yet")
@@ -603,6 +637,8 @@ class TransformerDecoder(nn.Module):
return ( return (
torch.stack(intermediate), torch.stack(intermediate),
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `Optional[List[Any]]`.
torch.stack(intermediate_ref_boxes), torch.stack(intermediate_ref_boxes),
( (
torch.stack(intermediate_presence_logits) torch.stack(intermediate_presence_logits)
@@ -688,8 +724,10 @@ class TransformerEncoderCrossAttention(nn.Module):
if self.batch_first: if self.batch_first:
# Convert to batch first # Convert to batch first
output = output.transpose(0, 1) output = output.transpose(0, 1)
# pyre-fixme[16]: `Optional` has no attribute `transpose`.
src_pos = src_pos.transpose(0, 1) src_pos = src_pos.transpose(0, 1)
prompt = prompt.transpose(0, 1) prompt = prompt.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
prompt_pos = prompt_pos.transpose(0, 1) prompt_pos = prompt_pos.transpose(0, 1)
for layer in self.layers: for layer in self.layers:
@@ -715,10 +753,13 @@ class TransformerEncoderCrossAttention(nn.Module):
if self.batch_first: if self.batch_first:
# Convert back to seq first # Convert back to seq first
# pyrefly: ignore [unbound-name]
normed_output = normed_output.transpose(0, 1) normed_output = normed_output.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
src_pos = src_pos.transpose(0, 1) src_pos = src_pos.transpose(0, 1)
return { return {
# pyre-fixme[61]: `normed_output` is undefined, or not always defined.
"memory": normed_output, "memory": normed_output,
"pos_embed": src_pos, "pos_embed": src_pos,
"padding_mask": src_key_padding_mask, "padding_mask": src_key_padding_mask,
@@ -839,6 +880,7 @@ class TransformerDecoderLayerv1(nn.Module):
tgt = tgt + self.dropout1(tgt2) tgt = tgt + self.dropout1(tgt2)
if dac: if dac:
# Recombine # Recombine
# pyre-fixme[61]: `other_tgt` is undefined, or not always defined.
tgt = torch.cat((tgt, other_tgt), dim=0) tgt = torch.cat((tgt, other_tgt), dim=0)
tgt2 = self.norm2(tgt) tgt2 = self.norm2(tgt)
tgt2 = self.cross_attn_image( tgt2 = self.cross_attn_image(
@@ -918,6 +960,8 @@ class TransformerDecoderLayerv2(TransformerDecoderLayerv1):
tgt = tgt + self.dropout2(tgt2) tgt = tgt + self.dropout2(tgt2)
return tgt return tgt
# pyre-fixme[14]: `forward_pre` overrides method defined in
# `TransformerDecoderLayerv1` inconsistently.
def forward_pre( def forward_pre(
self, self,
tgt, tgt,
@@ -993,7 +1037,11 @@ def functional_attention(
q, k[:, :, :num_k_rope] = apply_rotary_enc_real( q, k[:, :, :num_k_rope] = apply_rotary_enc_real(
q, q,
k[:, :, :num_k_rope], k[:, :, :num_k_rope],
# pyre-fixme[6]: For 3rd argument expected `Tensor` but got
# `Optional[Tensor]`.
freqs_cis_real=freqs_cis_real, freqs_cis_real=freqs_cis_real,
# pyre-fixme[6]: For 4th argument expected `Tensor` but got
# `Optional[Tensor]`.
freqs_cis_imag=freqs_cis_imag, freqs_cis_imag=freqs_cis_imag,
repeat_freqs_k=rope_k_repeat, repeat_freqs_k=rope_k_repeat,
) )
@@ -1068,6 +1116,7 @@ class SimpleRoPEAttention(nn.Module):
w = h = math.sqrt(q.shape[-2]) w = h = math.sqrt(q.shape[-2])
self.freqs_cis = self.freqs_cis.to(q.device) self.freqs_cis = self.freqs_cis.to(q.device)
if self.freqs_cis.shape[0] != q.shape[-2]: 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) self.freqs_cis = self.compute_cis(end_x=w, end_y=h, device=q.device)
if self.use_rope_real: if self.use_rope_real:
self.freqs_cis_real = self.freqs_cis.real self.freqs_cis_real = self.freqs_cis.real
@@ -1248,6 +1297,7 @@ class DecoupledTransformerDecoderLayerv2(nn.Module):
def forward(self, *args: Any, **kwds: Any) -> torch.Tensor: def forward(self, *args: Any, **kwds: Any) -> torch.Tensor:
if self.pre_norm: if self.pre_norm:
# pyrefly: ignore [bad-return]
return self.forward_pre(*args, **kwds) return self.forward_pre(*args, **kwds)
raise NotImplementedError raise NotImplementedError
@@ -1306,11 +1356,14 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
if self.batch_first: if self.batch_first:
# Convert to batch first # Convert to batch first
output = output.transpose(0, 1) output = output.transpose(0, 1)
# pyre-fixme[16]: `Optional` has no attribute `transpose`.
src_pos = src_pos.transpose(0, 1) src_pos = src_pos.transpose(0, 1)
image = image.transpose(0, 1) image = image.transpose(0, 1)
memory = memory.transpose(0, 1) memory = memory.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
memory_pos = memory_pos.transpose(0, 1) memory_pos = memory_pos.transpose(0, 1)
memory_image = memory_image.transpose(0, 1) memory_image = memory_image.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
memory_image_pos = memory_image_pos.transpose(0, 1) memory_image_pos = memory_image_pos.transpose(0, 1)
if memory_image.shape[1] != memory.shape[1]: if memory_image.shape[1] != memory.shape[1]:
@@ -1332,14 +1385,17 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
) )
if memory_image_pos is not None: if memory_image_pos is not None:
assert ( assert (
memory_pos.shape[1] - memory_image_pos.shape[1] memory_pos.shape[1] # pyrefly: ignore [missing-attribute]
- memory_image_pos.shape[1] # pyrefly: ignore [missing-attribute]
) == num_obj_ptr_tokens, ( ) == num_obj_ptr_tokens, (
# pyrefly: ignore [missing-attribute]
f"{memory_pos.shape[1]} - {memory_image_pos.shape[1]} != {num_obj_ptr_tokens}" f"{memory_pos.shape[1]} - {memory_image_pos.shape[1]} != {num_obj_ptr_tokens}"
) )
# tpos is the same in the batch anyway; note that memory_image always has a batch size of 1 # tpos is the same in the batch anyway; note that memory_image always has a batch size of 1
memory_image_pos = torch.cat( memory_image_pos = torch.cat(
[ [
memory_image_pos, memory_image_pos,
# pyrefly: ignore [unsupported-operation]
memory_pos[0:1, -num_obj_ptr_tokens:], memory_pos[0:1, -num_obj_ptr_tokens:],
], ],
dim=1, dim=1,
@@ -1367,6 +1423,7 @@ class TransformerEncoderDecoupledCrossAttention(nn.Module):
if self.batch_first: if self.batch_first:
# Convert back to seq first # Convert back to seq first
normed_output = normed_output.transpose(0, 1) normed_output = normed_output.transpose(0, 1)
# pyrefly: ignore [missing-attribute]
src_pos = src_pos.transpose(0, 1) src_pos = src_pos.transpose(0, 1)
return { return {
+2
View File
@@ -153,6 +153,7 @@ def edt_triton(data: torch.Tensor):
parabola_inter, parabola_inter,
H, H,
W, W,
# pyrefly: ignore [bad-argument-type]
horizontal=True, horizontal=True,
) )
@@ -169,6 +170,7 @@ def edt_triton(data: torch.Tensor):
parabola_inter, parabola_inter,
H, H,
W, W,
# pyrefly: ignore [bad-argument-type]
horizontal=False, horizontal=False,
) )
# don't forget to take sqrt at the end # don't forget to take sqrt at the end
+12 -1
View File
@@ -112,6 +112,7 @@ class TransformerEncoderLayer(nn.Module):
Returns: Returns:
Processed tensor Processed tensor
""" """
# pyrefly: ignore [unsupported-operation]
q = k = tgt + query_pos if self.pos_enc_at_attn else tgt q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
# Self attention # Self attention
@@ -186,6 +187,7 @@ class TransformerEncoderLayer(nn.Module):
tgt = tgt + self.dropout1(tgt2) tgt = tgt + self.dropout1(tgt2)
if dac: if dac:
# Recombine # Recombine
# pyrefly: ignore [unbound-name]
tgt = torch.cat((tgt, other_tgt), dim=0) tgt = torch.cat((tgt, other_tgt), dim=0)
tgt2 = self.norm2(tgt) tgt2 = self.norm2(tgt)
tgt2 = self.cross_attn_image( tgt2 = self.cross_attn_image(
@@ -512,6 +514,7 @@ class TransformerEncoderFusion(TransformerEncoder):
# Not needed here # Not needed here
return None return None
# pyrefly: ignore [bad-override]
def forward( def forward(
self, self,
src: List[Tensor], src: List[Tensor],
@@ -528,13 +531,21 @@ class TransformerEncoderFusion(TransformerEncoder):
if feat_sizes is not None: if feat_sizes is not None:
assert len(feat_sizes) == len(src) assert len(feat_sizes) == len(src)
if src_key_padding_mask is None: if src_key_padding_mask is None:
# pyrefly: ignore [bad-assignment]
src_key_padding_mask = [None] * len(src) src_key_padding_mask = [None] * len(src)
# pyrefly: ignore [not-iterable]
for i, (h, w) in enumerate(feat_sizes): for i, (h, w) in enumerate(feat_sizes):
src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
# pyrefly: ignore [unsupported-operation]
src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) 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] = ( src_key_padding_mask[i] = (
# pyrefly: ignore [unsupported-operation]
src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1) 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 None
) )
else: else:
+18 -1
View File
@@ -441,6 +441,7 @@ class FusedMaskEncoder(MaskEncoder):
self.fuser = fuser self.fuser = fuser
self.out_proj = nn.Identity() self.out_proj = nn.Identity()
if out_dim != in_dim: if out_dim != in_dim:
# pyrefly: ignore [bad-assignment]
self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1) 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) self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
@@ -504,6 +505,7 @@ class SequenceGeometryEncoder(nn.Module):
roi_size: int = 7, # for boxes pool roi_size: int = 7, # for boxes pool
add_cls: bool = True, add_cls: bool = True,
add_post_encode_proj: bool = True, add_post_encode_proj: bool = True,
# pyrefly: ignore [bad-function-definition]
mask_encoder: MaskEncoder = None, mask_encoder: MaskEncoder = None,
add_mask_label: bool = False, add_mask_label: bool = False,
use_act_ckpt: bool = False, use_act_ckpt: bool = False,
@@ -566,6 +568,7 @@ class SequenceGeometryEncoder(nn.Module):
self.img_pre_norm = nn.Identity() self.img_pre_norm = nn.Identity()
if self.points_pool_project is not None or self.boxes_pool_project is not None: 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.img_pre_norm = nn.LayerNorm(self.d_model)
self.encode = None self.encode = None
@@ -685,6 +688,7 @@ class SequenceGeometryEncoder(nn.Module):
masks: torch.Tensor, masks: torch.Tensor,
attn_mask: torch.Tensor, attn_mask: torch.Tensor,
mask_labels: torch.Tensor, mask_labels: torch.Tensor,
# pyrefly: ignore [bad-function-definition]
img_feats: torch.Tensor = None, img_feats: torch.Tensor = None,
): ):
n_masks, bs = masks.shape[:2] n_masks, bs = masks.shape[:2]
@@ -731,6 +735,7 @@ class SequenceGeometryEncoder(nn.Module):
else torch.zeros_like(seq_first_img_feats) else torch.zeros_like(seq_first_img_feats)
) )
# pyrefly: ignore [not-callable]
if self.points_pool_project or self.boxes_pool_project: if self.points_pool_project or self.boxes_pool_project:
assert len(img_feats) == len(img_sizes) assert len(img_feats) == len(img_sizes)
cur_img_feat = img_feats[-1] cur_img_feat = img_feats[-1]
@@ -756,9 +761,11 @@ class SequenceGeometryEncoder(nn.Module):
labels_br = geo_prompt.box_labels + 4 labels_br = geo_prompt.box_labels + 4
# Append to the existing points # Append to the existing points
# pyrefly: ignore [bad-unpacking]
points, _ = concat_padded_sequences( points, _ = concat_padded_sequences(
points, points_mask, top_left, boxes_mask points, points_mask, top_left, boxes_mask
) )
# pyrefly: ignore [bad-unpacking]
points_labels, points_mask = concat_padded_sequences( points_labels, points_mask = concat_padded_sequences(
points_labels.unsqueeze(-1), points_labels.unsqueeze(-1),
points_mask, points_mask,
@@ -767,9 +774,11 @@ class SequenceGeometryEncoder(nn.Module):
) )
points_labels = points_labels.squeeze(-1) points_labels = points_labels.squeeze(-1)
# pyrefly: ignore [bad-unpacking]
points, _ = concat_padded_sequences( points, _ = concat_padded_sequences(
points, points_mask, bottom_right, boxes_mask points, points_mask, bottom_right, boxes_mask
) )
# pyrefly: ignore [bad-unpacking]
points_labels, points_mask = concat_padded_sequences( points_labels, points_mask = concat_padded_sequences(
points_labels.unsqueeze(-1), points_labels.unsqueeze(-1),
points_mask, points_mask,
@@ -793,6 +802,7 @@ class SequenceGeometryEncoder(nn.Module):
img_feats=img_feats, img_feats=img_feats,
) )
# pyrefly: ignore [bad-unpacking]
final_embeds, final_mask = concat_padded_sequences( final_embeds, final_mask = concat_padded_sequences(
final_embeds, final_mask, boxes_embeds, boxes_mask final_embeds, final_mask, boxes_embeds, boxes_mask
) )
@@ -813,6 +823,7 @@ class SequenceGeometryEncoder(nn.Module):
cls_mask = torch.zeros( cls_mask = torch.zeros(
bs, 1, dtype=final_mask.dtype, device=final_mask.device 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 = concat_padded_sequences(
final_embeds, final_mask, cls, cls_mask final_embeds, final_mask, cls, cls_mask
) )
@@ -832,7 +843,13 @@ class SequenceGeometryEncoder(nn.Module):
final_embeds = self.encode_norm(final_embeds) final_embeds = self.encode_norm(final_embeds)
# Finally, concat mask embeddings if any # Finally, concat mask embeddings if any
if masks is not None and self.mask_encoder is not None: if masks is not None and self.mask_encoder is not None:
# pyrefly: ignore [bad-unpacking]
final_embeds, final_mask = concat_padded_sequences( final_embeds, final_mask = concat_padded_sequences(
final_embeds, final_mask, masks_embed, masks_mask # pyrefly: ignore [unbound-name]
final_embeds,
final_mask,
# pyrefly: ignore [unbound-name]
masks_embed,
masks_mask,
) )
return final_embeds, final_mask return final_embeds, final_mask
+35 -3
View File
@@ -42,7 +42,9 @@ def load_resource_as_video_frames(
Alternatively, if input is a list of PIL images, convert its format Alternatively, if input is a list of PIL images, convert its format
""" """
if isinstance(resource_path, list): if isinstance(resource_path, list):
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None] img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
# pyrefly: ignore [bad-assignment]
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None] 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 all(isinstance(img_pil, Image.Image) for img_pil in resource_path)
assert len(resource_path) is not None assert len(resource_path) is not None
@@ -60,7 +62,9 @@ def load_resource_as_video_frames(
# float16 precision should be sufficient for image tensor storage # float16 precision should be sufficient for image tensor storage
img = img.to(dtype=torch.float16) img = img.to(dtype=torch.float16)
# normalize by mean and std # normalize by mean and std
# pyrefly: ignore [unsupported-operation]
img -= img_mean img -= img_mean
# pyrefly: ignore [unsupported-operation]
img /= img_std img /= img_std
images.append(img) images.append(img)
images = torch.stack(images) images = torch.stack(images)
@@ -103,14 +107,20 @@ def load_image_as_single_frame_video(
images, image_height, image_width = _load_img_as_tensor(image_path, image_size) images, image_height, image_width = _load_img_as_tensor(image_path, image_size)
images = images.unsqueeze(0).half() images = images.unsqueeze(0).half()
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None] img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
# pyrefly: ignore [bad-assignment]
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None] img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
if not offload_video_to_cpu: if not offload_video_to_cpu:
images = images.cuda() images = images.cuda()
# pyrefly: ignore [missing-attribute]
img_mean = img_mean.cuda() img_mean = img_mean.cuda()
# pyrefly: ignore [missing-attribute]
img_std = img_std.cuda() img_std = img_std.cuda()
# normalize by mean and std # normalize by mean and std
# pyrefly: ignore [unsupported-operation]
images -= img_mean images -= img_mean
# pyrefly: ignore [unsupported-operation]
images /= img_std images /= img_std
return images, image_height, image_width return images, image_height, image_width
@@ -335,15 +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) 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) video_tensor = torch.from_numpy(frames_np).permute(0, 3, 1, 2) # (T, C, H, W)
# pyrefly: ignore [bad-assignment]
img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1) img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1)
# pyrefly: ignore [bad-assignment]
img_std = torch.tensor(img_std, dtype=torch.float16).view(1, 3, 1, 1) img_std = torch.tensor(img_std, dtype=torch.float16).view(1, 3, 1, 1)
if not offload_video_to_cpu: if not offload_video_to_cpu:
video_tensor = video_tensor.cuda() video_tensor = video_tensor.cuda()
# pyrefly: ignore [missing-attribute]
img_mean = img_mean.cuda() img_mean = img_mean.cuda()
# pyrefly: ignore [missing-attribute]
img_std = img_std.cuda() img_std = img_std.cuda()
# normalize by mean and std # normalize by mean and std
# pyrefly: ignore [unsupported-operation]
video_tensor -= img_mean video_tensor -= img_mean
# pyrefly: ignore [unsupported-operation]
video_tensor /= img_std video_tensor /= img_std
# pyrefly: ignore [bad-return]
return video_tensor, original_height, original_width return video_tensor, original_height, original_width
@@ -367,7 +384,9 @@ def _load_img_as_tensor(
"""Load and resize an image and convert it into a PyTorch tensor.""" """Load and resize an image and convert it into a PyTorch tensor."""
img = Image.open(img_path).convert("RGB") img = Image.open(img_path).convert("RGB")
orig_width, orig_height = img.width, img.height orig_width, orig_height = img.width, img.height
# pyrefly: ignore [bad-argument-type]
img = TF.resize(img, size=(image_size, image_size)) img = TF.resize(img, size=(image_size, image_size))
# pyrefly: ignore [bad-argument-type]
img = TF.to_tensor(img) img = TF.to_tensor(img)
return img, orig_height, orig_width return img, orig_height, orig_width
@@ -442,7 +461,14 @@ class TorchCodecDecoder:
which are not supported by `torchcodec.decoders.SimpleVideoDecoder` yet. which are not supported by `torchcodec.decoders.SimpleVideoDecoder` yet.
""" """
def __init__(self, source, dimension_order="NCHW", device="cpu", num_threads=1): def __init__(
self,
source: Union[str, bytes],
dimension_order: str = "NCHW",
device: str = "cpu",
num_threads: int = 1,
) -> None:
# pyrefly: ignore [missing-import]
from torchcodec import _core as core from torchcodec import _core as core
self._source = source # hold a reference to the source to prevent it from GC self._source = source # hold a reference to the source to prevent it from GC
@@ -473,6 +499,7 @@ class TorchCodecDecoder:
return self._num_frames return self._num_frames
def __getitem__(self, key: int) -> torch.Tensor: def __getitem__(self, key: int) -> torch.Tensor:
# pyrefly: ignore [missing-import]
from torchcodec import _core as core from torchcodec import _core as core
if key < 0: if key < 0:
@@ -506,13 +533,13 @@ class FIFOLock:
self._condition.wait() self._condition.wait()
# got the lock and it's our turn # got the lock and it's our turn
def release(self): def release(self) -> None:
with self._condition: with self._condition:
self._lock.release() self._lock.release()
self._waiters.get() self._waiters.get()
self._condition.notify_all() self._condition.notify_all()
def __enter__(self): def __enter__(self) -> None:
self.acquire() self.acquire()
def __exit__( def __exit__(
@@ -577,6 +604,7 @@ class AsyncVideoFileLoaderWithTorchCodec:
self.rank = int(os.environ.get("RANK", "0")) self.rank = int(os.environ.get("RANK", "0"))
self.world_size = int(os.environ.get("WORLD_SIZE", "1")) self.world_size = int(os.environ.get("WORLD_SIZE", "1"))
# pyrefly: ignore [bad-argument-type]
self.async_reader = TorchCodecDecoder(video_path, **decoder_option) self.async_reader = TorchCodecDecoder(video_path, **decoder_option)
# `num_frames_from_content` is the true number of frames in the video content # `num_frames_from_content` is the true number of frames in the video content
@@ -741,10 +769,14 @@ class AsyncVideoFileLoaderWithTorchCodec:
# release a few objects that cannot be pickled # release a few objects that cannot be pickled
reader = self.async_reader reader = self.async_reader
if reader is not None: if reader is not None:
# pyrefly: ignore [bad-assignment]
reader._source = None reader._source = None
# pyrefly: ignore [bad-assignment]
self.async_reader = None self.async_reader = None
self.pbar = None self.pbar = None
self.thread = None self.thread = None
# pyrefly: ignore [bad-assignment]
self.rand_seek_idx_queue = None self.rand_seek_idx_queue = None
# pyrefly: ignore [bad-assignment]
self.torchcodec_access_lock = contextlib.nullcontext() self.torchcodec_access_lock = contextlib.nullcontext()
return self.__dict__.copy() return self.__dict__.copy()
+3
View File
@@ -18,6 +18,7 @@ class LinearPresenceHead(nn.Sequential):
# a hack to make `LinearPresenceHead` compatible with old checkpoints # a hack to make `LinearPresenceHead` compatible with old checkpoints
super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1)) super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1))
# pyrefly: ignore [bad-override]
def forward(self, hs, prompt, prompt_mask): def forward(self, hs, prompt, prompt_mask):
return super().forward(hs) return super().forward(hs)
@@ -152,6 +153,7 @@ class SegmentationHead(nn.Module):
pixel_embed = pixel_embed.squeeze(0) pixel_embed = pixel_embed.squeeze(0)
else: else:
pixel_embed = pixel_embed[image_ids, ...] pixel_embed = pixel_embed[image_ids, ...]
# pyrefly: ignore [bad-return]
return pixel_embed return pixel_embed
def forward( def forward(
@@ -279,6 +281,7 @@ class UniversalSegmentationHead(SegmentationHead):
self.pixel_decoder.out_dim, self.d_model, kernel_size=1 self.pixel_decoder.out_dim, self.d_model, kernel_size=1
) )
# pyrefly: ignore [bad-override]
def forward( def forward(
self, self,
backbone_feats: List[torch.Tensor], backbone_feats: List[torch.Tensor],
+2
View File
@@ -71,6 +71,7 @@ class SimpleMaskDownSampler(nn.Module):
assert isinstance(self.interpol_size, (list, tuple)), ( assert isinstance(self.interpol_size, (list, tuple)), (
f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple." f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
) )
# pyrefly: ignore [bad-argument-type]
self.interpol_size = list(interpol_size) self.interpol_size = list(interpol_size)
assert len(self.interpol_size) == 2 assert len(self.interpol_size) == 2
@@ -206,4 +207,5 @@ class SimpleMaskEncoder(nn.Module):
pos = self.position_encoding(x).to(x.dtype) pos = self.position_encoding(x).to(x.dtype)
# pyrefly: ignore [bad-return]
return {"vision_features": x, "vision_pos_enc": [pos]} return {"vision_features": x, "vision_pos_enc": [pos]}
+35 -4
View File
@@ -21,6 +21,7 @@ from torch.overrides import handle_torch_function, has_torch_function
from typing_extensions import override from typing_extensions import override
try: try:
# pyre-fixme[21]: Could not find module `xformers`.
import xformers import xformers
except ImportError: except ImportError:
xformers = None xformers = None
@@ -112,6 +113,7 @@ def multi_head_attention_forward(
static_v: Optional[Tensor] = None, static_v: Optional[Tensor] = None,
average_attn_weights: bool = True, average_attn_weights: bool = True,
is_causal: bool = False, is_causal: bool = False,
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
attn_type: AttentionType = AttentionType.Vanilla, attn_type: AttentionType = AttentionType.Vanilla,
attn_sparsity: float = 0.0, attn_sparsity: float = 0.0,
attn_bias: Optional[Tensor] = None, attn_bias: Optional[Tensor] = None,
@@ -208,6 +210,7 @@ def multi_head_attention_forward(
assert in_proj_weight is not None, ( assert in_proj_weight is not None, (
"use_separate_proj_weight is False but in_proj_weight is None" "use_separate_proj_weight is False but in_proj_weight is None"
) )
# pyre-fixme[16]: Module `functional` has no attribute `_in_projection_packed`.
q, k, v = F._in_projection_packed( q, k, v = F._in_projection_packed(
query, key, value, in_proj_weight, in_proj_bias query, key, value, in_proj_weight, in_proj_bias
) )
@@ -225,6 +228,7 @@ def multi_head_attention_forward(
b_q = b_k = b_v = None b_q = b_k = b_v = None
else: else:
b_q, b_k, b_v = in_proj_bias.chunk(3) b_q, b_k, b_v = in_proj_bias.chunk(3)
# pyre-fixme[16]: Module `functional` has no attribute `_in_projection`.
q, k, v = F._in_projection( q, k, v = F._in_projection(
query, query,
key, key,
@@ -286,6 +290,7 @@ def multi_head_attention_forward(
# #
q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
if static_k is None: 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) k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else: else:
assert static_k.size(0) == bsz * num_heads, ( assert static_k.size(0) == bsz * num_heads, (
@@ -296,6 +301,7 @@ def multi_head_attention_forward(
) )
k = static_k k = static_k
if static_v is None: 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) v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
else: else:
assert static_v.size(0) == bsz * num_heads, ( assert static_v.size(0) == bsz * num_heads, (
@@ -310,10 +316,14 @@ def multi_head_attention_forward(
if add_zero_attn: if add_zero_attn:
zero_attn_shape = (bsz * num_heads, 1, head_dim) zero_attn_shape = (bsz * num_heads, 1, head_dim)
k = torch.cat( 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.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: if attn_mask is not None:
attn_mask = F.pad(attn_mask, (0, 1)) attn_mask = F.pad(attn_mask, (0, 1))
@@ -378,7 +388,9 @@ def multi_head_attention_forward(
attn_mask = attn_mask + attn_bias attn_mask = attn_mask + attn_bias
q = q.view(bsz, num_heads, tgt_len, head_dim) 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) 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) v = v.view(bsz, num_heads, src_len, head_dim)
if attn_type == AttentionType.Vanilla: if attn_type == AttentionType.Vanilla:
@@ -404,6 +416,7 @@ def multi_head_attention_forward(
elif attn_type == AttentionType.Xformer: elif attn_type == AttentionType.Xformer:
attn_output_weights = None attn_output_weights = None
assert not need_weights, "need_weights is not supported in efficient mode" assert not need_weights, "need_weights is not supported in efficient mode"
# pyrefly: ignore [missing-attribute]
attn_output = xformers.ops.memory_efficient_attention( attn_output = xformers.ops.memory_efficient_attention(
q.transpose(1, 2), q.transpose(1, 2),
k.transpose(1, 2), k.transpose(1, 2),
@@ -417,11 +430,15 @@ def multi_head_attention_forward(
assert not need_weights, "need_weights is not supported in efficient mode" assert not need_weights, "need_weights is not supported in efficient mode"
# Need to collapse heads and batch dimensions # Need to collapse heads and batch dimensions
q = q.reshape(bsz * num_heads, tgt_len, head_dim).contiguous() 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() 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() v = v.reshape(bsz * num_heads, src_len, head_dim).contiguous()
# pyrefly: ignore [missing-attribute]
row_offsets, column_indices = xformers.ops.find_locations_new( row_offsets, column_indices = xformers.ops.find_locations_new(
q, k, attn_sparsity, True q, k, attn_sparsity, True
) )
# pyrefly: ignore [missing-attribute]
attn_output = xformers.ops.sparse_memory_efficient_attention( attn_output = xformers.ops.sparse_memory_efficient_attention(
q, k, v, row_offsets, column_indices, attn_bias=attn_mask q, k, v, row_offsets, column_indices, attn_bias=attn_mask
).reshape(bsz, num_heads, tgt_len, head_dim) ).reshape(bsz, num_heads, tgt_len, head_dim)
@@ -468,6 +485,7 @@ class MultiheadAttention(nn.Module):
batch_first=False, batch_first=False,
device=None, device=None,
dtype=None, dtype=None,
# pyre-fixme[9]: attn_type has type `AttentionType`; used as `str`.
attn_type: AttentionType = AttentionType.Vanilla, attn_type: AttentionType = AttentionType.Vanilla,
sparsity: float = 0.0, sparsity: float = 0.0,
use_act_checkpoint: bool = False, use_act_checkpoint: bool = False,
@@ -591,6 +609,7 @@ class MultiheadAttention(nn.Module):
if not self._qkv_same_embed_dim: if not self._qkv_same_embed_dim:
if self.use_act_checkpoint: if self.use_act_checkpoint:
# pyrefly: ignore [not-iterable]
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint( attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward, multi_head_attention_forward,
query, query,
@@ -652,6 +671,7 @@ class MultiheadAttention(nn.Module):
) )
else: else:
if self.use_act_checkpoint: if self.use_act_checkpoint:
# pyrefly: ignore [not-iterable]
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint( attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
multi_head_attention_forward, multi_head_attention_forward,
query, query,
@@ -860,6 +880,7 @@ class MLP(nn.Module):
self.residual = residual self.residual = residual
# whether to apply a normalization layer to the output # whether to apply a normalization layer to the output
assert isinstance(out_norm, nn.Module) or out_norm is None assert isinstance(out_norm, nn.Module) or out_norm is None
# pyrefly: ignore [not-callable]
self.out_norm = out_norm or nn.Identity() self.out_norm = out_norm or nn.Identity()
def forward(self, x): def forward(self, x):
@@ -992,6 +1013,7 @@ class SAM3Output(list):
def __init__( def __init__(
self, self,
# pyre-fixme[9]: output has type `List[List[Dict[Any, Any]]]`; used as `None`.
output: List[List[Dict]] = None, output: List[List[Dict]] = None,
iter_mode: IterMode = IterMode.ALL_STEPS_PER_STAGE, iter_mode: IterMode = IterMode.ALL_STEPS_PER_STAGE,
loss_stages: Optional[List[int]] = None, loss_stages: Optional[List[int]] = None,
@@ -1014,17 +1036,26 @@ class SAM3Output(list):
# This is to avoid cyclic references and let SAM3Output be garabge collected. # This is to avoid cyclic references and let SAM3Output be garabge collected.
self_ref = weakref.ref(self) self_ref = weakref.ref(self)
self._mode2iter = { self._mode2iter = {
# pyrefly: ignore [missing-attribute]
SAM3Output.IterMode.ALL_STEPS_PER_STAGE: lambda: iter(self_ref().output), SAM3Output.IterMode.ALL_STEPS_PER_STAGE: lambda: iter(self_ref().output),
SAM3Output.IterMode.LAST_STEP_PER_STAGE: lambda: ( 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: ( 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 self.loss_stages = loss_stages
@override @override
# pyre-fixme[14]: `__iter__` overrides method defined in `list` inconsistently.
def __iter__(self) -> Iterator: def __iter__(self) -> Iterator:
return self._mode2iter[self.iter_mode]() return self._mode2iter[self.iter_mode]()
+4
View File
@@ -138,6 +138,7 @@ class MultiplexMaskDecoder(nn.Module):
if self.pred_obj_scores: if self.pred_obj_scores:
self.pred_obj_score_head = nn.Linear(transformer_dim, 1) self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
if pred_obj_scores_mlp: if pred_obj_scores_mlp:
# pyrefly: ignore [bad-assignment]
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) 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 # When outputting a single mask, optionally we can dynamically fall back to the best
@@ -315,6 +316,7 @@ class MultiplexMaskDecoder(nn.Module):
upscaled_embedding = self.output_upscaling(src) upscaled_embedding = self.output_upscaling(src)
else: else:
dc1, ln1, act1, dc2, act2 = self.output_upscaling dc1, ln1, act1, dc2, act2 = self.output_upscaling
# pyrefly: ignore [not-iterable]
feat_s0, feat_s1 = high_res_features feat_s0, feat_s1 = high_res_features
upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
@@ -361,11 +363,13 @@ class MultiplexMaskDecoder(nn.Module):
and not self.decode_mask_with_shared_tokens and not self.decode_mask_with_shared_tokens
): ):
object_score_logits = ( object_score_logits = (
# pyrefly: ignore [unbound-name]
self.pred_obj_score_head(obj_score_token_out) self.pred_obj_score_head(obj_score_token_out)
.view(b, self.multiplex_count, self.num_mask_output_per_object) .view(b, self.multiplex_count, self.num_mask_output_per_object)
.sum(-1, keepdim=True) .sum(-1, keepdim=True)
) )
else: else:
# pyrefly: ignore [unbound-name]
object_score_logits = self.pred_obj_score_head(obj_score_token_out) object_score_logits = self.pred_obj_score_head(obj_score_token_out)
else: else:
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
+20 -1
View File
@@ -197,6 +197,7 @@ class MultiplexState:
if not prefer_new_buckets: if not prefer_new_buckets:
# Fill empty slots in existing buckets first # Fill empty slots in existing buckets first
# pyrefly: ignore [not-iterable]
for bucket in self.assignments: for bucket in self.assignments:
for i in range(self.allowed_bucket_capacity): for i in range(self.allowed_bucket_capacity):
if bucket[i] == _PADDING_NUM: if bucket[i] == _PADDING_NUM:
@@ -219,11 +220,13 @@ class MultiplexState:
if len(object_indices) == 0: if len(object_indices) == 0:
break break
new_bucket[i] = _pop_next() new_bucket[i] = _pop_next()
# pyrefly: ignore [missing-attribute]
self.assignments.append(new_bucket) self.assignments.append(new_bucket)
buckets_created += 1 buckets_created += 1
# reinitialize all the settings # reinitialize all the settings
original_num_entries = self.total_valid_entries original_num_entries = self.total_valid_entries
# pyrefly: ignore [bad-argument-type]
self._initialize_assignments(self.assignments, object_ids=self.object_ids) self._initialize_assignments(self.assignments, object_ids=self.object_ids)
assert self.total_valid_entries == original_num_entries + num_new_objects, ( assert self.total_valid_entries == original_num_entries + num_new_objects, (
f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}" f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}"
@@ -251,9 +254,11 @@ class MultiplexState:
object_indices = object_indices.copy() object_indices = object_indices.copy()
# Mark objects as removed in assignments # Mark objects as removed in assignments
# pyrefly: ignore [not-iterable]
for bucket_idx, bucket in enumerate(self.assignments): for bucket_idx, bucket in enumerate(self.assignments):
for slot_idx, obj_id in enumerate(bucket): for slot_idx, obj_id in enumerate(bucket):
if obj_id in object_indices: if obj_id in object_indices:
# pyrefly: ignore [unsupported-operation]
self.assignments[bucket_idx][slot_idx] = _REMOVED_NUM self.assignments[bucket_idx][slot_idx] = _REMOVED_NUM
object_indices.remove(obj_id) object_indices.remove(obj_id)
@@ -266,6 +271,7 @@ class MultiplexState:
# and which buckets we will keep # and which buckets we will keep
buckets_to_remove = [] buckets_to_remove = []
buckets_to_keep = [] buckets_to_keep = []
# pyrefly: ignore [not-iterable]
for bucket_idx, bucket in enumerate(self.assignments): for bucket_idx, bucket in enumerate(self.assignments):
# Check if all objects in this bucket are removed or are paddings # Check if all objects in this bucket are removed or are paddings
all_removed = all( all_removed = all(
@@ -281,10 +287,12 @@ class MultiplexState:
# Remove buckets in reverse order to maintain correct indices # Remove buckets in reverse order to maintain correct indices
for bucket_idx in reversed(buckets_to_remove): for bucket_idx in reversed(buckets_to_remove):
# pyrefly: ignore [unsupported-operation]
del self.assignments[bucket_idx] del self.assignments[bucket_idx]
if len(buckets_to_keep) == 0: if len(buckets_to_keep) == 0:
logger.info(f"Removing all buckets: {buckets_to_remove}; state invalidated") logger.info(f"Removing all buckets: {buckets_to_remove}; state invalidated")
# pyrefly: ignore [bad-assignment]
self.assignments = None self.assignments = None
if self.object_ids is not None: if self.object_ids is not None:
self.object_ids = [] self.object_ids = []
@@ -293,6 +301,7 @@ class MultiplexState:
# After removal, remap object IDs to be sequential # After removal, remap object IDs to be sequential
# Collect all unique positive object IDs and create a mapping to sequential IDs # Collect all unique positive object IDs and create a mapping to sequential IDs
all_positive_ids = set() all_positive_ids = set()
# pyrefly: ignore [not-iterable]
for bucket in self.assignments: for bucket in self.assignments:
for obj_id in bucket: for obj_id in bucket:
if obj_id >= 0: 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)} id_mapping = {old_id: new_id for new_id, old_id in enumerate(sorted_ids)}
# Apply the mapping to assignments to make IDs sequential # Apply the mapping to assignments to make IDs sequential
# pyrefly: ignore [not-iterable]
for bucket in self.assignments: for bucket in self.assignments:
for i, obj_id in enumerate(bucket): for i, obj_id in enumerate(bucket):
if obj_id >= 0: if obj_id >= 0:
@@ -316,12 +326,15 @@ class MultiplexState:
# Map the original object_ids to their new positions # Map the original object_ids to their new positions
for old_idx, new_idx in id_mapping.items(): for old_idx, new_idx in id_mapping.items():
# pyrefly: ignore [unsupported-operation]
new_object_ids[new_idx] = self.object_ids[old_idx] new_object_ids[new_idx] = self.object_ids[old_idx]
assert not any(obj_id is None for obj_id in new_object_ids) assert not any(obj_id is None for obj_id in new_object_ids)
# pyrefly: ignore [bad-assignment]
self.object_ids = new_object_ids self.object_ids = new_object_ids
# Reinitialize the state to update all internal structures # Reinitialize the state to update all internal structures
# pyrefly: ignore [bad-argument-type]
self._initialize_assignments(self.assignments, object_ids=self.object_ids) self._initialize_assignments(self.assignments, object_ids=self.object_ids)
logger.info(f"Removed these buckets: {buckets_to_remove}") logger.info(f"Removed these buckets: {buckets_to_remove}")
@@ -357,6 +370,7 @@ class MultiplexState:
for i in range(self.num_buckets): for i in range(self.num_buckets):
for j in range(self.multiplex_count): for j in range(self.multiplex_count):
bucket_idx = i * self.multiplex_count + j bucket_idx = i * self.multiplex_count + j
# pyrefly: ignore [unsupported-operation]
object_idx = self.assignments[i][j] object_idx = self.assignments[i][j]
if object_idx >= 0: if object_idx >= 0:
self.mux_matrix[bucket_idx, object_idx] = 1.0 self.mux_matrix[bucket_idx, object_idx] = 1.0
@@ -426,7 +440,12 @@ class MultiplexState:
not the arbitrary object IDs that are passed in during initialization not the arbitrary object IDs that are passed in during initialization
""" """
all_valid_objects = { 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 return all_valid_objects
+8
View File
@@ -37,6 +37,7 @@ class Sam3DualViTDetNeck(nn.Module):
self.scale_factors = scale_factors self.scale_factors = scale_factors
use_bias = True use_bias = True
# pyrefly: ignore [bad-assignment, bad-index]
dim: int = self.trunk.channel_list[-1] dim: int = self.trunk.channel_list[-1]
for _, scale in enumerate(scale_factors): for _, scale in enumerate(scale_factors):
@@ -122,7 +123,9 @@ class Sam3DualViTDetNeck(nn.Module):
if self.sam2_convs is not None: if self.sam2_convs is not None:
sam2_x_out = self.sam2_convs[i](x) sam2_x_out = self.sam2_convs[i](x)
sam2_pos_out = self.position_encoding(sam2_x_out).to(sam2_x_out.dtype) sam2_pos_out = self.position_encoding(sam2_x_out).to(sam2_x_out.dtype)
# pyrefly: ignore [missing-attribute]
sam2_out.append(sam2_x_out) sam2_out.append(sam2_x_out)
# pyrefly: ignore [missing-attribute]
sam2_pos.append(sam2_pos_out) sam2_pos.append(sam2_pos_out)
return sam3_out, sam3_pos, sam2_out, sam2_pos return sam3_out, sam3_pos, sam2_out, sam2_pos
@@ -146,6 +149,7 @@ class Sam3TriViTDetNeck(nn.Module):
self.scale_factors = scale_factors self.scale_factors = scale_factors
use_bias = neck_norm is None use_bias = neck_norm is None
# pyrefly: ignore [bad-index]
dim = self.trunk.channel_list[-1] dim = self.trunk.channel_list[-1]
for _, scale in enumerate(scale_factors): for _, scale in enumerate(scale_factors):
@@ -154,6 +158,7 @@ class Sam3TriViTDetNeck(nn.Module):
if scale == 4.0: if scale == 4.0:
current.add_module( current.add_module(
"dconv_2x2_0", "dconv_2x2_0",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2), nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
) )
current.add_module( current.add_module(
@@ -162,12 +167,14 @@ class Sam3TriViTDetNeck(nn.Module):
) )
current.add_module( current.add_module(
"dconv_2x2_1", "dconv_2x2_1",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2), nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
) )
out_dim = dim // 4 out_dim = dim // 4
elif scale == 2.0: elif scale == 2.0:
current.add_module( current.add_module(
"dconv_2x2", "dconv_2x2",
# pyrefly: ignore [bad-argument-type]
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2), nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
) )
out_dim = dim // 2 out_dim = dim // 2
@@ -185,6 +192,7 @@ class Sam3TriViTDetNeck(nn.Module):
current.add_module( current.add_module(
"conv_1x1", "conv_1x1",
nn.Conv2d( nn.Conv2d(
# pyrefly: ignore [bad-argument-type]
in_channels=out_dim, in_channels=out_dim,
out_channels=d_model, out_channels=d_model,
kernel_size=1, kernel_size=1,
+13 -1
View File
@@ -166,9 +166,13 @@ class SAM3InteractiveImagePredictor(nn.Module):
def predict_batch( def predict_batch(
self, self,
# pyre-fixme[9]: point_coords_batch has type `List[ndarray]`; used as `None`.
point_coords_batch: List[np.ndarray] = None, point_coords_batch: List[np.ndarray] = None,
# pyre-fixme[9]: point_labels_batch has type `List[ndarray]`; used as `None`.
point_labels_batch: List[np.ndarray] = None, point_labels_batch: List[np.ndarray] = None,
# pyre-fixme[9]: box_batch has type `List[ndarray]`; used as `None`.
box_batch: List[np.ndarray] = None, box_batch: List[np.ndarray] = None,
# pyre-fixme[9]: mask_input_batch has type `List[ndarray]`; used as `None`.
mask_input_batch: List[np.ndarray] = None, mask_input_batch: List[np.ndarray] = None,
multimask_output: bool = True, multimask_output: bool = True,
return_logits: bool = False, return_logits: bool = False,
@@ -182,6 +186,7 @@ class SAM3InteractiveImagePredictor(nn.Module):
raise RuntimeError( raise RuntimeError(
"An image must be set with .set_image_batch(...) before mask prediction." "An image must be set with .set_image_batch(...) before mask prediction."
) )
# pyrefly: ignore [unsupported-operation]
num_images = len(self._features["image_embed"]) num_images = len(self._features["image_embed"])
all_masks = [] all_masks = []
all_ious = [] all_ious = []
@@ -389,6 +394,8 @@ class SAM3InteractiveImagePredictor(nn.Module):
# boxes are added at the beginning) to sam_prompt_encoder # boxes are added at the beginning) to sam_prompt_encoder
if concat_points is not None: if concat_points is not None:
concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Optional[Tensor]]`.
concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
concat_points = (concat_coords, concat_labels) concat_points = (concat_coords, concat_labels)
else: else:
@@ -406,9 +413,11 @@ class SAM3InteractiveImagePredictor(nn.Module):
) # multi object prediction ) # multi object prediction
high_res_features = [ high_res_features = [
feat_level[img_idx].unsqueeze(0) feat_level[img_idx].unsqueeze(0)
# pyrefly: ignore [unsupported-operation]
for feat_level in self._features["high_res_feats"] for feat_level in self._features["high_res_feats"]
] ]
low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder( 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_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
image_pe=self.model.sam_prompt_encoder.get_dense_pe(), image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
sparse_prompt_embeddings=sparse_embeddings, sparse_prompt_embeddings=sparse_embeddings,
@@ -420,7 +429,10 @@ class SAM3InteractiveImagePredictor(nn.Module):
# Upscale the masks to the original image resolution # Upscale the masks to the original image resolution
masks = self._transforms.postprocess_masks( 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) low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
if not return_logits: if not return_logits:
+1
View File
@@ -404,6 +404,7 @@ class Sam3BasePredictor:
f"{post_gpu_mem['reserved_bytes']} bytes)" f"{post_gpu_mem['reserved_bytes']} bytes)"
) )
gpu_mem = post_gpu_mem gpu_mem = post_gpu_mem
# pyrefly: ignore [bad-assignment]
result["gpu_mem"] = gpu_mem result["gpu_mem"] = gpu_mem
logger.info(f"removed session {session_id}") logger.info(f"removed session {session_id}")
return result return result
+25 -16
View File
@@ -55,6 +55,7 @@ class Sam3Image(torch.nn.Module):
detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score
separate_scorer_for_instance: bool = False, separate_scorer_for_instance: bool = False,
num_interactive_steps_val: int = 0, num_interactive_steps_val: int = 0,
# pyrefly: ignore [bad-function-definition]
inst_interactive_predictor: SAM3InteractiveImagePredictor = None, inst_interactive_predictor: SAM3InteractiveImagePredictor = None,
**kwargs, **kwargs,
): ):
@@ -211,12 +212,12 @@ class Sam3Image(torch.nn.Module):
def _run_encoder( def _run_encoder(
self, self,
backbone_out, backbone_out: Dict,
find_input, find_input: FindStage,
prompt, prompt: torch.Tensor,
prompt_mask, prompt_mask: torch.Tensor,
encoder_extra_kwargs: Optional[Dict] = None, encoder_extra_kwargs: Optional[Dict] = None,
): ) -> Tuple[Dict, Dict, Tuple]:
feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids) feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids)
backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple
@@ -527,6 +528,7 @@ class Sam3Image(torch.nn.Module):
point_embeddings, point_mask, point_labels = None, None, None point_embeddings, point_mask, point_labels = None, None, None
if find_input.input_points_before_embed is not None: if find_input.input_points_before_embed is not None:
# Point embeddings are batch first, switch to seq first # Point embeddings are batch first, switch to seq first
# pyrefly: ignore [missing-attribute]
point_embeddings = find_input.input_points_before_embed.transpose(0, 1) point_embeddings = find_input.input_points_before_embed.transpose(0, 1)
# they are stored as (x,y,label), so we unpack # they are stored as (x,y,label), so we unpack
@@ -569,6 +571,7 @@ class Sam3Image(torch.nn.Module):
find_input = input.find_inputs[0] find_input = input.find_inputs[0]
find_target = input.find_targets[0] find_target = input.find_targets[0]
# pyrefly: ignore [missing-attribute]
if find_input.input_points is not None and find_input.input_points.numel() > 0: if find_input.input_points is not None and find_input.input_points.numel() > 0:
print("Warning: Point prompts are ignored in PCS.") print("Warning: Point prompts are ignored in PCS.")
@@ -584,6 +587,7 @@ class Sam3Image(torch.nn.Module):
for cur_step in range(num_interactive_steps + 1): for cur_step in range(num_interactive_steps + 1):
if cur_step > 0: if cur_step > 0:
# We sample interactive geometric prompts (boxes, points) # We sample interactive geometric prompts (boxes, points)
# pyrefly: ignore [missing-attribute]
geometric_prompt, _ = self.interactive_prompt_sampler.sample( geometric_prompt, _ = self.interactive_prompt_sampler.sample(
geo_prompt=geometric_prompt, geo_prompt=geometric_prompt,
find_target=find_target, find_target=find_target,
@@ -725,22 +729,22 @@ class Sam3ImageOnVideoMultiGPU(Sam3Image):
def forward_video_grounding_multigpu( def forward_video_grounding_multigpu(
self, self,
backbone_out, backbone_out: Dict,
find_inputs, find_inputs: List,
geometric_prompt: Prompt, geometric_prompt: Prompt,
frame_idx, frame_idx: int,
num_frames, num_frames: int,
# `multigpu_buffer` is a dict to cache detector's outputs in a chunk between different calls # `multigpu_buffer` is a dict to cache detector's outputs in a chunk between different calls
multigpu_buffer, multigpu_buffer: Dict,
track_in_reverse=False, track_in_reverse: bool = False,
# whether to also return the SAM2 backbone features # whether to also return the SAM2 backbone features
return_sam2_backbone_feats=False, return_sam2_backbone_feats: bool = False,
# whether to perform NMS and suppress the scores of those detections removed by NMS # whether to perform NMS and suppress the scores of those detections removed by NMS
run_nms=False, run_nms: bool = False,
nms_prob_thresh=None, nms_prob_thresh: Optional[float] = None,
nms_iou_thresh=None, nms_iou_thresh: Optional[float] = None,
**kwargs, **kwargs,
): ) -> Tuple[Dict, Dict]:
""" """
Compute the detector's detection outputs in a distributed manner, where all GPUs process Compute the detector's detection outputs in a distributed manner, where all GPUs process
a chunk of frames (equal to the number of GPUs) at once and store them in cache. a chunk of frames (equal to the number of GPUs) at once and store them in cache.
@@ -784,6 +788,7 @@ class Sam3ImageOnVideoMultiGPU(Sam3Image):
else: else:
frame_idx_prev_b = frame_idx_prev_e = None frame_idx_prev_b = frame_idx_prev_e = None
if frame_idx_prev_b is not 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): for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
multigpu_buffer.pop(frame_idx_rm, None) multigpu_buffer.pop(frame_idx_rm, None)
@@ -888,9 +893,13 @@ class Sam3ImageOnVideoMultiGPU(Sam3Image):
} }
if self.gather_backbone_out: if self.gather_backbone_out:
# also add gathered SAM 2 backbone features to frame_buffer # also add gathered SAM 2 backbone features to frame_buffer
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_fpn_0"] = (fpn0[rank], fpn_handle0) frame_buffer["tracker_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_fpn_1"] = (fpn1[rank], fpn_handle1) frame_buffer["tracker_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2) frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
# pyrefly: ignore [unbound-name]
frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None) frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None)
multigpu_buffer[frame_idx_to_save] = frame_buffer multigpu_buffer[frame_idx_to_save] = frame_buffer
+1
View File
@@ -92,6 +92,7 @@ class Sam3Processor:
self.transform(v2.functional.to_image(image).to(self.device)) self.transform(v2.functional.to_image(image).to(self.device))
for image in images for image in images
] ]
# pyrefly: ignore [bad-argument-type, bad-assignment]
images = torch.stack(images, dim=0) images = torch.stack(images, dim=0)
state["backbone_out"] = self.model.backbone.forward_image(images) state["backbone_out"] = self.model.backbone.forward_image(images)
inst_interactivity_en = self.model.inst_interactive_predictor is not None inst_interactivity_en = self.model.inst_interactive_predictor is not None
+91 -4
View File
@@ -277,6 +277,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
self.new_det_thresh = new_det_thresh self.new_det_thresh = new_det_thresh
self.is_multiplex = is_multiplex self.is_multiplex = is_multiplex
self.running_in_prod = running_in_prod self.running_in_prod = running_in_prod
# pyrefly: ignore [bad-argument-type]
self.detector.running_in_prod = running_in_prod self.detector.running_in_prod = running_in_prod
assert ( assert (
@@ -427,6 +428,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
self._profiling_enabled = False self._profiling_enabled = False
os.environ["ENABLE_PROFILING"] = "0" os.environ["ENABLE_PROFILING"] = "0"
# pyre-fixme[14]: `_det_track_one_frame` overrides method defined in
# `Sam3VideoBase` inconsistently.
def _det_track_one_frame( def _det_track_one_frame(
self, self,
frame_idx: int, frame_idx: int,
@@ -585,6 +588,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
reverse=reverse, reverse=reverse,
det_out=det_out, det_out=det_out,
tracker_states_local=tracker_states_local, tracker_states_local=tracker_states_local,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=sam2_update_plan, tracker_update_plan=sam2_update_plan,
tracker_metadata_new=tracker_metadata_new, tracker_metadata_new=tracker_metadata_new,
orig_vid_height=orig_vid_height, orig_vid_height=orig_vid_height,
@@ -604,10 +608,12 @@ class Sam3MultiplexBase(Sam3VideoBase):
tracker_low_res_masks_global=tracker_low_res_masks_global, tracker_low_res_masks_global=tracker_low_res_masks_global,
tracker_obj_scores_global=tracker_obj_scores_global, tracker_obj_scores_global=tracker_obj_scores_global,
tracker_metadata_prev=tracker_metadata_prev, tracker_metadata_prev=tracker_metadata_prev,
# pyrefly: ignore [bad-argument-type]
sam2_update_plan=sam2_update_plan, sam2_update_plan=sam2_update_plan,
orig_vid_height=orig_vid_height, orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width, orig_vid_width=orig_vid_width,
reconditioned_obj_ids=reconditioned_obj_ids, reconditioned_obj_ids=reconditioned_obj_ids,
# pyrefly: ignore [bad-argument-type]
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids, det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
) )
obj_id_to_score = tracker_metadata_new["obj_id_to_score"] obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
@@ -636,6 +642,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
tracker_obj_scores_global, # a dict: obj_id --> sam2 frame-level scores tracker_obj_scores_global, # a dict: obj_id --> sam2 frame-level scores
) )
# pyre-fixme[14]: `run_backbone_and_detection` overrides method defined in
# `Sam3VideoBase` inconsistently.
def run_backbone_and_detection( def run_backbone_and_detection(
self, self,
frame_idx: int, frame_idx: int,
@@ -650,6 +658,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# Step 1: if text feature is not cached in `feature_cache`, compute and cache it # Step 1: if text feature is not cached in `feature_cache`, compute and cache it
text_batch_key = tuple(input_batch.find_text_batch) text_batch_key = tuple(input_batch.find_text_batch)
if "text" not in feature_cache or text_batch_key not in feature_cache["text"]: 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( text_outputs = self.detector.backbone.forward_text(
input_batch.find_text_batch, device=self.device input_batch.find_text_batch, device=self.device
) )
@@ -677,6 +686,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
"forward_video_grounding_batched_multigpu" "forward_video_grounding_batched_multigpu"
): ):
sam3_image_out, _ = ( sam3_image_out, _ = (
# pyrefly: ignore [not-callable]
self.detector.forward_video_grounding_batched_multigpu( self.detector.forward_video_grounding_batched_multigpu(
backbone_out=backbone_out, backbone_out=backbone_out,
find_inputs=input_batch.find_inputs, find_inputs=input_batch.find_inputs,
@@ -704,6 +714,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
feature_cache["multigpu_buffer"] = {} feature_cache["multigpu_buffer"] = {}
with torch.profiler.record_function("forward_video_grounding_multigpu"): with torch.profiler.record_function("forward_video_grounding_multigpu"):
# pyrefly: ignore [not-callable]
sam3_image_out, _ = self.detector.forward_video_grounding_multigpu( sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
backbone_out=backbone_out, backbone_out=backbone_out,
find_inputs=input_batch.find_inputs, find_inputs=input_batch.find_inputs,
@@ -751,9 +762,11 @@ class Sam3MultiplexBase(Sam3VideoBase):
# TODO: We do not need the interaction features every frame so there are rooms for optimization # 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_sam_mask_decoder = self.tracker.interactive_sam_mask_decoder
interaction_backbone_fpn = [ interaction_backbone_fpn = [
# pyrefly: ignore [missing-attribute]
interaction_sam_mask_decoder.conv_s0( interaction_sam_mask_decoder.conv_s0(
sam3_image_out["interactive_backbone_fpn_0"] sam3_image_out["interactive_backbone_fpn_0"]
), ),
# pyrefly: ignore [missing-attribute]
interaction_sam_mask_decoder.conv_s1( interaction_sam_mask_decoder.conv_s1(
sam3_image_out["interactive_backbone_fpn_1"] sam3_image_out["interactive_backbone_fpn_1"]
), ),
@@ -772,7 +785,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
backbone_cache["interactive"] = interaction_backbone_out backbone_cache["interactive"] = interaction_backbone_out
sam_mask_decoder = self.tracker.sam_mask_decoder sam_mask_decoder = self.tracker.sam_mask_decoder
sam2_backbone_fpn = [ sam2_backbone_fpn = [
# pyrefly: ignore [missing-attribute]
sam_mask_decoder.conv_s0(sam3_image_out["sam2_backbone_fpn_0"]), 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"]), 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 sam3_image_out["sam2_backbone_fpn_2"], # fpn_2 doesn't need additional conv
] ]
@@ -786,6 +801,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
with torch.profiler.record_function("run_backbone_and_detection.feature_cache"): with torch.profiler.record_function("run_backbone_and_detection.feature_cache"):
feature_cache[frame_idx] = ( feature_cache[frame_idx] = (
# pyre-fixme[16]: `Tensor` has no attribute `tensors`.
input_batch.img_batch.tensors[frame_idx], input_batch.img_batch.tensors[frame_idx],
backbone_cache, backbone_cache,
) )
@@ -847,6 +863,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
obj_scores_global = obj_scores_local obj_scores_global = obj_scores_local
return low_res_masks_global, obj_scores_global return low_res_masks_global, obj_scores_global
# pyre-fixme[14]: `_recondition_masklets` overrides method defined in
# `Sam3VideoBase` inconsistently.
def _recondition_masklets( def _recondition_masklets(
self, self,
frame_idx, frame_idx,
@@ -913,7 +931,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
new_masks_binary = ( new_masks_binary = (
F.interpolate( F.interpolate(
new_masks.unsqueeze(1), 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", mode="bilinear",
align_corners=False, align_corners=False,
).squeeze(1) ).squeeze(1)
@@ -959,6 +980,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
with torch.profiler.record_function( with torch.profiler.record_function(
"_recodition_masklets.add_new_masks" "_recodition_masklets.add_new_masks"
): ):
# pyrefly: ignore [not-callable]
self.tracker.add_new_masks( self.tracker.add_new_masks(
inference_state=inference_state, inference_state=inference_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -972,6 +994,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for i, trk_obj_id in enumerate(valid_trk_obj_ids): for i, trk_obj_id in enumerate(valid_trk_obj_ids):
for inference_state in tracker_states_local: for inference_state in tracker_states_local:
if trk_obj_id in inference_state["obj_ids"]: if trk_obj_id in inference_state["obj_ids"]:
# pyrefly: ignore [not-callable]
self.tracker.add_new_mask( self.tracker.add_new_mask(
inference_state=inference_state, inference_state=inference_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -991,6 +1014,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
return x return x
return deepcopy(x) return deepcopy(x)
# pyre-fixme[14]: `run_tracker_update_planning_phase` overrides method defined
# in `Sam3VideoBase` inconsistently.
def run_tracker_update_planning_phase( def run_tracker_update_planning_phase(
self, self,
frame_idx: int, frame_idx: int,
@@ -1041,6 +1066,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
reverse=reverse, reverse=reverse,
adt_result=adt_result, # Still lazy - no sync! adt_result=adt_result, # Still lazy - no sync!
tracker_metadata_prev=tracker_metadata_prev, tracker_metadata_prev=tracker_metadata_prev,
# pyre-fixme[6]: For 5th argument expected `Dict[str,
# Tensor]` but got `ndarray`.
gpu_metadata_prev=tracker_metadata_prev["gpu_metadata"], gpu_metadata_prev=tracker_metadata_prev["gpu_metadata"],
) )
) )
@@ -1068,11 +1095,15 @@ class Sam3MultiplexBase(Sam3VideoBase):
) )
if ( if (
self.reconstruction_bbox_iou_thresh > 0 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( with torch.profiler.record_function(
"evaluate_reconstruction_bbox_iou_thresh" "evaluate_reconstruction_bbox_iou_thresh"
): ):
# pyrefly: ignore [missing-attribute]
trk_obj_ids = adt_result.trk_id_to_max_iou_high_conf_det.keys() 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"]) sam2_obj_ids_all_gpu = list(tracker_metadata_prev["obj_ids_all_gpu"])
trk_ids = [ trk_ids = [
@@ -1080,6 +1111,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for trk_obj_id in trk_obj_ids for trk_obj_id in trk_obj_ids
if trk_obj_id in sam2_obj_ids_all_gpu 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_ids = list(adt_result.trk_id_to_max_iou_high_conf_det.values())
det_boxes_bbox_iou = det_out["bbox"][det_ids] det_boxes_bbox_iou = det_out["bbox"][det_ids]
@@ -1109,7 +1141,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
should_recondition_periodic = ( should_recondition_periodic = (
self.recondition_every_nth_frame > 0 self.recondition_every_nth_frame > 0
and frame_idx % 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 # Recondition if periodic or IoU condition met
@@ -1136,6 +1171,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
obj_id in reconditioned_obj_ids obj_id in reconditioned_obj_ids
for obj_id in state.get("obj_ids", []) for obj_id in state.get("obj_ids", [])
): ):
# pyrefly: ignore [not-callable]
self.tracker.propagate_in_video_preflight( self.tracker.propagate_in_video_preflight(
state, run_mem_encoder=True state, run_mem_encoder=True
) )
@@ -1384,6 +1420,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
} }
return sam2_update_plan, tracker_metadata_new return sam2_update_plan, tracker_metadata_new
# pyre-fixme[14]: `_suppress_overlapping_based_on_recent_occlusion` overrides
# method defined in `Sam3VideoBase` inconsistently.
def _suppress_overlapping_based_on_recent_occlusion( def _suppress_overlapping_based_on_recent_occlusion(
self, self,
frame_idx: int, frame_idx: int,
@@ -1502,6 +1540,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
total_buckets += state["multiplex_state"].num_buckets total_buckets += state["multiplex_state"].num_buckets
return total_buckets return total_buckets
# pyre-fixme[14]: `build_outputs` overrides method defined in `Sam3VideoBase`
# inconsistently.
def build_outputs( def build_outputs(
self, self,
frame_idx: int, frame_idx: int,
@@ -1516,7 +1556,10 @@ class Sam3MultiplexBase(Sam3VideoBase):
sam2_update_plan: Dict[str, np.ndarray], sam2_update_plan: Dict[str, np.ndarray],
orig_vid_height: int, orig_vid_height: int,
orig_vid_width: int, orig_vid_width: int,
# pyre-fixme[9]: reconditioned_obj_ids has type `Set[Any]`; used as `None`.
reconditioned_obj_ids: set = None, reconditioned_obj_ids: set = None,
# pyre-fixme[9]: det_to_matched_trk_obj_ids has type `Dict[Any, Any]`; used
# as `None`.
det_to_matched_trk_obj_ids: dict = None, det_to_matched_trk_obj_ids: dict = None,
): ):
new_det_fa_inds: np.ndarray = sam2_update_plan["new_det_fa_inds"] new_det_fa_inds: np.ndarray = sam2_update_plan["new_det_fa_inds"]
@@ -1588,11 +1631,14 @@ class Sam3MultiplexBase(Sam3VideoBase):
return obj_id_to_mask return obj_id_to_mask
# pyre-fixme[14]: `_get_objects_to_suppress_based_on_most_recently_occluded`
# overrides method defined in `Sam3VideoBase` inconsistently.
def _get_objects_to_suppress_based_on_most_recently_occluded( def _get_objects_to_suppress_based_on_most_recently_occluded(
self, self,
binary_low_res_masks: Tensor, binary_low_res_masks: Tensor,
last_occluded: Tensor, # GPU tensor (N_obj,) with frame indices last_occluded: Tensor, # GPU tensor (N_obj,) with frame indices
obj_ids: np.ndarray, # numpy array of object IDs obj_ids: np.ndarray, # numpy array of object IDs
# pyre-fixme[9]: frame_idx has type `int`; used as `None`.
frame_idx: int = None, frame_idx: int = None,
reverse: bool = False, reverse: bool = False,
): ):
@@ -1659,6 +1705,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
): ):
suppress_i_mask = suppress_i_mask.cpu().numpy() suppress_i_mask = suppress_i_mask.cpu().numpy()
suppress_j_mask = suppress_j_mask.cpu().numpy() suppress_j_mask = suppress_j_mask.cpu().numpy()
# pyre-fixme[9]: last_occluded has type `Tensor`; used as `ndarray`.
last_occluded = last_occluded.cpu().numpy() last_occluded = last_occluded.cpu().numpy()
# Find all suppression pairs without using torch.where # Find all suppression pairs without using torch.where
@@ -1705,6 +1752,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# propagate one frame # propagate one frame
num_frames_propagated = 0 num_frames_propagated = 0
with torch.profiler.record_function("sam2_predictor.propagate_in_video"): with torch.profiler.record_function("sam2_predictor.propagate_in_video"):
# pyrefly: ignore [not-callable]
for out in self.tracker.propagate_in_video( for out in self.tracker.propagate_in_video(
inference_state, inference_state,
start_frame_idx=frame_idx, start_frame_idx=frame_idx,
@@ -1723,15 +1771,21 @@ class Sam3MultiplexBase(Sam3VideoBase):
num_frames_propagated += 1 num_frames_propagated += 1
# only 1 frames should be propagated # only 1 frames should be propagated
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, ( assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}" f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
) )
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
assert isinstance(out_obj_ids, list) assert isinstance(out_obj_ids, list)
# Optionally filter to a subset of object ids (for partial propagation). # Optionally filter to a subset of object ids (for partial propagation).
# We also clamp indices to available rows to avoid CUDA index_select assertions. # We also clamp indices to available rows to avoid CUDA index_select assertions.
if filter_obj_ids is not None: 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: if len(out_obj_ids) > 0:
# pyrefly: ignore [unbound-name]
max_mask_rows = out_low_res_masks.shape[0] max_mask_rows = out_low_res_masks.shape[0]
# pyrefly: ignore [unbound-name]
max_score_rows = out_obj_scores.shape[0] max_score_rows = out_obj_scores.shape[0]
# Special case: common single-object refinement path where SAM2 returns a single mask row # 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. # but a longer out_obj_ids list for the state. Treat the lone row as the requested object.
@@ -1745,6 +1799,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
else: else:
keep_indices = [ keep_indices = [
i i
# pyre-fixme[61]: `out_obj_ids` is undefined, or not
# always defined.
for i, oid in enumerate(out_obj_ids) for i, oid in enumerate(out_obj_ids)
if oid in filter_obj_ids if oid in filter_obj_ids
and i < max_mask_rows and i < max_mask_rows
@@ -1767,9 +1823,13 @@ class Sam3MultiplexBase(Sam3VideoBase):
# no selected objects in this local state; skip appending # no selected objects in this local state; skip appending
out_obj_ids = [] out_obj_ids = []
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
if len(out_obj_ids) > 0: 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) obj_ids_local.extend(out_obj_ids)
# pyrefly: ignore [unbound-name]
low_res_masks_list.append(out_low_res_masks.squeeze(1)) low_res_masks_list.append(out_low_res_masks.squeeze(1))
# pyrefly: ignore [unbound-name]
obj_scores_list.append(out_obj_scores.squeeze(1)) obj_scores_list.append(out_obj_scores.squeeze(1))
# concatenate the output masklets from all local inference states # concatenate the output masklets from all local inference states
@@ -1793,6 +1853,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
) )
low_res_masks_local = low_res_masks_local.squeeze(1) low_res_masks_local = low_res_masks_local.squeeze(1)
else: else:
# pyrefly: ignore [bad-argument-type]
low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device) low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
obj_scores_local = torch.zeros(0, device=self.device) obj_scores_local = torch.zeros(0, device=self.device)
@@ -1833,6 +1894,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
return obj_ids_local, low_res_masks_local, obj_scores_local return obj_ids_local, low_res_masks_local, obj_scores_local
# pyre-fixme[14]: `_associate_det_trk` overrides method defined in
# `Sam3VideoBase` inconsistently.
def _associate_det_trk( def _associate_det_trk(
self, self,
det_masks: Tensor, det_masks: Tensor,
@@ -2058,6 +2121,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
if isinstance(adt_result, RealizedAssociateDetTrkresult): if isinstance(adt_result, RealizedAssociateDetTrkresult):
# No tracks exist, so no objects to remove/suppress # No tracks exist, so no objects to remove/suppress
empty_mask = torch.zeros(0, dtype=torch.bool, device=self.device) empty_mask = torch.zeros(0, dtype=torch.bool, device=self.device)
# pyre-fixme[7]: Expected `Tuple[Tensor, Tensor, Dict[str, Tensor]]` but
# got `Tuple[Tensor, Tensor, Dict[str, int]]`.
return empty_mask, empty_mask, {"N_obj": 0} return empty_mask, empty_mask, {"N_obj": 0}
device = adt_result.trk_is_unmatched.device device = adt_result.trk_is_unmatched.device
@@ -2432,6 +2497,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
removed_obj_ids.update(obj_ids_newly_removed) removed_obj_ids.update(obj_ids_newly_removed)
return obj_ids_newly_removed, rank0_metadata return obj_ids_newly_removed, rank0_metadata
# pyre-fixme[14]: `_tracker_update_memories` overrides method defined in
# `Sam3VideoBase` inconsistently.
def _tracker_update_memories( def _tracker_update_memories(
self, self,
sam2_inference_states: List[Any], sam2_inference_states: List[Any],
@@ -2447,6 +2514,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
return return
# Avoid an extra interpolation step by directly interpolating to `interpol_size` # Avoid an extra interpolation step by directly interpolating to `interpol_size`
high_res_H, high_res_W = ( high_res_H, high_res_W = (
# pyrefly: ignore [missing-attribute]
self.tracker.maskmem_backbone.mask_downsampler.interpol_size self.tracker.maskmem_backbone.mask_downsampler.interpol_size
) )
# NOTE: inspect this part if we observe OOMs in the demo # NOTE: inspect this part if we observe OOMs in the demo
@@ -2461,6 +2529,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
"sam2_predictor.propagate_in_video.apply_non_overlapping_constraints" "sam2_predictor.propagate_in_video.apply_non_overlapping_constraints"
): ):
# TODO: try _apply_object_wise_non_overlapping_constraints instead # 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 = self.tracker._suppress_object_pw_area_shrinkage(
high_res_masks high_res_masks
) )
@@ -2501,6 +2570,8 @@ class Sam3MultiplexBase(Sam3VideoBase):
# Get the local high-res masks and object score logits for this inference state # Get the local high-res masks and object score logits for this inference state
if self.is_multiplex and self.tracker.is_multiplex_dynamic: if self.is_multiplex and self.tracker.is_multiplex_dynamic:
local_idx = ( local_idx = (
# pyre-fixme[61]: `object_idx_assignment` is undefined, or not
# always defined.
torch.tensor(object_idx_assignment[state_i]) torch.tensor(object_idx_assignment[state_i])
.pin_memory() .pin_memory()
.to(device=high_res_masks.device, non_blocking=True) .to(device=high_res_masks.device, non_blocking=True)
@@ -2516,6 +2587,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
local_batch_size = local_high_res_masks.size(0) 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 # 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( encoded_mem = self.tracker._run_memory_encoder(
sam2_state, sam2_state,
frame_idx, frame_idx,
@@ -2547,9 +2619,13 @@ class Sam3MultiplexBase(Sam3VideoBase):
] ]
if self.is_multiplex: if self.is_multiplex:
output_dict[storage_key][frame_idx]["image_features"] = ( output_dict[storage_key][frame_idx]["image_features"] = (
# pyre-fixme[61]: `local_image_features` is undefined, or
# not always defined.
local_image_features local_image_features
) )
output_dict[storage_key][frame_idx]["image_pos_enc"] = ( output_dict[storage_key][frame_idx]["image_pos_enc"] = (
# pyre-fixme[61]: `local_image_pos_enc` is undefined, or not
# always defined.
local_image_pos_enc local_image_pos_enc
) )
@@ -2570,7 +2646,9 @@ class Sam3MultiplexBase(Sam3VideoBase):
newly_suppressed_objects = newly_suppressed_objects.float() newly_suppressed_objects = newly_suppressed_objects.float()
new_pointers = ( new_pointers = (
newly_suppressed_objects 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 + (1 - newly_suppressed_objects) * existing_pointers
) )
@@ -2584,6 +2662,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# for batched inference state, we also need to add per-object # for batched inference state, we also need to add per-object
# memory slides to support instance interactivity # memory slides to support instance interactivity
# pyrefly: ignore [not-callable]
self.tracker.add_output_per_object( self.tracker.add_output_per_object(
inference_state=sam2_state, inference_state=sam2_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -2634,6 +2713,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
new_sam2_state = best_state new_sam2_state = best_state
else: else:
# Need to create a new state # Need to create a new state
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state( new_sam2_state = self.tracker.init_state(
cached_features=feature_cache, cached_features=feature_cache,
video_height=orig_vid_height, video_height=orig_vid_height,
@@ -2654,6 +2734,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
if prev_sam2_state is not None: if prev_sam2_state is not None:
new_sam2_state = prev_sam2_state new_sam2_state = prev_sam2_state
else: else:
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state( new_sam2_state = self.tracker.init_state(
cached_features=feature_cache, cached_features=feature_cache,
video_height=orig_vid_height, video_height=orig_vid_height,
@@ -2665,6 +2746,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
else: else:
# batch objects that first appear on the same frame together # batch objects that first appear on the same frame together
# Clear inference state. Keep the cached image features if available. # Clear inference state. Keep the cached image features if available.
# pyrefly: ignore [not-callable]
new_sam2_state = self.tracker.init_state( new_sam2_state = self.tracker.init_state(
cached_features=feature_cache, cached_features=feature_cache,
video_height=orig_vid_height, video_height=orig_vid_height,
@@ -2685,6 +2767,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
input_mask_res = self.tracker.input_mask_size input_mask_res = self.tracker.input_mask_size
new_obj_masks = F.interpolate( new_obj_masks = F.interpolate(
new_obj_masks.unsqueeze(1), new_obj_masks.unsqueeze(1),
# pyrefly: ignore [bad-argument-type]
size=(input_mask_res, input_mask_res), size=(input_mask_res, input_mask_res),
mode="bilinear", mode="bilinear",
align_corners=False, align_corners=False,
@@ -2695,6 +2778,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
# add all objects at once # add all objects at once
# NOTE: In the current implementation, add_new_masks also runs the memory encoder # NOTE: In the current implementation, add_new_masks also runs the memory encoder
# the non-overlapping constraint is enforced # the non-overlapping constraint is enforced
# pyrefly: ignore [not-callable]
self.tracker.add_new_masks( self.tracker.add_new_masks(
inference_state=new_sam2_state, inference_state=new_sam2_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -2705,6 +2789,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
else: else:
# add object one by one # add object one by one
for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks): for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
# pyrefly: ignore [not-callable]
self.tracker.add_new_mask( self.tracker.add_new_mask(
inference_state=new_sam2_state, inference_state=new_sam2_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -2713,6 +2798,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
add_mask_to_memory=True, add_mask_to_memory=True,
) )
# NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects. # 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) self.tracker.propagate_in_video_preflight(new_sam2_state, run_mem_encoder=True)
return tracker_states_local return tracker_states_local
@@ -2730,6 +2816,7 @@ class Sam3MultiplexBase(Sam3VideoBase):
for sam2_inference_state in tracker_states_local_before_removal: for sam2_inference_state in tracker_states_local_before_removal:
# we try to remove `obj_id` on every inference state with `strict=False` # 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` # 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( new_obj_ids, _ = self.tracker.remove_objects(
sam2_inference_state, obj_ids, strict=False, need_output=False sam2_inference_state, obj_ids, strict=False, need_output=False
) )
+30
View File
@@ -32,6 +32,7 @@ class Sam3MultiplexImageBase(Sam3Image):
self.offload_outputs_to_cpu_for_eval = offload_outputs_to_cpu_for_eval 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 self.trim_outputs_for_eval = True # dummy option -- it doesn't do anything
# pyrefly: ignore [bad-override]
def forward( def forward(
self, self,
input: BatchedDatapoint, input: BatchedDatapoint,
@@ -135,7 +136,9 @@ class Sam3MultiplexImageBase(Sam3Image):
# Generate img_ids based on chunk frame indices # Generate img_ids based on chunk frame indices
# Each frame in the chunk gets its corresponding frame index # Each frame in the chunk gets its corresponding frame index
# The modulo for circular buffer access is handled in _get_img_feats # The modulo for circular buffer access is handled in _get_img_feats
# pyrefly: ignore [missing-attribute]
device = chunk_find_inputs[0].img_ids.device device = chunk_find_inputs[0].img_ids.device
# pyrefly: ignore [missing-attribute]
dtype = chunk_find_inputs[0].img_ids.dtype dtype = chunk_find_inputs[0].img_ids.dtype
img_ids_list = [ img_ids_list = [
torch.tensor([i], device=device, dtype=dtype) torch.tensor([i], device=device, dtype=dtype)
@@ -149,11 +152,13 @@ class Sam3MultiplexImageBase(Sam3Image):
# Concatenate text_ids # Concatenate text_ids
text_ids_list = [fi.text_ids for fi in chunk_find_inputs] text_ids_list = [fi.text_ids for fi in chunk_find_inputs]
# pyrefly: ignore [bad-argument-type]
batched_text_ids = torch.cat(text_ids_list, dim=0) batched_text_ids = torch.cat(text_ids_list, dim=0)
# Concatenate input_boxes # Concatenate input_boxes
input_boxes_list = [fi.input_boxes for fi in chunk_find_inputs] input_boxes_list = [fi.input_boxes for fi in chunk_find_inputs]
batched_input_boxes = ( batched_input_boxes = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_list, dim=0) torch.cat(input_boxes_list, dim=0)
if input_boxes_list[0] is not None if input_boxes_list[0] is not None
else None else None
@@ -162,6 +167,7 @@ class Sam3MultiplexImageBase(Sam3Image):
# Concatenate input_boxes_mask # Concatenate input_boxes_mask
input_boxes_mask_list = [fi.input_boxes_mask for fi in chunk_find_inputs] input_boxes_mask_list = [fi.input_boxes_mask for fi in chunk_find_inputs]
batched_input_boxes_mask = ( batched_input_boxes_mask = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_mask_list, dim=0) torch.cat(input_boxes_mask_list, dim=0)
if input_boxes_mask_list[0] is not None if input_boxes_mask_list[0] is not None
else None else None
@@ -170,6 +176,7 @@ class Sam3MultiplexImageBase(Sam3Image):
# Concatenate input_boxes_label # Concatenate input_boxes_label
input_boxes_label_list = [fi.input_boxes_label for fi in chunk_find_inputs] input_boxes_label_list = [fi.input_boxes_label for fi in chunk_find_inputs]
batched_input_boxes_label = ( batched_input_boxes_label = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_label_list, dim=0) torch.cat(input_boxes_label_list, dim=0)
if input_boxes_label_list[0] is not None if input_boxes_label_list[0] is not None
else None else None
@@ -178,6 +185,7 @@ class Sam3MultiplexImageBase(Sam3Image):
# Concatenate input_points # Concatenate input_points
input_points_list = [fi.input_points for fi in chunk_find_inputs] input_points_list = [fi.input_points for fi in chunk_find_inputs]
batched_input_points = ( batched_input_points = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_list, dim=0) torch.cat(input_points_list, dim=0)
if input_points_list[0] is not None if input_points_list[0] is not None
else None else None
@@ -186,6 +194,7 @@ class Sam3MultiplexImageBase(Sam3Image):
# Concatenate input_points_mask # Concatenate input_points_mask
input_points_mask_list = [fi.input_points_mask for fi in chunk_find_inputs] input_points_mask_list = [fi.input_points_mask for fi in chunk_find_inputs]
batched_input_points_mask = ( batched_input_points_mask = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_mask_list, dim=0) torch.cat(input_points_mask_list, dim=0)
if input_points_mask_list[0] is not None if input_points_mask_list[0] is not None
else None else None
@@ -196,6 +205,7 @@ class Sam3MultiplexImageBase(Sam3Image):
fi.input_boxes_before_embed for fi in chunk_find_inputs fi.input_boxes_before_embed for fi in chunk_find_inputs
] ]
batched_input_boxes_before_embed = ( batched_input_boxes_before_embed = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_boxes_before_embed_list, dim=0) torch.cat(input_boxes_before_embed_list, dim=0)
if input_boxes_before_embed_list[0] is not None if input_boxes_before_embed_list[0] is not None
else None else None
@@ -205,6 +215,7 @@ class Sam3MultiplexImageBase(Sam3Image):
fi.input_points_before_embed for fi in chunk_find_inputs fi.input_points_before_embed for fi in chunk_find_inputs
] ]
batched_input_points_before_embed = ( batched_input_points_before_embed = (
# pyrefly: ignore [bad-argument-type]
torch.cat(input_points_before_embed_list, dim=0) torch.cat(input_points_before_embed_list, dim=0)
if input_points_before_embed_list[0] is not None if input_points_before_embed_list[0] is not None
else None else None
@@ -215,10 +226,15 @@ class Sam3MultiplexImageBase(Sam3Image):
img_ids=batched_img_ids, img_ids=batched_img_ids,
img_ids_np=batched_img_ids_np, img_ids_np=batched_img_ids_np,
text_ids=batched_text_ids, text_ids=batched_text_ids,
# pyrefly: ignore [bad-argument-type]
input_boxes=batched_input_boxes, input_boxes=batched_input_boxes,
# pyrefly: ignore [bad-argument-type]
input_boxes_mask=batched_input_boxes_mask, input_boxes_mask=batched_input_boxes_mask,
# pyrefly: ignore [bad-argument-type]
input_boxes_label=batched_input_boxes_label, input_boxes_label=batched_input_boxes_label,
# pyrefly: ignore [bad-argument-type]
input_points=batched_input_points, input_points=batched_input_points,
# pyrefly: ignore [bad-argument-type]
input_points_mask=batched_input_points_mask, input_points_mask=batched_input_points_mask,
ptrs=None, # Not batching pointers for now ptrs=None, # Not batching pointers for now
ptrs_seg=None, ptrs_seg=None,
@@ -441,6 +457,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
else: else:
frame_idx_prev_b = frame_idx_prev_e = None frame_idx_prev_b = frame_idx_prev_e = None
if frame_idx_prev_b is not 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): for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
multigpu_buffer.pop(frame_idx_rm, None) multigpu_buffer.pop(frame_idx_rm, None)
@@ -596,24 +613,35 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
# also add gathered SAM 2 backbone features to frame_buffer # also add gathered SAM 2 backbone features to frame_buffer
if self.is_multiplex: if self.is_multiplex:
frame_buffer["interactive_backbone_fpn_0"] = ( frame_buffer["interactive_backbone_fpn_0"] = (
# pyrefly: ignore [unbound-name]
inte_fpn0[rank], inte_fpn0[rank],
# pyrefly: ignore [unbound-name]
inte_fpn_handle0, inte_fpn_handle0,
) )
frame_buffer["interactive_backbone_fpn_1"] = ( frame_buffer["interactive_backbone_fpn_1"] = (
# pyrefly: ignore [unbound-name]
inte_fpn1[rank], inte_fpn1[rank],
# pyrefly: ignore [unbound-name]
inte_fpn_handle1, inte_fpn_handle1,
) )
frame_buffer["interactive_backbone_fpn_2"] = ( frame_buffer["interactive_backbone_fpn_2"] = (
# pyrefly: ignore [unbound-name]
inte_fpn2[rank], inte_fpn2[rank],
# pyrefly: ignore [unbound-name]
inte_fpn_handle2, inte_fpn_handle2,
) )
frame_buffer["interactive_backbone_pos_enc"] = ( frame_buffer["interactive_backbone_pos_enc"] = (
# pyrefly: ignore [unbound-name]
inte_vision_pos_enc, inte_vision_pos_enc,
None, None,
) )
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_fpn_0"] = (fpn0[rank], fpn_handle0) frame_buffer["sam2_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_fpn_1"] = (fpn1[rank], fpn_handle1) frame_buffer["sam2_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2) frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
# pyrefly: ignore [unbound-name]
frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None) frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None)
multigpu_buffer[frame_idx_to_save] = frame_buffer multigpu_buffer[frame_idx_to_save] = frame_buffer
@@ -893,6 +921,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
out["sam2_backbone_fpn_2"] = sam2_bb["backbone_fpn"][2].tensors[ out["sam2_backbone_fpn_2"] = sam2_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1 local_idx : local_idx + 1
] ]
# pyrefly: ignore [unsupported-operation]
out["sam2_backbone_pos_enc"] = [ out["sam2_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in sam2_bb["vision_pos_enc"] x[local_idx : local_idx + 1] for x in sam2_bb["vision_pos_enc"]
] ]
@@ -908,6 +937,7 @@ class Sam3MultiplexDetector(Sam3MultiplexImageBase):
out["interactive_backbone_fpn_2"] = inte_bb["backbone_fpn"][2].tensors[ out["interactive_backbone_fpn_2"] = inte_bb["backbone_fpn"][2].tensors[
local_idx : local_idx + 1 local_idx : local_idx + 1
] ]
# pyrefly: ignore [unsupported-operation]
out["interactive_backbone_pos_enc"] = [ out["interactive_backbone_pos_enc"] = [
x[local_idx : local_idx + 1] for x in inte_bb["vision_pos_enc"] x[local_idx : local_idx + 1] for x in inte_bb["vision_pos_enc"]
] ]
@@ -7,6 +7,7 @@ from sam3 import perflib
try: try:
# Ronghang's generic GPU NMS implementation; install via # 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 # pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms
# pyrefly: ignore [missing-import]
from torch_generic_nms import generic_nms from torch_generic_nms import generic_nms
GENERIC_NMS_AVAILABLE = True GENERIC_NMS_AVAILABLE = True
+7
View File
@@ -1758,7 +1758,9 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
# set the model to single GPU for benchmark evaluation (to be compatible with trainer) # set the model to single GPU for benchmark evaluation (to be compatible with trainer)
orig_rank = self.rank orig_rank = self.rank
orig_world_size = self.world_size orig_world_size = self.world_size
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = 0 self.rank = self.detector.rank = 0
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = 1 self.world_size = self.detector.world_size = 1
# get data # get data
@@ -1810,7 +1812,9 @@ class Sam3MultiplexTracking(Sam3MultiplexBase):
preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels) preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels)
# revert the model to the original GPU and rank # revert the model to the original GPU and rank
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = orig_rank self.rank = self.detector.rank = orig_rank
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = orig_world_size self.world_size = self.detector.world_size = orig_world_size
return {video_id: preds} return {video_id: preds}
@@ -1866,6 +1870,7 @@ class Sam3MultiplexTrackingProd(Sam3MultiplexTracking):
} }
@torch.inference_mode() @torch.inference_mode()
# pyrefly: ignore [bad-override]
def propagate_in_video( def propagate_in_video(
self, self,
inference_state, inference_state,
@@ -2287,6 +2292,7 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
) )
@torch.inference_mode() @torch.inference_mode()
# pyrefly: ignore [bad-override]
def propagate_in_video( def propagate_in_video(
self, self,
inference_state, inference_state,
@@ -2357,6 +2363,7 @@ class Sam3MultiplexTrackingWithInteractivity(Sam3MultiplexTracking):
inference_state, obj_ids inference_state, obj_ids
) )
for sam2_state in tracker_states_local: for sam2_state in tracker_states_local:
# pyrefly: ignore [not-callable]
self.tracker.propagate_in_video_preflight( self.tracker.propagate_in_video_preflight(
sam2_state, run_mem_encoder=True sam2_state, run_mem_encoder=True
) )
+2
View File
@@ -36,6 +36,7 @@ def sample_box_points(
).repeat(B) ).repeat(B)
if noise > 0.0: if noise > 0.0:
if not isinstance(noise_bound, torch.Tensor): if not isinstance(noise_bound, torch.Tensor):
# pyrefly: ignore [bad-assignment]
noise_bound = torch.tensor(noise_bound, device=device) noise_bound = torch.tensor(noise_bound, device=device)
bbox_w = box_coords[..., 2] - box_coords[..., 0] bbox_w = box_coords[..., 2] - box_coords[..., 0]
bbox_h = box_coords[..., 3] - box_coords[..., 1] bbox_h = box_coords[..., 3] - box_coords[..., 1]
@@ -52,6 +53,7 @@ def sample_box_points(
box_coords = box_coords.reshape(-1, 2, 2) # always 2 points box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
box_labels = box_labels.reshape(-1, 2) box_labels = box_labels.reshape(-1, 2)
# pyrefly: ignore [bad-return]
return box_coords, box_labels return box_coords, box_labels
+114 -1
View File
@@ -36,12 +36,18 @@ class MaskletConfirmationStatus(Enum):
@dataclass @dataclass
class RealizedAssociateDetTrkresult: class RealizedAssociateDetTrkresult:
# pyre-fixme[11]: Annotation `array` is not defined as a type.
new_det_fa_inds: np.array new_det_fa_inds: np.array
# pyrefly: ignore [not-a-type]
unmatched_trk_obj_ids: np.array unmatched_trk_obj_ids: np.array
# pyrefly: ignore [not-a-type]
det_to_matched_trk_obj_ids: Dict[int, np.array] det_to_matched_trk_obj_ids: Dict[int, np.array]
trk_id_to_max_iou_high_conf_det: Dict[int, int] trk_id_to_max_iou_high_conf_det: Dict[int, int]
# pyrefly: ignore [not-a-type]
empty_trk_obj_ids: np.array empty_trk_obj_ids: np.array
# pyrefly: ignore [not-a-type]
new_det_obj_ids: Optional[np.array] = None new_det_obj_ids: Optional[np.array] = None
# pyrefly: ignore [not-a-type]
new_det_gpu_ids: Optional[np.array] = None new_det_gpu_ids: Optional[np.array] = None
num_obj_dropped_due_to_limit: Optional[int] = None num_obj_dropped_due_to_limit: Optional[int] = None
@@ -466,6 +472,7 @@ class Sam3VideoBase(nn.Module):
reverse=reverse, reverse=reverse,
det_out=det_out, det_out=det_out,
tracker_states_local=tracker_states_local, tracker_states_local=tracker_states_local,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=tracker_update_plan, tracker_update_plan=tracker_update_plan,
orig_vid_height=orig_vid_height, orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width, orig_vid_width=orig_vid_width,
@@ -483,10 +490,13 @@ class Sam3VideoBase(nn.Module):
tracker_low_res_masks_global=tracker_low_res_masks_global, tracker_low_res_masks_global=tracker_low_res_masks_global,
tracker_obj_scores_global=tracker_obj_scores_global, tracker_obj_scores_global=tracker_obj_scores_global,
tracker_metadata_prev=tracker_metadata_prev, tracker_metadata_prev=tracker_metadata_prev,
# pyrefly: ignore [bad-argument-type]
tracker_update_plan=tracker_update_plan, tracker_update_plan=tracker_update_plan,
orig_vid_height=orig_vid_height, orig_vid_height=orig_vid_height,
orig_vid_width=orig_vid_width, orig_vid_width=orig_vid_width,
# pyrefly: ignore [bad-argument-type]
reconditioned_obj_ids=reconditioned_obj_ids, reconditioned_obj_ids=reconditioned_obj_ids,
# pyrefly: ignore [bad-argument-type]
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids, det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
) )
obj_id_to_score = tracker_metadata_new["obj_id_to_score"] obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
@@ -546,6 +556,8 @@ class Sam3VideoBase(nn.Module):
# Step 1: if text feature is not cached in `feature_cache`, compute and cache it # Step 1: if text feature is not cached in `feature_cache`, compute and cache it
text_batch_key = tuple(input_batch.find_text_batch) text_batch_key = tuple(input_batch.find_text_batch)
if "text" not in feature_cache or text_batch_key not in feature_cache["text"]: if "text" not in feature_cache or text_batch_key not in feature_cache["text"]:
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `forward_text`.
text_outputs = self.detector.backbone.forward_text( text_outputs = self.detector.backbone.forward_text(
input_batch.find_text_batch, device=self.device input_batch.find_text_batch, device=self.device
) )
@@ -565,6 +577,7 @@ class Sam3VideoBase(nn.Module):
max_frame_num_to_track = tracking_bounds.get("max_frame_num_to_track") max_frame_num_to_track = tracking_bounds.get("max_frame_num_to_track")
start_frame_idx = tracking_bounds.get("propagate_in_video_start_frame_idx") start_frame_idx = tracking_bounds.get("propagate_in_video_start_frame_idx")
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
sam3_image_out, _ = self.detector.forward_video_grounding_multigpu( sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
backbone_out={ backbone_out={
"img_batch_all_stages": input_batch.img_batch, "img_batch_all_stages": input_batch.img_batch,
@@ -604,7 +617,11 @@ class Sam3VideoBase(nn.Module):
backbone_cache = {} backbone_cache = {}
sam_mask_decoder = self.tracker.sam_mask_decoder sam_mask_decoder = self.tracker.sam_mask_decoder
tracker_backbone_fpn = [ tracker_backbone_fpn = [
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `conv_s0`.
sam_mask_decoder.conv_s0(sam3_image_out["tracker_backbone_fpn_0"]), sam_mask_decoder.conv_s0(sam3_image_out["tracker_backbone_fpn_0"]),
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `conv_s1`.
sam_mask_decoder.conv_s1(sam3_image_out["tracker_backbone_fpn_1"]), sam_mask_decoder.conv_s1(sam3_image_out["tracker_backbone_fpn_1"]),
sam3_image_out["tracker_backbone_fpn_2"], # fpn_2 doesn't need conv sam3_image_out["tracker_backbone_fpn_2"], # fpn_2 doesn't need conv
] ]
@@ -684,12 +701,16 @@ class Sam3VideoBase(nn.Module):
tracker_obj_scores_global: Tensor, tracker_obj_scores_global: Tensor,
): ):
# Recondition the masklets based on the new detections # Recondition the masklets based on the new detections
# pyre-fixme[16]: `List` has no attribute `items`.
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items(): for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
new_mask = det_out["mask"][det_idx : det_idx + 1] new_mask = det_out["mask"][det_idx : det_idx + 1]
input_mask_res = self.tracker.input_mask_size input_mask_res = self.tracker.input_mask_size
new_mask_binary = ( new_mask_binary = (
F.interpolate( F.interpolate(
new_mask.unsqueeze(1), new_mask.unsqueeze(1),
# pyre-fixme[6]: For 2nd argument expected `Union[None,
# Sequence[int], int]` but got `Tuple[Union[Module, Tensor],
# Union[Module, Tensor]]`.
size=(input_mask_res, input_mask_res), size=(input_mask_res, input_mask_res),
mode="bilinear", mode="bilinear",
align_corners=False, align_corners=False,
@@ -712,6 +733,7 @@ class Sam3VideoBase(nn.Module):
logger.debug( logger.debug(
f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned." f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
) )
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
self.tracker.add_new_mask( self.tracker.add_new_mask(
inference_state=inference_state, inference_state=inference_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -721,6 +743,7 @@ class Sam3VideoBase(nn.Module):
reconditioned_states_idx.add(state_idx) reconditioned_states_idx.add(state_idx)
for idx in reconditioned_states_idx: for idx in reconditioned_states_idx:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
self.tracker.propagate_in_video_preflight( self.tracker.propagate_in_video_preflight(
tracker_states_local[idx], run_mem_encoder=True tracker_states_local[idx], run_mem_encoder=True
) )
@@ -807,6 +830,8 @@ class Sam3VideoBase(nn.Module):
new_det_obj_ids=new_det_obj_ids, new_det_obj_ids=new_det_obj_ids,
empty_trk_obj_ids=empty_trk_obj_ids, empty_trk_obj_ids=empty_trk_obj_ids,
unmatched_trk_obj_ids=unmatched_trk_obj_ids, unmatched_trk_obj_ids=unmatched_trk_obj_ids,
# pyre-fixme[6]: For 8th argument expected `Dict[str, Any]` but
# got `ndarray`.
rank0_metadata=rank0_metadata_new, rank0_metadata=rank0_metadata_new,
tracker_metadata=tracker_metadata_prev, tracker_metadata=tracker_metadata_prev,
) )
@@ -822,14 +847,27 @@ class Sam3VideoBase(nn.Module):
# (it's a small array with length==self.world_size, so broadcasting it is cheap) # (it's a small array with length==self.world_size, so broadcasting it is cheap)
num_obj_per_gpu_on_rank0 = tracker_metadata_prev["num_obj_per_gpu"] num_obj_per_gpu_on_rank0 = tracker_metadata_prev["num_obj_per_gpu"]
update_plan = [ update_plan = [
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
new_det_fa_inds, new_det_fa_inds,
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
new_det_obj_ids, new_det_obj_ids,
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
new_det_gpu_ids, new_det_gpu_ids,
num_obj_per_gpu_on_rank0, num_obj_per_gpu_on_rank0,
# pyre-fixme[61]: `unmatched_trk_obj_ids` is undefined, or not
# always defined.
unmatched_trk_obj_ids, unmatched_trk_obj_ids,
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
# always defined.
det_to_matched_trk_obj_ids, det_to_matched_trk_obj_ids,
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
# always defined.
obj_ids_newly_removed, obj_ids_newly_removed,
# pyre-fixme[61]: `num_obj_dropped_due_to_limit` is undefined, or
# not always defined.
num_obj_dropped_due_to_limit, num_obj_dropped_due_to_limit,
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or
# not always defined.
trk_id_to_max_iou_high_conf_det, trk_id_to_max_iou_high_conf_det,
] ]
assert len(update_plan) == NUM_BROADCAST_ITEMS, ( assert len(update_plan) == NUM_BROADCAST_ITEMS, (
@@ -864,13 +902,26 @@ class Sam3VideoBase(nn.Module):
# `tracker_update_plan` should be identical on all GPUs after broadcasting # `tracker_update_plan` should be identical on all GPUs after broadcasting
tracker_update_plan = { tracker_update_plan = {
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
"new_det_fa_inds": new_det_fa_inds, # npt.NDArray "new_det_fa_inds": new_det_fa_inds, # npt.NDArray
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
"new_det_obj_ids": new_det_obj_ids, # npt.NDArray "new_det_obj_ids": new_det_obj_ids, # npt.NDArray
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
"new_det_gpu_ids": new_det_gpu_ids, # npt.NDArray "new_det_gpu_ids": new_det_gpu_ids, # npt.NDArray
# pyre-fixme[61]: `unmatched_trk_obj_ids` is undefined, or not always
# defined.
"unmatched_trk_obj_ids": unmatched_trk_obj_ids, # npt.NDArray "unmatched_trk_obj_ids": unmatched_trk_obj_ids, # npt.NDArray
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
# always defined.
"det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict "det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not always
# defined.
"obj_ids_newly_removed": obj_ids_newly_removed, # set "obj_ids_newly_removed": obj_ids_newly_removed, # set
# pyre-fixme[61]: `num_obj_dropped_due_to_limit` is undefined, or not
# always defined.
"num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int "num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
# always defined.
"trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict "trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
"reconditioned_obj_ids": reconditioned_obj_ids, # set "reconditioned_obj_ids": reconditioned_obj_ids, # set
} }
@@ -882,8 +933,11 @@ class Sam3VideoBase(nn.Module):
# Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections # Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
if ( if (
self.reconstruction_bbox_iou_thresh > 0 self.reconstruction_bbox_iou_thresh > 0
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
# always defined.
and len(trk_id_to_max_iou_high_conf_det) > 0 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(): for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
det_box = det_out["bbox"][det_idx] det_box = det_out["bbox"][det_idx]
det_score = det_out["scores"][det_idx] det_score = det_out["scores"][det_idx]
@@ -934,6 +988,8 @@ class Sam3VideoBase(nn.Module):
should_recondition_periodic = ( should_recondition_periodic = (
self.recondition_every_nth_frame > 0 self.recondition_every_nth_frame > 0
and frame_idx % self.recondition_every_nth_frame == 0 and frame_idx % self.recondition_every_nth_frame == 0
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or not
# always defined.
and len(trk_id_to_max_iou_high_conf_det) > 0 and len(trk_id_to_max_iou_high_conf_det) > 0
) )
@@ -942,6 +998,8 @@ class Sam3VideoBase(nn.Module):
self._recondition_masklets( self._recondition_masklets(
frame_idx, frame_idx,
det_out, det_out,
# pyre-fixme[61]: `trk_id_to_max_iou_high_conf_det` is undefined, or
# not always defined.
trk_id_to_max_iou_high_conf_det, trk_id_to_max_iou_high_conf_det,
tracker_states_local, tracker_states_local,
tracker_metadata_prev, tracker_metadata_prev,
@@ -961,6 +1019,8 @@ class Sam3VideoBase(nn.Module):
tracker_low_res_masks_global, tracker_low_res_masks_global,
tracker_metadata_prev, tracker_metadata_prev,
tracker_metadata_new, tracker_metadata_new,
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined,
# or not always defined.
obj_ids_newly_removed, obj_ids_newly_removed,
reverse, reverse,
) )
@@ -977,15 +1037,24 @@ class Sam3VideoBase(nn.Module):
# note: except for "rank0_metadata" (that is only available on GPU 0), # note: except for "rank0_metadata" (that is only available on GPU 0),
# the updated `tracker_metadata_new` should be identical on all GPUs # the updated `tracker_metadata_new` should be identical on all GPUs
for rank in range(self.world_size): for rank in range(self.world_size):
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
# pyre-fixme[61]: `new_det_gpu_ids` is undefined, or not always defined.
new_det_obj_ids_this_gpu = new_det_obj_ids[new_det_gpu_ids == rank] new_det_obj_ids_this_gpu = new_det_obj_ids[new_det_gpu_ids == rank]
updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids_per_gpu"][rank] updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids_per_gpu"][rank]
if len(new_det_obj_ids_this_gpu) > 0: if len(new_det_obj_ids_this_gpu) > 0:
updated_obj_ids_this_gpu = np.concatenate( updated_obj_ids_this_gpu = np.concatenate(
[updated_obj_ids_this_gpu, new_det_obj_ids_this_gpu] [updated_obj_ids_this_gpu, new_det_obj_ids_this_gpu]
) )
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not always
# defined.
if len(obj_ids_newly_removed) > 0: if len(obj_ids_newly_removed) > 0:
is_removed = np.isin( is_removed = np.isin(
updated_obj_ids_this_gpu, list(obj_ids_newly_removed) # pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
# always defined.
updated_obj_ids_this_gpu,
# pyre-fixme[61]: `obj_ids_newly_removed` is undefined, or not
# always defined.
list(obj_ids_newly_removed),
) )
updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed] updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
tracker_metadata_new["obj_ids_per_gpu"][rank] = updated_obj_ids_this_gpu tracker_metadata_new["obj_ids_per_gpu"][rank] = updated_obj_ids_this_gpu
@@ -996,20 +1065,27 @@ class Sam3VideoBase(nn.Module):
tracker_metadata_new["obj_ids_per_gpu"] tracker_metadata_new["obj_ids_per_gpu"]
) )
# update object scores and the maximum object ID assigned so far # update object scores and the maximum object ID assigned so far
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
if len(new_det_obj_ids) > 0: if len(new_det_obj_ids) > 0:
tracker_metadata_new["obj_id_to_score"].update( tracker_metadata_new["obj_id_to_score"].update(
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]) zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
) )
# tracker scores are not available for new objects, use det score instead. # tracker scores are not available for new objects, use det score instead.
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
frame_idx frame_idx
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
# pyre-fixme[61]: `new_det_fa_inds` is undefined, or not always defined.
].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])) ].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
tracker_metadata_new["max_obj_id"] = max( tracker_metadata_new["max_obj_id"] = max(
tracker_metadata_new["max_obj_id"], tracker_metadata_new["max_obj_id"],
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
np.max(new_det_obj_ids), np.max(new_det_obj_ids),
) )
# for removed objects, we set their scores to a very low value (-1e4) but still # 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) # 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: for obj_id in obj_ids_newly_removed:
tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4 tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][
@@ -1023,7 +1099,10 @@ class Sam3VideoBase(nn.Module):
rank0_metadata=tracker_metadata_new["rank0_metadata"], rank0_metadata=tracker_metadata_new["rank0_metadata"],
obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids_all_gpu"], obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids_all_gpu"],
obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids_all_gpu"], obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids_all_gpu"],
# pyre-fixme[61]: `det_to_matched_trk_obj_ids` is undefined, or not
# always defined.
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids, det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
# pyre-fixme[61]: `new_det_obj_ids` is undefined, or not always defined.
new_det_obj_ids=new_det_obj_ids, new_det_obj_ids=new_det_obj_ids,
) )
tracker_metadata_new["rank0_metadata"] = rank0_metadata tracker_metadata_new["rank0_metadata"] = rank0_metadata
@@ -1080,6 +1159,7 @@ class Sam3VideoBase(nn.Module):
) )
to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded( to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
binary_tracker_low_res_masks_global, binary_tracker_low_res_masks_global,
# pyre-fixme[6]: For 2nd argument expected `List[int]` but got `Tensor`.
last_occluded_prev, last_occluded_prev,
obj_ids_global, obj_ids_global,
frame_idx, frame_idx,
@@ -1123,6 +1203,7 @@ class Sam3VideoBase(nn.Module):
is_on_this_gpu: npt.NDArray = new_det_gpu_ids == self.rank is_on_this_gpu: npt.NDArray = new_det_gpu_ids == self.rank
new_det_obj_ids_local: npt.NDArray = new_det_obj_ids[is_on_this_gpu] new_det_obj_ids_local: npt.NDArray = new_det_obj_ids[is_on_this_gpu]
new_det_fa_inds_local: npt.NDArray = new_det_fa_inds[is_on_this_gpu] new_det_fa_inds_local: npt.NDArray = new_det_fa_inds[is_on_this_gpu]
# pyre-fixme[9]: obj_ids_newly_removed has type `Set[int]`; used as `ndarray`.
obj_ids_newly_removed: Set[int] = tracker_update_plan["obj_ids_newly_removed"] obj_ids_newly_removed: Set[int] = tracker_update_plan["obj_ids_newly_removed"]
# Step 1: add new objects from the detector to SAM2 inference states # Step 1: add new objects from the detector to SAM2 inference states
@@ -1133,6 +1214,8 @@ class Sam3VideoBase(nn.Module):
tracker_states_local = self._tracker_add_new_objects( tracker_states_local = self._tracker_add_new_objects(
frame_idx=frame_idx, frame_idx=frame_idx,
num_frames=num_frames, num_frames=num_frames,
# pyre-fixme[6]: For 3rd argument expected `List[int]` but got
# `ndarray`.
new_obj_ids=new_det_obj_ids_local, new_obj_ids=new_det_obj_ids_local,
new_obj_masks=new_det_masks, new_obj_masks=new_det_masks,
tracker_states_local=tracker_states_local, tracker_states_local=tracker_states_local,
@@ -1143,6 +1226,7 @@ class Sam3VideoBase(nn.Module):
# Step 2: remove from SAM2 inference states those objects removed by heuristics # Step 2: remove from SAM2 inference states those objects removed by heuristics
if len(obj_ids_newly_removed) > 0: if len(obj_ids_newly_removed) > 0:
# pyre-fixme[6]: For 2nd argument expected `List[int]` but got `Set[int]`.
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed) self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
self._post_execution_phase_hook(tracker_states_local, tracker_metadata_new) self._post_execution_phase_hook(tracker_states_local, tracker_metadata_new)
@@ -1182,7 +1266,10 @@ class Sam3VideoBase(nn.Module):
tracker_update_plan: Dict[str, npt.NDArray], tracker_update_plan: Dict[str, npt.NDArray],
orig_vid_height: int, orig_vid_height: int,
orig_vid_width: int, orig_vid_width: int,
# pyre-fixme[9]: reconditioned_obj_ids has type `Set[Any]`; used as `None`.
reconditioned_obj_ids: set = None, reconditioned_obj_ids: set = None,
# pyre-fixme[9]: det_to_matched_trk_obj_ids has type `Dict[Any, Any]`; used
# as `None`.
det_to_matched_trk_obj_ids: dict = None, det_to_matched_trk_obj_ids: dict = None,
): ):
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"] new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
@@ -1255,6 +1342,7 @@ class Sam3VideoBase(nn.Module):
binary_low_res_masks: Tensor, binary_low_res_masks: Tensor,
last_occluded: List[int], last_occluded: List[int],
obj_ids: List[int], obj_ids: List[int],
# pyre-fixme[9]: frame_idx has type `int`; used as `None`.
frame_idx: int = None, frame_idx: int = None,
reverse: bool = False, reverse: bool = False,
): ):
@@ -1278,7 +1366,9 @@ class Sam3VideoBase(nn.Module):
) )
overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N] overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
# pyre-fixme[16]: `List` has no attribute `unsqueeze`.
last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1) last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
# pyrefly: ignore [missing-attribute]
last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N) last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
# Suppress most recently occluded # Suppress most recently occluded
cmp_op = torch.gt if not reverse else torch.lt cmp_op = torch.gt if not reverse else torch.lt
@@ -1309,6 +1399,7 @@ class Sam3VideoBase(nn.Module):
): ):
suppress_i_mask = suppress_i_mask.cpu().numpy() suppress_i_mask = suppress_i_mask.cpu().numpy()
suppress_j_mask = suppress_j_mask.cpu().numpy() suppress_j_mask = suppress_j_mask.cpu().numpy()
# pyre-fixme[16]: `List` has no attribute `cpu`.
last_occluded = last_occluded.cpu().numpy() last_occluded = last_occluded.cpu().numpy()
# Find all suppression pairs without using torch.where # Find all suppression pairs without using torch.where
@@ -1352,6 +1443,7 @@ class Sam3VideoBase(nn.Module):
# propagate one frame # propagate one frame
num_frames_propagated = 0 num_frames_propagated = 0
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
for out in self.tracker.propagate_in_video( for out in self.tracker.propagate_in_video(
inference_state, inference_state,
start_frame_idx=frame_idx, start_frame_idx=frame_idx,
@@ -1366,12 +1458,18 @@ class Sam3VideoBase(nn.Module):
num_frames_propagated += 1 num_frames_propagated += 1
# only 1 frames should be propagated # only 1 frames should be propagated
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, ( assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
# pyre-fixme[61]: `out_frame_idx` is undefined, or not always defined.
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}" f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
) )
# pyre-fixme[61]: `out_obj_ids` is undefined, or not always defined.
assert isinstance(out_obj_ids, list) 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) obj_ids_local.extend(out_obj_ids)
# pyrefly: ignore [unbound-name]
low_res_masks_list.append(out_low_res_masks.squeeze(1)) low_res_masks_list.append(out_low_res_masks.squeeze(1))
# pyrefly: ignore [unbound-name]
obj_scores_list.append(out_obj_scores.squeeze(1)) obj_scores_list.append(out_obj_scores.squeeze(1))
# concatenate the output masklets from all local inference states # concatenate the output masklets from all local inference states
@@ -1390,6 +1488,10 @@ class Sam3VideoBase(nn.Module):
) )
low_res_masks_local = low_res_masks_local.squeeze(1) low_res_masks_local = low_res_masks_local.squeeze(1)
else: else:
# pyre-fixme[6]: For 2nd argument expected `Union[int, SymInt]` but got
# `Union[Module, Tensor]`.
# pyre-fixme[6]: For 3rd argument expected `Union[int, SymInt]` but got
# `Union[Module, Tensor]`.
low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device) low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
obj_scores_local = torch.zeros(0, device=self.device) obj_scores_local = torch.zeros(0, device=self.device)
@@ -1666,6 +1768,8 @@ class Sam3VideoBase(nn.Module):
return return
# Avoid an extra interpolation step by directly interpolating to `interpol_size` # Avoid an extra interpolation step by directly interpolating to `interpol_size`
high_res_H, high_res_W = ( high_res_H, high_res_W = (
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `mask_downsampler`.
self.tracker.maskmem_backbone.mask_downsampler.interpol_size self.tracker.maskmem_backbone.mask_downsampler.interpol_size
) )
# NOTE: inspect this part if we observe OOMs in the demo # NOTE: inspect this part if we observe OOMs in the demo
@@ -1677,6 +1781,7 @@ class Sam3VideoBase(nn.Module):
) )
# We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics. # We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
if not hasattr(self, "_warm_up_complete") or self._warm_up_complete: if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
high_res_masks = self.tracker._suppress_object_pw_area_shrinkage( high_res_masks = self.tracker._suppress_object_pw_area_shrinkage(
high_res_masks high_res_masks
) )
@@ -1701,6 +1806,7 @@ class Sam3VideoBase(nn.Module):
local_batch_size = local_high_res_masks.size(0) 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 # Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
encoded_mem = self.tracker._run_memory_encoder( encoded_mem = self.tracker._run_memory_encoder(
tracker_state, tracker_state,
frame_idx, frame_idx,
@@ -1723,6 +1829,7 @@ class Sam3VideoBase(nn.Module):
] ]
# for batched inference state, we also need to add per-object # for batched inference state, we also need to add per-object
# memory slides to support instance interactivity # memory slides to support instance interactivity
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
self.tracker._add_output_per_object( self.tracker._add_output_per_object(
inference_state=tracker_state, inference_state=tracker_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -1750,6 +1857,7 @@ class Sam3VideoBase(nn.Module):
# prepare inference_state # prepare inference_state
# batch objects that first appear on the same frame together # batch objects that first appear on the same frame together
# Clear inference state. Keep the cached image features if available. # Clear inference state. Keep the cached image features if available.
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
new_tracker_state = self.tracker.init_state( new_tracker_state = self.tracker.init_state(
cached_features=feature_cache, cached_features=feature_cache,
video_height=orig_vid_height, video_height=orig_vid_height,
@@ -1767,6 +1875,8 @@ class Sam3VideoBase(nn.Module):
input_mask_res = self.tracker.input_mask_size input_mask_res = self.tracker.input_mask_size
new_obj_masks = F.interpolate( new_obj_masks = F.interpolate(
new_obj_masks.unsqueeze(1), new_obj_masks.unsqueeze(1),
# pyre-fixme[6]: For 2nd argument expected `Union[None, Sequence[int],
# int]` but got `Tuple[Union[Module, Tensor], Union[Module, Tensor]]`.
size=(input_mask_res, input_mask_res), size=(input_mask_res, input_mask_res),
mode="bilinear", mode="bilinear",
align_corners=False, align_corners=False,
@@ -1775,6 +1885,7 @@ class Sam3VideoBase(nn.Module):
# add object one by one # add object one by one
for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks): for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
self.tracker.add_new_mask( self.tracker.add_new_mask(
inference_state=new_tracker_state, inference_state=new_tracker_state,
frame_idx=frame_idx, frame_idx=frame_idx,
@@ -1783,6 +1894,7 @@ class Sam3VideoBase(nn.Module):
add_mask_to_memory=True, add_mask_to_memory=True,
) )
# NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects. # NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
self.tracker.propagate_in_video_preflight( self.tracker.propagate_in_video_preflight(
new_tracker_state, run_mem_encoder=True new_tracker_state, run_mem_encoder=True
) )
@@ -1799,6 +1911,7 @@ class Sam3VideoBase(nn.Module):
for tracker_inference_state in tracker_states_local_before_removal: for tracker_inference_state in tracker_states_local_before_removal:
# we try to remove `obj_id` on every inference state with `strict=False` # 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` # it will not do anything if an inference state doesn't contain `obj_id`
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
new_obj_ids, _ = self.tracker.remove_object( new_obj_ids, _ = self.tracker.remove_object(
tracker_inference_state, obj_id, strict=False, need_output=False tracker_inference_state, obj_id, strict=False, need_output=False
) )
+4
View File
@@ -911,7 +911,9 @@ class Sam3VideoInference(Sam3VideoBase):
# set the model to single GPU for benchmark evaluation (to be compatible with trainer) # set the model to single GPU for benchmark evaluation (to be compatible with trainer)
orig_rank = self.rank orig_rank = self.rank
orig_world_size = self.world_size orig_world_size = self.world_size
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = 0 self.rank = self.detector.rank = 0
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = 1 self.world_size = self.detector.world_size = 1
# get data # get data
@@ -952,7 +954,9 @@ class Sam3VideoInference(Sam3VideoBase):
preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels) preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels)
# revert the model to the original GPU and rank # revert the model to the original GPU and rank
# pyrefly: ignore [bad-argument-type]
self.rank = self.detector.rank = orig_rank self.rank = self.detector.rank = orig_rank
# pyrefly: ignore [bad-argument-type]
self.world_size = self.detector.world_size = orig_world_size self.world_size = self.detector.world_size = orig_world_size
return {video_id: preds} return {video_id: preds}
+11
View File
@@ -96,6 +96,17 @@ class Sam3VideoPredictor(Sam3BasePredictor):
f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}" f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
) )
def shutdown(self):
tracker = getattr(self.model, "tracker", None)
bf16_context = getattr(tracker, "bf16_context", None)
try:
if bf16_context is not None:
bf16_context.__exit__(None, None, None)
finally:
if tracker is not None:
tracker.bf16_context = None
super().shutdown()
class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor): class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
def __init__(self, *model_args, gpus_to_use=None, **model_kwargs): def __init__(self, *model_args, gpus_to_use=None, **model_kwargs):
+7
View File
@@ -77,9 +77,11 @@ class ResidualAttentionBlock(nn.Module):
attn_mask: Optional[torch.Tensor] = None, attn_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor: ) -> torch.Tensor:
k_x = ( k_x = (
# pyrefly: ignore [not-callable]
self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
) )
v_x = ( v_x = (
# pyrefly: ignore [not-callable]
self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None 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( x = q_x + self.ls_1(
@@ -138,6 +140,7 @@ class Transformer(nn.Module):
and not torch.jit.is_scripting() and not torch.jit.is_scripting()
and self.training and self.training
): ):
# pyrefly: ignore [bad-assignment]
x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False) x = checkpoint(r, x, None, None, attn_mask, use_reentrant=False)
else: else:
x = r( x = r(
@@ -217,6 +220,7 @@ class TextTransformer(nn.Module):
if proj_bias: if proj_bias:
self.text_projection = nn.Linear(width, output_dim) self.text_projection = nn.Linear(width, output_dim)
else: else:
# pyrefly: ignore [bad-assignment]
self.text_projection = nn.Parameter(torch.empty(width, output_dim)) self.text_projection = nn.Parameter(torch.empty(width, output_dim))
def build_causal_mask(self) -> torch.Tensor: def build_causal_mask(self) -> torch.Tensor:
@@ -289,6 +293,7 @@ class VETextEncoder(nn.Module):
self, self,
text: Union[List[str], Tuple[torch.Tensor, torch.Tensor, dict]], text: Union[List[str], Tuple[torch.Tensor, torch.Tensor, dict]],
input_boxes: Optional[List] = None, input_boxes: Optional[List] = None,
# pyrefly: ignore [bad-function-definition]
device: torch.device = None, device: torch.device = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if isinstance(text[0], str): if isinstance(text[0], str):
@@ -317,12 +322,14 @@ class VETextEncoder(nn.Module):
else: else:
# The text is already encoded, use as is. # The text is already encoded, use as is.
text_attention_mask, text_memory_resized, tokenized = text text_attention_mask, text_memory_resized, tokenized = text
# pyrefly: ignore [bad-index]
inputs_embeds = tokenized["inputs_embeds"] inputs_embeds = tokenized["inputs_embeds"]
assert input_boxes is None or len(input_boxes) == 0, ( assert input_boxes is None or len(input_boxes) == 0, (
"Can't replace boxes in text if it's already encoded" "Can't replace boxes in text if it's already encoded"
) )
# Note that the input_embeds are returned in pytorch's convention (sequence first) # Note that the input_embeds are returned in pytorch's convention (sequence first)
# pyrefly: ignore [bad-return]
return ( return (
text_attention_mask, text_attention_mask,
text_memory_resized, text_memory_resized,
+2
View File
@@ -137,6 +137,7 @@ class SimpleTokenizer(object):
): ):
self.byte_encoder = bytes_to_unicode() self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
# pyrefly: ignore [no-matching-overload]
with g_pathmgr.open(bpe_path, "rb") as fh: with g_pathmgr.open(bpe_path, "rb") as fh:
bpe_bytes = io.BytesIO(fh.read()) bpe_bytes = io.BytesIO(fh.read())
merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n") merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
@@ -252,4 +253,5 @@ class SimpleTokenizer(object):
tokens = tokens[:context_length] # Truncate tokens = tokens[:context_length] # Truncate
tokens[-1] = self.eot_token_id tokens[-1] = self.eot_token_id
result[i, : len(tokens)] = torch.tensor(tokens) result[i, : len(tokens)] = torch.tensor(tokens)
# pyrefly: ignore [bad-return]
return result return result
+2
View File
@@ -48,7 +48,9 @@ def copy_data_to_device(data, device: torch.device, *args: Any, **kwargs: Any):
}, },
) )
elif isinstance(data, Mapping): elif isinstance(data, Mapping):
# pyrefly: ignore [bad-instantiation]
return type(data)( return type(data)(
# pyrefly: ignore [bad-argument-count]
{ {
k: copy_data_to_device(v, device, *args, **kwargs) k: copy_data_to_device(v, device, *args, **kwargs)
for k, v in data.items() for k, v in data.items()
+109 -3
View File
@@ -58,11 +58,13 @@ class SAMOutput(TypedDict, total=True):
low_res_masks: torch.Tensor low_res_masks: torch.Tensor
high_res_masks: torch.Tensor high_res_masks: torch.Tensor
object_score_logits: 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 obj_ptr: NotRequired[torch.Tensor] # [num_objects, C], in data space
class StageOutput(TypedDict, total=False): class StageOutput(TypedDict, total=False):
# metadata # metadata
# pyrefly: ignore [invalid-annotation, not-a-type]
conditioning_objects: Required[set[int]] conditioning_objects: Required[set[int]]
# The outputs from a single stage; could be used as memory # The outputs from a single stage; could be used as memory
@@ -308,6 +310,7 @@ class VideoTrackingMultiplex(nn.Module):
# with memories from past frames # with memories from past frames
assert transformer.decoder is None, "transformer should be encoder-only" assert transformer.decoder is None, "transformer should be encoder-only"
self.transformer = transformer self.transformer = transformer
# pyre-fixme[8]: Attribute has type `int`; used as `Union[Module, Tensor]`.
self.hidden_dim: int = transformer.d_model self.hidden_dim: int = transformer.d_model
# Part 3: memory encoder for the previous frame's outputs # Part 3: memory encoder for the previous frame's outputs
@@ -317,6 +320,8 @@ class VideoTrackingMultiplex(nn.Module):
self.maskmem_backbone.out_proj, "weight" self.maskmem_backbone.out_proj, "weight"
): ):
# if there is compression of memories along channel dim # if there is compression of memories along channel dim
# pyre-fixme[16]: Item `Tensor` of `Tensor | Module` has no attribute
# `weight`.
mem_dim = self.maskmem_backbone.out_proj.weight.shape[0] mem_dim = self.maskmem_backbone.out_proj.weight.shape[0]
assert mem_dim == self.hidden_dim, ( assert mem_dim == self.hidden_dim, (
"there should be no compression of memory embeddings" "there should be no compression of memory embeddings"
@@ -883,11 +888,14 @@ class VideoTrackingMultiplex(nn.Module):
# Extract object pointer from the SAM output token # Extract object pointer from the SAM output token
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
if is_interactive: if is_interactive:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
obj_ptr = self.interactive_obj_ptr_proj(sam_output_token) obj_ptr = self.interactive_obj_ptr_proj(sam_output_token)
else: else:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
obj_ptr = self.obj_ptr_proj(sam_output_token) obj_ptr = self.obj_ptr_proj(sam_output_token)
if self.pred_obj_scores and self.use_no_obj_ptr: if self.pred_obj_scores and self.use_no_obj_ptr:
# pyrefly: ignore [unbound-name]
lambda_is_obj_appearing = is_obj_appearing.float() lambda_is_obj_appearing = is_obj_appearing.float()
if self.use_linear_no_obj_ptr: if self.use_linear_no_obj_ptr:
obj_ptr = lambda_is_obj_appearing * obj_ptr + ( obj_ptr = lambda_is_obj_appearing * obj_ptr + (
@@ -910,6 +918,7 @@ class VideoTrackingMultiplex(nn.Module):
obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr
) )
# pyrefly: ignore [bad-typed-dict-key]
outputs: SAMOutput = { outputs: SAMOutput = {
"low_res_multimasks": low_res_multimasks, "low_res_multimasks": low_res_multimasks,
"high_res_multimasks": high_res_multimasks, "high_res_multimasks": high_res_multimasks,
@@ -919,6 +928,7 @@ class VideoTrackingMultiplex(nn.Module):
"object_score_logits": object_score_logits, "object_score_logits": object_score_logits,
} }
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space
return outputs return outputs
@@ -997,15 +1007,18 @@ class VideoTrackingMultiplex(nn.Module):
obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr obj_ptr + (1 - lambda_is_obj_appearing) * selected_no_obj_ptr
) )
# pyrefly: ignore [bad-typed-dict-key]
outputs: SAMOutput = { outputs: SAMOutput = {
"low_res_multimasks": low_res_masks, "low_res_multimasks": low_res_masks,
"high_res_multimasks": high_res_masks, "high_res_multimasks": high_res_masks,
"ious": ious, "ious": ious,
"low_res_masks": low_res_masks, "low_res_masks": low_res_masks,
"high_res_masks": high_res_masks, "high_res_masks": high_res_masks,
# pyre-fixme[61]: `object_score_logits` is undefined, or not always defined.
"object_score_logits": object_score_logits, "object_score_logits": object_score_logits,
} }
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space outputs["obj_ptr"] = obj_ptr # [num_objects, C], in data space
return outputs return outputs
@@ -1037,6 +1050,7 @@ class VideoTrackingMultiplex(nn.Module):
need_propagation_out = need_interactive_out or need_propagation_out need_propagation_out = need_interactive_out or need_propagation_out
need_interactive_out = False need_interactive_out = False
# this also means that convs for backbone_fpn are shared # this also means that convs for backbone_fpn are shared
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
backbone_out = self.backbone.forward_image( backbone_out = self.backbone.forward_image(
img_batch, img_batch,
need_sam3_out=need_sam3_out, need_sam3_out=need_sam3_out,
@@ -1044,6 +1058,7 @@ class VideoTrackingMultiplex(nn.Module):
) )
backbone_out["interactive"] = backbone_out["sam2_backbone_out"] backbone_out["interactive"] = backbone_out["sam2_backbone_out"]
else: else:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
backbone_out = self.backbone.forward_image( backbone_out = self.backbone.forward_image(
img_batch, img_batch,
need_sam3_out=need_sam3_out, need_sam3_out=need_sam3_out,
@@ -1360,8 +1375,12 @@ class VideoTrackingMultiplex(nn.Module):
for t_pos in range(1, self.num_maskmem): for t_pos in range(1, self.num_maskmem):
t_rel = self.num_maskmem - t_pos # how many frames before current frame t_rel = self.num_maskmem - t_pos # how many frames before current frame
if self.use_memory_selection: if self.use_memory_selection:
# pyre-fixme[61]: `valid_indices` is undefined, or not always
# defined.
if t_rel > len(valid_indices): if t_rel > len(valid_indices):
continue continue
# pyre-fixme[61]: `valid_indices` is undefined, or not always
# defined.
prev_frame_idx = valid_indices[-t_rel] prev_frame_idx = valid_indices[-t_rel]
else: else:
if t_rel == 1: if t_rel == 1:
@@ -1448,7 +1467,9 @@ class VideoTrackingMultiplex(nn.Module):
# image features are in (HW)BC # image features are in (HW)BC
image_feat = prev["image_features"].cuda() image_feat = prev["image_features"].cuda()
image_pos_embed = prev["image_pos_enc"].cuda() + tpos_enc image_pos_embed = prev["image_pos_enc"].cuda() + tpos_enc
# pyrefly: ignore [unbound-name]
to_cat_image_feat.append(image_feat) to_cat_image_feat.append(image_feat)
# pyrefly: ignore [unbound-name]
to_cat_image_pos_embed.append(image_pos_embed) to_cat_image_pos_embed.append(image_pos_embed)
to_cat_prompt_pos_embed.append(maskmem_enc) to_cat_prompt_pos_embed.append(maskmem_enc)
@@ -1491,8 +1512,12 @@ class VideoTrackingMultiplex(nn.Module):
if t < 0 or (num_frames is not None and t >= num_frames): if t < 0 or (num_frames is not None and t >= num_frames):
break break
else: else:
# pyre-fixme[61]: `valid_indices` is undefined, or not
# always defined.
if -t_diff <= -len(valid_indices): if -t_diff <= -len(valid_indices):
break break
# pyre-fixme[61]: `valid_indices` is undefined, or not
# always defined.
t = valid_indices[-t_diff] t = valid_indices[-t_diff]
out = output_dict["non_cond_frame_outputs"].get( out = output_dict["non_cond_frame_outputs"].get(
@@ -1580,13 +1605,20 @@ class VideoTrackingMultiplex(nn.Module):
if self.save_image_features: if self.save_image_features:
assert prompt_mask is None assert prompt_mask is None
assert vision_mask is None assert vision_mask is None
# pyre-fixme[61]: `to_cat_image_feat` is undefined, or not always defined.
# pyre-fixme[61]: `to_cat_image_pos_embed` is undefined, or not always
# defined.
if len(to_cat_image_feat) == 0 or len(to_cat_image_pos_embed) == 0: if len(to_cat_image_feat) == 0 or len(to_cat_image_pos_embed) == 0:
# Memory image features were cleared; fall back to current-frame features. # Memory image features were cleared; fall back to current-frame features.
pix_feat = vision_feat.permute(1, 2, 0).view(B, C, H, W) pix_feat = vision_feat.permute(1, 2, 0).view(B, C, H, W)
return pix_feat return pix_feat
# pyre-fixme[61]: `to_cat_image_feat` is undefined, or not always defined.
image_feat = torch.cat(to_cat_image_feat, dim=0) image_feat = torch.cat(to_cat_image_feat, dim=0)
# pyre-fixme[61]: `to_cat_image_pos_embed` is undefined, or not always
# defined.
image_pos_embed = torch.cat(to_cat_image_pos_embed, dim=0) image_pos_embed = torch.cat(to_cat_image_pos_embed, dim=0)
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
encoder_out = self.transformer.encoder( encoder_out = self.transformer.encoder(
image=current_vision_feats[-1], image=current_vision_feats[-1],
src=vision_feat, src=vision_feat,
@@ -1599,6 +1631,7 @@ class VideoTrackingMultiplex(nn.Module):
num_obj_ptr_tokens=num_obj_ptr_tokens, num_obj_ptr_tokens=num_obj_ptr_tokens,
) )
else: else:
# pyre-fixme[29]: `Union[Module, Tensor]` is not a function.
encoder_out = self.transformer.encoder( encoder_out = self.transformer.encoder(
src=vision_feat, src=vision_feat,
src_key_padding_mask=vision_mask, src_key_padding_mask=vision_mask,
@@ -1684,7 +1717,10 @@ class VideoTrackingMultiplex(nn.Module):
device=mask_for_mem.device, device=mask_for_mem.device,
dtype=mask_for_mem.dtype, dtype=mask_for_mem.dtype,
) )
# pyre-fixme[6]: For 1st argument expected
# `pyre_extensions.PyreReadOnly[Sized]` but got `Optional[Iterable[Any]]`.
if len(conditioning_objects) > 0: if len(conditioning_objects) > 0:
# pyre-fixme[6]: For 1st argument expected `Union[None, slice[Any, An...
cond_values[conditioning_objects] = self.condition_as_mask_input_fg cond_values[conditioning_objects] = self.condition_as_mask_input_fg
# Broadcast to full spatial dimensions: [N] -> [N, 1, H, W] # Broadcast to full spatial dimensions: [N] -> [N, 1, H, W]
embedded_conditions = cond_values.view(-1, 1, 1, 1).expand_as(mask_for_mem) embedded_conditions = cond_values.view(-1, 1, 1, 1).expand_as(mask_for_mem)
@@ -1752,7 +1788,11 @@ class VideoTrackingMultiplex(nn.Module):
obj_non_cond_embed = multiplex_state.demux(obj_non_cond_embed) obj_non_cond_embed = multiplex_state.demux(obj_non_cond_embed)
if self.training: if self.training:
obj_merged_embed = obj_merged_embed.clone() obj_merged_embed = obj_merged_embed.clone()
# pyre-fixme[61]: `unconditioning_objects` is undefined, or not
# always defined.
obj_merged_embed[unconditioning_objects] = obj_non_cond_embed[ obj_merged_embed[unconditioning_objects] = obj_non_cond_embed[
# pyre-fixme[61]: `unconditioning_objects` is undefined, or not
# always defined.
unconditioning_objects unconditioning_objects
] ]
@@ -1829,6 +1869,7 @@ class VideoTrackingMultiplex(nn.Module):
# Retrieve image features according to img_ids (if they are already computed). # Retrieve image features according to img_ids (if they are already computed).
current_image = input.img_batch.tensors[img_ids] current_image = input.img_batch.tensors[img_ids]
current_backbone_features = {} current_backbone_features = {}
# pyrefly: ignore [unbound-name]
for neck_k, neck_out in backbone_features.items(): for neck_k, neck_out in backbone_features.items():
current_backbone_features[neck_k] = { current_backbone_features[neck_k] = {
"vision_feats": [ "vision_feats": [
@@ -1888,6 +1929,8 @@ class VideoTrackingMultiplex(nn.Module):
else: else:
output_dict["non_cond_frame_outputs"][stage_id] = current_out output_dict["non_cond_frame_outputs"][stage_id] = current_out
# pyre-fixme[6]: For 2nd argument expected `Dict[int, StageOutput]` but got
# `MultiplexState`.
output_dict["multiplex_state"] = multiplex_state output_dict["multiplex_state"] = multiplex_state
if return_dict: if return_dict:
@@ -2034,10 +2077,15 @@ class VideoTrackingMultiplex(nn.Module):
# pix_feat = pix_feat.view(-1, self.hidden_dim, *interactive_feat_sizes[-1]) # 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 # 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_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( sam_outputs = self._use_mask_as_output(
backbone_features=interactive_pix_feat, backbone_features=interactive_pix_feat,
# pyre-fixme[6]: For 2nd argument expected `List[Tensor]` but got
# `Optional[List[Any]]`.
high_res_features=interactive_high_res_features, high_res_features=interactive_high_res_features,
mask_inputs=mask_inputs, mask_inputs=mask_inputs,
multiplex_state=multiplex_state, multiplex_state=multiplex_state,
@@ -2156,12 +2204,15 @@ class VideoTrackingMultiplex(nn.Module):
"obj_ptr", "obj_ptr",
] ]
for k in keys_to_merge: for k in keys_to_merge:
# pyre-fixme[26]: TypedDict key must be a string literal.
src = interaction_out[k] src = interaction_out[k]
# pyre-fixme[26]: TypedDict key must be a string literal.
dst = propagation_out[k] dst = propagation_out[k]
# Align dtype for floating tensors before indexed assignment # Align dtype for floating tensors before indexed assignment
if torch.is_tensor(src) and torch.is_tensor(dst): if torch.is_tensor(src) and torch.is_tensor(dst):
if torch.is_floating_point(src) and src.dtype != dst.dtype: if torch.is_floating_point(src) and src.dtype != dst.dtype:
src = src.to(dtype=dst.dtype) src = src.to(dtype=dst.dtype)
# pyre-fixme[26]: TypedDict key must be a string literal.
propagation_out[k][objects_to_interact] = src propagation_out[k][objects_to_interact] = src
sam_outputs = propagation_out sam_outputs = propagation_out
@@ -2311,6 +2362,7 @@ class VideoTrackingMultiplex(nn.Module):
high_res_multimasks = high_res_multimasks.clone() high_res_multimasks = high_res_multimasks.clone()
ious = ious.clone() ious = ious.clone()
object_score_logits = object_score_logits.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 obj_ptr = obj_ptr.clone() if self.use_obj_ptrs_in_encoder else None
# Update masks for the interacted objects # Update masks for the interacted objects
@@ -2361,6 +2413,9 @@ class VideoTrackingMultiplex(nn.Module):
) )
object_score_logits[objects_to_interact] = interact_object_score_logits object_score_logits[objects_to_interact] = interact_object_score_logits
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
# pyre-fixme[61]: `interact_obj_ptr` is undefined, or not always
# defined.
obj_ptr[objects_to_interact] = interact_obj_ptr obj_ptr[objects_to_interact] = interact_obj_ptr
all_pred_masks.append(low_res_masks) all_pred_masks.append(low_res_masks)
@@ -2398,6 +2453,7 @@ class VideoTrackingMultiplex(nn.Module):
current_out["pred_masks_high_res"] = high_res_masks current_out["pred_masks_high_res"] = high_res_masks
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# similar to spatial memory, the object pointers are stored with multiplex # similar to spatial memory, the object pointers are stored with multiplex
# pyre-fixme[61]: `obj_ptr` is undefined, or not always defined.
current_out["obj_ptr"] = multiplex_state.mux(obj_ptr) current_out["obj_ptr"] = multiplex_state.mux(obj_ptr)
if self.use_memory_selection: if self.use_memory_selection:
current_out["object_score_logits"] = object_score_logits current_out["object_score_logits"] = object_score_logits
@@ -2426,10 +2482,13 @@ class VideoTrackingMultiplex(nn.Module):
multiplex_state=multiplex_state, multiplex_state=multiplex_state,
) )
current_out["maskmem_features"] = maskmem_features current_out["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
current_out["maskmem_pos_enc"] = maskmem_pos_enc current_out["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features: if self.save_image_features:
# pyrefly: ignore [unsupported-operation]
current_out["image_features"] = propagation_vision_feats[-1] current_out["image_features"] = propagation_vision_feats[-1]
# pyrefly: ignore [unsupported-operation]
current_out["image_pos_enc"] = propagation_vision_pos_embeds[-1] 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 # this is to avoid recomputing some of these features for add_new_masks_to_existing_state
@@ -2437,11 +2496,17 @@ class VideoTrackingMultiplex(nn.Module):
if need_aux_output: if need_aux_output:
if interactive_pix_feat is None: if interactive_pix_feat is None:
interactive_pix_feat = self._get_interactive_pix_mem( 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 aux_output["interactive_pix_feat"] = interactive_pix_feat
# pyrefly: ignore [unsupported-operation]
aux_output["interactive_high_res_features"] = interactive_high_res_features aux_output["interactive_high_res_features"] = interactive_high_res_features
# pyrefly: ignore [unsupported-operation]
aux_output["propagation_vision_feats"] = propagation_vision_feats aux_output["propagation_vision_feats"] = propagation_vision_feats
# pyrefly: ignore [unsupported-operation]
aux_output["propagation_feat_sizes"] = propagation_feat_sizes aux_output["propagation_feat_sizes"] = propagation_feat_sizes
return current_out, aux_output return current_out, aux_output
@@ -2505,9 +2570,13 @@ class VideoTrackingMultiplex(nn.Module):
if past_out is not None: if past_out is not None:
if ( if (
self.use_memory_selection self.use_memory_selection
# pyre-fixme[58]: `<` is not supported for operand types
# `Union[int, Tensor]` and `float`.
and past_out.get("eff_iou_score", 0) < self.mf_threshold and past_out.get("eff_iou_score", 0) < self.mf_threshold
) or not self.use_memory_selection: ) or not self.use_memory_selection:
output_dict["non_cond_frame_outputs"][past_frame_idx] = ( output_dict["non_cond_frame_outputs"][past_frame_idx] = (
# pyre-fixme[6]: For 2nd argument expected `StageOutput` but
# got `Optional[StageOutput]`.
_trim_past_out(past_out, current_out) _trim_past_out(past_out, current_out)
) )
@@ -2520,6 +2589,8 @@ class VideoTrackingMultiplex(nn.Module):
) )
if past_out is not None: if past_out is not None:
output_dict["non_cond_frame_outputs"][far_old_frame_idx] = ( output_dict["non_cond_frame_outputs"][far_old_frame_idx] = (
# pyre-fixme[6]: For 2nd argument expected `StageOutput` but
# got `Optional[StageOutput]`.
_trim_past_out(past_out, current_out) _trim_past_out(past_out, current_out)
) )
@@ -2742,6 +2813,9 @@ def _append(
if k1 not in d1: if k1 not in d1:
return return
# pyre-fixme[26]: TypedDict key must be a string literal.
# pyre-fixme[6]: For 1st argument expected `Union[List[Tensor], tuple[Tensor,
# ...]]` but got `List[Union[Set[int], Tensor]]`.
d1[k1] = torch.cat([d1[k1], d2[k2]], dim=dim) d1[k1] = torch.cat([d1[k1], d2[k2]], dim=dim)
@@ -2758,6 +2832,9 @@ def _merge(
else: else:
if k1 not in d1: if k1 not in d1:
return return
# pyre-fixme[16]: `set` has no attribute `__setitem__`.
# pyre-fixme[26]: TypedDict key must be a string literal.
# pyre-fixme[16]: `set` has no attribute `dtype`.
d1[k1][d2_idx] = d2[k2].to(dtype=d1[k1].dtype) d1[k1][d2_idx] = d2[k2].to(dtype=d1[k1].dtype)
@@ -3181,14 +3258,21 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# Merge the input masks # Merge the input masks
if "input_masks" in prev_output: if "input_masks" in prev_output:
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
prev_output["input_masks"] = torch.cat( prev_output["input_masks"] = torch.cat(
[prev_output["input_masks"], new_masks], dim=0 # pyre-fixme[6]: For 1st argument expected `Union[List[Tensor],
# tuple[Tensor, ...]]` but got `List[Union[Set[int], Tensor]]`.
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
[prev_output["input_masks"], new_masks],
dim=0,
) )
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# Merge the object pointers. Note that the pointers in SAMOutput are in the data space, # Merge the object pointers. Note that the pointers in SAMOutput are in the data space,
# while those in StageOutput are in the mux space. # while those in StageOutput are in the mux space.
# pyrefly: ignore [unbound-name]
new_pointers = mask_output["obj_ptr"].to(existing_pointers.dtype) 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) combined_pointers = torch.cat([existing_pointers, new_pointers], dim=0)
prev_output["obj_ptr"] = multiplex_state.mux(combined_pointers) prev_output["obj_ptr"] = multiplex_state.mux(combined_pointers)
@@ -3213,6 +3297,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
multiplex_state=multiplex_state, multiplex_state=multiplex_state,
) )
prev_output["maskmem_features"] = maskmem_features prev_output["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
prev_output["maskmem_pos_enc"] = maskmem_pos_enc prev_output["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features: if self.save_image_features:
# They should already be in the state; no modification is needed # They should already be in the state; no modification is needed
@@ -3308,13 +3393,18 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# Merge the input masks # Merge the input masks
if "input_masks" in prev_output: if "input_masks" in prev_output:
# pyre-fixme[16]: `set` has no attribute `__setitem__`.
# pyre-fixme[27]: TypedDict `StageOutput` has no key `input_masks`.
prev_output["input_masks"][obj_idxs_in_mask] = new_masks prev_output["input_masks"][obj_idxs_in_mask] = new_masks
if self.use_obj_ptrs_in_encoder: if self.use_obj_ptrs_in_encoder:
# Merge the object pointers. Note that the pointers in SAMOutput are in the data space, # Merge the object pointers. Note that the pointers in SAMOutput are in the data space,
# while those in StageOutput are in the mux space. # while those in StageOutput are in the mux space.
# pyrefly: ignore [unbound-name]
new_pointers = mask_output["obj_ptr"].to(existing_pointers.dtype) 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 existing_pointers[obj_idxs_in_mask] = new_pointers
# pyre-fixme[61]: `existing_pointers` is undefined, or not always defined.
prev_output["obj_ptr"] = multiplex_state.mux(existing_pointers) prev_output["obj_ptr"] = multiplex_state.mux(existing_pointers)
# Step 3: Update the set of conditioning objects at this frame # Step 3: Update the set of conditioning objects at this frame
@@ -3338,6 +3428,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
multiplex_state=multiplex_state, multiplex_state=multiplex_state,
) )
prev_output["maskmem_features"] = maskmem_features prev_output["maskmem_features"] = maskmem_features
# pyrefly: ignore [bad-assignment]
prev_output["maskmem_pos_enc"] = maskmem_pos_enc prev_output["maskmem_pos_enc"] = maskmem_pos_enc
if self.save_image_features: if self.save_image_features:
# They should already be in the state; no modification is needed # They should already be in the state; no modification is needed
@@ -3426,6 +3517,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
return current_out return current_out
# pyrefly: ignore [bad-override]
def forward_tracking( def forward_tracking(
self, self,
backbone_out, backbone_out,
@@ -3486,6 +3578,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# Retrieve image features according to img_ids (if they are already computed). # Retrieve image features according to img_ids (if they are already computed).
current_image = input.img_batch.tensors[img_ids] current_image = input.img_batch.tensors[img_ids]
current_backbone_features = {} current_backbone_features = {}
# pyrefly: ignore [unbound-name]
for neck_k, neck_out in backbone_features.items(): for neck_k, neck_out in backbone_features.items():
current_backbone_features[neck_k] = { current_backbone_features[neck_k] = {
"vision_feats": [ "vision_feats": [
@@ -3581,6 +3674,8 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
else: else:
output_dict["non_cond_frame_outputs"][stage_id] = current_out output_dict["non_cond_frame_outputs"][stage_id] = current_out
# pyre-fixme[6]: For 2nd argument expected `Dict[int, StageOutput]` but got
# `MultiplexState`.
output_dict["multiplex_state"] = multiplex_state output_dict["multiplex_state"] = multiplex_state
if return_dict: if return_dict:
@@ -3606,6 +3701,7 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# since we have remapped the object appearance order, we would need to map it back here # since we have remapped the object appearance order, we would need to map it back here
inverse_object_appearance_order = [None for _ in object_appearance_order] inverse_object_appearance_order = [None for _ in object_appearance_order]
for idx, obj_id in enumerate(object_appearance_order): for idx, obj_id in enumerate(object_appearance_order):
# pyre-fixme[6]: For 2nd argument expected `None` but got `int`.
inverse_object_appearance_order[obj_id] = idx inverse_object_appearance_order[obj_id] = idx
assert all(i is not None for i in inverse_object_appearance_order) assert all(i is not None for i in inverse_object_appearance_order)
@@ -3617,14 +3713,20 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
# This only happens if we evaluate on the new (fully annotated) YouTubeVOS set. # This only happens if we evaluate on the new (fully annotated) YouTubeVOS set.
if len(inverse_object_appearance_order) < num_objects: if len(inverse_object_appearance_order) < num_objects:
inverse_object_appearance_order.extend( inverse_object_appearance_order.extend(
# pyre-fixme[6]: For 1st argument expected `Iterable[None]` but
# got `List[int]`.
list(range(len(inverse_object_appearance_order), num_objects)) list(range(len(inverse_object_appearance_order), num_objects))
) )
# we need to pad the outputs with zeros (for the frames before the object appears) # we need to pad the outputs with zeros (for the frames before the object appears)
# pyre-fixme[16]: `Optional` has no attribute `__getitem__`.
last_mask = all_frame_outputs[-1]["pred_masks"] last_mask = all_frame_outputs[-1]["pred_masks"]
# pyrefly: ignore [missing-attribute]
shape = last_mask.shape[1:] shape = last_mask.shape[1:]
# pyrefly: ignore [missing-attribute]
dtype = last_mask.dtype dtype = last_mask.dtype
# pyrefly: ignore [missing-attribute]
device = last_mask.device device = last_mask.device
for stage_i, frame_out in enumerate(all_frame_outputs): for stage_i, frame_out in enumerate(all_frame_outputs):
if frame_out is None: if frame_out is None:
@@ -3636,14 +3738,18 @@ class VideoTrackingDynamicMultiplex(VideoTrackingMultiplex):
continue continue
pred_mask = frame_out["pred_masks"] pred_mask = frame_out["pred_masks"]
# pyrefly: ignore [missing-attribute]
if pred_mask.shape[0] < num_objects: if pred_mask.shape[0] < num_objects:
# pyrefly: ignore [missing-attribute]
shape = pred_mask.shape[ shape = pred_mask.shape[
1: 1:
] # might have a different shape, e.g., input mask ] # might have a different shape, e.g., input mask
frame_out["pred_masks"] = torch.cat( frame_out["pred_masks"] = torch.cat(
# pyrefly: ignore [bad-argument-type]
[ [
pred_mask, pred_mask,
torch.zeros( torch.zeros(
# pyrefly: ignore [missing-attribute]
(num_objects - pred_mask.shape[0], *shape), (num_objects - pred_mask.shape[0], *shape),
device=device, device=device,
dtype=dtype, dtype=dtype,
@@ -2734,6 +2734,7 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
propagation_vision_feats=propagation_vision_feats, propagation_vision_feats=propagation_vision_feats,
propagation_feat_sizes=propagation_feat_sizes, propagation_feat_sizes=propagation_feat_sizes,
new_masks=mask_inputs, new_masks=mask_inputs,
# pyrefly: ignore [bad-argument-type]
obj_idxs_in_mask=new_obj_idxs, obj_idxs_in_mask=new_obj_idxs,
obj_ids_in_mask=new_obj_ids, obj_ids_in_mask=new_obj_ids,
prev_output=existing_out, prev_output=existing_out,
@@ -2768,10 +2769,12 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
propagation_vision_feats=propagation_vision_feats, propagation_vision_feats=propagation_vision_feats,
propagation_feat_sizes=propagation_feat_sizes, propagation_feat_sizes=propagation_feat_sizes,
new_masks=( new_masks=(
# pyrefly: ignore [bad-argument-type]
mask_inputs mask_inputs
if mask_inputs is not None if mask_inputs is not None
else new_masks_from_points else new_masks_from_points
), ),
# pyrefly: ignore [bad-argument-type]
obj_idxs_in_mask=new_obj_idxs, obj_idxs_in_mask=new_obj_idxs,
obj_ids_in_mask=new_obj_ids, obj_ids_in_mask=new_obj_ids,
prev_output=existing_out, prev_output=existing_out,
@@ -3217,6 +3220,7 @@ class VideoTrackingMultiplexDemo(VideoTrackingDynamicMultiplex):
class Sam3VideoTrackingMultiplexDemo(VideoTrackingMultiplexDemo): class Sam3VideoTrackingMultiplexDemo(VideoTrackingMultiplexDemo):
@torch.inference_mode() @torch.inference_mode()
# pyrefly: ignore [bad-override-param-name]
def init_state( def init_state(
self, self,
video_height, video_height,
+19
View File
@@ -271,6 +271,7 @@ def get_abs_pos(
# add cls_token back, flatten spatial dims # add cls_token back, flatten spatial dims
assert has_cls_token assert has_cls_token
return torch.cat( return torch.cat(
# pyrefly: ignore [unbound-name]
[cls_pos, new_abs_pos.permute(0, 2, 3, 1).reshape(1, h * w, -1)], [cls_pos, new_abs_pos.permute(0, 2, 3, 1).reshape(1, h * w, -1)],
dim=1, dim=1,
) )
@@ -280,6 +281,7 @@ def get_abs_pos(
return abs_pos.reshape(1, h, w, -1) return abs_pos.reshape(1, h, w, -1)
else: else:
assert has_cls_token assert has_cls_token
# pyrefly: ignore [unbound-name]
return torch.cat([cls_pos, abs_pos], dim=1) return torch.cat([cls_pos, abs_pos], dim=1)
@@ -394,6 +396,7 @@ class Attention(nn.Module):
use_rel_pos: bool = False, use_rel_pos: bool = False,
rel_pos_zero_init: bool = True, rel_pos_zero_init: bool = True,
input_size: Optional[Tuple[int, int]] = None, input_size: Optional[Tuple[int, int]] = None,
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla, attn_type: AttentionType = AttentionType.Vanilla,
cls_token: bool = False, cls_token: bool = False,
use_rope: bool = False, use_rope: bool = False,
@@ -565,7 +568,9 @@ class Attention(nn.Module):
return apply_rotary_enc_real( return apply_rotary_enc_real(
q, q,
k, k,
# pyrefly: ignore [bad-argument-type]
freqs_cis_imag=self.freqs_cis_imag, freqs_cis_imag=self.freqs_cis_imag,
# pyrefly: ignore [bad-argument-type]
freqs_cis_real=self.freqs_cis_real, freqs_cis_real=self.freqs_cis_real,
) )
return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis) return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis)
@@ -594,16 +599,23 @@ class Attention(nn.Module):
q, k = concat_rel_pos( q, k = concat_rel_pos(
q.flatten(0, 1), q.flatten(0, 1),
k.flatten(0, 1), k.flatten(0, 1),
# pyrefly: ignore [bad-argument-type]
(H, W), (H, W),
# pyrefly: ignore [bad-argument-type]
x.shape[1:3], x.shape[1:3],
# pyrefly: ignore [bad-argument-type]
self.rel_pos_h, self.rel_pos_h,
# pyrefly: ignore [bad-argument-type]
self.rel_pos_w, self.rel_pos_w,
rescale=True, rescale=True,
# pyrefly: ignore [bad-argument-type]
relative_coords=self.relative_coords, relative_coords=self.relative_coords,
) )
# sdpa expects [B, nheads, H*W, C] so we transpose back # sdpa expects [B, nheads, H*W, C] so we transpose back
# pyrefly: ignore [bad-argument-type]
q = q.reshape(B, self.num_heads, H * W, -1) q = q.reshape(B, self.num_heads, H * W, -1)
# pyrefly: ignore [bad-argument-type]
k = k.reshape(B, self.num_heads, H * W, -1) k = k.reshape(B, self.num_heads, H * W, -1)
if self.attn_type == AttentionType.Vanilla: if self.attn_type == AttentionType.Vanilla:
@@ -620,8 +632,10 @@ class Attention(nn.Module):
if ndim == 4: if ndim == 4:
x = ( x = (
# pyrefly: ignore [bad-argument-type]
x.view(B, self.num_heads, H, W, -1) x.view(B, self.num_heads, H, W, -1)
.permute(0, 2, 3, 1, 4) .permute(0, 2, 3, 1, 4)
# pyrefly: ignore [bad-argument-type]
.reshape(B, H, W, -1) .reshape(B, H, W, -1)
) )
else: else:
@@ -656,6 +670,7 @@ class Block(nn.Module):
cls_token: bool = False, cls_token: bool = False,
dropout: float = 0.0, dropout: float = 0.0,
init_values: Optional[float] = None, init_values: Optional[float] = None,
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla, attn_type: AttentionType = AttentionType.Vanilla,
use_fa3: bool = False, use_fa3: bool = False,
use_rope_real: bool = False, use_rope_real: bool = False,
@@ -732,6 +747,7 @@ class Block(nn.Module):
x = self.ls1(self.attn(x)) x = self.ls1(self.attn(x))
# Reverse window partition # Reverse window partition
if self.window_size > 0: if self.window_size > 0:
# pyrefly: ignore [unbound-name]
x = window_unpartition(x, self.window_size, pad_hw, (H, W)) x = window_unpartition(x, self.window_size, pad_hw, (H, W))
x = shortcut + self.dropout(self.drop_path(x)) x = shortcut + self.dropout(self.drop_path(x))
@@ -778,6 +794,7 @@ class ViT(nn.Module):
dropout: float = 0.0, dropout: float = 0.0,
return_interm_layers: bool = False, return_interm_layers: bool = False,
init_values: Optional[float] = None, # for layerscale init_values: Optional[float] = None, # for layerscale
# pyrefly: ignore [bad-function-definition]
attn_type: AttentionType = AttentionType.Vanilla, attn_type: AttentionType = AttentionType.Vanilla,
ln_pre: bool = False, ln_pre: bool = False,
ln_post: bool = False, ln_post: bool = False,
@@ -832,6 +849,7 @@ class ViT(nn.Module):
if isinstance(rel_pos_blocks, bool) and rel_pos_blocks: if isinstance(rel_pos_blocks, bool) and rel_pos_blocks:
self.rel_pos_blocks = [True] * depth self.rel_pos_blocks = [True] * depth
else: else:
# pyrefly: ignore [not-iterable]
for i in rel_pos_blocks: for i in rel_pos_blocks:
self.rel_pos_blocks[i] = True self.rel_pos_blocks[i] = True
@@ -872,6 +890,7 @@ class ViT(nn.Module):
num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches 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)) self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
else: else:
# pyrefly: ignore [bad-assignment]
self.pos_embed = None self.pos_embed = None
# stochastic depth decay rule # stochastic depth decay rule
+3
View File
@@ -39,6 +39,7 @@ class SAM3VLBackbone(nn.Module):
""" """
super().__init__() super().__init__()
self.vision_backbone: Sam3DualViTDetNeck = ( self.vision_backbone: Sam3DualViTDetNeck = (
# pyrefly: ignore [bad-assignment]
torch.compile(visual) if compile_visual else visual torch.compile(visual) if compile_visual else visual
) )
self.language_backbone = text self.language_backbone = text
@@ -278,6 +279,7 @@ class VisionOnly(nn.Module):
eval_chunk_size=4, eval_chunk_size=4,
eval_cast_to_cpu=False, eval_cast_to_cpu=False,
scalp=0, scalp=0,
# pyrefly: ignore [bad-function-definition]
compile_mode: str = None, compile_mode: str = None,
compile_extra_args: Optional[dict] = None, compile_extra_args: Optional[dict] = None,
): ):
@@ -343,6 +345,7 @@ class TriHeadVisionOnly(VisionOnly):
eval_chunk_size=4, eval_chunk_size=4,
eval_cast_to_cpu=False, eval_cast_to_cpu=False,
scalp=0, scalp=0,
# pyrefly: ignore [bad-function-definition]
compile_mode: str = None, compile_mode: str = None,
compile_extra_args: Optional[dict] = 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, strict_state_dict_loading=False,
) )
del tracker_model.backbone del tracker_model.backbone
# pyrefly: ignore [bad-assignment]
tracker_model.backbone = None tracker_model.backbone = None
sam2_predictor = Sam3MultiplexPredictorWrapper( sam2_predictor = Sam3MultiplexPredictorWrapper(
+1
View File
@@ -6,6 +6,7 @@ import logging
import torch import torch
try: try:
# pyrefly: ignore [missing-import]
from cc_torch import get_connected_components from cc_torch import get_connected_components
HAS_CC_TORCH = True HAS_CC_TORCH = True
+1
View File
@@ -9,6 +9,7 @@ import torch
def flash_attn_func_op( def flash_attn_func_op(
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor q: torch.Tensor, k: torch.Tensor, v: torch.Tensor
) -> torch.Tensor: ) -> torch.Tensor:
# pyrefly: ignore [missing-import]
from flash_attn_interface import flash_attn_func as fa3 from flash_attn_interface import flash_attn_func as fa3
return fa3(q, k, v) return fa3(q, k, v)
+1
View File
@@ -10,6 +10,7 @@ from sam3.perflib.masks_ops import mask_iou
try: try:
# pyrefly: ignore [missing-import]
from torch_generic_nms import generic_nms as generic_nms_cuda from torch_generic_nms import generic_nms as generic_nms_cuda
GENERIC_NMS_AVAILABLE = True GENERIC_NMS_AVAILABLE = True
+16 -2
View File
@@ -432,7 +432,9 @@ def connected_components_triton(input_tensor: torch.Tensor):
_init_labels_kernel[grid_init]( _init_labels_kernel[grid_init](
input_tensor, input_tensor,
labels, labels,
# pyrefly: ignore [bad-argument-type]
numel, numel,
# pyrefly: ignore [bad-argument-type]
BLOCK_SIZE=BLOCK_SIZE, BLOCK_SIZE=BLOCK_SIZE,
) )
@@ -446,6 +448,7 @@ def connected_components_triton(input_tensor: torch.Tensor):
# --- Phase 3 --- # --- Phase 3 ---
BLOCK_SIZE = 256 BLOCK_SIZE = 256
grid_jump = lambda meta: (triton.cdiv(numel, meta["BLOCK_SIZE"]),) grid_jump = lambda meta: (triton.cdiv(numel, meta["BLOCK_SIZE"]),)
# pyrefly: ignore [bad-argument-type]
_pointer_jump_kernel[grid_jump](labels, output, numel, BLOCK_SIZE=BLOCK_SIZE) _pointer_jump_kernel[grid_jump](labels, output, numel, BLOCK_SIZE=BLOCK_SIZE)
# --- Phase 4 --- # --- Phase 4 ---
@@ -459,12 +462,23 @@ def connected_components_triton(input_tensor: torch.Tensor):
# 4.1: Count the occurrences of each label # 4.1: Count the occurrences of each label
grid_count = (triton.cdiv(numel, BLOCK_SIZE),) grid_count = (triton.cdiv(numel, BLOCK_SIZE),)
_count_labels_kernel[grid_count]( _count_labels_kernel[grid_count](
output, sizes_histogram, numel, BLOCK_SIZE=BLOCK_SIZE # pyrefly: ignore [bad-argument-type]
output,
sizes_histogram,
numel,
# pyrefly: ignore [bad-argument-type]
BLOCK_SIZE=BLOCK_SIZE,
) )
# 2.2: Broadcast the counts to the final output tensor # 2.2: Broadcast the counts to the final output tensor
grid_broadcast = (triton.cdiv(numel, BLOCK_SIZE),) grid_broadcast = (triton.cdiv(numel, BLOCK_SIZE),)
_broadcast_sizes_kernel[grid_broadcast]( _broadcast_sizes_kernel[grid_broadcast](
output, sizes_histogram, component_sizes_out, numel, BLOCK_SIZE=BLOCK_SIZE # pyrefly: ignore [bad-argument-type]
output,
sizes_histogram,
component_sizes_out,
numel,
# pyrefly: ignore [bad-argument-type]
BLOCK_SIZE=BLOCK_SIZE,
) )
return output.view(out_shape) + 1, component_sizes_out.view(out_shape) return output.view(out_shape) + 1, component_sizes_out.view(out_shape)
+2
View File
@@ -27,8 +27,10 @@ def _nms_suppression_kernel(
iou_mask_ptr: tl.tensor, # [N, N] iou_mask_ptr: tl.tensor, # [N, N]
keep_mask_ptr: tl.tensor, # [N] keep_mask_ptr: tl.tensor, # [N]
# Scalars # Scalars
# pyrefly: ignore [not-a-type]
num_boxes: tl.int32, num_boxes: tl.int32,
# Strides # Strides
# pyrefly: ignore [not-a-type]
iou_mask_stride: tl.int32, iou_mask_stride: tl.int32,
# Constexprs # Constexprs
cxpr_block_size: tl.constexpr, cxpr_block_size: tl.constexpr,
+5
View File
@@ -98,6 +98,7 @@ class MaskDecoder(nn.Module):
if self.pred_obj_scores: if self.pred_obj_scores:
self.pred_obj_score_head = nn.Linear(transformer_dim, 1) self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
if pred_obj_scores_mlp: if pred_obj_scores_mlp:
# pyrefly: ignore [bad-assignment]
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) 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 # When outputting a single mask, optionally we can dynamically fall back to the best
@@ -132,6 +133,7 @@ class MaskDecoder(nn.Module):
torch.Tensor: batched predictions of mask quality torch.Tensor: batched predictions of mask quality
torch.Tensor: batched SAM token for mask output torch.Tensor: batched SAM token for mask output
""" """
# pyrefly: ignore [bad-unpacking]
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks( masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
image_embeddings=image_embeddings, image_embeddings=image_embeddings,
image_pe=image_pe, image_pe=image_pe,
@@ -162,6 +164,7 @@ class MaskDecoder(nn.Module):
sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
# Prepare output # Prepare output
# pyrefly: ignore [bad-return]
return masks, iou_pred, sam_tokens_out, object_score_logits return masks, iou_pred, sam_tokens_out, object_score_logits
def predict_masks( def predict_masks(
@@ -219,6 +222,7 @@ class MaskDecoder(nn.Module):
upscaled_embedding = self.output_upscaling(src) upscaled_embedding = self.output_upscaling(src)
else: else:
dc1, ln1, act1, dc2, act2 = self.output_upscaling dc1, ln1, act1, dc2, act2 = self.output_upscaling
# pyrefly: ignore [not-iterable]
feat_s0, feat_s1 = high_res_features feat_s0, feat_s1 = high_res_features
upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
@@ -241,6 +245,7 @@ class MaskDecoder(nn.Module):
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 # 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) object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
# pyrefly: ignore [bad-return]
return masks, iou_pred, mask_tokens_out, object_score_logits return masks, iou_pred, mask_tokens_out, object_score_logits
def _get_stability_scores(self, mask_logits): def _get_stability_scores(self, mask_logits):
+8
View File
@@ -97,21 +97,25 @@ class PromptEncoder(nn.Module):
) )
point_embedding = torch.where( point_embedding = torch.where(
(labels == 0).unsqueeze(-1), (labels == 0).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[0].weight, point_embedding + self.point_embeddings[0].weight,
point_embedding, point_embedding,
) )
point_embedding = torch.where( point_embedding = torch.where(
(labels == 1).unsqueeze(-1), (labels == 1).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[1].weight, point_embedding + self.point_embeddings[1].weight,
point_embedding, point_embedding,
) )
point_embedding = torch.where( point_embedding = torch.where(
(labels == 2).unsqueeze(-1), (labels == 2).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[2].weight, point_embedding + self.point_embeddings[2].weight,
point_embedding, point_embedding,
) )
point_embedding = torch.where( point_embedding = torch.where(
(labels == 3).unsqueeze(-1), (labels == 3).unsqueeze(-1),
# pyrefly: ignore [unsupported-operation]
point_embedding + self.point_embeddings[3].weight, point_embedding + self.point_embeddings[3].weight,
point_embedding, point_embedding,
) )
@@ -124,7 +128,9 @@ class PromptEncoder(nn.Module):
corner_embedding = self.pe_layer.forward_with_coords( corner_embedding = self.pe_layer.forward_with_coords(
coords, self.input_image_size coords, self.input_image_size
) )
# pyrefly: ignore [unsupported-operation]
corner_embedding[:, 0, :] += self.point_embeddings[2].weight corner_embedding[:, 0, :] += self.point_embeddings[2].weight
# pyrefly: ignore [unsupported-operation]
corner_embedding[:, 1, :] += self.point_embeddings[3].weight corner_embedding[:, 1, :] += self.point_embeddings[3].weight
return corner_embedding return corner_embedding
@@ -152,6 +158,7 @@ class PromptEncoder(nn.Module):
return 1 return 1
def _get_device(self) -> torch.device: def _get_device(self) -> torch.device:
# pyrefly: ignore [bad-return]
return self.point_embeddings[0].weight.device return self.point_embeddings[0].weight.device
def forward( def forward(
@@ -217,6 +224,7 @@ class PositionEmbeddingRandom(nn.Module):
"""Positionally encode points that are normalized to [0,1].""" """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 # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
coords = 2 * coords - 1 coords = 2 * coords - 1
# pyrefly: ignore [unsupported-operation]
coords = coords @ self.positional_encoding_gaussian_matrix coords = coords @ self.positional_encoding_gaussian_matrix
coords = 2 * np.pi * coords coords = 2 * np.pi * coords
# outputs d_1 x ... x d_n x C shape # outputs d_1 x ... x d_n x C shape
+1
View File
@@ -160,4 +160,5 @@ class VisionRotaryEmbeddingVE(nn.Module):
self.register_buffer("freqs_sin", freqs_sin) self.register_buffer("freqs_sin", freqs_sin)
def forward(self, t: torch.Tensor): def forward(self, t: torch.Tensor):
# pyrefly: ignore [unsupported-operation]
return t * self.freqs_cos + rotate_half(t) * self.freqs_sin return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
+1
View File
@@ -195,6 +195,7 @@ class Attention(nn.Module):
num_heads: int, num_heads: int,
downsample_rate: int = 1, downsample_rate: int = 1,
dropout: float = 0.0, dropout: float = 0.0,
# pyrefly: ignore [bad-function-definition]
kv_in_dim: int = None, kv_in_dim: int = None,
use_fa3: bool = False, use_fa3: bool = False,
) -> None: ) -> None:
+49 -7
View File
@@ -211,9 +211,11 @@ def collate_fn_api(
for q in data.find_queries: for q in data.find_queries:
stage_id = q.query_processing_order stage_id = q.query_processing_order
# pyrefly: ignore [missing-attribute]
stages[stage_id].img_ids.append(q.image_id + offset_img_id) stages[stage_id].img_ids.append(q.image_id + offset_img_id)
if q.query_text not in text_batch: if q.query_text not in text_batch:
text_batch.append(q.query_text) text_batch.append(q.query_text)
# pyrefly: ignore [missing-attribute]
stages[stage_id].text_ids.append(text_batch.index(q.query_text)) stages[stage_id].text_ids.append(text_batch.index(q.query_text))
assert q.inference_metadata is not None, ( assert q.inference_metadata is not None, (
@@ -229,52 +231,68 @@ def collate_fn_api(
assert q.input_bbox_label is not None assert q.input_bbox_label is not None
nb_boxes = q.input_bbox.numel() // 4 nb_boxes = q.input_bbox.numel() // 4
assert len(q.input_bbox_label) == nb_boxes assert len(q.input_bbox_label) == nb_boxes
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes.append(q.input_bbox.view(nb_boxes, 4)) stages[stage_id].input_boxes.append(q.input_bbox.view(nb_boxes, 4))
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes_label.append( stages[stage_id].input_boxes_label.append(
q.input_bbox_label.view(nb_boxes) q.input_bbox_label.view(nb_boxes)
) )
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes_mask.append( stages[stage_id].input_boxes_mask.append(
torch.zeros(nb_boxes, dtype=torch.bool) torch.zeros(nb_boxes, dtype=torch.bool)
) )
else: else:
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes.append(torch.zeros(0, 4)) stages[stage_id].input_boxes.append(torch.zeros(0, 4))
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes_label.append( stages[stage_id].input_boxes_label.append(
torch.zeros(0, dtype=torch.bool) torch.zeros(0, dtype=torch.bool)
) )
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_boxes_mask.append( stages[stage_id].input_boxes_mask.append(
torch.ones(0, dtype=torch.bool) torch.ones(0, dtype=torch.bool)
) )
if q.input_points is not None: if q.input_points is not None:
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_points.append( stages[stage_id].input_points.append(
q.input_points.squeeze(0) # Strip a trivial batch index q.input_points.squeeze(0) # Strip a trivial batch index
) )
# All masks will be padded up to the longest length # All masks will be padded up to the longest length
# with 1s before final conversion to batchd tensors # with 1s before final conversion to batchd tensors
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_points_mask.append( stages[stage_id].input_points_mask.append(
torch.zeros(q.input_points.shape[1]) torch.zeros(q.input_points.shape[1])
) )
else: else:
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_points.append( stages[stage_id].input_points.append(
torch.empty(0, input_points_embedding_dim) torch.empty(0, input_points_embedding_dim)
) )
# pyrefly: ignore [missing-attribute]
stages[stage_id].input_points_mask.append(torch.empty(0)) stages[stage_id].input_points_mask.append(torch.empty(0))
current_out_boxes = [] current_out_boxes = []
current_out_object_ids = [] current_out_object_ids = []
# Set the object ids referred to by this query # Set the object ids referred to by this query
# pyrefly: ignore [missing-attribute]
stages[stage_id].object_ids.append(q.object_ids_output) stages[stage_id].object_ids.append(q.object_ids_output)
for object_id in q.object_ids_output: for object_id in q.object_ids_output:
current_out_boxes.append( current_out_boxes.append(
data.images[q.image_id].objects[object_id].bbox data.images[q.image_id].objects[object_id].bbox
) )
current_out_object_ids.append(object_id) current_out_object_ids.append(object_id)
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].boxes.extend(current_out_boxes) find_targets[stage_id].boxes.extend(current_out_boxes)
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].object_ids.extend(current_out_object_ids) find_targets[stage_id].object_ids.extend(current_out_object_ids)
if repeats > 0: if repeats > 0:
for _ in range(repeats): for _ in range(repeats):
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].repeated_boxes.extend(current_out_boxes) find_targets[stage_id].repeated_boxes.extend(current_out_boxes)
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].num_boxes.append(len(current_out_boxes)) find_targets[stage_id].num_boxes.append(len(current_out_boxes))
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].is_exhaustive.append(q.is_exhaustive) find_targets[stage_id].is_exhaustive.append(q.is_exhaustive)
if with_seg_masks: if with_seg_masks:
@@ -287,11 +305,15 @@ def collate_fn_api(
current_is_valid_segment.append(1) current_is_valid_segment.append(1)
else: else:
dummy_mask = torch.zeros( dummy_mask = torch.zeros(
data.images[q.image_id].data.shape[-2:], dtype=torch.bool # pyrefly: ignore [missing-attribute]
data.images[q.image_id].data.shape[-2:],
dtype=torch.bool,
) )
current_seg_mask.append(dummy_mask) current_seg_mask.append(dummy_mask)
current_is_valid_segment.append(0) current_is_valid_segment.append(0)
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].segments.extend(current_seg_mask) find_targets[stage_id].segments.extend(current_seg_mask)
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].is_valid_segment.extend(current_is_valid_segment) find_targets[stage_id].is_valid_segment.extend(current_is_valid_segment)
else: else:
# We are not loading segmentation masks # We are not loading segmentation masks
@@ -299,6 +321,7 @@ def collate_fn_api(
find_targets[stage_id].is_valid_segment = None find_targets[stage_id].is_valid_segment = None
if q.semantic_target is not None: if q.semantic_target is not None:
# pyrefly: ignore [missing-attribute]
find_targets[stage_id].semantic_segments.append(q.semantic_target) find_targets[stage_id].semantic_segments.append(q.semantic_target)
offset_img_id += len(data.images) offset_img_id += len(data.images)
@@ -306,24 +329,39 @@ def collate_fn_api(
# Pad input points to equal sequence lengths # Pad input points to equal sequence lengths
for i in range(len(stages)): for i in range(len(stages)):
stages[i].input_points = pad_tensor_list_to_longest( stages[i].input_points = pad_tensor_list_to_longest(
stages[i].input_points, dim=0, pad_val=0 # pyrefly: ignore [bad-argument-type]
stages[i].input_points,
dim=0,
pad_val=0,
) )
# Masked-out regions indicated by 1s. # Masked-out regions indicated by 1s.
stages[i].input_points_mask = pad_tensor_list_to_longest( stages[i].input_points_mask = pad_tensor_list_to_longest(
stages[i].input_points_mask, dim=0, pad_val=1 # pyrefly: ignore [bad-argument-type]
stages[i].input_points_mask,
dim=0,
pad_val=1,
) )
# Pad input boxes to equal sequence lengths # Pad input boxes to equal sequence lengths
for i in range(len(stages)): for i in range(len(stages)):
stages[i].input_boxes = pad_tensor_list_to_longest( stages[i].input_boxes = pad_tensor_list_to_longest(
stages[i].input_boxes, dim=0, pad_val=0 # pyrefly: ignore [bad-argument-type]
stages[i].input_boxes,
dim=0,
pad_val=0,
) )
stages[i].input_boxes_label = pad_tensor_list_to_longest( stages[i].input_boxes_label = pad_tensor_list_to_longest(
stages[i].input_boxes_label, dim=0, pad_val=0 # pyrefly: ignore [bad-argument-type]
stages[i].input_boxes_label,
dim=0,
pad_val=0,
) )
# Masked-out regions indicated by 1s. # Masked-out regions indicated by 1s.
stages[i].input_boxes_mask = pad_tensor_list_to_longest( stages[i].input_boxes_mask = pad_tensor_list_to_longest(
stages[i].input_boxes_mask, dim=0, pad_val=1 # pyrefly: ignore [bad-argument-type]
stages[i].input_boxes_mask,
dim=0,
pad_val=1,
) )
# Convert to tensors # Convert to tensors
@@ -333,7 +371,9 @@ def collate_fn_api(
find_metadatas[i] = convert_my_tensors(find_metadatas[i]) find_metadatas[i] = convert_my_tensors(find_metadatas[i])
# get padded representation for the boxes # get padded representation for the boxes
find_targets[i].boxes_padded = packed_to_padded_naive( find_targets[i].boxes_padded = packed_to_padded_naive(
find_targets[i].boxes.view(-1, 4), find_targets[i].num_boxes # pyrefly: ignore [missing-attribute]
find_targets[i].boxes.view(-1, 4),
find_targets[i].num_boxes,
) )
find_targets[i].object_ids_padded = packed_to_padded_naive( find_targets[i].object_ids_padded = packed_to_padded_naive(
find_targets[i].object_ids, find_targets[i].num_boxes, fill_value=-1 find_targets[i].object_ids, find_targets[i].num_boxes, fill_value=-1
@@ -342,7 +382,9 @@ def collate_fn_api(
# Finalize the image batch # Finalize the image batch
# check sizes # check sizes
for img in img_batch[1:]: for img in img_batch[1:]:
# pyrefly: ignore [missing-attribute]
assert img.shape == img_batch[0].shape, "All images must have the same size" 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) image_batch = torch.stack(img_batch)
if load_image_in_fp16: if load_image_in_fp16:
# Optionally, cast the image tensors to fp16, which helps save GPU memory on # Optionally, cast the image tensors to fp16, which helps save GPU memory on
+6
View File
@@ -157,6 +157,7 @@ class CustomCocoDetectionAPI(VisionDataset):
zstd_dict_path=None, zstd_dict_path=None,
filter_query=None, filter_query=None,
coco_json_loader: Callable = COCO_FROM_JSON, coco_json_loader: Callable = COCO_FROM_JSON,
# pyrefly: ignore [bad-function-definition]
limit_ids: int = None, limit_ids: int = None,
) -> None: ) -> None:
super().__init__(root) super().__init__(root)
@@ -182,6 +183,7 @@ class CustomCocoDetectionAPI(VisionDataset):
) -> Tuple[List[Tuple[int, PILImage.Image]], List[Dict[str, Any]]]: ) -> Tuple[List[Tuple[int, PILImage.Image]], List[Dict[str, Any]]]:
all_images = [] all_images = []
all_img_metadata = [] all_img_metadata = []
# pyrefly: ignore [missing-attribute]
for current_meta in self.coco.loadImagesFromDatapoint(datapoint_id): for current_meta in self.coco.loadImagesFromDatapoint(datapoint_id):
img_id = current_meta["id"] img_id = current_meta["id"]
if img_ids_to_load is not None and img_id not in img_ids_to_load: if img_ids_to_load is not None and img_id not in img_ids_to_load:
@@ -256,7 +258,9 @@ class CustomCocoDetectionAPI(VisionDataset):
def _load_datapoint(self, index: int) -> Datapoint: def _load_datapoint(self, index: int) -> Datapoint:
"""A separate method for easy overriding in subclasses.""" """A separate method for easy overriding in subclasses."""
id = self.ids[index].item() id = self.ids[index].item()
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id) pil_images, img_metadata = self._load_images(id)
# pyrefly: ignore [missing-attribute]
queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id) queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id)
return self.load_queries(pil_images, annotations, queries, img_metadata) return self.load_queries(pil_images, annotations, queries, img_metadata)
@@ -454,6 +458,7 @@ class Sam3ImageDataset(CustomCocoDetectionAPI):
zstd_dict_path=None, zstd_dict_path=None,
filter_query=None, filter_query=None,
coco_json_loader: Callable = COCO_FROM_JSON, coco_json_loader: Callable = COCO_FROM_JSON,
# pyrefly: ignore [bad-function-definition]
limit_ids: int = None, limit_ids: int = None,
): ):
super(Sam3ImageDataset, self).__init__( super(Sam3ImageDataset, self).__init__(
@@ -483,6 +488,7 @@ class Sam3ImageDataset(CustomCocoDetectionAPI):
self._MAX_RETRIES = 100 self._MAX_RETRIES = 100
# pyrefly: ignore [bad-override-param-name]
def __getitem__(self, idx): def __getitem__(self, idx):
return self.__orig_getitem__(idx) return self.__orig_getitem__(idx)
+7 -1
View File
@@ -18,7 +18,6 @@ import torchvision
# from decord import cpu, VideoReader # from decord import cpu, VideoReader
from iopath.common.file_io import PathManager from iopath.common.file_io import PathManager
from PIL import Image as PILImage
from .sam3_image_dataset import Datapoint, Sam3ImageDataset from .sam3_image_dataset import Datapoint, Sam3ImageDataset
@@ -92,6 +91,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
def _load_datapoint(self, index: int) -> Datapoint: def _load_datapoint(self, index: int) -> Datapoint:
id = self.ids[index].item() id = self.ids[index].item()
# pyrefly: ignore [missing-attribute]
queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id) queries, annotations = self.coco.loadQueriesAndAnnotationsFromDatapoint(id)
# we subsample the video frames during training # we subsample the video frames during training
@@ -115,6 +115,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
remap_stage_id=True, remap_stage_id=True,
reverse_time_axis=reverse_time_axis, reverse_time_axis=reverse_time_axis,
) )
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id, kept_img_ids) pil_images, img_metadata = self._load_images(id, kept_img_ids)
if reverse_time_axis: if reverse_time_axis:
# reverse the temporal ordering of the images and their metadata # reverse the temporal ordering of the images and their metadata
@@ -122,6 +123,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
pil_images = pil_images[::-1] pil_images = pil_images[::-1]
img_metadata = img_metadata[::-1] img_metadata = img_metadata[::-1]
else: else:
# pyrefly: ignore [bad-argument-type]
pil_images, img_metadata = self._load_images(id) pil_images, img_metadata = self._load_images(id)
# check that all the images have the same image size (they are expected # check that all the images have the same image size (they are expected
@@ -262,7 +264,9 @@ class VideoGroundingDataset(Sam3ImageDataset):
assert query.query_processing_order == 0 assert query.query_processing_order == 0
# check and make sure that a query doesn't contain pointers or references # check and make sure that a query doesn't contain pointers or references
# to other queries (that cannot be tiled) # to other queries (that cannot be tiled)
# pyrefly: ignore [missing-attribute]
assert query.ptr_x is None and query.ptr_y is None assert query.ptr_x is None and query.ptr_y is None
# pyrefly: ignore [missing-attribute]
assert query.ptr_mem is None assert query.ptr_mem is None
# assert query.wkdata_qid is None # assert query.wkdata_qid is None
# assert query.other_positive_qids is None # assert query.other_positive_qids is None
@@ -295,6 +299,7 @@ class VideoGroundingDataset(Sam3ImageDataset):
images=tiled_images, images=tiled_images,
raw_images=tiled_raw_images, raw_images=tiled_raw_images,
find_queries=tiled_find_queries, find_queries=tiled_find_queries,
# pyrefly: ignore [unexpected-keyword]
get_queries=tiled_get_queries, get_queries=tiled_get_queries,
) )
@@ -323,5 +328,6 @@ class VideoGroundingDataset(Sam3ImageDataset):
images=datapoint.images, images=datapoint.images,
raw_images=datapoint.raw_images, raw_images=datapoint.raw_images,
find_queries=sampled_find_queries, find_queries=sampled_find_queries,
# pyrefly: ignore [missing-attribute, unexpected-keyword]
get_queries=datapoint.get_queries, get_queries=datapoint.get_queries,
) )
+2
View File
@@ -32,12 +32,14 @@ class TorchDataset:
if enable_distributed_sampler: if enable_distributed_sampler:
self.sampler = DistributedSampler(self.dataset, shuffle=self.shuffle) self.sampler = DistributedSampler(self.dataset, shuffle=self.shuffle)
else: else:
# pyrefly: ignore [bad-assignment]
self.sampler = None self.sampler = None
def get_loader(self, epoch) -> Iterable: def get_loader(self, epoch) -> Iterable:
if self.sampler: if self.sampler:
self.sampler.set_epoch(epoch) self.sampler.set_epoch(epoch)
if hasattr(self.dataset, "epoch"): if hasattr(self.dataset, "epoch"):
# pyrefly: ignore [missing-attribute]
self.dataset.epoch = epoch self.dataset.epoch = epoch
if hasattr(self.dataset, "set_epoch"): if hasattr(self.dataset, "set_epoch"):
self.dataset.set_epoch(epoch) self.dataset.set_epoch(epoch)
+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" "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): def get_loss(self, outputs, targets, indices, num_boxes):
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape" assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
assert outputs["pred_logits"].shape[-1] == 1, "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"]) self.target_keys.extend(["boxes", "boxes_xyxy"])
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes): 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 """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] 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 return losses
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes): def get_loss(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the masks: the focal loss and the dice loss. """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] 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_head = presence_head
self.presence_loss = presence_loss self.presence_loss = presence_loss
# pyrefly: ignore [bad-override]
def get_loss(self, out_dict, targets): def get_loss(self, out_dict, targets):
outputs = out_dict["semantic_seg"] outputs = out_dict["semantic_seg"]
presence_logit = out_dict["presence_logit"] presence_logit = out_dict["presence_logit"]
@@ -1170,6 +1174,7 @@ class Det2TrkAssoc(LossWithWeights):
if self.use_fp_loss: if self.use_fp_loss:
self.target_keys.append("is_exhaustive") self.target_keys.append("is_exhaustive")
# pyrefly: ignore [bad-override]
def get_loss(self, outputs, targets, indices, num_boxes): def get_loss(self, outputs, targets, indices, num_boxes):
det2trk_assoc_logits = outputs["det2trk_assoc_logits"] det2trk_assoc_logits = outputs["det2trk_assoc_logits"]
device = det2trk_assoc_logits.device device = det2trk_assoc_logits.device
@@ -1237,6 +1242,7 @@ class TrackingByDetectionAssoc(LossWithWeights):
assert "loss_det2trk_assoc" in self.weight_dict assert "loss_det2trk_assoc" in self.weight_dict
assert "loss_trk2det_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): def get_loss(self, outputs, targets, indices, num_boxes):
# Part A: gather object id matching between detection and tracking # Part A: gather object id matching between detection and tracking
det2trk_assoc_logits = outputs["det2trk_assoc_logits"] # (B, Q_det+1, Q_trk+1) 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) return loss.view(input_shape)
@staticmethod @staticmethod
# pyrefly: ignore [bad-override]
def backward(ctx, grad_output): def backward(ctx, grad_output):
inputs, targets = ctx.saved_tensors inputs, targets = ctx.saved_tensors
alpha = ctx.alpha alpha = ctx.alpha
@@ -294,6 +295,7 @@ class SigmoidFocalLossReduced(torch.autograd.Function):
return loss.sum() return loss.sum()
@staticmethod @staticmethod
# pyrefly: ignore [bad-override]
def backward(ctx, grad_output): def backward(ctx, grad_output):
inputs, targets = ctx.saved_tensors inputs, targets = ctx.saved_tensors
alpha = ctx.alpha alpha = ctx.alpha
+4 -1
View File
@@ -9,6 +9,7 @@ import numpy as np
# Check if Numba is available # Check if Numba is available
HAS_NUMBA = False HAS_NUMBA = False
try: try:
# pyrefly: ignore [missing-import]
import numba as nb import numba as nb
HAS_NUMBA = True HAS_NUMBA = True
@@ -70,6 +71,7 @@ def process_track_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
# Suppress non-kept tracks # Suppress non-kept tracks
for idx, track in enumerate(track_detections): for idx, track in enumerate(track_detections):
if idx not in keep: if idx not in keep:
# pyrefly: ignore [bad-argument-type]
tracks[track["track_idx"]]["bboxes"] = [None] * len(track["bboxes"]) tracks[track["track_idx"]]["bboxes"] = [None] * len(track["bboxes"])
return video_groups return video_groups
@@ -103,6 +105,7 @@ def process_frame_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
# Apply NMS # Apply NMS
if frame_detections: if frame_detections:
# pyrefly: ignore [bad-argument-type]
bboxes = np.stack([d["bbox"] for d in frame_detections]) bboxes = np.stack([d["bbox"] for d in frame_detections])
scores = np.array( scores = np.array(
[d["score"] for d in frame_detections], dtype=np.float32 [d["score"] for d in frame_detections], dtype=np.float32
@@ -155,7 +158,7 @@ def compute_track_iou_matrix(
if HAS_NUMBA: if HAS_NUMBA:
# pyrefly: ignore [unbound-name]
@nb.jit(nopython=True, parallel=True) @nb.jit(nopython=True, parallel=True)
def _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas): def _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas):
"""Numba-optimized IoU matrix computation for track-level NMS""" """Numba-optimized IoU matrix computation for track-level NMS"""
+22 -3
View File
@@ -103,6 +103,7 @@ def set_default_parameters(
if default_count == 0: if default_count == 0:
# No default scheduler specified, add a default, but without any scheduler # No default scheduler specified, add a default, but without any scheduler
# for that option # for that option
# pyrefly: ignore [bad-argument-type]
scheduler_cfgs.append({"parameter_names": default_params}) scheduler_cfgs.append({"parameter_names": default_params})
@@ -122,6 +123,7 @@ def name_constraints_to_parameters(
param_constraints. param_constraints.
""" """
matching_names = set.intersection(*param_constraints) matching_names = set.intersection(*param_constraints)
# pyrefly: ignore [bad-return]
return [value for name, value in named_parameters.items() if name in matching_names] return [value for name, value in named_parameters.items() if name in matching_names]
@@ -218,6 +220,7 @@ def unix_module_cls_pattern_to_parameter_names(
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} " f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
) )
allowed_parameter_names.append(matching_parameters) allowed_parameter_names.append(matching_parameters)
# pyrefly: ignore [bad-argument-type]
return set.union(*allowed_parameter_names) return set.union(*allowed_parameter_names)
@@ -260,8 +263,12 @@ def _unix_pattern_to_parameter_names(
""" """
if "param_names" not in scheduler_cfg and "module_cls_names" not in scheduler_cfg: if "param_names" not in scheduler_cfg and "module_cls_names" not in scheduler_cfg:
return None return None
# pyrefly: ignore [missing-attribute]
return unix_param_pattern_to_parameter_names( return unix_param_pattern_to_parameter_names(
scheduler_cfg.get("param_names"), parameter_names # pyrefly: ignore [bad-argument-type]
scheduler_cfg.get("param_names"),
# pyrefly: ignore [bad-argument-type]
parameter_names,
).union( ).union(
unix_module_cls_pattern_to_parameter_names( unix_module_cls_pattern_to_parameter_names(
scheduler_cfg.get("module_cls_names"), module_cls_to_param_names scheduler_cfg.get("module_cls_names"), module_cls_to_param_names
@@ -270,7 +277,10 @@ def _unix_pattern_to_parameter_names(
def get_module_cls_to_param_names( def get_module_cls_to_param_names(
model: nn.Module, param_allowlist: Set[str] = None # pyrefly: ignore [bad-function-definition]
model: nn.Module,
# pyrefly: ignore [bad-function-definition]
param_allowlist: Set[str] = None,
) -> Dict[Type, str]: ) -> Dict[Type, str]:
"""Produce a mapping from all the modules classes to the names of parames they own. """Produce a mapping from all the modules classes to the names of parames they own.
@@ -290,13 +300,16 @@ def get_module_cls_to_param_names(
full_param_name = get_full_parameter_name(module_name, param_name) full_param_name = get_full_parameter_name(module_name, param_name)
if param_allowlist is None or full_param_name in param_allowlist: if param_allowlist is None or full_param_name in param_allowlist:
module_cls_to_params[module_cls].add(full_param_name) module_cls_to_params[module_cls].add(full_param_name)
# pyrefly: ignore [bad-return]
return module_cls_to_params return module_cls_to_params
def construct_optimizer( def construct_optimizer(
model: torch.nn.Module, model: torch.nn.Module,
optimizer_conf: Any, optimizer_conf: Any,
# pyrefly: ignore [bad-function-definition]
options_conf: Mapping[str, List] = None, options_conf: Mapping[str, List] = None,
# pyrefly: ignore [bad-function-definition]
param_group_modifiers_conf: List[Callable] = None, param_group_modifiers_conf: List[Callable] = None,
param_allowlist: Optional[Set[str]] = None, param_allowlist: Optional[Set[str]] = None,
validate_param_groups=True, validate_param_groups=True,
@@ -360,7 +373,10 @@ def construct_optimizer(
scheduler_cfgs=all_scheduler_cfgs, model=model scheduler_cfgs=all_scheduler_cfgs, model=model
) )
schedulers, param_groups = map_scheduler_cfgs_to_param_groups( schedulers, param_groups = map_scheduler_cfgs_to_param_groups(
all_scheduler_cfgs, named_parameters # pyrefly: ignore [bad-argument-type]
all_scheduler_cfgs,
# pyrefly: ignore [bad-argument-type]
named_parameters,
) )
if validate_param_groups: if validate_param_groups:
validate_param_group_params(param_groups, model) validate_param_group_params(param_groups, model)
@@ -403,6 +419,7 @@ class ValueScaler:
return val * self.mult_val return val * self.mult_val
# pyrefly: ignore [bad-function-definition]
def rgetattr(obj, rattrs: str = None): def rgetattr(obj, rattrs: str = None):
""" """
Like getattr(), but supports dotted notation for nested objects. Like getattr(), but supports dotted notation for nested objects.
@@ -422,6 +439,7 @@ def layer_decay_param_modifier(
layer_decay_value: float, layer_decay_value: float,
layer_decay_min: Optional[float] = None, layer_decay_min: Optional[float] = None,
apply_to: Optional[str] = None, apply_to: Optional[str] = None,
# pyrefly: ignore [bad-function-definition]
overrides: List[Dict] = (), overrides: List[Dict] = (),
) -> List[List[Dict]]: ) -> List[List[Dict]]:
""" """
@@ -443,6 +461,7 @@ def layer_decay_param_modifier(
Returns Returns
- scheduler_configs: same structure as the input, elements can be modified - scheduler_configs: same structure as the input, elements can be modified
""" """
# pyrefly: ignore [bad-argument-type]
model = rgetattr(model, apply_to) model = rgetattr(model, apply_to)
num_layers = model.get_num_layers() + 1 num_layers = model.get_num_layers() + 1
layer_decays = [ layer_decays = [
+1
View File
@@ -10,6 +10,7 @@ import traceback
from argparse import ArgumentParser from argparse import ArgumentParser
from copy import deepcopy from copy import deepcopy
# pyrefly: ignore [missing-import]
import submitit import submitit
import torch import torch
from hydra import compose, initialize_config_module from hydra import compose, initialize_config_module
+24 -1
View File
@@ -68,6 +68,7 @@ class OptimAMPConf:
@dataclass @dataclass
class OptimConf: class OptimConf:
# pyre-fixme[8]: Attribute has type `Optimizer`; used as `None`.
optimizer: torch.optim.Optimizer = None optimizer: torch.optim.Optimizer = None
options: Optional[Dict[str, Any]] = None options: Optional[Dict[str, Any]] = None
param_group_modifiers: Optional[List] = None param_group_modifiers: Optional[List] = None
@@ -111,6 +112,7 @@ class CheckpointConf:
save_freq: int save_freq: int
save_list: List[int] = field(default_factory=list) save_list: List[int] = field(default_factory=list)
model_weight_initializer: Any = None model_weight_initializer: Any = None
# pyre-fixme[8]: Attribute has type `List[str]`; used as `None`.
save_best_meters: List[str] = None save_best_meters: List[str] = None
skip_saving_parameters: List[str] = field(default_factory=list) skip_saving_parameters: List[str] = field(default_factory=list)
initialize_after_preemption: Optional[bool] = None initialize_after_preemption: Optional[bool] = None
@@ -157,7 +159,9 @@ class Trainer:
accelerator: str = "cuda", accelerator: str = "cuda",
seed_value: int = 123, seed_value: int = 123,
val_epoch_freq: int = 1, val_epoch_freq: int = 1,
# pyre-fixme[9]: distributed has type `Dict[str, bool]`; used as `None`.
distributed: Dict[str, bool] = None, distributed: Dict[str, bool] = None,
# pyre-fixme[9]: cuda has type `Dict[str, bool]`; used as `None`.
cuda: Dict[str, bool] = None, cuda: Dict[str, bool] = None,
env_variables: Optional[Dict[str, Any]] = None, env_variables: Optional[Dict[str, Any]] = None,
optim: Optional[Dict[str, Any]] = None, optim: Optional[Dict[str, Any]] = None,
@@ -183,7 +187,12 @@ class Trainer:
self.meters_conf = meters self.meters_conf = meters
self.loss_conf = loss self.loss_conf = loss
self.gradient_accumulation_steps = gradient_accumulation_steps self.gradient_accumulation_steps = gradient_accumulation_steps
# pyre-fixme[9]: distributed has type `Dict[str, bool]`; used as
# `DistributedConf`.
# pyre-fixme[6]: For 1st argument expected `Optional[str]` but got
# `Union[bool, _VT]`.
distributed = DistributedConf(**distributed or {}) distributed = DistributedConf(**distributed or {})
# pyre-fixme[9]: cuda has type `Dict[str, bool]`; used as `CudaConf`.
cuda = CudaConf(**cuda or {}) cuda = CudaConf(**cuda or {})
self.where = 0.0 self.where = 0.0
@@ -218,6 +227,7 @@ class Trainer:
self._construct_optimizers() self._construct_optimizers()
self._setup_dataloaders() self._setup_dataloaders()
# pyre-fixme[16]: `Trainer` has no attribute `device`.
self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f") self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
if self.checkpoint_conf.resume_from is not None: if self.checkpoint_conf.resume_from is not None:
@@ -450,6 +460,7 @@ class Trainer:
self.steps = checkpoint["steps"] self.steps = checkpoint["steps"]
self.ckpt_time_elapsed = checkpoint.get("time_elapsed") self.ckpt_time_elapsed = checkpoint.get("time_elapsed")
# pyre-fixme[16]: `Optional` has no attribute `enabled`.
if self.optim_conf.amp.enabled and "scaler" in checkpoint: if self.optim_conf.amp.enabled and "scaler" in checkpoint:
self.scaler.load_state_dict(checkpoint["scaler"]) self.scaler.load_state_dict(checkpoint["scaler"])
@@ -491,7 +502,9 @@ class Trainer:
model: nn.Module, model: nn.Module,
phase: str, phase: str,
): ):
# pyre-fixme[16]: `BatchedDatapoint` has no attribute `popitem`.
key, batch = batch.popitem() key, batch = batch.popitem()
# pyre-fixme[16]: `Trainer` has no attribute `device`.
batch = copy_data_to_device(batch, self.device, non_blocking=True) batch = copy_data_to_device(batch, self.device, non_blocking=True)
find_stages = model(batch) find_stages = model(batch)
@@ -925,8 +938,12 @@ class Trainer:
accum_steps = len(batch) accum_steps = len(batch)
else: else:
accum_steps = 1 accum_steps = 1
# pyre-fixme[9]: batch has type `BatchedDatapoint`; used as
# `List[BatchedDatapoint]`.
batch = [batch] batch = [batch]
# pyre-fixme[6]: For 1st argument expected `Iterable[_T]` but got
# `BatchedDatapoint`.
for i, chunked_batch in enumerate(batch): for i, chunked_batch in enumerate(batch):
ddp_context = ( ddp_context = (
self.model.no_sync() self.model.no_sync()
@@ -936,7 +953,9 @@ class Trainer:
with ddp_context: with ddp_context:
with torch.amp.autocast( with torch.amp.autocast(
device_type="cuda", device_type="cuda",
# pyre-fixme[16]: `Optional` has no attribute `enabled`.
enabled=self.optim_conf.amp.enabled, enabled=self.optim_conf.amp.enabled,
# pyre-fixme[16]: `Optional` has no attribute `amp_dtype`.
dtype=get_amp_type(self.optim_conf.amp.amp_dtype), dtype=get_amp_type(self.optim_conf.amp.amp_dtype),
): ):
loss_dict, batch_size, extra_losses = self._step( loss_dict, batch_size, extra_losses = self._step(
@@ -961,7 +980,11 @@ class Trainer:
for extra_loss_key, extra_loss in extra_losses.items(): for extra_loss_key, extra_loss in extra_losses.items():
if extra_loss_key not in extra_loss_mts: if extra_loss_key not in extra_loss_mts:
extra_loss_mts[extra_loss_key] = AverageMeter( extra_loss_mts[extra_loss_key] = AverageMeter(
extra_loss_key, self.device, ":.2e" # pyre-fixme[16]: `Trainer` has no attribute `device`.
extra_loss_key,
# pyre-fixme[16]: `Trainer` has no attribute `device`.
self.device,
":.2e",
) )
extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size) extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size)
+1
View File
@@ -284,6 +284,7 @@ class RandomSizeCrop:
else: else:
w = random.randint(self.min_size, min(img.width, self.max_size)) w = random.randint(self.min_size, min(img.width, self.max_size))
h = random.randint(self.min_size, min(img.height, self.max_size)) h = random.randint(self.min_size, min(img.height, self.max_size))
# pyrefly: ignore [bad-argument-type]
region = T.RandomCrop.get_params(img, (h, w)) region = T.RandomCrop.get_params(img, (h, w))
result_img, result_target = crop(img, target, region) result_img, result_target = crop(img, target, region)
return result_img, result_target return result_img, result_target
+37
View File
@@ -871,10 +871,12 @@ class ToTensorAPI:
def __call__(self, datapoint: Datapoint, **kwargs): def __call__(self, datapoint: Datapoint, **kwargs):
for img in datapoint.images: for img in datapoint.images:
if self.v2: if self.v2:
# pyrefly: ignore [missing-attribute]
img.data = Fv2.to_image_tensor(img.data) img.data = Fv2.to_image_tensor(img.data)
# img.data = Fv2.to_dtype(img.data, torch.uint8, scale=True) # img.data = Fv2.to_dtype(img.data, torch.uint8, scale=True)
# img.data = Fv2.convert_image_dtype(img.data, torch.uint8) # img.data = Fv2.convert_image_dtype(img.data, torch.uint8)
else: else:
# pyrefly: ignore [bad-argument-type]
img.data = F.to_tensor(img.data) img.data = F.to_tensor(img.data)
return datapoint return datapoint
@@ -888,9 +890,11 @@ class NormalizeAPI:
def __call__(self, datapoint: Datapoint, **kwargs): def __call__(self, datapoint: Datapoint, **kwargs):
for img in datapoint.images: for img in datapoint.images:
if self.v2: if self.v2:
# pyrefly: ignore [bad-argument-type]
img.data = Fv2.convert_image_dtype(img.data, torch.float32) img.data = Fv2.convert_image_dtype(img.data, torch.float32)
img.data = Fv2.normalize(img.data, mean=self.mean, std=self.std) img.data = Fv2.normalize(img.data, mean=self.mean, std=self.std)
else: else:
# pyrefly: ignore [bad-argument-type]
img.data = F.normalize(img.data, mean=self.mean, std=self.std) img.data = F.normalize(img.data, mean=self.mean, std=self.std)
for obj in img.objects: for obj in img.objects:
boxes = obj.bbox boxes = obj.bbox
@@ -904,6 +908,7 @@ class NormalizeAPI:
for query in datapoint.find_queries: for query in datapoint.find_queries:
if query.input_bbox is not None: if query.input_bbox is not None:
boxes = query.input_bbox boxes = query.input_bbox
# pyrefly: ignore [missing-attribute]
cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:] cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
boxes = box_xyxy_to_cxcywh(boxes) boxes = box_xyxy_to_cxcywh(boxes)
boxes = boxes / torch.tensor( boxes = boxes / torch.tensor(
@@ -912,6 +917,7 @@ class NormalizeAPI:
query.input_bbox = boxes query.input_bbox = boxes
if query.input_points is not None: if query.input_points is not None:
points = query.input_points points = query.input_points
# pyrefly: ignore [missing-attribute]
cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:] 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) points = points / torch.tensor([cur_w, cur_h, 1.0], dtype=torch.float32)
query.input_points = points query.input_points = points
@@ -998,14 +1004,23 @@ class ColorJitter:
) = T.ColorJitter.get_params( ) = T.ColorJitter.get_params(
self.brightness, self.contrast, self.saturation, self.hue self.brightness, self.contrast, self.saturation, self.hue
) )
# pyrefly: ignore [unbound-name]
for fn_id in fn_idx: for fn_id in fn_idx:
# pyrefly: ignore [unbound-name]
if fn_id == 0 and brightness_factor is not None: if fn_id == 0 and brightness_factor is not None:
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_brightness(img.data, brightness_factor) img.data = F.adjust_brightness(img.data, brightness_factor)
# pyrefly: ignore [unbound-name]
elif fn_id == 1 and contrast_factor is not None: elif fn_id == 1 and contrast_factor is not None:
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_contrast(img.data, contrast_factor) img.data = F.adjust_contrast(img.data, contrast_factor)
# pyrefly: ignore [unbound-name]
elif fn_id == 2 and saturation_factor is not None: elif fn_id == 2 and saturation_factor is not None:
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_saturation(img.data, saturation_factor) img.data = F.adjust_saturation(img.data, saturation_factor)
# pyrefly: ignore [unbound-name]
elif fn_id == 3 and hue_factor is not None: elif fn_id == 3 and hue_factor is not None:
# pyrefly: ignore [bad-argument-type]
img.data = F.adjust_hue(img.data, hue_factor) img.data = F.adjust_hue(img.data, hue_factor)
return datapoint return datapoint
@@ -1058,6 +1073,7 @@ class RandomAffine:
return datapoint return datapoint
def transform_datapoint(self, datapoint: Datapoint): def transform_datapoint(self, datapoint: Datapoint):
# pyrefly: ignore [bad-argument-type]
_, height, width = F.get_dimensions(datapoint.images[0].data) _, height, width = F.get_dimensions(datapoint.images[0].data)
img_size = [width, height] img_size = [width, height]
@@ -1073,6 +1089,7 @@ class RandomAffine:
for img_idx, img in enumerate(datapoint.images): for img_idx, img in enumerate(datapoint.images):
this_masks = [ this_masks = [
# pyrefly: ignore [missing-attribute]
obj.segment.unsqueeze(0) if obj.segment is not None else None obj.segment.unsqueeze(0) if obj.segment is not None else None
for obj in img.objects for obj in img.objects
] ]
@@ -1094,9 +1111,12 @@ class RandomAffine:
transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]])) transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
else: else:
transformed_mask = F.affine( transformed_mask = F.affine(
# pyrefly: ignore [bad-argument-type]
this_masks[i], this_masks[i],
# pyrefly: ignore [bad-argument-type, unbound-name]
*affine_params, *affine_params,
interpolation=InterpolationMode.NEAREST, interpolation=InterpolationMode.NEAREST,
# pyrefly: ignore [bad-argument-type]
fill=0.0, fill=0.0,
) )
if img_idx == 0 and transformed_mask.max() == 0: if img_idx == 0 and transformed_mask.max() == 0:
@@ -1112,7 +1132,9 @@ class RandomAffine:
img.objects[i].segment = transformed_masks[i] img.objects[i].segment = transformed_masks[i]
img.data = F.affine( img.data = F.affine(
# pyrefly: ignore [bad-argument-type]
img.data, img.data,
# pyrefly: ignore [bad-argument-type, unbound-name]
*affine_params, *affine_params,
interpolation=self.image_interpolation, interpolation=self.image_interpolation,
fill=self.fill_img, fill=self.fill_img,
@@ -1174,6 +1196,7 @@ class RandomResizedCrop:
if self.consistent_transform: if self.consistent_transform:
# Create a random crop transformation # Create a random crop transformation
crop_params = T.RandomResizedCrop.get_params( crop_params = T.RandomResizedCrop.get_params(
# pyrefly: ignore [bad-argument-type]
img=datapoint.images[0].data, img=datapoint.images[0].data,
scale=self.scale, scale=self.scale,
ratio=ratio, ratio=ratio,
@@ -1183,12 +1206,14 @@ class RandomResizedCrop:
if not self.consistent_transform: if not self.consistent_transform:
# Create a random crop transformation # Create a random crop transformation
crop_params = T.RandomResizedCrop.get_params( crop_params = T.RandomResizedCrop.get_params(
# pyrefly: ignore [bad-argument-type]
img=img.data, img=img.data,
scale=self.scale, scale=self.scale,
ratio=ratio, ratio=ratio,
) )
this_masks = [ this_masks = [
# pyrefly: ignore [missing-attribute]
obj.segment.unsqueeze(0) if obj.segment is not None else None obj.segment.unsqueeze(0) if obj.segment is not None else None
for obj in img.objects for obj in img.objects
] ]
@@ -1201,7 +1226,9 @@ class RandomResizedCrop:
transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]])) transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
else: else:
transformed_mask = F.resized_crop( transformed_mask = F.resized_crop(
# pyrefly: ignore [bad-argument-type]
this_masks[i], this_masks[i],
# pyrefly: ignore [unbound-name]
*crop_params, *crop_params,
size=self.size, size=self.size,
interpolation=InterpolationMode.NEAREST, interpolation=InterpolationMode.NEAREST,
@@ -1220,7 +1247,9 @@ class RandomResizedCrop:
img.objects[i].segment = transformed_masks[i] img.objects[i].segment = transformed_masks[i]
img.data = F.resized_crop( img.data = F.resized_crop(
# pyrefly: ignore [bad-argument-type]
img.data, img.data,
# pyrefly: ignore [unbound-name]
*crop_params, *crop_params,
size=self.size, size=self.size,
interpolation=InterpolationMode.BILINEAR, interpolation=InterpolationMode.BILINEAR,
@@ -1237,6 +1266,7 @@ class ResizeToMaxIfAbove:
self.max_size = max_size self.max_size = max_size
def __call__(self, datapoint: Datapoint, **kwargs): def __call__(self, datapoint: Datapoint, **kwargs):
# pyrefly: ignore [bad-argument-type]
_, height, width = F.get_dimensions(datapoint.images[0].data) _, height, width = F.get_dimensions(datapoint.images[0].data)
if height <= self.max_size and width <= self.max_size: if height <= self.max_size and width <= self.max_size:
@@ -1252,11 +1282,14 @@ class ResizeToMaxIfAbove:
size = new_height, new_width size = new_height, new_width
for index in range(len(datapoint.images)): for index in range(len(datapoint.images)):
# pyrefly: ignore [bad-argument-type]
datapoint.images[index].data = F.resize(datapoint.images[index].data, size) datapoint.images[index].data = F.resize(datapoint.images[index].data, size)
for obj in datapoint.images[index].objects: for obj in datapoint.images[index].objects:
obj.segment = F.resize( obj.segment = F.resize(
# pyrefly: ignore [unsupported-operation]
obj.segment[None, None], obj.segment[None, None],
# pyrefly: ignore [bad-argument-type]
size, size,
interpolation=InterpolationMode.NEAREST, interpolation=InterpolationMode.NEAREST,
).squeeze() ).squeeze()
@@ -1302,6 +1335,7 @@ class MotionBlur:
if not self.consistent_transform: if not self.consistent_transform:
# Generate a new motion blur kernel for each image # Generate a new motion blur kernel for each image
kernel = self._generate_motion_blur_kernel() kernel = self._generate_motion_blur_kernel()
# pyrefly: ignore [unbound-name]
img.data = self._apply_motion_blur(img.data, kernel) img.data = self._apply_motion_blur(img.data, kernel)
return datapoint return datapoint
@@ -1364,6 +1398,7 @@ class LargeScaleJitter:
log_ratio = torch.log(torch.tensor(self.aspect_ratio_range)) log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
scale_factor = torch.empty(1).uniform_(*self.scale_range).item() scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
aspect_ratio = torch.exp( aspect_ratio = torch.exp(
# pyrefly: ignore [bad-argument-type]
torch.empty(1).uniform_(log_ratio[0], log_ratio[1]) torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
).item() ).item()
@@ -1373,10 +1408,12 @@ class LargeScaleJitter:
log_ratio = torch.log(torch.tensor(self.aspect_ratio_range)) log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
scale_factor = torch.empty(1).uniform_(*self.scale_range).item() scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
aspect_ratio = torch.exp( aspect_ratio = torch.exp(
# pyrefly: ignore [bad-argument-type]
torch.empty(1).uniform_(log_ratio[0], log_ratio[1]) torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
).item() ).item()
# Compute the dimensions of the jittered crop # Compute the dimensions of the jittered crop
# pyrefly: ignore [not-iterable]
original_width, original_height = img.data.size original_width, original_height = img.data.size
target_area = original_width * original_height * scale_factor target_area = original_width * original_height * scale_factor
crop_width = int(round((target_area * aspect_ratio) ** 0.5)) crop_width = int(round((target_area * aspect_ratio) ** 0.5))
@@ -12,8 +12,11 @@ from sam3.train.data.sam3_image_dataset import Datapoint, FindQuery, Object
class FilterDataPointQueries: class FilterDataPointQueries:
# pyrefly: ignore [bad-assignment]
find_ids_to_filter: set = None find_ids_to_filter: set = None
# pyrefly: ignore [bad-assignment]
get_ids_to_filter: set = None get_ids_to_filter: set = None
# pyrefly: ignore [bad-assignment]
obj_ids_to_filter: set = None # stored as pairs (img_id, obj_id) obj_ids_to_filter: set = None # stored as pairs (img_id, obj_id)
def identify_queries_to_filter(self, datapoint: Datapoint) -> None: def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
@@ -34,7 +37,12 @@ class FilterQueryWithText(FilterDataPointQueries):
""" """
def __init__( def __init__(
self, exclude_find_keys: List[str] = None, exclude_get_keys: List[str] = None # pyrefly: ignore [bad-function-definition]
self,
# pyrefly: ignore [bad-function-definition]
exclude_find_keys: List[str] = None,
# pyrefly: ignore [bad-function-definition]
exclude_get_keys: List[str] = None,
): ):
self.find_filter_keys = exclude_find_keys if exclude_find_keys else [] self.find_filter_keys = exclude_find_keys if exclude_find_keys else []
self.get_filter_keys = exclude_get_keys if exclude_get_keys else [] self.get_filter_keys = exclude_get_keys if exclude_get_keys else []
@@ -393,7 +401,7 @@ class FlexibleFilterFindGetQueries:
# The deletion may have removed intermediate steps, so we need to remap to make them contiguous again # The deletion may have removed intermediate steps, so we need to remap to make them contiguous again
all_stages = sorted( all_stages = sorted(
list(set(q.query_processing_order for q in datapoint.find_queries)) list({q.query_processing_order for q in datapoint.find_queries})
) )
stage_map = {qpo: i for i, qpo in enumerate(all_stages)} stage_map = {qpo: i for i, qpo in enumerate(all_stages)}
for i in range(len(datapoint.find_queries)): for i in range(len(datapoint.find_queries)):
@@ -402,12 +410,12 @@ class FlexibleFilterFindGetQueries:
# Final step, clear up objects that are not used anymore # Final step, clear up objects that are not used anymore
for img_id in range(len(datapoint.images)): for img_id in range(len(datapoint.images)):
all_objects_ids = set( all_objects_ids = {
i i
for find in datapoint.find_queries for find in datapoint.find_queries
for i in find.object_ids_output for i in find.object_ids_output
if find.image_id == img_id if find.image_id == img_id
) }
unused_ids = ( unused_ids = (
set(range(len(datapoint.images[img_id].objects))) - all_objects_ids set(range(len(datapoint.images[img_id].objects))) - all_objects_ids
) )
+3
View File
@@ -334,8 +334,11 @@ class RandomizeInputBbox:
assert isinstance(img, torch.Tensor) assert isinstance(img, torch.Tensor)
h, w = img.shape[-2:] h, w = img.shape[-2:]
# pyre-fixme[16]: Optional type has no attribute `shape`.
for box_id in range(query.input_bbox.shape[0]): for box_id in range(query.input_bbox.shape[0]):
# pyre-fixme[16]: Optional type has no attribute `__setitem__`.
query.input_bbox[box_id, :] = noise_box( query.input_bbox[box_id, :] = noise_box(
# pyre-fixme[16]: Optional type has no attribute `__getitem__`.
query.input_bbox[box_id, :].view(4), query.input_bbox[box_id, :].view(4),
(h, w), (h, w),
box_noise_std=self.box_noise_std, box_noise_std=self.box_noise_std,
+18 -2
View File
@@ -31,8 +31,12 @@ class InstanceToSemantic(object):
# we need to double check that all rles are the correct size # we need to double check that all rles are the correct size
# Otherwise cocotools will fail silently to an empty [0,0] mask # Otherwise cocotools will fail silently to an empty [0,0] mask
for seg in all_segs: for seg in all_segs:
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any] |
# Tensor` has no attribute `__getitem__`.
assert seg["size"] == all_segs[0]["size"], ( assert seg["size"] == all_segs[0]["size"], (
"Instance segments have inconsistent sizes. " "Instance segments have inconsistent sizes. "
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any]
# | Tensor` has no attribute `__getitem__`.
f"Found sizes {seg['size']} and {all_segs[0]['size']}" f"Found sizes {seg['size']} and {all_segs[0]['size']}"
) )
fquery.semantic_target = mask_utils.merge(all_segs) fquery.semantic_target = mask_utils.merge(all_segs)
@@ -54,6 +58,7 @@ class InstanceToSemantic(object):
isinstance(segment, torch.Tensor) isinstance(segment, torch.Tensor)
and segment.dtype == torch.uint8 and segment.dtype == torch.uint8
) )
# pyre-fixme[16]: Optional type has no attribute `__ior__`.
fquery.semantic_target |= segment fquery.semantic_target |= segment
if self.delete_instance: if self.delete_instance:
@@ -74,6 +79,8 @@ class RecomputeBoxesFromMasks:
# Note: if the mask is empty, the bounding box will be undefined # Note: if the mask is empty, the bounding box will be undefined
# The empty targets should be subsequently filtered # The empty targets should be subsequently filtered
obj.bbox = masks_to_boxes(obj.segment) obj.bbox = masks_to_boxes(obj.segment)
# pyre-fixme[16]: Item `None` of `None | dict[Any, Any] | Tensor`
# has no attribute `sum`.
obj.area = obj.segment.sum().item() obj.area = obj.segment.sum().item()
return datapoint return datapoint
@@ -114,6 +121,7 @@ class DecodeRle:
# segment is uint8 and remains uint8 throughout the transforms # segment is uint8 and remains uint8 throughout the transforms
obj.segment = torch.tensor(obj.segment).to(torch.uint8) obj.segment = torch.tensor(obj.segment).to(torch.uint8)
# pyre-fixme[16]: `dict` has no attribute `shape`.
if list(obj.segment.shape) != [img_h, img_w]: if list(obj.segment.shape) != [img_h, img_w]:
# Should not happen often, but adding for security # Should not happen often, but adding for security
if not warning_shown: if not warning_shown:
@@ -124,7 +132,12 @@ class DecodeRle:
warning_shown = True warning_shown = True
obj.segment = F.resize( obj.segment = F.resize(
obj.segment[None], (img_h, img_w) # pyre-fixme[6]: For 2nd argument expected `List[int]`
# but got `Tuple[int, int]`.
obj.segment[None],
# pyre-fixme[6]: For 2nd argument expected `List[int]`
# but got `Tuple[int, int]`.
(img_h, img_w),
).squeeze(0) ).squeeze(0)
assert list(obj.segment.shape) == [img_h, img_w] assert list(obj.segment.shape) == [img_h, img_w]
@@ -148,7 +161,10 @@ class DecodeRle:
warning_shown = True warning_shown = True
query.semantic_target = F.resize( 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) ).squeeze(0)
assert tuple(query.semantic_target.shape) == imgId2size[query.image_id] assert tuple(query.semantic_target.shape) == imgId2size[query.image_id]
+19 -2
View File
@@ -61,6 +61,7 @@ def filter_params_matching_unix_pattern(
all_keys = list(state_dict.keys()) all_keys = list(state_dict.keys())
included_keys = unix_pattern_to_parameter_names(patterns, all_keys) included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
# pyrefly: ignore [not-iterable]
return {k: state_dict[k] for k in included_keys} return {k: state_dict[k] for k in included_keys}
@@ -82,6 +83,7 @@ def exclude_params_matching_unix_pattern(
all_keys = list(state_dict.keys()) all_keys = list(state_dict.keys())
excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys) excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
# pyrefly: ignore [not-iterable]
return {k: v for k, v in state_dict.items() if k not in excluded_keys} return {k: v for k, v in state_dict.items() if k not in excluded_keys}
@@ -180,8 +182,12 @@ class CkptExcludeKernel:
if len(self.key_pattern) == 0: if len(self.key_pattern) == 0:
return state_dict return state_dict
exclude_keys = unix_pattern_to_parameter_names( exclude_keys = unix_pattern_to_parameter_names(
self.key_pattern, state_dict.keys() # pyrefly: ignore [bad-argument-type]
self.key_pattern,
# pyrefly: ignore [bad-argument-type]
state_dict.keys(),
) )
# pyrefly: ignore [not-iterable]
return {k: v for k, v in state_dict.items() if k not in exclude_keys} return {k: v for k, v in state_dict.items() if k not in exclude_keys}
@@ -245,6 +251,7 @@ def get_state_dict(checkpoint, ckpt_state_dict_keys):
def load_checkpoint_and_apply_kernels( def load_checkpoint_and_apply_kernels(
checkpoint_path: str, checkpoint_path: str,
# pyrefly: ignore [bad-function-definition]
checkpoint_kernels: List[Callable] = None, checkpoint_kernels: List[Callable] = None,
ckpt_state_dict_keys: Tuple[str] = ("state_dict",), ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
map_location: str = "cpu", map_location: str = "cpu",
@@ -297,13 +304,16 @@ def check_load_state_dict_errors(
missing_keys, missing_keys,
unexpected_keys, unexpected_keys,
strict: bool, strict: bool,
# pyrefly: ignore [bad-function-definition]
ignore_missing_keys: List[str] = None, ignore_missing_keys: List[str] = None,
# pyrefly: ignore [bad-function-definition]
ignore_unexpected_keys: List[str] = None, ignore_unexpected_keys: List[str] = None,
): ):
if ignore_missing_keys is not None and len(ignore_missing_keys) > 0: if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
ignored_keys = unix_pattern_to_parameter_names( ignored_keys = unix_pattern_to_parameter_names(
ignore_missing_keys, missing_keys ignore_missing_keys, missing_keys
) )
# pyrefly: ignore [not-iterable]
missing_keys = [key for key in missing_keys if key not in ignored_keys] 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: if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
@@ -311,7 +321,11 @@ def check_load_state_dict_errors(
ignore_unexpected_keys, unexpected_keys ignore_unexpected_keys, unexpected_keys
) )
unexpected_keys = [ unexpected_keys = [
key for key in unexpected_keys if key not in ignored_unexpected_keys # pyrefly: ignore [not-iterable]
key
for key in unexpected_keys
# pyrefly: ignore [not-iterable]
if key not in ignored_unexpected_keys
] ]
err = "State key mismatch." err = "State key mismatch."
@@ -330,8 +344,11 @@ def load_state_dict_into_model(
state_dict: Dict, state_dict: Dict,
model: nn.Module, model: nn.Module,
strict: bool = True, strict: bool = True,
# pyrefly: ignore [bad-function-definition]
ignore_missing_keys: List[str] = None, ignore_missing_keys: List[str] = None,
# pyrefly: ignore [bad-function-definition]
ignore_unexpected_keys: List[str] = None, ignore_unexpected_keys: List[str] = None,
# pyrefly: ignore [bad-function-definition]
checkpoint_kernels: List[Callable] = None, checkpoint_kernels: List[Callable] = None,
): ):
""" """
+4
View File
@@ -271,6 +271,7 @@ def all_reduce_max(tensor: torch.Tensor) -> torch.Tensor:
def all_reduce_op( def all_reduce_op(
tensor: torch.Tensor, tensor: torch.Tensor,
op: torch.distributed.ReduceOp, op: torch.distributed.ReduceOp,
# pyrefly: ignore [bad-function-definition]
after_op_func: Callable[[torch.Tensor], torch.Tensor] = None, after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
) -> torch.Tensor: ) -> torch.Tensor:
""" """
@@ -436,10 +437,12 @@ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True)
# Fetch from the source # Fetch from the source
length_tensor = torch.LongTensor([0]) length_tensor = torch.LongTensor([0])
length_tensor = broadcast(length_tensor, src=src) length_tensor = broadcast(length_tensor, src=src)
# pyrefly: ignore [no-matching-overload]
data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8) data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
data_tensor = broadcast(data_tensor, src=src) data_tensor = broadcast(data_tensor, src=src)
if use_disk: if use_disk:
with tempfile.TemporaryFile("r+b") as f: with tempfile.TemporaryFile("r+b") as f:
# pyrefly: ignore [bad-argument-type]
f.write(data_tensor.numpy()) f.write(data_tensor.numpy())
# remove reference to the data tensor and hope that Python garbage # remove reference to the data tensor and hope that Python garbage
# collects it # collects it
@@ -447,6 +450,7 @@ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True)
f.seek(0) f.seek(0)
obj = torch.load(f, weights_only=False) obj = torch.load(f, weights_only=False)
else: else:
# pyrefly: ignore [bad-argument-type]
buffer = io.BytesIO(data_tensor.numpy()) buffer = io.BytesIO(data_tensor.numpy())
obj = torch.load(buffer, weights_only=False) obj = torch.load(buffer, weights_only=False)
return obj return obj
+1
View File
@@ -36,6 +36,7 @@ class TensorBoardWriterWrapper:
self, self,
path: str, path: str,
*args: Any, *args: Any,
# pyrefly: ignore [bad-function-definition]
filename_suffix: str = None, filename_suffix: str = None,
summary_writer_method: Any = SummaryWriter, summary_writer_method: Any = SummaryWriter,
**kwargs: Any, **kwargs: Any,
+1
View File
@@ -712,6 +712,7 @@ def get_all_annotations_for_frame(
get_media_dir(media_dir=media_dir, dataset=dataset), file_name get_media_dir(media_dir=media_dir, dataset=dataset), file_name
) )
frame = cv2.imread(file_path) frame = cv2.imread(file_path)
# pyrefly: ignore [no-matching-overload]
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Get the masks and noun phrases annotated in this video in this frame # Get the masks and noun phrases annotated in this video in this frame
+243
View File
@@ -0,0 +1,243 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
"""
SAM3 encoder torch.compile A/B benchmark — production-faithful.
Builds ``Sam3VideoPredictorMultiGPU`` with the EXACT constructor arguments that
scene_service's ``Sam3DenseTrackingModel.load_model`` uses (see
``fbcode/genai/media_editing/project/sam_stateful/inferencer/dense_tracking.py``),
plus the ``sam3_v4.pt`` production checkpoint, with ``compile`` toggled on/off.
It then measures steady-state propagation throughput (FPS), per-frame latency,
and peak GPU memory on a synthetic moving-circles video.
This isolates the win from ``torch.compile`` (dominated by the ViT image encoder,
which is the ~1.3s hotspot) on the same model + GPU class the IPNext tenant serves.
Usage:
buck run @fbcode//mode/opt \
fbcode//deeplearning/projects/sam3_release:bench_compile -- \
--checkpoint /tmp/sam3_v4.pt --num_objects 5 --n_frames 50 --compile
# eager baseline:
buck run @fbcode//mode/opt \
fbcode//deeplearning/projects/sam3_release:bench_compile -- \
--checkpoint /tmp/sam3_v4.pt --num_objects 5 --n_frames 50 --no-compile
"""
import argparse
import getpass
import os
import time
import torch
# Reuse the author's synthetic-video + timing helpers (same package, via :sam3).
from scripts.measure_speed import main_loop, max_memory_allocated, synthesize_video_data
def build_prod_predictor(checkpoint_path: str, do_compile: bool):
"""Construct the predictor identically to Sam3DenseTrackingModel.load_model."""
from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
return Sam3VideoPredictorMultiGPU(
checkpoint_path=checkpoint_path,
bpe_path=None,
has_presence_token=True,
geo_encoder_use_img_cross_attn=True,
strict_state_dict_loading=False,
apply_temporal_disambiguation=True,
async_loading_frames=False,
video_loader_type="cv2",
compile=do_compile,
gpus_to_use=[0],
)
def time_scene_frame(
model_wrapper,
image_path: str,
labels: list[str],
n_iters: int = 12,
warmup_iters: int = 5,
) -> tuple[float, float]:
"""Replicate scene_service's per-frame SAM3 sequence (Sam3Client.getMasksStream).
For each ingested frame, subscribe_scene_objects drives exactly:
start_session(single image) -> add_prompt(label) x K -> close/reset
i.e. a FRESH session per frame (image re-encoded every frame, no cross-frame
reuse) with the K subscription labels sharing that one image encode. This is
the real production unit -- NOT video propagate_in_video. Returns (median, min)
ms per frame.
Runs warmup_iters discarded iterations first so the single-image detection path
is compiled/settled (the propagate warm-up does NOT exercise this path), then
times n_iters."""
def _one_frame() -> float:
torch.cuda.synchronize()
t0 = time.perf_counter()
resp = model_wrapper.handle_request(
{"type": "start_session", "resource_path": image_path}
)
sid = resp["session_id"]
for label in labels:
model_wrapper.handle_request(
{
"type": "add_prompt",
"session_id": sid,
"frame_index": 0,
"text": label,
}
)
torch.cuda.synchronize()
dt = (time.perf_counter() - t0) * 1000.0
model_wrapper.handle_request({"type": "reset_session", "session_id": sid})
return dt
for _ in range(warmup_iters):
_one_frame()
times_ms = [_one_frame() for _ in range(n_iters)]
times_ms.sort()
return times_ms[len(times_ms) // 2], times_ms[0] # median, min
def run(
checkpoint_path: str,
num_objects: int,
n_frames: int,
radius: int,
speed: int,
width: int,
height: int,
video_dir: str,
do_compile: bool,
full_warmup: bool = False,
native_warmup: bool = False,
) -> float:
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
synthesize_video_data(
num_objects=num_objects,
out_dir=video_dir,
radius=radius,
speed=speed,
width=width,
height=height,
n_frames=n_frames,
)
mode = "COMPILED" if do_compile else "EAGER"
print(f"\n=== Building {mode} predictor from {checkpoint_path} ===")
model_wrapper = build_prod_predictor(checkpoint_path, do_compile)
# --native-warmup mirrors the production Sam3DenseTrackingModel.warmup path:
# install the compile wrappers directly via _compile_model() (NOT via a video
# propagate) and skip the propagate rounds entirely, so the only thing that
# compiles the served graphs is the single-image add_prompt warm-up inside
# time_scene_frame. Run under TORCH_LOGS=recompiles to prove no recompile
# fires on the TIMED single-image iters (all recompiles absorbed in warmup).
best_fps = 0.0
if do_compile and native_warmup:
print("Native warmup: _compile_model() direct (no propagate)...")
model_wrapper.model._compile_model()
else:
response = model_wrapper.handle_request(
{"type": "start_session", "resource_path": video_dir}
)
session_id = response["session_id"]
if do_compile and full_warmup:
try:
print("Warming up torch.compile (varying object counts)...")
model_wrapper.model.warm_up_compilation()
except Exception as e:
print(f"warm_up_compilation() failed ({e!r}); relying on lazy compile.")
print("Warm-up rounds...")
fps = 0.0
for _ in range(3):
fps = max(main_loop(model_wrapper, session_id, "circle"), fps)
print("Timing rounds...")
for i in range(10):
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
f = main_loop(model_wrapper, session_id, "circle")
best_fps = max(best_fps, f)
print(f" round {i + 1}: {f:.2f} FPS")
max_memory_allocated()
#
# scene_service per-frame SAM3 cost: start_session(single image) + K add_prompt.
image_path = os.path.join(video_dir, "000.jpg")
scene_ms = {}
for k in (1, 3):
labels = ["circle", "square", "triangle"][:k]
med, mn = time_scene_frame(model_wrapper, image_path, labels)
scene_ms[k] = med
print(f" scene per-frame K={k} labels: {med:.2f} ms median ({mn:.2f} ms min)")
per_frame_ms = 1000.0 / best_fps if best_fps > 0 else float("nan")
print(
f"\n=== RESULT {mode}: "
f"scene/frame K=1 {scene_ms[1]:.2f} ms | K=3 {scene_ms[3]:.2f} ms | "
f"propagate {best_fps:.2f} FPS ({per_frame_ms:.2f} ms/frame) | "
f"num_objects={num_objects} {width}x{height} ==="
)
return best_fps
def main() -> None:
username = getpass.getuser()
os.environ["TORCHINDUCTOR_CACHE_DIR"] = f"/tmp/torchinductor_cache_{username}"
os.environ["USE_PERFLIB"] = "1"
parser = argparse.ArgumentParser(
description="SAM3 production-model torch.compile A/B benchmark"
)
parser.add_argument("--checkpoint", type=str, default="/tmp/sam3_v4.pt")
parser.add_argument(
"--video_dir", type=str, default="/tmp/sam3_bench_compile/synth_video"
)
parser.add_argument("--num_objects", type=int, default=5)
parser.add_argument("--n_frames", type=int, default=50)
parser.add_argument("--radius", type=int, default=50)
parser.add_argument("--speed", type=int, default=20)
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument(
"--compile",
action=argparse.BooleanOptionalAction,
default=True,
help="torch.compile the model; use --no-compile for the eager baseline",
)
parser.add_argument(
"--full-warmup",
action="store_true",
help="run prod warm_up_compilation (object-count sweep) instead of lazy compile",
)
parser.add_argument(
"--native-warmup",
action="store_true",
help="mirror prod Sam3DenseTrackingModel.warmup: _compile_model() direct + "
"single-image warm only (no propagate); validates 0 serve-time recompiles",
)
args = parser.parse_args()
run(
checkpoint_path=args.checkpoint,
num_objects=args.num_objects,
n_frames=args.n_frames,
radius=args.radius,
speed=args.speed,
width=args.width,
height=args.height,
video_dir=args.video_dir,
do_compile=args.compile,
full_warmup=args.full_warmup,
native_warmup=args.native_warmup,
)
if __name__ == "__main__":
main()
@@ -8,6 +8,8 @@ from multiprocessing import Pool
from pathlib import Path from pathlib import Path
import requests import requests
# pyrefly: ignore [missing-import]
from fathomnet.api import images from fathomnet.api import images
from tqdm import tqdm from tqdm import tqdm
@@ -10,6 +10,8 @@ from pathlib import Path
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import requests import requests
# pyrefly: ignore [missing-import]
import utils import utils
from PIL import Image from PIL import Image
from tqdm import tqdm from tqdm import tqdm
+3
View File
@@ -10,7 +10,10 @@ import sys
from concurrent.futures import as_completed, ThreadPoolExecutor from concurrent.futures import as_completed, ThreadPoolExecutor
from pathlib import Path from pathlib import Path
# pyrefly: ignore [missing-source-for-stubs]
import yt_dlp import yt_dlp
# pyrefly: ignore [missing-import]
from utils import ( from utils import (
annotation_files, annotation_files,
config, config,
+4 -2
View File
@@ -16,6 +16,8 @@ from multiprocessing import Pool
from PIL import Image from PIL import Image
from tqdm import tqdm from tqdm import tqdm
# pyrefly: ignore [missing-import]
from utils import ( from utils import (
annotation_files, annotation_files,
config, config,
@@ -76,7 +78,7 @@ def main():
with open(os.path.join(config["path_annotations"], file), "r") as f: with open(os.path.join(config["path_annotations"], file), "r") as f:
annotation = json.load(f) annotation = json.load(f)
images = annotation["images"] images = annotation["images"]
images = set( images = {
( (
image["original_video"], image["original_video"],
image["global_frame_idx"], image["global_frame_idx"],
@@ -84,7 +86,7 @@ def main():
tuple(image["image_size"]), tuple(image["image_size"]),
) )
for image in images for image in images
) }
args_list = [(image, dataset_name, config) for image in images] args_list = [(image, dataset_name, config) for image in images]
with Pool(os.cpu_count()) as pool: with Pool(os.cpu_count()) as pool:
outputs = list( outputs = list(
@@ -6,6 +6,8 @@ from multiprocessing import Pool
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
# pyrefly: ignore [missing-import]
import utils import utils
from tqdm import tqdm from tqdm import tqdm
@@ -8,6 +8,8 @@ import os
from functools import partial from functools import partial
import pandas as pd import pandas as pd
# pyrefly: ignore [missing-import]
from saco_yt1b_frame_prep_util import YtVideoPrep from saco_yt1b_frame_prep_util import YtVideoPrep
from tqdm import tqdm from tqdm import tqdm
@@ -7,6 +7,8 @@ import os
import subprocess import subprocess
import pandas as pd import pandas as pd
# pyrefly: ignore [missing-source-for-stubs]
import yt_dlp import yt_dlp
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+3
View File
@@ -153,9 +153,11 @@ def run_test(
height: int, height: int,
n_frames: int, n_frames: int,
synthesize_data: bool = True, synthesize_data: bool = True,
# pyrefly: ignore [bad-function-definition]
profile_save_dir: str = None, profile_save_dir: str = None,
profile_end_frame: int = -1, profile_end_frame: int = -1,
do_compile: bool = True, do_compile: bool = True,
# pyrefly: ignore [bad-function-definition]
checkpoint_path: str = None, checkpoint_path: str = None,
) -> float: ) -> float:
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__() torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
@@ -183,6 +185,7 @@ def run_test(
build_kwargs["checkpoint_path"] = checkpoint_path build_kwargs["checkpoint_path"] = checkpoint_path
if version == "sam3.1": if version == "sam3.1":
build_kwargs["warm_up"] = do_compile build_kwargs["warm_up"] = do_compile
# pyrefly: ignore [bad-assignment]
build_kwargs["max_num_objects"] = num_objects build_kwargs["max_num_objects"] = num_objects
model_wrapper = build_sam3_predictor(**build_kwargs) model_wrapper = build_sam3_predictor(**build_kwargs)
+28
View File
@@ -0,0 +1,28 @@
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import types
import unittest
import torch
from sam3.model.sam3_video_predictor import Sam3VideoPredictor
class TestVideoPredictorShutdown(unittest.TestCase):
def test_exits_tracker_autocast_context(self) -> None:
predictor = Sam3VideoPredictor.__new__(Sam3VideoPredictor)
context = torch.amp.autocast("cpu", dtype=torch.bfloat16)
context.__enter__()
tracker = types.SimpleNamespace(bf16_context=context)
predictor.model = types.SimpleNamespace(tracker=tracker)
predictor._all_inference_states = {}
self.assertTrue(torch.is_autocast_enabled("cpu"))
predictor.shutdown()
predictor.shutdown()
self.assertFalse(torch.is_autocast_enabled("cpu"))
self.assertIsNone(tracker.bf16_context)
if __name__ == "__main__":
unittest.main()