yayalong commited on
Commit
b349f0e
·
verified ·
1 Parent(s): 376e4e3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. third_party/GraspGen/sam3/sam3/agent/__init__.py +3 -0
  2. third_party/GraspGen/sam3/sam3/agent/agent_core.py +565 -0
  3. third_party/GraspGen/sam3/sam3/agent/client_llm.py +207 -0
  4. third_party/GraspGen/sam3/sam3/agent/client_sam3.py +139 -0
  5. third_party/GraspGen/sam3/sam3/agent/inference.py +67 -0
  6. third_party/GraspGen/sam3/sam3/agent/viz.py +118 -0
  7. third_party/GraspGen/sam3/sam3/eval/coco_reindex.py +232 -0
  8. third_party/GraspGen/sam3/sam3/eval/coco_writer.py +354 -0
  9. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/__init__.py +3 -0
  10. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.py +116 -0
  11. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/__init__.py +6 -0
  12. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/_timing.py +70 -0
  13. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/eval.py +398 -0
  14. third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/utils.py +197 -0
  15. third_party/GraspGen/sam3/sam3/eval/postprocessors.py +652 -0
  16. third_party/GraspGen/sam3/sam3/eval/saco_veval_evaluators.py +840 -0
  17. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/__init__.py +7 -0
  18. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/_timing.py +71 -0
  19. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/config.py +155 -0
  20. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/__init__.py +7 -0
  21. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/_base_dataset.py +381 -0
  22. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/coco.py +639 -0
  23. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/tao.py +661 -0
  24. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/eval.py +277 -0
  25. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/__init__.py +6 -0
  26. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.py +150 -0
  27. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/teta.py +401 -0
  28. third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/utils.py +48 -0
  29. third_party/GraspGen/sam3/sam3/eval/ytvis_coco_wrapper.py +148 -0
  30. third_party/GraspGen/sam3/sam3/model/__init__.py +3 -0
  31. third_party/GraspGen/sam3/sam3/model/act_ckpt_utils.py +116 -0
  32. third_party/GraspGen/sam3/sam3/model/box_ops.py +219 -0
  33. third_party/GraspGen/sam3/sam3/model/data_misc.py +210 -0
  34. third_party/GraspGen/sam3/sam3/model/decoder.py +953 -0
  35. third_party/GraspGen/sam3/sam3/model/edt.py +175 -0
  36. third_party/GraspGen/sam3/sam3/model/encoder.py +596 -0
  37. third_party/GraspGen/sam3/sam3/model/geometry_encoders.py +838 -0
  38. third_party/GraspGen/sam3/sam3/model/io_utils.py +715 -0
  39. third_party/GraspGen/sam3/sam3/model/maskformer_segmentation.py +327 -0
  40. third_party/GraspGen/sam3/sam3/model/memory.py +203 -0
  41. third_party/GraspGen/sam3/sam3/model/model_misc.py +430 -0
  42. third_party/GraspGen/sam3/sam3/model/necks.py +126 -0
  43. third_party/GraspGen/sam3/sam3/model/position_encoding.py +126 -0
  44. third_party/GraspGen/sam3/sam3/model/sam1_task_predictor.py +457 -0
  45. third_party/GraspGen/sam3/sam3/model/sam3_image.py +880 -0
  46. third_party/GraspGen/sam3/sam3/model/sam3_image_processor.py +222 -0
  47. third_party/GraspGen/sam3/sam3/model/sam3_tracker_base.py +1185 -0
  48. third_party/GraspGen/sam3/sam3/model/sam3_tracker_utils.py +428 -0
  49. third_party/GraspGen/sam3/sam3/model/sam3_tracking_predictor.py +1369 -0
  50. third_party/GraspGen/sam3/sam3/model/sam3_video_base.py +1768 -0
third_party/GraspGen/sam3/sam3/agent/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
third_party/GraspGen/sam3/sam3/agent/agent_core.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import copy
6
+ import json
7
+ import os
8
+
9
+ import cv2
10
+ from PIL import Image
11
+
12
+ from .client_llm import send_generate_request
13
+ from .client_sam3 import call_sam_service
14
+ from .viz import visualize
15
+
16
+
17
+ def save_debug_messages(messages_list, debug, debug_folder_path, debug_jsonl_path):
18
+ """Save messages to debug jsonl file if debug is enabled"""
19
+ if debug and debug_jsonl_path:
20
+ # Ensure the debug directory exists before writing
21
+ os.makedirs(debug_folder_path, exist_ok=True)
22
+ with open(debug_jsonl_path, "w") as f:
23
+ for msg in messages_list:
24
+ f.write(json.dumps(msg, indent=4) + "\n")
25
+
26
+
27
+ def cleanup_debug_files(debug, debug_folder_path, debug_jsonl_path):
28
+ """Clean up debug files when function successfully returns"""
29
+ if debug and debug_folder_path:
30
+ try:
31
+ if os.path.exists(debug_jsonl_path):
32
+ os.remove(debug_jsonl_path)
33
+ if os.path.exists(debug_folder_path):
34
+ os.rmdir(debug_folder_path)
35
+ except Exception as e:
36
+ print(f"Warning: Could not clean up debug files: {e}")
37
+
38
+
39
+ def count_images(messages):
40
+ """Count the total number of images present in the messages history."""
41
+ total = 0
42
+ for message in messages:
43
+ # Check if message has content (should be a list)
44
+ if "content" in message and isinstance(message["content"], list):
45
+ # Iterate through each content item
46
+ for content_item in message["content"]:
47
+ # Check if content item is a dict with type "image"
48
+ if (
49
+ isinstance(content_item, dict)
50
+ and content_item.get("type") == "image"
51
+ ):
52
+ total += 1
53
+ return total
54
+
55
+
56
+ def _prune_messages_for_next_round(
57
+ messages_list,
58
+ used_text_prompts,
59
+ latest_sam3_text_prompt,
60
+ img_path,
61
+ initial_text_prompt,
62
+ ):
63
+ """Return a new messages list that contains only:
64
+ 1) messages[:2] (with optional warning text added to the second message's content)
65
+ 2) the latest assistant message (and everything after it) that contains a segment_phrase tool call
66
+ """
67
+ # There should not be more than 10 messages in the conversation history
68
+ assert len(messages_list) < 10
69
+
70
+ # Part 1: always keep the first two message JSONs
71
+ part1 = copy.deepcopy(messages_list[:2])
72
+
73
+ # Part 2: search backwards for the latest assistant message containing a segment_phrase tool call
74
+ part2_start_idx = None
75
+ for idx in range(len(messages_list) - 1, 1, -1):
76
+ msg = messages_list[idx]
77
+ # We only consider assistant messages with a "content" list
78
+ if msg.get("role") != "assistant" or "content" not in msg:
79
+ continue
80
+ # Look for any content element that is a text containing the segment_phrase tool call
81
+ for content in msg["content"]:
82
+ if (
83
+ isinstance(content, dict)
84
+ and content.get("type") == "text"
85
+ and "<tool>" in content.get("text", "")
86
+ and "segment_phrase" in content.get("text", "")
87
+ ):
88
+ part2_start_idx = idx
89
+ break
90
+ if part2_start_idx is not None:
91
+ break
92
+
93
+ part2 = messages_list[part2_start_idx:] if part2_start_idx is not None else []
94
+
95
+ # Part 3: decide whether to add warning text to the second message in part1
96
+ previously_used = (
97
+ [p for p in used_text_prompts if p != latest_sam3_text_prompt]
98
+ if latest_sam3_text_prompt
99
+ else list(used_text_prompts)
100
+ )
101
+ if part2 and len(previously_used) > 0:
102
+ warning_text = f'Note that we have previously called the segment_phrase tool with each "text_prompt" in this list: {list(previously_used)}, but none of the generated results were satisfactory. So make sure that you do not use any of these phrases as the "text_prompt" to call the segment_phrase tool again.'
103
+ # Replace the second message entirely to keep exactly 2 content items
104
+ part1[1] = {
105
+ "role": "user",
106
+ "content": [
107
+ {"type": "image", "image": img_path},
108
+ {
109
+ "type": "text",
110
+ "text": f"The above image is the raw input image. The initial user input query is: '{initial_text_prompt}'."
111
+ + " "
112
+ + warning_text,
113
+ },
114
+ ],
115
+ }
116
+ assert len(part1[1]["content"]) == 2
117
+
118
+ # Build the new messages list: part1 (with optional warning), then part2
119
+ new_messages = list(part1)
120
+ new_messages.extend(part2)
121
+ return new_messages
122
+
123
+
124
+ def agent_inference(
125
+ img_path: str,
126
+ initial_text_prompt: str,
127
+ debug: bool = False,
128
+ send_generate_request=send_generate_request,
129
+ call_sam_service=call_sam_service,
130
+ max_generations: int = 100,
131
+ output_dir="../../sam3_agent_out",
132
+ ):
133
+ """
134
+ Given a text prompt and an image, this tool will perform all aspects of agentic problem solving,
135
+ while saving sam3 and MLLM outputs to their respective directories.
136
+
137
+ Args:
138
+ img_path: Path to the input image
139
+ initial_text_prompt: Initial text prompt from the user
140
+ debug: Whether to enable debug mode
141
+ max_generations: Maximum number of send_generate_request calls allowed (default: 100)
142
+ """
143
+ # setup dir
144
+ sam_output_dir = os.path.join(output_dir, "sam_out")
145
+ error_save_dir = os.path.join(output_dir, "none_out")
146
+ debug_save_dir = os.path.join(output_dir, "agent_debug_out")
147
+ os.makedirs(sam_output_dir, exist_ok=True)
148
+ os.makedirs(error_save_dir, exist_ok=True)
149
+ os.makedirs(debug_save_dir, exist_ok=True)
150
+ current_dir = os.path.dirname(os.path.abspath(__file__))
151
+ MLLM_SYSTEM_PROMPT_PATH = os.path.join(
152
+ current_dir, "system_prompts/system_prompt.txt"
153
+ )
154
+ ITERATIVE_CHECKING_SYSTEM_PROMPT_PATH = os.path.join(
155
+ current_dir, "system_prompts/system_prompt_iterative_checking.txt"
156
+ )
157
+ # init variables
158
+ PATH_TO_LATEST_OUTPUT_JSON = ""
159
+ LATEST_SAM3_TEXT_PROMPT = ""
160
+ USED_TEXT_PROMPTS = (
161
+ set()
162
+ ) # Track all previously used text prompts for segment_phrase
163
+ generation_count = 0 # Counter for number of send_generate_request calls
164
+
165
+ # debug setup
166
+ debug_folder_path = None
167
+ debug_jsonl_path = None
168
+ if debug:
169
+ debug_folder_path = os.path.join(
170
+ debug_save_dir, f"{img_path.rsplit('/', 1)[-1].rsplit('.', 1)[0]}"
171
+ )
172
+ debug_jsonl_path = os.path.join(debug_folder_path, "debug_history.json")
173
+ os.makedirs(debug_folder_path, exist_ok=True)
174
+
175
+ # The helper functions are now defined outside the agent_inference function
176
+ with open(MLLM_SYSTEM_PROMPT_PATH, "r") as f:
177
+ system_prompt = f.read().strip()
178
+ with open(ITERATIVE_CHECKING_SYSTEM_PROMPT_PATH, "r") as f:
179
+ iterative_checking_system_prompt = f.read().strip()
180
+
181
+ # Construct the initial message list
182
+ messages = [
183
+ {"role": "system", "content": system_prompt},
184
+ {
185
+ "role": "user",
186
+ "content": [
187
+ {"type": "image", "image": img_path},
188
+ {
189
+ "type": "text",
190
+ "text": f"The above image is the raw input image. The initial user input query is: '{initial_text_prompt}'.",
191
+ },
192
+ ],
193
+ },
194
+ ]
195
+ print(f"> Text prompt: {initial_text_prompt}")
196
+ print(f"> Image path: {img_path}")
197
+
198
+ print("\n\n")
199
+ print("-" * 30 + f" Round {str(generation_count + 1)}" + "-" * 30)
200
+ print("\n\n")
201
+ generated_text = send_generate_request(messages)
202
+ print(f"\n>>> MLLM Response [start]\n{generated_text}\n<<< MLLM Response [end]\n")
203
+ while generated_text is not None:
204
+ save_debug_messages(messages, debug, debug_folder_path, debug_jsonl_path)
205
+ assert (
206
+ "<tool>" in generated_text,
207
+ f"Generated text does not contain <tool> tag: {generated_text}",
208
+ )
209
+ generated_text = generated_text.split("</tool>", 1)[0] + "</tool>"
210
+ tool_call_json_str = (
211
+ generated_text.split("<tool>")[-1]
212
+ .split("</tool>")[0]
213
+ .strip()
214
+ .replace(r"}}}", r"}}") # remove extra } if any
215
+ )
216
+ try:
217
+ tool_call = json.loads(tool_call_json_str)
218
+ except json.JSONDecodeError:
219
+ raise ValueError(f"Invalid JSON in tool call: {tool_call_json_str}")
220
+
221
+ if PATH_TO_LATEST_OUTPUT_JSON == "":
222
+ # The first tool call must be segment_phrase or report_no_mask
223
+ assert (
224
+ tool_call["name"] == "segment_phrase"
225
+ or tool_call["name"] == "report_no_mask"
226
+ )
227
+
228
+ if tool_call["name"] == "segment_phrase":
229
+ print("🔍 Calling segment_phrase tool...")
230
+ assert list(tool_call["parameters"].keys()) == ["text_prompt"]
231
+
232
+ # Check if this text_prompt has been used before
233
+ current_text_prompt = tool_call["parameters"]["text_prompt"]
234
+ if current_text_prompt in USED_TEXT_PROMPTS:
235
+ print(
236
+ f"❌ Text prompt '{current_text_prompt}' has been used before. Requesting a different prompt."
237
+ )
238
+ duplicate_prompt_message = f"You have previously used '{current_text_prompt}' as your text_prompt to call the segment_phrase tool. You may not use it again. Please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase prompt, while adhering to all the rules stated in the system prompt. You must also never use any of the following text_prompt(s): {str(list(USED_TEXT_PROMPTS))}."
239
+ messages.append(
240
+ {
241
+ "role": "assistant",
242
+ "content": [{"type": "text", "text": generated_text}],
243
+ }
244
+ )
245
+ messages.append(
246
+ {
247
+ "role": "user",
248
+ "content": [{"type": "text", "text": duplicate_prompt_message}],
249
+ }
250
+ )
251
+ else:
252
+ # Add the text_prompt to the set of used prompts
253
+ USED_TEXT_PROMPTS.add(current_text_prompt)
254
+ LATEST_SAM3_TEXT_PROMPT = current_text_prompt
255
+ PATH_TO_LATEST_OUTPUT_JSON = call_sam_service(
256
+ image_path=img_path,
257
+ text_prompt=current_text_prompt,
258
+ output_folder_path=sam_output_dir,
259
+ )
260
+ sam3_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
261
+ sam3_output_image_path = sam3_outputs["output_image_path"]
262
+ num_masks = len(sam3_outputs["pred_boxes"])
263
+
264
+ messages.append(
265
+ {
266
+ "role": "assistant",
267
+ "content": [{"type": "text", "text": generated_text}],
268
+ }
269
+ )
270
+ if num_masks == 0:
271
+ print("❌ No masks generated by SAM3, reporting no mask to Qwen.")
272
+ sam3_output_text_message = f"The segment_phrase tool did not generate any masks for the text_prompt '{current_text_prompt}'. Now, please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase text_prompt, while adhering to all the rules stated in the system prompt. Please be reminded that the original user query was '{initial_text_prompt}'."
273
+ messages.append(
274
+ {
275
+ "role": "user",
276
+ "content": [
277
+ {"type": "text", "text": sam3_output_text_message}
278
+ ],
279
+ }
280
+ )
281
+ else:
282
+ sam3_output_text_message = rf"The segment_phrase tool generated {num_masks} available masks. All {num_masks} available masks are rendered in this image below, now you must analyze the {num_masks} available mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action. Please be reminded that the original user query was '{initial_text_prompt}'."
283
+ messages.append(
284
+ {
285
+ "role": "user",
286
+ "content": [
287
+ {"type": "text", "text": sam3_output_text_message},
288
+ {"type": "image", "image": sam3_output_image_path},
289
+ ],
290
+ }
291
+ )
292
+ print("\n\n>>> sam3_output_text_message:\n", sam3_output_text_message)
293
+
294
+ elif tool_call["name"] == "examine_each_mask":
295
+ print("🔍 Calling examine_each_mask tool...")
296
+ assert LATEST_SAM3_TEXT_PROMPT != ""
297
+
298
+ # Make sure that the last message is a image
299
+ assert messages[-1]["content"][1]["type"] == "image", (
300
+ "Second content element should be an image"
301
+ )
302
+ messages.pop() # Remove the last user message
303
+ # Add simplified replacement message
304
+ simplified_message = {
305
+ "role": "user",
306
+ "content": [
307
+ {
308
+ "type": "text",
309
+ "text": "The segment_phrase tool generated several masks. Now you must analyze the mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action.",
310
+ }
311
+ ],
312
+ }
313
+ messages.append(simplified_message)
314
+
315
+ current_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
316
+ num_masks = len(current_outputs["pred_masks"])
317
+ masks_to_keep = []
318
+
319
+ # MLLM check the mask one by one
320
+ for i in range(num_masks):
321
+ print(f"🔍 Checking mask {i + 1}/{num_masks}...")
322
+ image_w_mask_i, image_w_zoomed_in_mask_i = visualize(current_outputs, i)
323
+
324
+ image_w_zoomed_in_mask_i_path = os.path.join(
325
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png".replace("/", "_")
326
+ ).replace(".png", f"_zoom_in_mask_{i + 1}.png")
327
+ image_w_mask_i_path = os.path.join(
328
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png".replace("/", "_")
329
+ ).replace(".png", f"_selected_mask_{i + 1}.png")
330
+ image_w_zoomed_in_mask_i.save(image_w_zoomed_in_mask_i_path)
331
+ image_w_mask_i.save(image_w_mask_i_path)
332
+
333
+ iterative_checking_messages = [
334
+ {"role": "system", "content": iterative_checking_system_prompt},
335
+ {
336
+ "role": "user",
337
+ "content": [
338
+ {"type": "text", "text": f"The raw input image: "},
339
+ {"type": "image", "image": img_path},
340
+ {
341
+ "type": "text",
342
+ "text": f"The initial user input query is: '{initial_text_prompt}'",
343
+ },
344
+ {
345
+ "type": "text",
346
+ "text": f"Image with the predicted segmentation mask rendered on it: ",
347
+ },
348
+ {"type": "image", "image": image_w_mask_i_path},
349
+ {
350
+ "type": "text",
351
+ "text": f"Image with the zoomed-in mask: ",
352
+ },
353
+ {"type": "image", "image": image_w_zoomed_in_mask_i_path},
354
+ ],
355
+ },
356
+ ]
357
+ checking_generated_text = send_generate_request(
358
+ iterative_checking_messages
359
+ )
360
+
361
+ # Process the generated text to determine if the mask should be kept or rejected
362
+ if checking_generated_text is None:
363
+ raise ValueError(
364
+ "Generated text is None, which is unexpected. Please check the Qwen server and the input parameters."
365
+ )
366
+ print(f"Generated text for mask {i + 1}: {checking_generated_text}")
367
+ verdict = (
368
+ checking_generated_text.split("<verdict>")[-1]
369
+ .split("</verdict>")[0]
370
+ .strip()
371
+ )
372
+ if "Accept" in verdict:
373
+ assert not "Reject" in verdict
374
+ print(f"Mask {i + 1} accepted, keeping it in the outputs.")
375
+ masks_to_keep.append(i)
376
+ elif "Reject" in verdict:
377
+ assert not "Accept" in verdict
378
+ print(f"Mask {i + 1} rejected, removing it from the outputs.")
379
+ else:
380
+ raise ValueError(
381
+ f"Unexpected verdict in generated text: {checking_generated_text}. Expected 'Accept' or 'Reject'."
382
+ )
383
+
384
+ updated_outputs = {
385
+ "original_image_path": current_outputs["original_image_path"],
386
+ "orig_img_h": current_outputs["orig_img_h"],
387
+ "orig_img_w": current_outputs["orig_img_w"],
388
+ "pred_boxes": [current_outputs["pred_boxes"][i] for i in masks_to_keep],
389
+ "pred_scores": [
390
+ current_outputs["pred_scores"][i] for i in masks_to_keep
391
+ ],
392
+ "pred_masks": [current_outputs["pred_masks"][i] for i in masks_to_keep],
393
+ }
394
+
395
+ image_w_check_masks = visualize(updated_outputs)
396
+ image_w_check_masks_path = os.path.join(
397
+ sam_output_dir, rf"{LATEST_SAM3_TEXT_PROMPT}.png"
398
+ ).replace(
399
+ ".png",
400
+ f"_selected_masks_{'-'.join(map(str, [i + 1 for i in masks_to_keep]))}.png".replace(
401
+ "/", "_"
402
+ ),
403
+ )
404
+ image_w_check_masks.save(image_w_check_masks_path)
405
+ # save the updated json outputs and append to message history
406
+ messages.append(
407
+ {
408
+ "role": "assistant",
409
+ "content": [{"type": "text", "text": generated_text}],
410
+ }
411
+ )
412
+ if len(masks_to_keep) == 0:
413
+ messages.append(
414
+ {
415
+ "role": "user",
416
+ "content": [
417
+ {
418
+ "type": "text",
419
+ "text": f"The original user query was: '{initial_text_prompt}'. The examine_each_mask tool examined and rejected all of the masks generated by the segment_phrase tool. Now, please call the segment_phrase tool again with a different, perhaps more general, or more creative simple noun phrase text_prompt, while adhering to all the rules stated in the system prompt.",
420
+ }
421
+ ],
422
+ }
423
+ )
424
+ else:
425
+ messages.append(
426
+ {
427
+ "role": "user",
428
+ "content": [
429
+ {
430
+ "type": "text",
431
+ "text": f"The original user query was: '{initial_text_prompt}'. After calling the examine_each_mask tool on the available masks, the number of available masks is now {len(masks_to_keep)}. All {len(masks_to_keep)} available masks are rendered in this image below, now you must analyze the {len(masks_to_keep)} available mask(s) carefully, compare them against the raw input image and the original user query, and determine your next action.",
432
+ },
433
+ {"type": "image", "image": image_w_check_masks_path},
434
+ ],
435
+ }
436
+ )
437
+
438
+ # Create a new filename based on the original path to avoid filename length issues
439
+ base_path = PATH_TO_LATEST_OUTPUT_JSON
440
+ # Remove any existing "masks_" suffix to avoid duplication
441
+ if "masks_" in base_path:
442
+ base_path = base_path.split("masks_")[0] + ".json"
443
+ # Create new filename with current masks; use a clearer suffix when empty
444
+ if len(masks_to_keep) == 0:
445
+ PATH_TO_LATEST_OUTPUT_JSON = base_path.replace(
446
+ ".json", "masks_none.json"
447
+ )
448
+ else:
449
+ PATH_TO_LATEST_OUTPUT_JSON = base_path.replace(
450
+ ".json", f"masks_{'_'.join(map(str, masks_to_keep))}.json"
451
+ )
452
+ json.dump(updated_outputs, open(PATH_TO_LATEST_OUTPUT_JSON, "w"), indent=4)
453
+
454
+ elif tool_call["name"] == "select_masks_and_return":
455
+ print("🔍 Calling select_masks_and_return tool...")
456
+ current_outputs = json.load(open(PATH_TO_LATEST_OUTPUT_JSON, "r"))
457
+
458
+ assert list(tool_call["parameters"].keys()) == ["final_answer_masks"]
459
+ masks_to_keep = tool_call["parameters"]["final_answer_masks"]
460
+
461
+ # Keep only valid mask indices, remove duplicates, and preserve deterministic ascending order
462
+ available_masks = set(range(1, len(current_outputs["pred_masks"]) + 1))
463
+ masks_to_keep = sorted({i for i in masks_to_keep if i in available_masks})
464
+ # Change this to a update message telling the model to try again along with information about errors made.
465
+
466
+ final_outputs = {
467
+ "original_image_path": current_outputs["original_image_path"],
468
+ "orig_img_h": current_outputs["orig_img_h"],
469
+ "orig_img_w": current_outputs["orig_img_w"],
470
+ "pred_boxes": [
471
+ current_outputs["pred_boxes"][i - 1] for i in masks_to_keep
472
+ ],
473
+ "pred_scores": [
474
+ current_outputs["pred_scores"][i - 1] for i in masks_to_keep
475
+ ],
476
+ "pred_masks": [
477
+ current_outputs["pred_masks"][i - 1] for i in masks_to_keep
478
+ ],
479
+ }
480
+
481
+ rendered_final_output = visualize(final_outputs)
482
+ messages.append(
483
+ {
484
+ "role": "assistant",
485
+ "content": [{"type": "text", "text": generated_text}],
486
+ }
487
+ )
488
+
489
+ # Clean up debug files before successful return
490
+ cleanup_debug_files(debug, debug_folder_path, debug_jsonl_path)
491
+ return messages, final_outputs, rendered_final_output
492
+
493
+ elif tool_call["name"] == "report_no_mask":
494
+ print("🔍 Calling report_no_mask tool...")
495
+ height, width = cv2.imread(img_path).shape[:2]
496
+ final_outputs = {
497
+ "original_image_path": img_path,
498
+ "orig_img_h": height,
499
+ "orig_img_w": width,
500
+ "pred_boxes": [],
501
+ "pred_scores": [],
502
+ "pred_masks": [],
503
+ }
504
+ rendered_final_output = Image.open(img_path)
505
+ messages.append(
506
+ {
507
+ "role": "assistant",
508
+ "content": [{"type": "text", "text": generated_text}],
509
+ }
510
+ )
511
+ return messages, final_outputs, rendered_final_output
512
+
513
+ else:
514
+ raise ValueError(f"Unknown tool call: {tool_call['name']}")
515
+
516
+ # sometimes the MLLM don't know when to stop, and generates multiple tool calls in one round, so we need to split the generated text by </tool> and only keep the first one
517
+
518
+ for message in messages:
519
+ if message["role"] == "assistant" and "content" in message:
520
+ for content in message["content"]:
521
+ if (
522
+ isinstance(content, dict)
523
+ and content.get("type") == "text"
524
+ and "text" in content
525
+ ):
526
+ content["text"] = (
527
+ content["text"].split("</tool>", 1)[0] + "</tool>\n\n"
528
+ )
529
+ # Prune the messages history before the next MLLM generation round according to the 3-part rules.
530
+ # This keeps history compact and ensures the model sees only the allowed parts.
531
+ messages = _prune_messages_for_next_round(
532
+ messages,
533
+ USED_TEXT_PROMPTS,
534
+ LATEST_SAM3_TEXT_PROMPT,
535
+ img_path,
536
+ initial_text_prompt,
537
+ )
538
+ # make sure there can never be more than 2 images in the context
539
+ assert count_images(messages) <= 2
540
+ generation_count += 1
541
+ if generation_count > max_generations:
542
+ raise ValueError(
543
+ f"Exceeded maximum number of allowed generation requests ({max_generations})"
544
+ )
545
+
546
+ print("\n\n")
547
+ print("-" * 30 + f" Round {str(generation_count + 1)}" + "-" * 30)
548
+ print("\n\n")
549
+ generated_text = send_generate_request(messages)
550
+ print(
551
+ f"\n>>> MLLM Response [start]\n{generated_text}\n<<< MLLM Response [end]\n"
552
+ )
553
+
554
+ print("\n\n>>> SAM 3 Agent execution ended.\n\n")
555
+
556
+ error_save_path = os.path.join(
557
+ error_save_dir,
558
+ f"{img_path.rsplit('/', 1)[-1].rsplit('.', 1)[0]}_error_history.json",
559
+ )
560
+ with open(error_save_path, "w") as f:
561
+ json.dump(messages, f, indent=4)
562
+ print("Saved messages history that caused error to:", error_save_path)
563
+ raise ValueError(
564
+ rf"Generated text is None, which is unexpected. Please check the Qwen server and the input parameters for image path: {img_path} and initial text prompt: {initial_text_prompt}."
565
+ )
third_party/GraspGen/sam3/sam3/agent/client_llm.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import base64
6
+ import os
7
+ from typing import Any, Optional
8
+
9
+ from openai import OpenAI
10
+
11
+
12
+ def get_image_base64_and_mime(image_path):
13
+ """Convert image file to base64 string and get MIME type"""
14
+ try:
15
+ # Get MIME type based on file extension
16
+ ext = os.path.splitext(image_path)[1].lower()
17
+ mime_types = {
18
+ ".jpg": "image/jpeg",
19
+ ".jpeg": "image/jpeg",
20
+ ".png": "image/png",
21
+ ".gif": "image/gif",
22
+ ".webp": "image/webp",
23
+ ".bmp": "image/bmp",
24
+ }
25
+ mime_type = mime_types.get(ext, "image/jpeg") # Default to JPEG
26
+
27
+ # Convert image to base64
28
+ with open(image_path, "rb") as image_file:
29
+ base64_data = base64.b64encode(image_file.read()).decode("utf-8")
30
+ return base64_data, mime_type
31
+ except Exception as e:
32
+ print(f"Error converting image to base64: {e}")
33
+ return None, None
34
+
35
+
36
+ def send_generate_request(
37
+ messages,
38
+ server_url=None,
39
+ model="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
40
+ api_key=None,
41
+ max_tokens=4096,
42
+ ):
43
+ """
44
+ Sends a request to the OpenAI-compatible API endpoint using the OpenAI client library.
45
+
46
+ Args:
47
+ server_url (str): The base URL of the server, e.g. "http://127.0.0.1:8000"
48
+ messages (list): A list of message dicts, each containing role and content.
49
+ model (str): The model to use for generation (default: "llama-4")
50
+ max_tokens (int): Maximum number of tokens to generate (default: 4096)
51
+
52
+ Returns:
53
+ str: The generated response text from the server.
54
+ """
55
+ # Process messages to convert image paths to base64
56
+ processed_messages = []
57
+ for message in messages:
58
+ processed_message = message.copy()
59
+ if message["role"] == "user" and "content" in message:
60
+ processed_content = []
61
+ for c in message["content"]:
62
+ if isinstance(c, dict) and c.get("type") == "image":
63
+ # Convert image path to base64 format
64
+ image_path = c["image"]
65
+
66
+ print("image_path", image_path)
67
+ new_image_path = image_path.replace(
68
+ "?", "%3F"
69
+ ) # Escape ? in the path
70
+
71
+ # Read the image file and convert to base64
72
+ try:
73
+ base64_image, mime_type = get_image_base64_and_mime(
74
+ new_image_path
75
+ )
76
+ if base64_image is None:
77
+ print(
78
+ f"Warning: Could not convert image to base64: {new_image_path}"
79
+ )
80
+ continue
81
+
82
+ # Create the proper image_url structure with base64 data
83
+ processed_content.append(
84
+ {
85
+ "type": "image_url",
86
+ "image_url": {
87
+ "url": f"data:{mime_type};base64,{base64_image}",
88
+ "detail": "high",
89
+ },
90
+ }
91
+ )
92
+
93
+ except FileNotFoundError:
94
+ print(f"Warning: Image file not found: {new_image_path}")
95
+ continue
96
+ except Exception as e:
97
+ print(f"Warning: Error processing image {new_image_path}: {e}")
98
+ continue
99
+ else:
100
+ processed_content.append(c)
101
+
102
+ processed_message["content"] = processed_content
103
+ processed_messages.append(processed_message)
104
+
105
+ # Create OpenAI client with custom base URL
106
+ client = OpenAI(api_key=api_key, base_url=server_url)
107
+
108
+ try:
109
+ print(f"🔍 Calling model {model}...")
110
+ response = client.chat.completions.create(
111
+ model=model,
112
+ messages=processed_messages,
113
+ max_completion_tokens=max_tokens,
114
+ n=1,
115
+ )
116
+ # print(f"Received response: {response.choices[0].message}")
117
+
118
+ # Extract the response content
119
+ if response.choices and len(response.choices) > 0:
120
+ return response.choices[0].message.content
121
+ else:
122
+ print(f"Unexpected response format: {response}")
123
+ return None
124
+
125
+ except Exception as e:
126
+ print(f"Request failed: {e}")
127
+ return None
128
+
129
+
130
+ def send_direct_request(
131
+ llm: Any,
132
+ messages: list[dict[str, Any]],
133
+ sampling_params: Any,
134
+ ) -> Optional[str]:
135
+ """
136
+ Run inference on a vLLM model instance directly without using a server.
137
+
138
+ Args:
139
+ llm: Initialized vLLM LLM instance (passed from external initialization)
140
+ messages: List of message dicts with role and content (OpenAI format)
141
+ sampling_params: vLLM SamplingParams instance (initialized externally)
142
+
143
+ Returns:
144
+ str: Generated response text, or None if inference fails
145
+ """
146
+ try:
147
+ # Process messages to handle images (convert to base64 if needed)
148
+ processed_messages = []
149
+ for message in messages:
150
+ processed_message = message.copy()
151
+ if message["role"] == "user" and "content" in message:
152
+ processed_content = []
153
+ for c in message["content"]:
154
+ if isinstance(c, dict) and c.get("type") == "image":
155
+ # Convert image path to base64 format
156
+ image_path = c["image"]
157
+ new_image_path = image_path.replace("?", "%3F")
158
+
159
+ try:
160
+ base64_image, mime_type = get_image_base64_and_mime(
161
+ new_image_path
162
+ )
163
+ if base64_image is None:
164
+ print(
165
+ f"Warning: Could not convert image: {new_image_path}"
166
+ )
167
+ continue
168
+
169
+ # vLLM expects image_url format
170
+ processed_content.append(
171
+ {
172
+ "type": "image_url",
173
+ "image_url": {
174
+ "url": f"data:{mime_type};base64,{base64_image}"
175
+ },
176
+ }
177
+ )
178
+ except Exception as e:
179
+ print(
180
+ f"Warning: Error processing image {new_image_path}: {e}"
181
+ )
182
+ continue
183
+ else:
184
+ processed_content.append(c)
185
+
186
+ processed_message["content"] = processed_content
187
+ processed_messages.append(processed_message)
188
+
189
+ print("🔍 Running direct inference with vLLM...")
190
+
191
+ # Run inference using vLLM's chat interface
192
+ outputs = llm.chat(
193
+ messages=processed_messages,
194
+ sampling_params=sampling_params,
195
+ )
196
+
197
+ # Extract the generated text from the first output
198
+ if outputs and len(outputs) > 0:
199
+ generated_text = outputs[0].outputs[0].text
200
+ return generated_text
201
+ else:
202
+ print(f"Unexpected output format: {outputs}")
203
+ return None
204
+
205
+ except Exception as e:
206
+ print(f"Direct inference failed: {e}")
207
+ return None
third_party/GraspGen/sam3/sam3/agent/client_sam3.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import json
6
+ import os
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from sam3.model.box_ops import box_xyxy_to_xywh
11
+ from sam3.train.masks_ops import rle_encode
12
+
13
+ from .helpers.mask_overlap_removal import remove_overlapping_masks
14
+ from .viz import visualize
15
+
16
+
17
+ def sam3_inference(processor, image_path, text_prompt):
18
+ """Run SAM 3 image inference with text prompts and format the outputs"""
19
+ image = Image.open(image_path)
20
+ orig_img_w, orig_img_h = image.size
21
+
22
+ # model inference
23
+ inference_state = processor.set_image(image)
24
+ inference_state = processor.set_text_prompt(
25
+ state=inference_state, prompt=text_prompt
26
+ )
27
+
28
+ # format and assemble outputs
29
+ pred_boxes_xyxy = torch.stack(
30
+ [
31
+ inference_state["boxes"][:, 0] / orig_img_w,
32
+ inference_state["boxes"][:, 1] / orig_img_h,
33
+ inference_state["boxes"][:, 2] / orig_img_w,
34
+ inference_state["boxes"][:, 3] / orig_img_h,
35
+ ],
36
+ dim=-1,
37
+ ) # normalized in range [0, 1]
38
+ pred_boxes_xywh = box_xyxy_to_xywh(pred_boxes_xyxy).tolist()
39
+ pred_masks = rle_encode(inference_state["masks"].squeeze(1))
40
+ pred_masks = [m["counts"] for m in pred_masks]
41
+ outputs = {
42
+ "orig_img_h": orig_img_h,
43
+ "orig_img_w": orig_img_w,
44
+ "pred_boxes": pred_boxes_xywh,
45
+ "pred_masks": pred_masks,
46
+ "pred_scores": inference_state["scores"].tolist(),
47
+ }
48
+ return outputs
49
+
50
+
51
+ def call_sam_service(
52
+ sam3_processor,
53
+ image_path: str,
54
+ text_prompt: str,
55
+ output_folder_path: str = "sam3_output",
56
+ ):
57
+ """
58
+ Loads an image, sends it with a text prompt to the service,
59
+ saves the results, and renders the visualization.
60
+ """
61
+ print(f"📞 Loading image '{image_path}' and sending with prompt '{text_prompt}'...")
62
+
63
+ text_prompt_for_save_path = (
64
+ text_prompt.replace("/", "_") if "/" in text_prompt else text_prompt
65
+ )
66
+
67
+ os.makedirs(
68
+ os.path.join(output_folder_path, image_path.replace("/", "-")), exist_ok=True
69
+ )
70
+ output_json_path = os.path.join(
71
+ output_folder_path,
72
+ image_path.replace("/", "-"),
73
+ rf"{text_prompt_for_save_path}.json",
74
+ )
75
+ output_image_path = os.path.join(
76
+ output_folder_path,
77
+ image_path.replace("/", "-"),
78
+ rf"{text_prompt_for_save_path}.png",
79
+ )
80
+
81
+ try:
82
+ # Send the image and text prompt as a multipart/form-data request
83
+ serialized_response = sam3_inference(sam3_processor, image_path, text_prompt)
84
+
85
+ # 1. Prepare the response dictionary
86
+ serialized_response = remove_overlapping_masks(serialized_response)
87
+ serialized_response = {
88
+ "original_image_path": image_path,
89
+ "output_image_path": output_image_path,
90
+ **serialized_response,
91
+ }
92
+
93
+ # 2. Reorder predictions by scores (highest to lowest) if scores are available
94
+ if "pred_scores" in serialized_response and serialized_response["pred_scores"]:
95
+ # Create indices sorted by scores in descending order
96
+ score_indices = sorted(
97
+ range(len(serialized_response["pred_scores"])),
98
+ key=lambda i: serialized_response["pred_scores"][i],
99
+ reverse=True,
100
+ )
101
+
102
+ # Reorder all three lists based on the sorted indices
103
+ serialized_response["pred_scores"] = [
104
+ serialized_response["pred_scores"][i] for i in score_indices
105
+ ]
106
+ serialized_response["pred_boxes"] = [
107
+ serialized_response["pred_boxes"][i] for i in score_indices
108
+ ]
109
+ serialized_response["pred_masks"] = [
110
+ serialized_response["pred_masks"][i] for i in score_indices
111
+ ]
112
+
113
+ # 3. Remove any invalid RLE masks that is too short (shorter than 5 characters)
114
+ valid_masks = []
115
+ valid_boxes = []
116
+ valid_scores = []
117
+ for i, rle in enumerate(serialized_response["pred_masks"]):
118
+ if len(rle) > 4:
119
+ valid_masks.append(rle)
120
+ valid_boxes.append(serialized_response["pred_boxes"][i])
121
+ valid_scores.append(serialized_response["pred_scores"][i])
122
+ serialized_response["pred_masks"] = valid_masks
123
+ serialized_response["pred_boxes"] = valid_boxes
124
+ serialized_response["pred_scores"] = valid_scores
125
+
126
+ with open(output_json_path, "w") as f:
127
+ json.dump(serialized_response, f, indent=4)
128
+ print(f"✅ Raw JSON response saved to '{output_json_path}'")
129
+
130
+ # 4. Render and save visualizations on the image and save it in the SAM3 output folder
131
+ print("🔍 Rendering visualizations on the image ...")
132
+ viz_image = visualize(serialized_response)
133
+ os.makedirs(os.path.dirname(output_image_path), exist_ok=True)
134
+ viz_image.save(output_image_path)
135
+ print("✅ Saved visualization at:", output_image_path)
136
+ except Exception as e:
137
+ print(f"❌ Error calling service: {e}")
138
+
139
+ return output_json_path
third_party/GraspGen/sam3/sam3/agent/inference.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import json
6
+ import os
7
+
8
+ from sam3.agent.agent_core import agent_inference
9
+
10
+
11
+ def run_single_image_inference(
12
+ image_path,
13
+ text_prompt,
14
+ llm_config,
15
+ send_generate_request,
16
+ call_sam_service,
17
+ output_dir="agent_output",
18
+ debug=False,
19
+ ):
20
+ """Run inference on a single image with provided prompt"""
21
+
22
+ llm_name = llm_config["name"]
23
+
24
+ if not os.path.exists(image_path):
25
+ raise FileNotFoundError(f"Image file not found: {image_path}")
26
+
27
+ # Create output directory
28
+ os.makedirs(output_dir, exist_ok=True)
29
+
30
+ # Generate output file names
31
+ image_basename = os.path.splitext(os.path.basename(image_path))[0]
32
+ prompt_for_filename = text_prompt.replace("/", "_").replace(" ", "_")
33
+
34
+ base_filename = f"{image_basename}_{prompt_for_filename}_agent_{llm_name}"
35
+ output_json_path = os.path.join(output_dir, f"{base_filename}_pred.json")
36
+ output_image_path = os.path.join(output_dir, f"{base_filename}_pred.png")
37
+ agent_history_path = os.path.join(output_dir, f"{base_filename}_history.json")
38
+
39
+ # Check if output already exists and skip
40
+ if os.path.exists(output_json_path):
41
+ print(f"Output JSON {output_json_path} already exists. Skipping.")
42
+ return
43
+
44
+ print(f"{'-' * 30} Starting SAM 3 Agent Session... {'-' * 30} ")
45
+ agent_history, final_output_dict, rendered_final_output = agent_inference(
46
+ image_path,
47
+ text_prompt,
48
+ send_generate_request=send_generate_request,
49
+ call_sam_service=call_sam_service,
50
+ output_dir=output_dir,
51
+ debug=debug,
52
+ )
53
+ print(f"{'-' * 30} End of SAM 3 Agent Session... {'-' * 30} ")
54
+
55
+ final_output_dict["text_prompt"] = text_prompt
56
+ final_output_dict["image_path"] = image_path
57
+
58
+ # Save outputs
59
+ json.dump(final_output_dict, open(output_json_path, "w"), indent=4)
60
+ json.dump(agent_history, open(agent_history_path, "w"), indent=4)
61
+ rendered_final_output.save(output_image_path)
62
+
63
+ print(f"\n✅ Successfully processed single image!")
64
+ print(f"Output JSON: {output_json_path}")
65
+ print(f"Output Image: {output_image_path}")
66
+ print(f"Agent History: {agent_history_path}")
67
+ return output_image_path
third_party/GraspGen/sam3/sam3/agent/viz.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import cv2
6
+ import numpy as np
7
+ import pycocotools.mask as mask_utils
8
+ from PIL import Image
9
+
10
+ from .helpers.visualizer import Visualizer
11
+ from .helpers.zoom_in import render_zoom_in
12
+
13
+
14
+ def visualize(
15
+ input_json: dict,
16
+ zoom_in_index: int | None = None,
17
+ mask_alpha: float = 0.15,
18
+ label_mode: str = "1",
19
+ font_size_multiplier: float = 1.2,
20
+ boarder_width_multiplier: float = 0,
21
+ ):
22
+ """
23
+ Unified visualization function.
24
+
25
+ If zoom_in_index is None:
26
+ - Render all masks in input_json (equivalent to visualize_masks_from_result_json).
27
+ - Returns: PIL.Image
28
+
29
+ If zoom_in_index is provided:
30
+ - Returns two PIL.Images:
31
+ 1) Output identical to zoom_in_and_visualize(input_json, index).
32
+ 2) The same instance rendered via the general overlay using the color
33
+ returned by (1), equivalent to calling visualize_masks_from_result_json
34
+ on a single-mask json_i with color=color_hex.
35
+ """
36
+ # Common fields
37
+ orig_h = int(input_json["orig_img_h"])
38
+ orig_w = int(input_json["orig_img_w"])
39
+ img_path = input_json["original_image_path"]
40
+
41
+ # ---------- Mode A: Full-scene render ----------
42
+ if zoom_in_index is None:
43
+ boxes = np.array(input_json["pred_boxes"])
44
+ rle_masks = [
45
+ {"size": (orig_h, orig_w), "counts": rle}
46
+ for rle in input_json["pred_masks"]
47
+ ]
48
+ binary_masks = [mask_utils.decode(rle) for rle in rle_masks]
49
+
50
+ img_bgr = cv2.imread(img_path)
51
+ if img_bgr is None:
52
+ raise FileNotFoundError(f"Could not read image: {img_path}")
53
+ img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
54
+
55
+ viz = Visualizer(
56
+ img_rgb,
57
+ font_size_multiplier=font_size_multiplier,
58
+ boarder_width_multiplier=boarder_width_multiplier,
59
+ )
60
+ viz.overlay_instances(
61
+ boxes=boxes,
62
+ masks=rle_masks,
63
+ binary_masks=binary_masks,
64
+ assigned_colors=None,
65
+ alpha=mask_alpha,
66
+ label_mode=label_mode,
67
+ )
68
+ pil_all_masks = Image.fromarray(viz.output.get_image())
69
+ return pil_all_masks
70
+
71
+ # ---------- Mode B: Zoom-in pair ----------
72
+ else:
73
+ idx = int(zoom_in_index)
74
+ num_masks = len(input_json.get("pred_masks", []))
75
+ if idx < 0 or idx >= num_masks:
76
+ raise ValueError(
77
+ f"zoom_in_index {idx} is out of range (0..{num_masks - 1})."
78
+ )
79
+
80
+ # (1) Replicate zoom_in_and_visualize
81
+ object_data = {
82
+ "labels": [{"noun_phrase": f"mask_{idx}"}],
83
+ "segmentation": {
84
+ "counts": input_json["pred_masks"][idx],
85
+ "size": [orig_h, orig_w],
86
+ },
87
+ }
88
+ pil_img = Image.open(img_path)
89
+ pil_mask_i_zoomed, color_hex = render_zoom_in(
90
+ object_data, pil_img, mask_alpha=mask_alpha
91
+ )
92
+
93
+ # (2) Single-instance render with the same color
94
+ boxes_i = np.array([input_json["pred_boxes"][idx]])
95
+ rle_i = {"size": (orig_h, orig_w), "counts": input_json["pred_masks"][idx]}
96
+ bin_i = mask_utils.decode(rle_i)
97
+
98
+ img_bgr_i = cv2.imread(img_path)
99
+ if img_bgr_i is None:
100
+ raise FileNotFoundError(f"Could not read image: {img_path}")
101
+ img_rgb_i = cv2.cvtColor(img_bgr_i, cv2.COLOR_BGR2RGB)
102
+
103
+ viz_i = Visualizer(
104
+ img_rgb_i,
105
+ font_size_multiplier=font_size_multiplier,
106
+ boarder_width_multiplier=boarder_width_multiplier,
107
+ )
108
+ viz_i.overlay_instances(
109
+ boxes=boxes_i,
110
+ masks=[rle_i],
111
+ binary_masks=[bin_i],
112
+ assigned_colors=[color_hex],
113
+ alpha=mask_alpha,
114
+ label_mode=label_mode,
115
+ )
116
+ pil_mask_i = Image.fromarray(viz_i.output.get_image())
117
+
118
+ return pil_mask_i, pil_mask_i_zoomed
third_party/GraspGen/sam3/sam3/eval/coco_reindex.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ Self-contained COCO JSON re-indexing function that creates temporary files.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional, Tuple
14
+
15
+
16
+ def reindex_coco_to_temp(input_json_path: str) -> Optional[str]:
17
+ """
18
+ Convert 0-indexed COCO JSON file to 1-indexed and save to temporary location.
19
+
20
+ Args:
21
+ input_json_path: Path to the input COCO JSON file
22
+
23
+ Returns:
24
+ Path to the new 1-indexed JSON file in temporary directory, or None if no conversion needed
25
+
26
+ Raises:
27
+ FileNotFoundError: If input file doesn't exist
28
+ json.JSONDecodeError: If input file is not valid JSON
29
+ ValueError: If input file is not a valid COCO format
30
+ """
31
+
32
+ def is_coco_json(data: Dict[str, Any]) -> bool:
33
+ """Check if data appears to be a COCO format file."""
34
+ if not isinstance(data, dict):
35
+ return False
36
+ # A COCO file should have at least one of these keys
37
+ coco_keys = {"images", "annotations", "categories"}
38
+ return any(key in data for key in coco_keys)
39
+
40
+ def check_zero_indexed(data: Dict[str, Any]) -> Tuple[bool, bool, bool]:
41
+ """
42
+ Check if annotations, images, or categories start from index 0.
43
+
44
+ Returns:
45
+ Tuple of (annotations_zero_indexed, images_zero_indexed, categories_zero_indexed)
46
+ """
47
+ annotations_zero = False
48
+ images_zero = False
49
+ categories_zero = False
50
+
51
+ # Check annotations
52
+ annotations = data.get("annotations", [])
53
+ if annotations and any(ann.get("id", -1) == 0 for ann in annotations):
54
+ annotations_zero = True
55
+
56
+ # Check images
57
+ images = data.get("images", [])
58
+ if images and any(img.get("id", -1) == 0 for img in images):
59
+ images_zero = True
60
+
61
+ # Check categories
62
+ categories = data.get("categories", [])
63
+ if categories and any(cat.get("id", -1) == 0 for cat in categories):
64
+ categories_zero = True
65
+
66
+ return annotations_zero, images_zero, categories_zero
67
+
68
+ def reindex_coco_data(data: Dict[str, Any]) -> Dict[str, Any]:
69
+ """Convert 0-indexed COCO data to 1-indexed."""
70
+ modified_data = data.copy()
71
+
72
+ annotations_zero, images_zero, categories_zero = check_zero_indexed(data)
73
+
74
+ # Create ID mapping for consistency
75
+ image_id_mapping = {}
76
+ category_id_mapping = {}
77
+
78
+ # Process images first (since annotations reference image IDs)
79
+ if images_zero and "images" in modified_data:
80
+ for img in modified_data["images"]:
81
+ old_id = img["id"]
82
+ new_id = old_id + 1
83
+ image_id_mapping[old_id] = new_id
84
+ img["id"] = new_id
85
+
86
+ # Process categories (since annotations reference category IDs)
87
+ if categories_zero and "categories" in modified_data:
88
+ for cat in modified_data["categories"]:
89
+ old_id = cat["id"]
90
+ new_id = old_id + 1
91
+ category_id_mapping[old_id] = new_id
92
+ cat["id"] = new_id
93
+
94
+ # Process annotations
95
+ if "annotations" in modified_data:
96
+ for ann in modified_data["annotations"]:
97
+ # Update annotation ID if needed
98
+ if annotations_zero:
99
+ ann["id"] = ann["id"] + 1
100
+
101
+ # Update image_id reference if images were reindexed
102
+ if images_zero and ann.get("image_id") is not None:
103
+ old_image_id = ann["image_id"]
104
+ if old_image_id in image_id_mapping:
105
+ ann["image_id"] = image_id_mapping[old_image_id]
106
+
107
+ # Update category_id reference if categories were reindexed
108
+ if categories_zero and ann.get("category_id") is not None:
109
+ old_category_id = ann["category_id"]
110
+ if old_category_id in category_id_mapping:
111
+ ann["category_id"] = category_id_mapping[old_category_id]
112
+
113
+ return modified_data
114
+
115
+ # Validate input path
116
+ if not os.path.exists(input_json_path):
117
+ raise FileNotFoundError(f"Input file not found: {input_json_path}")
118
+
119
+ # Load and validate JSON data
120
+ try:
121
+ with open(input_json_path, "r", encoding="utf-8") as f:
122
+ data = json.load(f)
123
+ except json.JSONDecodeError as e:
124
+ raise json.JSONDecodeError(f"Invalid JSON in {input_json_path}: {e}")
125
+
126
+ # Validate COCO format
127
+ if not is_coco_json(data):
128
+ raise ValueError(
129
+ f"File does not appear to be in COCO format: {input_json_path}"
130
+ )
131
+
132
+ # Check if reindexing is needed
133
+ annotations_zero, images_zero, categories_zero = check_zero_indexed(data)
134
+
135
+ if not (annotations_zero or images_zero or categories_zero):
136
+ # No conversion needed - just copy to temp location
137
+ input_path = Path(input_json_path)
138
+ temp_dir = tempfile.mkdtemp()
139
+ temp_filename = f"{input_path.stem}_1_indexed{input_path.suffix}"
140
+ temp_path = os.path.join(temp_dir, temp_filename)
141
+
142
+ with open(temp_path, "w", encoding="utf-8") as f:
143
+ json.dump(data, f, indent=2, ensure_ascii=False)
144
+
145
+ return temp_path
146
+
147
+ # Perform reindexing
148
+ modified_data = reindex_coco_data(data)
149
+
150
+ # Create temporary file
151
+ input_path = Path(input_json_path)
152
+ temp_dir = tempfile.mkdtemp()
153
+ temp_filename = f"{input_path.stem}_1_indexed{input_path.suffix}"
154
+ temp_path = os.path.join(temp_dir, temp_filename)
155
+
156
+ # Write modified data to temporary file
157
+ with open(temp_path, "w", encoding="utf-8") as f:
158
+ json.dump(modified_data, f, indent=2, ensure_ascii=False)
159
+
160
+ return temp_path
161
+
162
+
163
+ # Example usage and test function
164
+ def test_reindex_function():
165
+ """Test the reindex function with a sample COCO file."""
166
+
167
+ # Create a test COCO file
168
+ test_data = {
169
+ "info": {"description": "Test COCO dataset", "version": "1.0", "year": 2023},
170
+ "images": [
171
+ {"id": 0, "width": 640, "height": 480, "file_name": "test1.jpg"},
172
+ {"id": 1, "width": 640, "height": 480, "file_name": "test2.jpg"},
173
+ ],
174
+ "categories": [
175
+ {"id": 0, "name": "person", "supercategory": "person"},
176
+ {"id": 1, "name": "car", "supercategory": "vehicle"},
177
+ ],
178
+ "annotations": [
179
+ {
180
+ "id": 0,
181
+ "image_id": 0,
182
+ "category_id": 0,
183
+ "bbox": [100, 100, 50, 75],
184
+ "area": 3750,
185
+ "iscrowd": 0,
186
+ },
187
+ {
188
+ "id": 1,
189
+ "image_id": 1,
190
+ "category_id": 1,
191
+ "bbox": [200, 150, 120, 80],
192
+ "area": 9600,
193
+ "iscrowd": 0,
194
+ },
195
+ ],
196
+ }
197
+
198
+ # Create temporary test file
199
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
200
+ json.dump(test_data, f, indent=2)
201
+ test_file_path = f.name
202
+
203
+ try:
204
+ # Test the function
205
+ result_path = reindex_coco_to_temp(test_file_path)
206
+ print(f"Original file: {test_file_path}")
207
+ print(f"Converted file: {result_path}")
208
+
209
+ # Load and display the result
210
+ with open(result_path, "r") as f:
211
+ result_data = json.load(f)
212
+
213
+ print("\nConverted data sample:")
214
+ print(f"First image ID: {result_data['images'][0]['id']}")
215
+ print(f"First category ID: {result_data['categories'][0]['id']}")
216
+ print(f"First annotation ID: {result_data['annotations'][0]['id']}")
217
+ print(f"First annotation image_id: {result_data['annotations'][0]['image_id']}")
218
+ print(
219
+ f"First annotation category_id: {result_data['annotations'][0]['category_id']}"
220
+ )
221
+
222
+ # Clean up
223
+ os.unlink(result_path)
224
+ os.rmdir(os.path.dirname(result_path))
225
+
226
+ finally:
227
+ # Clean up test file
228
+ os.unlink(test_file_path)
229
+
230
+
231
+ if __name__ == "__main__":
232
+ test_reindex_function()
third_party/GraspGen/sam3/sam3/eval/coco_writer.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ COCO prediction dumper for distributed training.
7
+
8
+ Handles collection and dumping of COCO-format predictions from models.
9
+ Supports distributed processing with multiple GPUs/processes.
10
+ """
11
+
12
+ import copy
13
+ import gc
14
+ import heapq
15
+ import json
16
+ import logging
17
+ import os
18
+ from collections import defaultdict
19
+ from pathlib import Path
20
+ from typing import Any, Optional
21
+
22
+ import pycocotools.mask as mask_utils
23
+ import torch
24
+ from iopath.common.file_io import g_pathmgr
25
+ from sam3.eval.coco_eval_offline import convert_to_xywh
26
+ from sam3.train.masks_ops import rle_encode
27
+ from sam3.train.utils.distributed import (
28
+ all_gather,
29
+ gather_to_rank_0_via_filesys,
30
+ get_rank,
31
+ is_main_process,
32
+ )
33
+
34
+
35
+ ### Helper functions and classes
36
+
37
+
38
+ class HeapElement:
39
+ """Utility class to make a heap with a custom comparator based on score."""
40
+
41
+ def __init__(self, val):
42
+ self.val = val
43
+
44
+ def __lt__(self, other):
45
+ return self.val["score"] < other.val["score"]
46
+
47
+
48
+ class PredictionDumper:
49
+ """
50
+ Handles collection and dumping of COCO-format predictions from a model.
51
+
52
+ This class processes model outputs through a postprocessor, converts them to COCO format,
53
+ and saves them to disk. It supports distributed processing with multiple GPUs/processes.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ dump_dir: str,
59
+ postprocessor,
60
+ maxdets: int,
61
+ iou_type: str,
62
+ gather_pred_via_filesys: bool = False,
63
+ merge_predictions: bool = False,
64
+ pred_file_evaluators: Optional[Any] = None,
65
+ ):
66
+ """
67
+ Initialize the PredictionDumper.
68
+
69
+ Args:
70
+ dump_dir: Directory to dump predictions.
71
+ postprocessor: Module to convert the model's output into COCO format.
72
+ maxdets: Maximum number of detections per image.
73
+ iou_type: IoU type to evaluate. Can include "bbox", "segm"
74
+ gather_pred_via_filesys: If True, use the filesystem for collective gathers across
75
+ processes (requires a shared filesystem). Otherwise, use torch collective ops.
76
+ merge_predictions: If True, merge predictions from all processes and dump to a single file.
77
+ """
78
+ self.iou_type = iou_type
79
+ self.maxdets = maxdets
80
+ self.dump_dir = dump_dir
81
+ self.postprocessor = postprocessor
82
+ self.gather_pred_via_filesys = gather_pred_via_filesys
83
+ self.merge_predictions = merge_predictions
84
+ self.pred_file_evaluators = pred_file_evaluators
85
+ if self.pred_file_evaluators is not None:
86
+ assert merge_predictions, (
87
+ "merge_predictions must be True if pred_file_evaluators are provided"
88
+ )
89
+ assert self.dump_dir is not None, "dump_dir must be provided"
90
+
91
+ if is_main_process():
92
+ os.makedirs(self.dump_dir, exist_ok=True)
93
+ logging.info(f"Created prediction dump directory: {self.dump_dir}")
94
+
95
+ # Initialize state
96
+ self.reset()
97
+
98
+ def update(self, *args, **kwargs):
99
+ """
100
+ Process and accumulate predictions from model outputs.
101
+
102
+ Args:
103
+ *args, **kwargs: Arguments passed to postprocessor.process_results()
104
+ """
105
+ predictions = self.postprocessor.process_results(*args, **kwargs)
106
+ results = self.prepare(predictions, self.iou_type)
107
+ self._dump(results)
108
+
109
+ def _dump(self, results):
110
+ """
111
+ Add results to the dump list with precision rounding.
112
+
113
+ Args:
114
+ results: List of prediction dictionaries in COCO format.
115
+ """
116
+ dumped_results = copy.deepcopy(results)
117
+ for r in dumped_results:
118
+ if "bbox" in r:
119
+ r["bbox"] = [round(coord, 5) for coord in r["bbox"]]
120
+ r["score"] = round(r["score"], 5)
121
+ self.dump.extend(dumped_results)
122
+
123
+ def synchronize_between_processes(self):
124
+ """
125
+ Synchronize predictions across all processes and save to disk.
126
+
127
+ If gather_pred_via_filesys is True, uses filesystem for gathering.
128
+ Otherwise, uses torch distributed collective operations.
129
+ Saves per-rank predictions to separate JSON files.
130
+ """
131
+ logging.info("Prediction Dumper: Synchronizing between processes")
132
+
133
+ if not self.merge_predictions:
134
+ dumped_file = (
135
+ Path(self.dump_dir)
136
+ / f"coco_predictions_{self.iou_type}_{get_rank()}.json"
137
+ )
138
+ logging.info(
139
+ f"Prediction Dumper: Dumping local predictions to {dumped_file}"
140
+ )
141
+ with g_pathmgr.open(str(dumped_file), "w") as f:
142
+ json.dump(self.dump, f)
143
+ else:
144
+ self.dump = self.gather_and_merge_predictions()
145
+ dumped_file = Path(self.dump_dir) / f"coco_predictions_{self.iou_type}.json"
146
+ if is_main_process():
147
+ logging.info(
148
+ f"Prediction Dumper: Dumping merged predictions to {dumped_file}"
149
+ )
150
+ with g_pathmgr.open(str(dumped_file), "w") as f:
151
+ json.dump(self.dump, f)
152
+
153
+ self.reset()
154
+ return dumped_file
155
+
156
+ def gather_and_merge_predictions(self):
157
+ """
158
+ Gather predictions from all processes and merge them, keeping top predictions per image.
159
+
160
+ This method collects predictions from all processes, then keeps only the top maxdets
161
+ predictions per image based on score. It also deduplicates predictions by (image_id, category_id).
162
+
163
+ Returns:
164
+ List of merged prediction dictionaries.
165
+ """
166
+ logging.info("Prediction Dumper: Gathering predictions from all processes")
167
+ gc.collect()
168
+
169
+ if self.gather_pred_via_filesys:
170
+ dump = gather_to_rank_0_via_filesys(self.dump)
171
+ else:
172
+ dump = all_gather(self.dump, force_cpu=True)
173
+
174
+ # Combine predictions, keeping only top maxdets per image
175
+ preds_by_image = defaultdict(list)
176
+ seen_img_cat = set()
177
+
178
+ for cur_dump in dump:
179
+ cur_seen_img_cat = set()
180
+ for p in cur_dump:
181
+ image_id = p["image_id"]
182
+ cat_id = p["category_id"]
183
+
184
+ # Skip if we've already seen this image/category pair in a previous dump
185
+ if (image_id, cat_id) in seen_img_cat:
186
+ continue
187
+
188
+ cur_seen_img_cat.add((image_id, cat_id))
189
+
190
+ # Use a min-heap to keep top predictions
191
+ if len(preds_by_image[image_id]) < self.maxdets:
192
+ heapq.heappush(preds_by_image[image_id], HeapElement(p))
193
+ else:
194
+ heapq.heappushpop(preds_by_image[image_id], HeapElement(p))
195
+
196
+ seen_img_cat.update(cur_seen_img_cat)
197
+
198
+ # Flatten the heap elements back to a list
199
+ merged_dump = sum(
200
+ [[h.val for h in cur_preds] for cur_preds in preds_by_image.values()], []
201
+ )
202
+
203
+ return merged_dump
204
+
205
+ def compute_synced(self):
206
+ """
207
+ Synchronize predictions across processes and compute summary.
208
+
209
+ Returns:
210
+ Summary dictionary from summarize().
211
+ """
212
+ dumped_file = self.synchronize_between_processes()
213
+ if not is_main_process():
214
+ return {"": 0.0}
215
+
216
+ meters = {}
217
+ if self.pred_file_evaluators is not None:
218
+ for evaluator in self.pred_file_evaluators:
219
+ results = evaluator.evaluate(dumped_file)
220
+ meters.update(results)
221
+
222
+ if len(meters) == 0:
223
+ meters = {"": 0.0}
224
+ return meters
225
+
226
+ def compute(self):
227
+ """
228
+ Compute without synchronization.
229
+
230
+ Returns:
231
+ Empty metric dictionary.
232
+ """
233
+ return {"": 0.0}
234
+
235
+ def reset(self):
236
+ """Reset internal state for a new evaluation round."""
237
+ self.dump = []
238
+
239
+ def prepare(self, predictions, iou_type):
240
+ """
241
+ Route predictions to the appropriate preparation method based on iou_type.
242
+
243
+ Args:
244
+ predictions: Dictionary mapping image IDs to prediction dictionaries.
245
+ iou_type: Type of evaluation ("bbox", "segm").
246
+
247
+ Returns:
248
+ List of COCO-format prediction dictionaries.
249
+ """
250
+ if iou_type == "bbox":
251
+ return self.prepare_for_coco_detection(predictions)
252
+ elif iou_type == "segm":
253
+ return self.prepare_for_coco_segmentation(predictions)
254
+ else:
255
+ raise ValueError(f"Unknown iou type: {iou_type}")
256
+
257
+ def prepare_for_coco_detection(self, predictions):
258
+ """
259
+ Convert predictions to COCO detection format.
260
+
261
+ Args:
262
+ predictions: Dictionary mapping image IDs to prediction dictionaries
263
+ containing "boxes", "scores", and "labels".
264
+
265
+ Returns:
266
+ List of COCO-format detection dictionaries.
267
+ """
268
+ coco_results = []
269
+ for original_id, prediction in predictions.items():
270
+ if len(prediction) == 0:
271
+ continue
272
+
273
+ boxes = prediction["boxes"]
274
+ boxes = convert_to_xywh(boxes).tolist()
275
+ scores = prediction["scores"].tolist()
276
+ labels = prediction["labels"].tolist()
277
+
278
+ coco_results.extend(
279
+ [
280
+ {
281
+ "image_id": original_id,
282
+ "category_id": labels[k],
283
+ "bbox": box,
284
+ "score": scores[k],
285
+ }
286
+ for k, box in enumerate(boxes)
287
+ ]
288
+ )
289
+ return coco_results
290
+
291
+ @torch.no_grad()
292
+ def prepare_for_coco_segmentation(self, predictions):
293
+ """
294
+ Convert predictions to COCO segmentation format.
295
+
296
+ Args:
297
+ predictions: Dictionary mapping image IDs to prediction dictionaries
298
+ containing "masks" or "masks_rle", "scores", and "labels".
299
+ Optionally includes "boundaries" and "dilated_boundaries".
300
+
301
+ Returns:
302
+ List of COCO-format segmentation dictionaries with RLE-encoded masks.
303
+ """
304
+ coco_results = []
305
+ for original_id, prediction in predictions.items():
306
+ if len(prediction) == 0:
307
+ continue
308
+
309
+ scores = prediction["scores"].tolist()
310
+ labels = prediction["labels"].tolist()
311
+
312
+ boxes = None
313
+ if "boxes" in prediction:
314
+ boxes = prediction["boxes"]
315
+ boxes = convert_to_xywh(boxes).tolist()
316
+ assert len(boxes) == len(scores)
317
+
318
+ if "masks_rle" in prediction:
319
+ rles = prediction["masks_rle"]
320
+ areas = []
321
+ for rle in rles:
322
+ cur_area = mask_utils.area(rle)
323
+ h, w = rle["size"]
324
+ areas.append(cur_area / (h * w))
325
+ else:
326
+ masks = prediction["masks"]
327
+ masks = masks > 0.5
328
+ h, w = masks.shape[-2:]
329
+
330
+ areas = masks.flatten(1).sum(1) / (h * w)
331
+ areas = areas.tolist()
332
+
333
+ rles = rle_encode(masks.squeeze(1))
334
+
335
+ # Memory cleanup
336
+ del masks
337
+ del prediction["masks"]
338
+
339
+ assert len(areas) == len(rles) == len(scores)
340
+
341
+ for k, rle in enumerate(rles):
342
+ payload = {
343
+ "image_id": original_id,
344
+ "category_id": labels[k],
345
+ "segmentation": rle,
346
+ "score": scores[k],
347
+ "area": areas[k],
348
+ }
349
+ if boxes is not None:
350
+ payload["bbox"] = boxes[k]
351
+
352
+ coco_results.append(payload)
353
+
354
+ return coco_results
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
4
+
5
+ """run_youtube_vis.py
6
+ Run example:
7
+ run_youtube_vis.py --USE_PARALLEL False --METRICS HOTA --TRACKERS_TO_EVAL STEm_Seg
8
+ Command Line Arguments: Defaults, # Comments
9
+ Eval arguments:
10
+ 'USE_PARALLEL': False,
11
+ 'NUM_PARALLEL_CORES': 8,
12
+ 'BREAK_ON_ERROR': True, # Raises exception and exits with error
13
+ 'RETURN_ON_ERROR': False, # if not BREAK_ON_ERROR, then returns from function on error
14
+ 'LOG_ON_ERROR': os.path.join(code_path, 'error_log.txt'), # if not None, save any errors into a log file.
15
+ 'PRINT_RESULTS': True,
16
+ 'PRINT_ONLY_COMBINED': False,
17
+ 'PRINT_CONFIG': True,
18
+ 'TIME_PROGRESS': True,
19
+ 'DISPLAY_LESS_PROGRESS': True,
20
+ 'OUTPUT_SUMMARY': True,
21
+ 'OUTPUT_EMPTY_CLASSES': True, # If False, summary files are not output for classes with no detections
22
+ 'OUTPUT_DETAILED': True,
23
+ 'PLOT_CURVES': True,
24
+ Dataset arguments:
25
+ 'GT_FOLDER': os.path.join(code_path, 'data/gt/youtube_vis/youtube_vis_training'), # Location of GT data
26
+ 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/youtube_vis/youtube_vis_training'),
27
+ # Trackers location
28
+ 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
29
+ 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder)
30
+ 'CLASSES_TO_EVAL': None, # Classes to eval (if None, all classes)
31
+ 'SPLIT_TO_EVAL': 'training', # Valid: 'training', 'val'
32
+ 'PRINT_CONFIG': True, # Whether to print current config
33
+ 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
34
+ 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
35
+ 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
36
+ Metric arguments:
37
+ 'METRICS': ['TrackMAP', 'HOTA', 'CLEAR', 'Identity']
38
+ """
39
+
40
+ import argparse
41
+ import os
42
+ import sys
43
+ from multiprocessing import freeze_support
44
+
45
+ from . import trackeval
46
+
47
+
48
+ def run_ytvis_eval(args=None, gt_json=None, dt_json=None):
49
+ # Command line interface:
50
+ default_eval_config = trackeval.Evaluator.get_default_eval_config()
51
+ # print only combined since TrackMAP is undefined for per sequence breakdowns
52
+ default_eval_config["PRINT_ONLY_COMBINED"] = True
53
+ default_dataset_config = trackeval.datasets.YouTubeVIS.get_default_dataset_config()
54
+ default_metrics_config = {"METRICS": ["HOTA"]}
55
+ config = {
56
+ **default_eval_config,
57
+ **default_dataset_config,
58
+ **default_metrics_config,
59
+ } # Merge default configs
60
+ parser = argparse.ArgumentParser()
61
+ for setting in config.keys():
62
+ if type(config[setting]) == list or type(config[setting]) == type(None):
63
+ parser.add_argument("--" + setting, nargs="+")
64
+ else:
65
+ parser.add_argument("--" + setting)
66
+ args = parser.parse_args(args).__dict__
67
+ for setting in args.keys():
68
+ if args[setting] is not None:
69
+ if type(config[setting]) == type(True):
70
+ if args[setting] == "True":
71
+ x = True
72
+ elif args[setting] == "False":
73
+ x = False
74
+ else:
75
+ raise Exception(
76
+ "Command line parameter " + setting + "must be True or False"
77
+ )
78
+ elif type(config[setting]) == type(1):
79
+ x = int(args[setting])
80
+ elif type(args[setting]) == type(None):
81
+ x = None
82
+ else:
83
+ x = args[setting]
84
+ config[setting] = x
85
+ eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()}
86
+ dataset_config = {
87
+ k: v for k, v in config.items() if k in default_dataset_config.keys()
88
+ }
89
+ metrics_config = {
90
+ k: v for k, v in config.items() if k in default_metrics_config.keys()
91
+ }
92
+
93
+ # Run code
94
+ evaluator = trackeval.Evaluator(eval_config)
95
+ # allow directly specifying the GT JSON data and Tracker (result)
96
+ # JSON data as Python objects, without reading from files.
97
+ dataset_config["GT_JSON_OBJECT"] = gt_json
98
+ dataset_config["TRACKER_JSON_OBJECT"] = dt_json
99
+ dataset_list = [trackeval.datasets.YouTubeVIS(dataset_config)]
100
+ metrics_list = []
101
+ # for metric in [trackeval.metrics.TrackMAP, trackeval.metrics.HOTA, trackeval.metrics.CLEAR,
102
+ # trackeval.metrics.Identity]:
103
+ for metric in [trackeval.metrics.HOTA]:
104
+ if metric.get_name() in metrics_config["METRICS"]:
105
+ metrics_list.append(metric())
106
+ if len(metrics_list) == 0:
107
+ raise Exception("No metrics selected for evaluation")
108
+ output_res, output_msg = evaluator.evaluate(dataset_list, metrics_list)
109
+ return output_res, output_msg
110
+
111
+
112
+ if __name__ == "__main__":
113
+ import sys
114
+
115
+ freeze_support()
116
+ run_ytvis_eval(sys.argv[1:])
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
4
+
5
+ from . import datasets, metrics, utils
6
+ from .eval import Evaluator
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/_timing.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
4
+
5
+ import inspect
6
+ from functools import wraps
7
+ from time import perf_counter
8
+
9
+ DO_TIMING = False
10
+ DISPLAY_LESS_PROGRESS = False
11
+ timer_dict = {}
12
+ counter = 0
13
+
14
+
15
+ def time(f):
16
+ @wraps(f)
17
+ def wrap(*args, **kw):
18
+ if DO_TIMING:
19
+ # Run function with timing
20
+ ts = perf_counter()
21
+ result = f(*args, **kw)
22
+ te = perf_counter()
23
+ tt = te - ts
24
+
25
+ # Get function name
26
+ arg_names = inspect.getfullargspec(f)[0]
27
+ if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS:
28
+ return result
29
+ elif arg_names[0] == "self":
30
+ method_name = type(args[0]).__name__ + "." + f.__name__
31
+ else:
32
+ method_name = f.__name__
33
+
34
+ # Record accumulative time in each function for analysis
35
+ if method_name in timer_dict.keys():
36
+ timer_dict[method_name] += tt
37
+ else:
38
+ timer_dict[method_name] = tt
39
+
40
+ # If code is finished, display timing summary
41
+ if method_name == "Evaluator.evaluate":
42
+ print("")
43
+ print("Timing analysis:")
44
+ for key, value in timer_dict.items():
45
+ print("%-70s %2.4f sec" % (key, value))
46
+ else:
47
+ # Get function argument values for printing special arguments of interest
48
+ arg_titles = ["tracker", "seq", "cls"]
49
+ arg_vals = []
50
+ for i, a in enumerate(arg_names):
51
+ if a in arg_titles:
52
+ arg_vals.append(args[i])
53
+ arg_text = "(" + ", ".join(arg_vals) + ")"
54
+
55
+ # Display methods and functions with different indentation.
56
+ if arg_names[0] == "self":
57
+ print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt))
58
+ elif arg_names[0] == "test":
59
+ pass
60
+ else:
61
+ global counter
62
+ counter += 1
63
+ print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
64
+
65
+ return result
66
+ else:
67
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
68
+ return f(*args, **kw)
69
+
70
+ return wrap
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/eval.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
4
+
5
+ import os
6
+ import time
7
+ import traceback
8
+ from functools import partial
9
+ from multiprocessing.pool import Pool
10
+
11
+ import numpy as np
12
+
13
+ from . import _timing, utils
14
+ from .metrics import Count
15
+ from .utils import TrackEvalException
16
+
17
+ try:
18
+ import tqdm
19
+
20
+ TQDM_IMPORTED = True
21
+ except ImportError as _:
22
+ TQDM_IMPORTED = False
23
+
24
+
25
+ class Evaluator:
26
+ """Evaluator class for evaluating different metrics for different datasets"""
27
+
28
+ @staticmethod
29
+ def get_default_eval_config():
30
+ """Returns the default config values for evaluation"""
31
+ code_path = utils.get_code_path()
32
+ default_config = {
33
+ "USE_PARALLEL": False,
34
+ "NUM_PARALLEL_CORES": 8,
35
+ "BREAK_ON_ERROR": True, # Raises exception and exits with error
36
+ "RETURN_ON_ERROR": False, # if not BREAK_ON_ERROR, then returns from function on error
37
+ "LOG_ON_ERROR": os.path.join(
38
+ code_path, "error_log.txt"
39
+ ), # if not None, save any errors into a log file.
40
+ "PRINT_RESULTS": True,
41
+ "PRINT_ONLY_COMBINED": False,
42
+ "PRINT_CONFIG": True,
43
+ "TIME_PROGRESS": True,
44
+ "DISPLAY_LESS_PROGRESS": True,
45
+ "OUTPUT_SUMMARY": True,
46
+ "OUTPUT_EMPTY_CLASSES": True, # If False, summary files are not output for classes with no detections
47
+ "OUTPUT_DETAILED": True,
48
+ "PLOT_CURVES": True,
49
+ }
50
+ return default_config
51
+
52
+ def __init__(self, config=None):
53
+ """Initialise the evaluator with a config file"""
54
+ self.config = utils.init_config(config, self.get_default_eval_config(), "Eval")
55
+ # Only run timing analysis if not run in parallel.
56
+ if self.config["TIME_PROGRESS"] and not self.config["USE_PARALLEL"]:
57
+ _timing.DO_TIMING = True
58
+ if self.config["DISPLAY_LESS_PROGRESS"]:
59
+ _timing.DISPLAY_LESS_PROGRESS = True
60
+
61
+ def _combine_results(
62
+ self,
63
+ res,
64
+ metrics_list,
65
+ metric_names,
66
+ dataset,
67
+ res_field="COMBINED_SEQ",
68
+ target_tag=None,
69
+ ):
70
+ assert res_field.startswith("COMBINED_SEQ")
71
+ # collecting combined cls keys (cls averaged, det averaged, super classes)
72
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
73
+ combined_cls_keys = []
74
+ res[res_field] = {}
75
+
76
+ # narrow the target for evaluation
77
+ if target_tag is not None:
78
+ target_video_ids = [
79
+ annot["video_id"]
80
+ for annot in dataset.gt_data["annotations"]
81
+ if target_tag in annot["tags"]
82
+ ]
83
+ vid2name = {
84
+ video["id"]: video["file_names"][0].split("/")[0]
85
+ for video in dataset.gt_data["videos"]
86
+ }
87
+ target_video_ids = set(target_video_ids)
88
+ target_video = [vid2name[video_id] for video_id in target_video_ids]
89
+
90
+ if len(target_video) == 0:
91
+ raise TrackEvalException(
92
+ "No sequences found with the tag %s" % target_tag
93
+ )
94
+
95
+ target_annotations = [
96
+ annot
97
+ for annot in dataset.gt_data["annotations"]
98
+ if annot["video_id"] in target_video_ids
99
+ ]
100
+ assert all(target_tag in annot["tags"] for annot in target_annotations), (
101
+ f"Not all annotations in the target sequences have the target tag {target_tag}. "
102
+ "We currently only support a target tag at the sequence level, not at the annotation level."
103
+ )
104
+ else:
105
+ target_video = seq_list
106
+
107
+ # combine sequences for each class
108
+ for c_cls in class_list:
109
+ res[res_field][c_cls] = {}
110
+ for metric, metric_name in zip(metrics_list, metric_names):
111
+ curr_res = {
112
+ seq_key: seq_value[c_cls][metric_name]
113
+ for seq_key, seq_value in res.items()
114
+ if not seq_key.startswith("COMBINED_SEQ")
115
+ and seq_key in target_video
116
+ }
117
+ res[res_field][c_cls][metric_name] = metric.combine_sequences(curr_res)
118
+ # combine classes
119
+ if dataset.should_classes_combine:
120
+ combined_cls_keys += [
121
+ "cls_comb_cls_av",
122
+ "cls_comb_det_av",
123
+ "all",
124
+ ]
125
+ res[res_field]["cls_comb_cls_av"] = {}
126
+ res[res_field]["cls_comb_det_av"] = {}
127
+ for metric, metric_name in zip(metrics_list, metric_names):
128
+ cls_res = {
129
+ cls_key: cls_value[metric_name]
130
+ for cls_key, cls_value in res[res_field].items()
131
+ if cls_key not in combined_cls_keys
132
+ }
133
+ res[res_field]["cls_comb_cls_av"][metric_name] = (
134
+ metric.combine_classes_class_averaged(cls_res)
135
+ )
136
+ res[res_field]["cls_comb_det_av"][metric_name] = (
137
+ metric.combine_classes_det_averaged(cls_res)
138
+ )
139
+ # combine classes to super classes
140
+ if dataset.use_super_categories:
141
+ for cat, sub_cats in dataset.super_categories.items():
142
+ combined_cls_keys.append(cat)
143
+ res[res_field][cat] = {}
144
+ for metric, metric_name in zip(metrics_list, metric_names):
145
+ cat_res = {
146
+ cls_key: cls_value[metric_name]
147
+ for cls_key, cls_value in res[res_field].items()
148
+ if cls_key in sub_cats
149
+ }
150
+ res[res_field][cat][metric_name] = (
151
+ metric.combine_classes_det_averaged(cat_res)
152
+ )
153
+ return res, combined_cls_keys
154
+
155
+ def _summarize_results(
156
+ self,
157
+ res,
158
+ tracker,
159
+ metrics_list,
160
+ metric_names,
161
+ dataset,
162
+ res_field,
163
+ combined_cls_keys,
164
+ ):
165
+ config = self.config
166
+ output_fol = dataset.get_output_fol(tracker)
167
+ tracker_display_name = dataset.get_display_name(tracker)
168
+ for c_cls in res[
169
+ res_field
170
+ ].keys(): # class_list + combined classes if calculated
171
+ summaries = []
172
+ details = []
173
+ num_dets = res[res_field][c_cls]["Count"]["Dets"]
174
+ if config["OUTPUT_EMPTY_CLASSES"] or num_dets > 0:
175
+ for metric, metric_name in zip(metrics_list, metric_names):
176
+ # for combined classes there is no per sequence evaluation
177
+ if c_cls in combined_cls_keys:
178
+ table_res = {res_field: res[res_field][c_cls][metric_name]}
179
+ else:
180
+ table_res = {
181
+ seq_key: seq_value[c_cls][metric_name]
182
+ for seq_key, seq_value in res.items()
183
+ }
184
+
185
+ if config["PRINT_RESULTS"] and config["PRINT_ONLY_COMBINED"]:
186
+ dont_print = (
187
+ dataset.should_classes_combine
188
+ and c_cls not in combined_cls_keys
189
+ )
190
+ if not dont_print:
191
+ metric.print_table(
192
+ {res_field: table_res[res_field]},
193
+ tracker_display_name,
194
+ c_cls,
195
+ res_field,
196
+ res_field,
197
+ )
198
+ elif config["PRINT_RESULTS"]:
199
+ metric.print_table(
200
+ table_res, tracker_display_name, c_cls, res_field, res_field
201
+ )
202
+ if config["OUTPUT_SUMMARY"]:
203
+ summaries.append(metric.summary_results(table_res))
204
+ if config["OUTPUT_DETAILED"]:
205
+ details.append(metric.detailed_results(table_res))
206
+ if config["PLOT_CURVES"]:
207
+ metric.plot_single_tracker_results(
208
+ table_res,
209
+ tracker_display_name,
210
+ c_cls,
211
+ output_fol,
212
+ )
213
+ if config["OUTPUT_SUMMARY"]:
214
+ utils.write_summary_results(summaries, c_cls, output_fol)
215
+ if config["OUTPUT_DETAILED"]:
216
+ utils.write_detailed_results(details, c_cls, output_fol)
217
+
218
+ @_timing.time
219
+ def evaluate(self, dataset_list, metrics_list, show_progressbar=False):
220
+ """Evaluate a set of metrics on a set of datasets"""
221
+ config = self.config
222
+ metrics_list = metrics_list + [Count()] # Count metrics are always run
223
+ metric_names = utils.validate_metrics_list(metrics_list)
224
+ dataset_names = [dataset.get_name() for dataset in dataset_list]
225
+ output_res = {}
226
+ output_msg = {}
227
+
228
+ for dataset, dataset_name in zip(dataset_list, dataset_names):
229
+ # Get dataset info about what to evaluate
230
+ output_res[dataset_name] = {}
231
+ output_msg[dataset_name] = {}
232
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
233
+ print(
234
+ "\nEvaluating %i tracker(s) on %i sequence(s) for %i class(es) on %s dataset using the following "
235
+ "metrics: %s\n"
236
+ % (
237
+ len(tracker_list),
238
+ len(seq_list),
239
+ len(class_list),
240
+ dataset_name,
241
+ ", ".join(metric_names),
242
+ )
243
+ )
244
+
245
+ # Evaluate each tracker
246
+ for tracker in tracker_list:
247
+ # if not config['BREAK_ON_ERROR'] then go to next tracker without breaking
248
+ try:
249
+ # Evaluate each sequence in parallel or in series.
250
+ # returns a nested dict (res), indexed like: res[seq][class][metric_name][sub_metric field]
251
+ # e.g. res[seq_0001][pedestrian][hota][DetA]
252
+ print("\nEvaluating %s\n" % tracker)
253
+ time_start = time.time()
254
+ if config["USE_PARALLEL"]:
255
+ if show_progressbar and TQDM_IMPORTED:
256
+ seq_list_sorted = sorted(seq_list)
257
+
258
+ with (
259
+ Pool(config["NUM_PARALLEL_CORES"]) as pool,
260
+ tqdm.tqdm(total=len(seq_list)) as pbar,
261
+ ):
262
+ _eval_sequence = partial(
263
+ eval_sequence,
264
+ dataset=dataset,
265
+ tracker=tracker,
266
+ class_list=class_list,
267
+ metrics_list=metrics_list,
268
+ metric_names=metric_names,
269
+ )
270
+ results = []
271
+ for r in pool.imap(
272
+ _eval_sequence, seq_list_sorted, chunksize=20
273
+ ):
274
+ results.append(r)
275
+ pbar.update()
276
+ res = dict(zip(seq_list_sorted, results))
277
+
278
+ else:
279
+ with Pool(config["NUM_PARALLEL_CORES"]) as pool:
280
+ _eval_sequence = partial(
281
+ eval_sequence,
282
+ dataset=dataset,
283
+ tracker=tracker,
284
+ class_list=class_list,
285
+ metrics_list=metrics_list,
286
+ metric_names=metric_names,
287
+ )
288
+ results = pool.map(_eval_sequence, seq_list)
289
+ res = dict(zip(seq_list, results))
290
+ else:
291
+ res = {}
292
+ if show_progressbar and TQDM_IMPORTED:
293
+ seq_list_sorted = sorted(seq_list)
294
+ for curr_seq in tqdm.tqdm(seq_list_sorted):
295
+ res[curr_seq] = eval_sequence(
296
+ curr_seq,
297
+ dataset,
298
+ tracker,
299
+ class_list,
300
+ metrics_list,
301
+ metric_names,
302
+ )
303
+ else:
304
+ for curr_seq in sorted(seq_list):
305
+ res[curr_seq] = eval_sequence(
306
+ curr_seq,
307
+ dataset,
308
+ tracker,
309
+ class_list,
310
+ metrics_list,
311
+ metric_names,
312
+ )
313
+
314
+ # Combine results over all sequences and then over all classes
315
+ res, combined_cls_keys = self._combine_results(
316
+ res, metrics_list, metric_names, dataset, "COMBINED_SEQ"
317
+ )
318
+
319
+ if np.all(
320
+ ["tags" in annot for annot in dataset.gt_data["annotations"]]
321
+ ):
322
+ # Combine results over the challenging sequences and then over all classes
323
+ # currently only support "tracking_challenging_pair"
324
+ res, _ = self._combine_results(
325
+ res,
326
+ metrics_list,
327
+ metric_names,
328
+ dataset,
329
+ "COMBINED_SEQ_CHALLENGING",
330
+ "tracking_challenging_pair",
331
+ )
332
+
333
+ # Print and output results in various formats
334
+ if config["TIME_PROGRESS"]:
335
+ print(
336
+ "\nAll sequences for %s finished in %.2f seconds"
337
+ % (tracker, time.time() - time_start)
338
+ )
339
+
340
+ self._summarize_results(
341
+ res,
342
+ tracker,
343
+ metrics_list,
344
+ metric_names,
345
+ dataset,
346
+ "COMBINED_SEQ",
347
+ combined_cls_keys,
348
+ )
349
+ if "COMBINED_SEQ_CHALLENGING" in res:
350
+ self._summarize_results(
351
+ res,
352
+ tracker,
353
+ metrics_list,
354
+ metric_names,
355
+ dataset,
356
+ "COMBINED_SEQ_CHALLENGING",
357
+ combined_cls_keys,
358
+ )
359
+
360
+ # Output for returning from function
361
+ output_res[dataset_name][tracker] = res
362
+ output_msg[dataset_name][tracker] = "Success"
363
+
364
+ except Exception as err:
365
+ output_res[dataset_name][tracker] = None
366
+ if type(err) == TrackEvalException:
367
+ output_msg[dataset_name][tracker] = str(err)
368
+ else:
369
+ output_msg[dataset_name][tracker] = "Unknown error occurred."
370
+ print("Tracker %s was unable to be evaluated." % tracker)
371
+ print(err)
372
+ traceback.print_exc()
373
+ if config["LOG_ON_ERROR"] is not None:
374
+ with open(config["LOG_ON_ERROR"], "a") as f:
375
+ print(dataset_name, file=f)
376
+ print(tracker, file=f)
377
+ print(traceback.format_exc(), file=f)
378
+ print("\n\n\n", file=f)
379
+ if config["BREAK_ON_ERROR"]:
380
+ raise err
381
+ elif config["RETURN_ON_ERROR"]:
382
+ return output_res, output_msg
383
+
384
+ return output_res, output_msg
385
+
386
+
387
+ @_timing.time
388
+ def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names):
389
+ """Function for evaluating a single sequence"""
390
+
391
+ raw_data = dataset.get_raw_seq_data(tracker, seq)
392
+ seq_res = {}
393
+ for cls in class_list:
394
+ seq_res[cls] = {}
395
+ data = dataset.get_preprocessed_seq_data(raw_data, cls)
396
+ for metric, met_name in zip(metrics_list, metric_names):
397
+ seq_res[cls][met_name] = metric.eval_sequence(data)
398
+ return seq_res
third_party/GraspGen/sam3/sam3/eval/hota_eval_toolkit/trackeval/utils.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+
3
+ # pyre-unsafe
4
+
5
+ import argparse
6
+ import csv
7
+ import os
8
+ from collections import OrderedDict
9
+
10
+
11
+ def init_config(config, default_config, name=None):
12
+ """Initialise non-given config values with defaults"""
13
+ if config is None:
14
+ config = default_config
15
+ else:
16
+ for k in default_config.keys():
17
+ if k not in config.keys():
18
+ config[k] = default_config[k]
19
+ if name and config["PRINT_CONFIG"]:
20
+ print("\n%s Config:" % name)
21
+ for c in config.keys():
22
+ print("%-20s : %-30s" % (c, config[c]))
23
+ return config
24
+
25
+
26
+ def update_config(config):
27
+ """
28
+ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
29
+ :param config: the config to update
30
+ :return: the updated config
31
+ """
32
+ parser = argparse.ArgumentParser()
33
+ for setting in config.keys():
34
+ if type(config[setting]) == list or type(config[setting]) == type(None):
35
+ parser.add_argument("--" + setting, nargs="+")
36
+ else:
37
+ parser.add_argument("--" + setting)
38
+ args = parser.parse_args().__dict__
39
+ for setting in args.keys():
40
+ if args[setting] is not None:
41
+ if type(config[setting]) == type(True):
42
+ if args[setting] == "True":
43
+ x = True
44
+ elif args[setting] == "False":
45
+ x = False
46
+ else:
47
+ raise Exception(
48
+ "Command line parameter " + setting + "must be True or False"
49
+ )
50
+ elif type(config[setting]) == type(1):
51
+ x = int(args[setting])
52
+ elif type(args[setting]) == type(None):
53
+ x = None
54
+ else:
55
+ x = args[setting]
56
+ config[setting] = x
57
+ return config
58
+
59
+
60
+ def get_code_path():
61
+ """Get base path where code is"""
62
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
63
+
64
+
65
+ def validate_metrics_list(metrics_list):
66
+ """Get names of metric class and ensures they are unique, further checks that the fields within each metric class
67
+ do not have overlapping names.
68
+ """
69
+ metric_names = [metric.get_name() for metric in metrics_list]
70
+ # check metric names are unique
71
+ if len(metric_names) != len(set(metric_names)):
72
+ raise TrackEvalException(
73
+ "Code being run with multiple metrics of the same name"
74
+ )
75
+ fields = []
76
+ for m in metrics_list:
77
+ fields += m.fields
78
+ # check metric fields are unique
79
+ if len(fields) != len(set(fields)):
80
+ raise TrackEvalException(
81
+ "Code being run with multiple metrics with fields of the same name"
82
+ )
83
+ return metric_names
84
+
85
+
86
+ def write_summary_results(summaries, cls, output_folder):
87
+ """Write summary results to file"""
88
+
89
+ fields = sum([list(s.keys()) for s in summaries], [])
90
+ values = sum([list(s.values()) for s in summaries], [])
91
+
92
+ # In order to remain consistent upon new fields being adding, for each of the following fields if they are present
93
+ # they will be output in the summary first in the order below. Any further fields will be output in the order each
94
+ # metric family is called, and within each family either in the order they were added to the dict (python >= 3.6) or
95
+ # randomly (python < 3.6).
96
+ default_order = [
97
+ "HOTA",
98
+ "DetA",
99
+ "AssA",
100
+ "DetRe",
101
+ "DetPr",
102
+ "AssRe",
103
+ "AssPr",
104
+ "LocA",
105
+ "OWTA",
106
+ "HOTA(0)",
107
+ "LocA(0)",
108
+ "HOTALocA(0)",
109
+ "MOTA",
110
+ "MOTP",
111
+ "MODA",
112
+ "CLR_Re",
113
+ "CLR_Pr",
114
+ "MTR",
115
+ "PTR",
116
+ "MLR",
117
+ "CLR_TP",
118
+ "CLR_FN",
119
+ "CLR_FP",
120
+ "IDSW",
121
+ "MT",
122
+ "PT",
123
+ "ML",
124
+ "Frag",
125
+ "sMOTA",
126
+ "IDF1",
127
+ "IDR",
128
+ "IDP",
129
+ "IDTP",
130
+ "IDFN",
131
+ "IDFP",
132
+ "Dets",
133
+ "GT_Dets",
134
+ "IDs",
135
+ "GT_IDs",
136
+ ]
137
+ default_ordered_dict = OrderedDict(
138
+ zip(default_order, [None for _ in default_order])
139
+ )
140
+ for f, v in zip(fields, values):
141
+ default_ordered_dict[f] = v
142
+ for df in default_order:
143
+ if default_ordered_dict[df] is None:
144
+ del default_ordered_dict[df]
145
+ fields = list(default_ordered_dict.keys())
146
+ values = list(default_ordered_dict.values())
147
+
148
+ out_file = os.path.join(output_folder, cls + "_summary.txt")
149
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
150
+ with open(out_file, "w", newline="") as f:
151
+ writer = csv.writer(f, delimiter=" ")
152
+ writer.writerow(fields)
153
+ writer.writerow(values)
154
+
155
+
156
+ def write_detailed_results(details, cls, output_folder):
157
+ """Write detailed results to file"""
158
+ sequences = details[0].keys()
159
+ fields = ["seq"] + sum([list(s["COMBINED_SEQ"].keys()) for s in details], [])
160
+ out_file = os.path.join(output_folder, cls + "_detailed.csv")
161
+ os.makedirs(os.path.dirname(out_file), exist_ok=True)
162
+ with open(out_file, "w", newline="") as f:
163
+ writer = csv.writer(f)
164
+ writer.writerow(fields)
165
+ for seq in sorted(sequences):
166
+ if seq == "COMBINED_SEQ":
167
+ continue
168
+ writer.writerow([seq] + sum([list(s[seq].values()) for s in details], []))
169
+ writer.writerow(
170
+ ["COMBINED"] + sum([list(s["COMBINED_SEQ"].values()) for s in details], [])
171
+ )
172
+
173
+
174
+ def load_detail(file):
175
+ """Loads detailed data for a tracker."""
176
+ data = {}
177
+ with open(file) as f:
178
+ for i, row_text in enumerate(f):
179
+ row = row_text.replace("\r", "").replace("\n", "").split(",")
180
+ if i == 0:
181
+ keys = row[1:]
182
+ continue
183
+ current_values = row[1:]
184
+ seq = row[0]
185
+ if seq == "COMBINED":
186
+ seq = "COMBINED_SEQ"
187
+ if (len(current_values) == len(keys)) and seq != "":
188
+ data[seq] = {}
189
+ for key, value in zip(keys, current_values):
190
+ data[seq][key] = float(value)
191
+ return data
192
+
193
+
194
+ class TrackEvalException(Exception):
195
+ """Custom exception for catching expected errors."""
196
+
197
+ ...
third_party/GraspGen/sam3/sam3/eval/postprocessors.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Postprocessors class to transform MDETR output according to the downstream task"""
6
+
7
+ import dataclasses
8
+ import logging
9
+ from collections import defaultdict
10
+ from typing import Dict, List, Optional
11
+
12
+ import numpy as np
13
+ import torch
14
+ from sam3.model import box_ops
15
+ from sam3.model.data_misc import BatchedInferenceMetadata, interpolate
16
+ from sam3.train.masks_ops import rle_encode, robust_rle_encode
17
+ from torch import nn
18
+
19
+
20
+ class PostProcessNullOp(nn.Module):
21
+ def __init__(self, **kwargs):
22
+ super(PostProcessNullOp).__init__()
23
+ pass
24
+
25
+ def forward(self, input):
26
+ pass
27
+
28
+ def process_results(self, **kwargs):
29
+ return kwargs["find_stages"]
30
+
31
+
32
+ class PostProcessImage(nn.Module):
33
+ """This module converts the model's output into the format expected by the coco api"""
34
+
35
+ def __init__(
36
+ self,
37
+ max_dets_per_img: int,
38
+ iou_type="bbox",
39
+ to_cpu: bool = True,
40
+ use_original_ids: bool = False,
41
+ use_original_sizes_box: bool = False,
42
+ use_original_sizes_mask: bool = False,
43
+ convert_mask_to_rle: bool = False,
44
+ always_interpolate_masks_on_gpu: bool = True,
45
+ use_presence: bool = True,
46
+ detection_threshold: float = -1.0,
47
+ ) -> None:
48
+ super().__init__()
49
+ self.max_dets_per_img = max_dets_per_img
50
+ self.iou_type = iou_type
51
+ self.to_cpu = to_cpu
52
+ self.convert_mask_to_rle = convert_mask_to_rle
53
+ self.always_interpolate_masks_on_gpu = always_interpolate_masks_on_gpu
54
+
55
+ self.use_presence = use_presence
56
+ self.detection_threshold = detection_threshold
57
+ self.use_original_ids = use_original_ids
58
+ self.use_original_sizes_box = use_original_sizes_box
59
+ self.use_original_sizes_mask = use_original_sizes_mask
60
+
61
+ @torch.no_grad()
62
+ def forward(
63
+ self,
64
+ outputs,
65
+ target_sizes_boxes,
66
+ target_sizes_masks,
67
+ forced_labels=None,
68
+ consistent=False,
69
+ ret_tensordict: bool = False, # This is experimental
70
+ ):
71
+ """Perform the computation
72
+ Parameters:
73
+ outputs: raw outputs of the model
74
+ target_sizes_boxes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
75
+ For evaluation, this must be the original image size (before any data augmentation)
76
+ For visualization, this should be the image size after data augment, but before padding
77
+ target_sizes_masks: same but used to resize masks
78
+ forced_labels: tensor of dimension [batch_size] containing the label to force for each image of the batch
79
+ This is useful when evaluating the model using standard metrics (eg on COCO, LVIS). In that case,
80
+ we query the model with every possible class label, so we when we pass the predictions to the evaluator,
81
+ we want to make sure that the predicted "class" matches the one that was queried.
82
+ consistent: whether all target sizes are equal
83
+ ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
84
+ """
85
+ if ret_tensordict:
86
+ assert consistent is True, (
87
+ "We don't support returning TensorDict if the outputs have different shapes"
88
+ ) # NOTE: It's possible but we don't support it.
89
+ assert self.detection_threshold <= 0.0, "TODO: implement?"
90
+ try:
91
+ from tensordict import TensorDict
92
+ except ImportError:
93
+ logging.info(
94
+ "tensordict is not installed. Install by running `pip install tensordict --no-deps`. Falling back by setting `ret_tensordict=False`"
95
+ )
96
+ ret_tensordict = False
97
+
98
+ out_bbox = outputs["pred_boxes"] if "pred_boxes" in outputs else None
99
+ out_logits = outputs["pred_logits"]
100
+ pred_masks = outputs["pred_masks"] if self.iou_type == "segm" else None
101
+ out_probs = out_logits.sigmoid()
102
+ if self.use_presence:
103
+ presence_score = outputs["presence_logit_dec"].sigmoid().unsqueeze(1)
104
+ out_probs = out_probs * presence_score
105
+
106
+ assert target_sizes_boxes.shape[1] == 2
107
+ assert target_sizes_masks.shape[1] == 2
108
+ batch_size = target_sizes_boxes.shape[0]
109
+
110
+ boxes, scores, labels, keep = self._process_boxes_and_labels(
111
+ target_sizes_boxes, forced_labels, out_bbox, out_probs
112
+ )
113
+ assert boxes is None or len(boxes) == batch_size
114
+ out_masks = self._process_masks(
115
+ target_sizes_masks, pred_masks, consistent=consistent, keep=keep
116
+ )
117
+ del pred_masks
118
+
119
+ if boxes is None:
120
+ assert out_masks is not None
121
+ assert not ret_tensordict, (
122
+ "We don't support returning TensorDict if the output does not contain boxes"
123
+ )
124
+ B = len(out_masks)
125
+ boxes = [None] * B
126
+ scores = [None] * B
127
+ labels = [None] * B
128
+
129
+ results = {
130
+ "scores": scores,
131
+ "labels": labels,
132
+ "boxes": boxes,
133
+ }
134
+ if out_masks is not None:
135
+ if self.convert_mask_to_rle:
136
+ results.update(masks_rle=out_masks)
137
+ else:
138
+ results.update(masks=out_masks)
139
+
140
+ if ret_tensordict:
141
+ results = TensorDict(results).auto_batch_size_()
142
+ if self.to_cpu:
143
+ results = results.cpu()
144
+ else:
145
+ # Convert a dictonary of lists/tensors to list of dictionaries
146
+ results = [
147
+ dict(zip(results.keys(), res_tuple))
148
+ for res_tuple in zip(*results.values())
149
+ ]
150
+
151
+ return results
152
+
153
+ def _process_masks(self, target_sizes, pred_masks, consistent=True, keep=None):
154
+ if pred_masks is None:
155
+ return None
156
+ if self.always_interpolate_masks_on_gpu:
157
+ gpu_device = target_sizes.device
158
+ assert gpu_device.type == "cuda"
159
+ pred_masks = pred_masks.to(device=gpu_device)
160
+ if consistent:
161
+ assert keep is None, "TODO: implement?"
162
+ # All masks should have the same shape, expected when processing a batch of size 1
163
+ target_size = target_sizes.unique(dim=0)
164
+ assert target_size.size(0) == 1, "Expecting all target sizes to be equal"
165
+ out_masks = (
166
+ interpolate(
167
+ pred_masks,
168
+ target_size.squeeze().tolist(),
169
+ mode="bilinear",
170
+ align_corners=False,
171
+ ).sigmoid()
172
+ > 0.5
173
+ )
174
+ if self.convert_mask_to_rle:
175
+ raise RuntimeError("TODO: implement?")
176
+ if self.to_cpu:
177
+ out_masks = out_masks.cpu()
178
+ else:
179
+ out_masks = [[]] * len(pred_masks)
180
+
181
+ assert keep is None or len(keep) == len(pred_masks)
182
+ for i, mask in enumerate(pred_masks):
183
+ h, w = target_sizes[i]
184
+ if keep is not None:
185
+ mask = mask[keep[i]]
186
+ # Uses the gpu version fist, moves masks to cpu if it fails"""
187
+ try:
188
+ interpolated = (
189
+ interpolate(
190
+ mask.unsqueeze(1),
191
+ (h, w),
192
+ mode="bilinear",
193
+ align_corners=False,
194
+ ).sigmoid()
195
+ > 0.5
196
+ )
197
+ except Exception as e:
198
+ logging.info("Issue found, reverting to CPU mode!")
199
+ mask_device = mask.device
200
+ mask = mask.cpu()
201
+ interpolated = (
202
+ interpolate(
203
+ mask.unsqueeze(1),
204
+ (h, w),
205
+ mode="bilinear",
206
+ align_corners=False,
207
+ ).sigmoid()
208
+ > 0.5
209
+ )
210
+ interpolated = interpolated.to(mask_device)
211
+
212
+ if self.convert_mask_to_rle:
213
+ out_masks[i] = robust_rle_encode(interpolated.squeeze(1))
214
+ else:
215
+ out_masks[i] = interpolated
216
+ if self.to_cpu:
217
+ out_masks[i] = out_masks[i].cpu()
218
+
219
+ return out_masks
220
+
221
+ def _process_boxes_and_labels(
222
+ self, target_sizes, forced_labels, out_bbox, out_probs
223
+ ):
224
+ if out_bbox is None:
225
+ return None, None, None, None
226
+ assert len(out_probs) == len(target_sizes)
227
+ if self.to_cpu:
228
+ out_probs = out_probs.cpu()
229
+ scores, labels = out_probs.max(-1)
230
+ if forced_labels is None:
231
+ labels = torch.ones_like(labels)
232
+ else:
233
+ labels = forced_labels[:, None].expand_as(labels)
234
+
235
+ # convert to [x0, y0, x1, y1] format
236
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
237
+
238
+ img_h, img_w = target_sizes.unbind(1)
239
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
240
+ boxes = boxes * scale_fct[:, None, :]
241
+
242
+ if self.to_cpu:
243
+ boxes = boxes.cpu()
244
+
245
+ keep = None
246
+ if self.detection_threshold > 0:
247
+ # Filter out the boxes with scores below the detection threshold
248
+ keep = scores > self.detection_threshold
249
+ assert len(keep) == len(boxes) == len(scores) == len(labels)
250
+
251
+ boxes = [b[k.to(b.device)] for b, k in zip(boxes, keep)]
252
+ scores = [s[k.to(s.device)] for s, k in zip(scores, keep)]
253
+ labels = [l[k.to(l.device)] for l, k in zip(labels, keep)]
254
+
255
+ return boxes, scores, labels, keep
256
+
257
+ def process_results(
258
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
259
+ ):
260
+ if find_stages.loss_stages is not None:
261
+ find_metadatas = [find_metadatas[i] for i in find_stages.loss_stages]
262
+ assert len(find_stages) == len(find_metadatas)
263
+ results = {}
264
+ for outputs, meta in zip(find_stages, find_metadatas):
265
+ img_size_for_boxes = (
266
+ meta.original_size
267
+ if self.use_original_sizes_box
268
+ else torch.ones_like(meta.original_size)
269
+ )
270
+ img_size_for_masks = (
271
+ meta.original_size
272
+ if self.use_original_sizes_mask
273
+ else torch.ones_like(meta.original_size)
274
+ )
275
+ detection_results = self(
276
+ outputs,
277
+ img_size_for_boxes,
278
+ img_size_for_masks,
279
+ forced_labels=(
280
+ meta.original_category_id if self.use_original_ids else None
281
+ ),
282
+ )
283
+ ids = (
284
+ meta.original_image_id if self.use_original_ids else meta.coco_image_id
285
+ )
286
+ assert len(detection_results) == len(ids)
287
+ for img_id, result in zip(ids, detection_results):
288
+ if img_id.item() not in results:
289
+ results[img_id.item()] = result
290
+ else:
291
+ assert set(results[img_id.item()].keys()) == set(result.keys())
292
+ for k in result.keys():
293
+ if isinstance(result[k], torch.Tensor):
294
+ results[img_id.item()][k] = torch.cat(
295
+ [results[img_id.item()][k], result[k]], dim=0
296
+ )
297
+ elif isinstance(result[k], list):
298
+ results[img_id.item()][k] += result[k]
299
+ else:
300
+ raise NotImplementedError(
301
+ f"Unexpected type {type(result[k])} in result."
302
+ )
303
+ # Prune the results to the max number of detections per image.
304
+ for img_id, result in results.items():
305
+ if (
306
+ self.max_dets_per_img > 0
307
+ and len(result["scores"]) > self.max_dets_per_img
308
+ ):
309
+ _, topk_indexes = torch.topk(
310
+ result["scores"], self.max_dets_per_img, dim=0
311
+ )
312
+ if self.to_cpu:
313
+ topk_indexes = topk_indexes.cpu()
314
+ for k in result.keys():
315
+ if isinstance(results[img_id][k], list):
316
+ results[img_id][k] = [
317
+ results[img_id][k][i] for i in topk_indexes.tolist()
318
+ ]
319
+ else:
320
+ results[img_id][k] = results[img_id][k].to(topk_indexes.device)[
321
+ topk_indexes
322
+ ]
323
+
324
+ return results
325
+
326
+
327
+ class PostProcessAPIVideo(PostProcessImage):
328
+ """This module converts the video model's output into the format expected by the YT-VIS api"""
329
+
330
+ def __init__(
331
+ self,
332
+ *args,
333
+ to_cpu: bool = True,
334
+ convert_mask_to_rle: bool = False,
335
+ always_interpolate_masks_on_gpu: bool = True,
336
+ prob_thresh: float = 0.5,
337
+ use_presence: bool = False,
338
+ **kwargs,
339
+ ):
340
+ super().__init__(
341
+ *args,
342
+ # Here we always set `convert_mask_to_rle=False` in the base `PostProcessAPI` class
343
+ # (so that its `_process_masks` won't return a list of RLEs). If we want to return
344
+ # RLEs for video masklets, we handle it in this `PostProcessAPIVideo` class instead.
345
+ convert_mask_to_rle=False,
346
+ # Here we always set `to_cpu=False` in the base `PostProcessAPI` class (so that
347
+ # the interpolated masks won't be automatically moved back to CPU). We will handle
348
+ # it in this `PostProcessAPIVideo` class instead.
349
+ always_interpolate_masks_on_gpu=always_interpolate_masks_on_gpu,
350
+ use_presence=use_presence,
351
+ **kwargs,
352
+ )
353
+ # Expected keys in the output dict to postprocess
354
+ self.EXPECTED_KEYS = [
355
+ "pred_logits",
356
+ "pred_boxes",
357
+ "pred_masks",
358
+ ]
359
+ # Whether to post-process video masklets (under packed representation) into RLE format
360
+ self.convert_mask_to_rle_for_video = convert_mask_to_rle
361
+ self.to_cpu_for_video = to_cpu
362
+ self.prob_thresh = prob_thresh
363
+
364
+ def process_results(
365
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
366
+ ):
367
+ """
368
+ Tracking Postprocessor for SAM 3 video model.
369
+ This function takes in the output of the SAM 3 video model and processes it to extract all the tracklet predictions.
370
+ Args:
371
+ find_stages: A list of tensors representing the output of the SAM 3 video model.
372
+ find_metadatas: A list of BatchedInferenceMetadata objects containing metadata about each frame.
373
+ **kwargs: Additional keyword arguments.
374
+ Returns:
375
+ A dictionary of predcitions with video_id as key.
376
+ """
377
+
378
+ # Import tensordict here to avoid global dependency.
379
+ try:
380
+ from tensordict import TensorDict
381
+ except ImportError as e:
382
+ logging.error(
383
+ "tensordict is not installed, please install by running `pip install tensordict --no-deps`"
384
+ )
385
+ raise e
386
+ # Notes and assumptions:
387
+ # 1- This postprocessor assumes results only for a single video.
388
+ # 2- There are N stage outputs corresponding to N video frames
389
+ # 3- Each stage outputs contains PxQ preds, where P is number of prompts and Q is number of object queries. The output should also contain the tracking object ids corresponding to each object query.
390
+ # 4- The tracking object id has a default value of -1, indicating that the object query is not tracking any object in the frame, and hence its predictions can be ingored for a given frame.
391
+ # 5- Some objects may be tracked in a subset of frames only. So, we first extract the predictions in a packed representation (for efficient postprocessing -- specially memory)
392
+ # and then we convert the packed representation into a padded one, where we zero pad boxes/masks for objects that are not tracked in some frames.
393
+ # 6- We refer to objects by an object id, which is a tuple (prompt_idx, obj_id)
394
+
395
+ assert len(find_stages) > 0, "There is nothing to postprocess?"
396
+ PROMPT_AXIS, OBJ_QUERY_AXIS = (0, 1)
397
+ NO_OBJ_ID = -1
398
+ # Maps object ID -> [indices in packed tensor]
399
+ tracked_objects_packed_idx = defaultdict(list)
400
+ # Maps object ID -> [indices in padded tensor (abs frame index)]
401
+ tracked_objects_frame_idx = defaultdict(list)
402
+ total_num_preds = 0
403
+ # This will hold the packed representation of predictions.
404
+ vid_preds_packed: List[TensorDict] = []
405
+ vid_masklets_rle_packed: List[Optional[Dict]] = []
406
+ video_id = -1 # We assume single video postprocessing, this ID should be unique in the datapoint.
407
+
408
+ for frame_idx, (frame_outs, meta) in enumerate(
409
+ zip(find_stages, find_metadatas)
410
+ ):
411
+ # only store keys we need to extract the results
412
+ frame_outs_td = TensorDict(
413
+ {k: frame_outs[k] for k in self.EXPECTED_KEYS}
414
+ ).auto_batch_size_() # Shape is [P,Q,...]
415
+ meta_td = TensorDict(
416
+ dataclasses.asdict(meta)
417
+ ).auto_batch_size_() # Shape is [P,...]
418
+ unique_vid_id = meta.original_image_id.unique()
419
+ assert unique_vid_id.size(0) == 1
420
+ if video_id == -1:
421
+ video_id = unique_vid_id.item()
422
+ else:
423
+ assert video_id == unique_vid_id.item(), (
424
+ "We can only postprocess one video per datapoint"
425
+ )
426
+ # keeping track of which objects appear in the current frame
427
+ obj_ids_per_frame = frame_outs["pred_object_ids"]
428
+ assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2)
429
+ if self.prob_thresh is not None:
430
+ # only keep the predictions on this frame with probability above the threshold
431
+ # (remove those predictions during the keep-alive period of a tracking query,
432
+ # where its "pred_object_ids" is still the tracked object ID rather than -1)
433
+ pred_probs = frame_outs["pred_logits"].sigmoid().squeeze(-1)
434
+ obj_ids_per_frame = torch.where(
435
+ pred_probs >= self.prob_thresh, obj_ids_per_frame, NO_OBJ_ID
436
+ )
437
+ tracked_obj_ids_idx = torch.where(obj_ids_per_frame != NO_OBJ_ID)
438
+ # Object id is a tuple of (prompt_idx, obj_id). This is because the model can assign same obj_id for two different prompts.
439
+ tracked_obj_ids = [
440
+ (p_id.item(), obj_ids_per_frame[p_id, q_id].item())
441
+ for p_id, q_id in zip(
442
+ tracked_obj_ids_idx[PROMPT_AXIS],
443
+ tracked_obj_ids_idx[OBJ_QUERY_AXIS],
444
+ )
445
+ ]
446
+ if len(tracked_obj_ids) == 0:
447
+ continue
448
+ # For each object, we keep track of the packed and padded (frame index) indices
449
+ for oid in tracked_obj_ids:
450
+ tracked_objects_packed_idx[oid].append(total_num_preds)
451
+ tracked_objects_frame_idx[oid].append(frame_idx)
452
+ total_num_preds += 1
453
+
454
+ # Since we have P*Q masks per frame, mask interpolation is the GPU memory bottleneck or time bottleneck in case of cpu processing.
455
+ # Instead, we first extract results only for tracked objects, reducing the number of masks to K = sum_i(tracked_objs_per_ith_prompt), hopefully <<< P*Q
456
+ tracked_objs_outs_td = frame_outs_td[
457
+ tracked_obj_ids_idx
458
+ ] # [P,Q,...] --> [K,...]
459
+ meta_td = meta_td[tracked_obj_ids_idx[PROMPT_AXIS].cpu()]
460
+ if self.always_interpolate_masks_on_gpu:
461
+ gpu_device = meta_td["original_size"].device
462
+ assert gpu_device.type == "cuda"
463
+ tracked_objs_outs_td = tracked_objs_outs_td.to(device=gpu_device)
464
+ frame_results_td = self(
465
+ tracked_objs_outs_td.unsqueeze(1),
466
+ (
467
+ meta_td["original_size"]
468
+ if self.use_original_sizes
469
+ else torch.ones_like(meta_td["original_size"])
470
+ ),
471
+ forced_labels=(
472
+ meta_td["original_category_id"] if self.use_original_ids else None
473
+ ),
474
+ consistent=True,
475
+ ret_tensordict=True,
476
+ ).squeeze(1)
477
+ del tracked_objs_outs_td
478
+
479
+ # Optionally, remove "masks" from output tensor dict and directly encode them
480
+ # to RLE format under packed representations
481
+ if self.convert_mask_to_rle_for_video:
482
+ interpolated_binary_masks = frame_results_td.pop("masks")
483
+ rle_list = rle_encode(interpolated_binary_masks, return_areas=True)
484
+ vid_masklets_rle_packed.extend(rle_list)
485
+ # Optionally, move output TensorDict to CPU (do this after RLE encoding step above)
486
+ if self.to_cpu_for_video:
487
+ frame_results_td = frame_results_td.cpu()
488
+ vid_preds_packed.append(frame_results_td)
489
+
490
+ if len(vid_preds_packed) == 0:
491
+ logging.debug(f"Video {video_id} has no predictions")
492
+ return {video_id: []}
493
+
494
+ vid_preds_packed = torch.cat(vid_preds_packed, dim=0)
495
+ ############### Construct a padded representation of the predictions ###############
496
+ num_preds = len(tracked_objects_packed_idx)
497
+ num_frames = len(find_stages)
498
+ # We zero pad any missing prediction
499
+ # NOTE: here, we also have padded tensors for "scores" and "labels", but we overwrite them later.
500
+ padded_frames_results = TensorDict(
501
+ {
502
+ k: torch.zeros(
503
+ num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype
504
+ )
505
+ for k, v in vid_preds_packed.items()
506
+ },
507
+ batch_size=[
508
+ num_preds,
509
+ num_frames,
510
+ ],
511
+ )
512
+ padded_frames_results["scores"][...] = -1e8 # a very low score for empty object
513
+ # Track scores and labels of each pred tracklet, only for frames where the model was able to track that object
514
+ tracklet_scores = []
515
+ tracklet_labels = []
516
+ # Optionally, fill the list of RLEs for masklets
517
+ # note: only frames with actual predicted masks (in packed format) will be
518
+ # filled with RLEs; the rest will remains None in results["masks_rle"]
519
+ if self.convert_mask_to_rle_for_video:
520
+ vid_masklets_rle_padded = [[None] * num_frames for _ in range(num_preds)]
521
+ for o_idx, oid in enumerate(tracked_objects_packed_idx):
522
+ oid2packed_idx = tracked_objects_packed_idx[oid]
523
+ oid2padded_idx = tracked_objects_frame_idx[oid]
524
+ obj_packed_results = vid_preds_packed[oid2packed_idx]
525
+ padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results
526
+ if self.convert_mask_to_rle_for_video:
527
+ for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx):
528
+ vid_masklets_rle_padded[o_idx][padded_idx] = (
529
+ vid_masklets_rle_packed[packed_idx]
530
+ )
531
+ # NOTE: We need a single confidence score per tracklet for the mAP metric.
532
+ # We use the average confidence score across time. (How does this impact AP?)
533
+ tracklet_scores.append(obj_packed_results["scores"].mean())
534
+ # We also need to have a unique category Id per tracklet.
535
+ # This is not a problem for phrase AP, however, for mAP we do majority voting across time.
536
+ tracklet_labels.append(obj_packed_results["labels"].mode()[0])
537
+
538
+ results = padded_frames_results.to_dict()
539
+ results["scores"] = torch.stack(tracklet_scores, dim=0)
540
+ results["labels"] = torch.stack(tracklet_labels, dim=0)
541
+ if self.convert_mask_to_rle_for_video:
542
+ results["masks_rle"] = vid_masklets_rle_padded
543
+ # we keep the frame-level scores since it's needed by some evaluation scripts
544
+ results["per_frame_scores"] = padded_frames_results["scores"]
545
+
546
+ return {video_id: results}
547
+
548
+
549
+ class PostProcessTracking(PostProcessImage):
550
+ """This module converts the model's output into the format expected by the coco api"""
551
+
552
+ def __init__(
553
+ self,
554
+ max_dets_per_img: int,
555
+ iou_type="bbox",
556
+ force_single_mask: bool = False,
557
+ **kwargs,
558
+ ) -> None:
559
+ super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs)
560
+ self.force_single_mask = force_single_mask
561
+
562
+ def process_results(
563
+ self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs
564
+ ):
565
+ assert len(find_stages) == len(find_metadatas)
566
+ results = {}
567
+ for outputs, meta in zip(find_stages, find_metadatas):
568
+ if self.force_single_mask:
569
+ scores, labels = outputs["pred_logits"].max(-1)
570
+ m = []
571
+ for i in range(len(outputs["pred_masks"])):
572
+ score, idx = scores[i].max(0)
573
+ m.append(outputs["pred_masks"][i][idx])
574
+ outputs["pred_masks"] = torch.stack(m, 0).unsqueeze(1)
575
+ detection_results = self(outputs, meta.original_size, consistent=False)
576
+ assert len(detection_results) == len(meta.coco_image_id)
577
+ results.update(
578
+ {
579
+ (media_id.item(), object_id.item(), frame_index.item()): result
580
+ for media_id, object_id, frame_index, result in zip(
581
+ meta.original_image_id,
582
+ meta.object_id,
583
+ meta.frame_index,
584
+ detection_results,
585
+ )
586
+ }
587
+ )
588
+ return results
589
+
590
+
591
+ class PostProcessCounting(nn.Module):
592
+ """This module converts the model's output to be evaluated for counting tasks"""
593
+
594
+ def __init__(
595
+ self,
596
+ use_original_ids: bool = False,
597
+ threshold: float = 0.5,
598
+ use_presence: bool = False,
599
+ ) -> None:
600
+ """
601
+ Args:
602
+ use_original_ids: whether to use the original image ids or the coco ids
603
+ threshold: threshold for counting (values above this are counted)
604
+ """
605
+ super().__init__()
606
+ self.use_original_ids = use_original_ids
607
+ self.threshold = threshold
608
+ self.use_presence = use_presence
609
+
610
+ def forward(self, outputs, target_sizes):
611
+ """Perform the computation
612
+ Parameters:
613
+ outputs: raw outputs of the model
614
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
615
+ """
616
+ # Extract scores from model outputs and apply sigmoid
617
+ scores = torch.sigmoid(outputs["pred_logits"]).squeeze(-1) # [B, N]
618
+ if self.use_presence:
619
+ presence_score = outputs["presence_logit_dec"].sigmoid()
620
+ if presence_score.ndim == 1:
621
+ presence_score = presence_score.unsqueeze(1) # [B, 1]
622
+ scores = scores * presence_score # [B, N]
623
+
624
+ # Calculate counts by summing values above threshold
625
+ counts = (scores > self.threshold).float().sum(dim=1)
626
+
627
+ assert len(counts) == len(target_sizes)
628
+ results = []
629
+ for count in counts:
630
+ results.append({"count": count.item()})
631
+
632
+ return results
633
+
634
+ @torch.no_grad()
635
+ def process_results(
636
+ self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs
637
+ ):
638
+ assert len(find_stages) == len(find_metadatas)
639
+ results = {}
640
+ for outputs, meta in zip(find_stages, find_metadatas):
641
+ detection_results = self(
642
+ outputs,
643
+ meta.original_size,
644
+ )
645
+ ids = (
646
+ meta.original_image_id if self.use_original_ids else meta.coco_image_id
647
+ )
648
+ assert len(detection_results) == len(ids)
649
+ for img_id, result in zip(ids, detection_results):
650
+ results[img_id.item()] = result
651
+
652
+ return results
third_party/GraspGen/sam3/sam3/eval/saco_veval_evaluators.py ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import json
5
+ import os
6
+ import tempfile
7
+ from collections import defaultdict
8
+ from typing import Dict, Optional, Sequence, Tuple
9
+
10
+ import numpy as np
11
+ import pycocotools.mask
12
+ from sam3.eval.cgf1_eval import CGF1_METRICS
13
+ from sam3.eval.conversion_util import (
14
+ convert_ytbvis_to_cocovid_gt,
15
+ convert_ytbvis_to_cocovid_pred,
16
+ )
17
+ from sam3.eval.hota_eval_toolkit.run_ytvis_eval import run_ytvis_eval
18
+ from sam3.eval.teta_eval_toolkit import config, Evaluator, metrics
19
+ from sam3.eval.teta_eval_toolkit.datasets import COCO, TAO
20
+ from sam3.eval.ytvis_coco_wrapper import YTVIS
21
+ from sam3.eval.ytvis_eval import VideoDemoF1Eval, YTVISeval
22
+ from sam3.train.nms_helper import process_frame_level_nms, process_track_level_nms
23
+
24
+
25
+ def _get_metric_index(metric_name: str, iou_threshold: Optional[float] = None) -> int:
26
+ """
27
+ Find the index of a metric in CGF1_METRICS by name and IoU threshold.
28
+
29
+ Args:
30
+ metric_name: Name of the metric (e.g., "cgF1", "precision", "recall")
31
+ iou_threshold: IoU threshold (None for average over 0.5:0.95, or specific value like 0.5, 0.75)
32
+
33
+ Returns:
34
+ Index of the metric in CGF1_METRICS
35
+
36
+ Raises:
37
+ ValueError: If metric not found
38
+ """
39
+ for idx, metric in enumerate(CGF1_METRICS):
40
+ if metric.name == metric_name and metric.iou_threshold == iou_threshold:
41
+ return idx
42
+ raise ValueError(
43
+ f"Metric '{metric_name}' with IoU threshold {iou_threshold} not found in CGF1_METRICS"
44
+ )
45
+
46
+
47
+ class BasePredFileEvaluator:
48
+ """A base class for evaluating a prediction file."""
49
+
50
+ pass
51
+
52
+
53
+ class YTVISPredFileEvaluator(BasePredFileEvaluator):
54
+ """Evaluate class mAP for YT-VIS prediction files."""
55
+
56
+ def __init__(
57
+ self,
58
+ gt_ann_file: str,
59
+ dataset_name: str = "video",
60
+ iou_types: Optional[Sequence[str]] = None,
61
+ ):
62
+ self.gt_ann_file = gt_ann_file
63
+ self.dataset_name = dataset_name
64
+ self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"]
65
+ assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
66
+
67
+ def evaluate(self, pred_file: str) -> Dict[str, float]:
68
+ # use our internal video evaluation toolkit for YT-VIS pred file
69
+ # (i.e. the same one we're using for video phrase AP)
70
+ results = {}
71
+ use_cats = True # YT-VIS mAP evaluation uses categories
72
+ ytvisGT = YTVIS(self.gt_ann_file, ignore_gt_cats=not use_cats)
73
+ # the original YT-VIS GT annotations have uncompressed RLEs ("counts" is an integer list)
74
+ # rather than compressed RLEs ("counts" is a string), so we first convert them here.
75
+ if "segm" in self.iou_types:
76
+ for ann in ytvisGT.dataset["annotations"]:
77
+ ann["segmentations"] = [
78
+ _compress_rle(rle) for rle in ann["segmentations"]
79
+ ]
80
+
81
+ with open(pred_file) as f:
82
+ dt = json.load(f)
83
+ # Our prediction file saves "video_id" and absolute (unnormalized) boxes.
84
+ # Note that we should use the official (original) YT-VIS annotations (i.e. the one
85
+ # saved via "scripts/datasets/training/ytvis_split.py", instead of the one saved
86
+ # via "scripts/api_db_to_ytvis_json.py") in this evaluator, which contain absolute
87
+ # boxes coordinates in its GT annotations.
88
+ for d in dt:
89
+ d["image_id"] = d["video_id"]
90
+ ytvisDT = ytvisGT.loadRes(dt)
91
+
92
+ for iou_type in self.iou_types:
93
+ ytvisEval = YTVISeval(ytvisGT, ytvisDT, iou_type)
94
+
95
+ # set the area ranges for small, medium, and large objects (using
96
+ # absolute pixel areas) as in the official YT-VIS evaluation toolkit:
97
+ # https://github.com/achalddave/ytvosapi/blob/eca601117c9f86bad084cb91f1d918e9ab665a75/PythonAPI/ytvostools/ytvoseval.py#L538
98
+ ytvisEval.params.areaRng = [
99
+ [0**2, 1e5**2],
100
+ [0**2, 128**2],
101
+ [128**2, 256**2],
102
+ [256**2, 1e5**2],
103
+ ]
104
+ ytvisEval.params.areaRngLbl = ["all", "small", "medium", "large"]
105
+ ytvisEval.params.useCats = use_cats
106
+
107
+ ytvisEval.evaluate()
108
+ ytvisEval.accumulate()
109
+ ytvisEval.summarize()
110
+ result_key = f"{self.dataset_name}_{'mask' if iou_type == 'segm' else 'bbox'}_mAP_50_95"
111
+ results[result_key] = ytvisEval.stats[0]
112
+
113
+ # video-NP level results not supported for `YTVISPredFileEvaluator` yet
114
+ video_np_level_results = {}
115
+ return results, video_np_level_results
116
+
117
+
118
+ class VideoPhraseApEvaluator(BasePredFileEvaluator):
119
+ """Evaluate Video Phrase AP with YT-VIS format prediction and GT files."""
120
+
121
+ def __init__(
122
+ self,
123
+ gt_ann_file: str,
124
+ dataset_name: str = "video",
125
+ iou_types: Optional[Sequence[str]] = None,
126
+ ):
127
+ self.gt_ann_file = gt_ann_file
128
+ self.dataset_name = dataset_name
129
+ self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"]
130
+ assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
131
+
132
+ def evaluate(self, pred_file: str) -> Dict[str, float]:
133
+ with open(self.gt_ann_file) as f:
134
+ gt = json.load(f)
135
+ with open(pred_file) as f:
136
+ dt = json.load(f)
137
+ # For phrase AP and demo F1 evaluation, we need to remap each pair of (video_id, category_id) to
138
+ # a new unique video_id, so that we don't mix detections from different categories under `useCat=False`
139
+ gt, dt = remap_video_category_pairs_to_unique_video_ids(gt, dt)
140
+ if "segm" in self.iou_types:
141
+ for ann in gt["annotations"]:
142
+ ann["segmentations"] = [
143
+ _compress_rle(rle) for rle in ann["segmentations"]
144
+ ]
145
+ for d in dt:
146
+ d["image_id"] = d["video_id"]
147
+
148
+ results = {}
149
+ use_cats = False # Phrase AP evaluation does not use categories
150
+ ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
151
+ ytvisGT.dataset = gt
152
+ ytvisGT.createIndex()
153
+ ytvisDT = ytvisGT.loadRes(dt)
154
+
155
+ for iou_type in self.iou_types:
156
+ phraseApEval = YTVISeval(ytvisGT, ytvisDT, iou_type)
157
+
158
+ # set the area ranges for small, medium, and large objects (using
159
+ # absolute pixel areas) as in the official YT-VIS evaluation toolkit:
160
+ # https://github.com/achalddave/ytvosapi/blob/eca601117c9f86bad084cb91f1d918e9ab665a75/PythonAPI/ytvostools/ytvoseval.py#L538
161
+ phraseApEval.params.areaRng = [
162
+ [0**2, 1e5**2],
163
+ [0**2, 128**2],
164
+ [128**2, 256**2],
165
+ [256**2, 1e5**2],
166
+ ]
167
+ phraseApEval.params.areaRngLbl = ["all", "small", "medium", "large"]
168
+ phraseApEval.params.useCats = use_cats
169
+
170
+ phraseApEval.evaluate()
171
+ phraseApEval.accumulate()
172
+ phraseApEval.summarize()
173
+ result_prefix = f"{self.dataset_name}"
174
+ result_prefix += f"_{'mask' if iou_type == 'segm' else 'bbox'}_phrase_ap"
175
+ # fetch Phrase AP results from the corresponding indices in `phraseApEval.stats`
176
+ # (see `_summarizeDets` in https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/cocoeval.py)
177
+ results[result_prefix + "_50_95"] = phraseApEval.stats[0] # IoU=0.5:0.95
178
+ results[result_prefix + "_50"] = phraseApEval.stats[1] # IoU=0.5
179
+ results[result_prefix + "_75"] = phraseApEval.stats[2] # IoU=0.75
180
+
181
+ # video-NP level results not supported for `VideoPhraseApEvaluator` yet
182
+ video_np_level_results = {}
183
+ return results, video_np_level_results
184
+
185
+
186
+ class VideoCGF1Evaluator(BasePredFileEvaluator):
187
+ """Evaluate Video Demo F1 with YT-VIS format prediction and GT files."""
188
+
189
+ def __init__(
190
+ self,
191
+ gt_ann_file: str,
192
+ dataset_name: str = "video",
193
+ prob_thresh: float = 0.5,
194
+ iou_types: Optional[Sequence[str]] = None,
195
+ ):
196
+ self.gt_ann_file = gt_ann_file
197
+ self.dataset_name = dataset_name
198
+ self.prob_thresh = prob_thresh
199
+ self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"]
200
+ assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
201
+
202
+ def evaluate(self, pred_file: str) -> Dict[str, float]:
203
+ with open(self.gt_ann_file) as f:
204
+ gt = json.load(f)
205
+ with open(pred_file) as f:
206
+ dt = json.load(f)
207
+ # compute IL_MCC and CG-F1 can only be computed if we have "video_np_pairs" keys in the GT JSON
208
+ compute_ilmcc_and_cgf1 = "video_np_pairs" in gt
209
+ if not compute_ilmcc_and_cgf1:
210
+ print(
211
+ f"Warning: IL_MCC and CG-F1 are not computed for {pred_file=} as it does not have 'video_np_pairs' keys in the GT JSON"
212
+ )
213
+ # For phrase AP and demo F1 evaluation, we need to remap each pair of (video_id, category_id) to
214
+ # a new unique video_id, so that we don't mix detections from different categories under `useCat=False`
215
+ gt, dt = remap_video_category_pairs_to_unique_video_ids(
216
+ gt, dt, add_negative_np_pairs=compute_ilmcc_and_cgf1
217
+ )
218
+ if "segm" in self.iou_types:
219
+ for ann in gt["annotations"]:
220
+ ann["segmentations"] = [
221
+ _compress_rle(rle) for rle in ann["segmentations"]
222
+ ]
223
+ for d in dt:
224
+ d["image_id"] = d["video_id"]
225
+
226
+ results = {}
227
+ use_cats = False # Demo F1 evaluation does not use categories
228
+ ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats)
229
+ ytvisGT.dataset = gt
230
+ ytvisGT.createIndex()
231
+ ytvisDT = ytvisGT.loadRes(dt)
232
+
233
+ video_np_level_results = {}
234
+ for iou_type in self.iou_types:
235
+ demoF1Eval = VideoDemoF1Eval(ytvisGT, ytvisDT, iou_type, self.prob_thresh)
236
+
237
+ demoF1Eval.params.useCats = use_cats
238
+ demoF1Eval.params.areaRng = [[0**2, 1e5**2]]
239
+ demoF1Eval.params.areaRngLbl = ["all"]
240
+ demoF1Eval.params.maxDets = [100000]
241
+
242
+ demoF1Eval.evaluate()
243
+ demoF1Eval.accumulate()
244
+ demoF1Eval.summarize()
245
+ result_prefix = f"{self.dataset_name}"
246
+ result_prefix += f"_{'mask' if iou_type == 'segm' else 'bbox'}_demo"
247
+
248
+ stats = demoF1Eval.stats
249
+
250
+ if compute_ilmcc_and_cgf1:
251
+ # Average IoU threshold (0.5:0.95)
252
+ cgf1_micro_avg_idx = _get_metric_index("cgF1", None)
253
+ positive_micro_f1_avg_idx = _get_metric_index("positive_micro_F1", None)
254
+ ilmcc_avg_idx = _get_metric_index("IL_MCC", None)
255
+ results[result_prefix + "_cgf1_micro_50_95"] = stats[cgf1_micro_avg_idx]
256
+ results[result_prefix + "_ilmcc_50_95"] = stats[ilmcc_avg_idx]
257
+ results[result_prefix + "_positive_micro_f1_50_95"] = stats[
258
+ positive_micro_f1_avg_idx
259
+ ]
260
+
261
+ # IoU = 0.5
262
+ cgf1_micro_50_idx = _get_metric_index("cgF1", 0.5)
263
+ positive_micro_f1_50_idx = _get_metric_index("positive_micro_F1", 0.5)
264
+ results[result_prefix + "_cgf1_micro_50"] = stats[cgf1_micro_50_idx]
265
+ results[result_prefix + "_ilmcc_50"] = float(
266
+ np.array(stats[cgf1_micro_50_idx])
267
+ / np.array(stats[positive_micro_f1_50_idx])
268
+ )
269
+ results[result_prefix + "_positive_micro_f1_50"] = stats[
270
+ positive_micro_f1_50_idx
271
+ ]
272
+
273
+ # IoU = 0.75
274
+ cgf1_micro_75_idx = _get_metric_index("cgF1", 0.75)
275
+ positive_micro_f1_75_idx = _get_metric_index("positive_micro_F1", 0.75)
276
+ results[result_prefix + "_cgf1_micro_75"] = stats[cgf1_micro_75_idx]
277
+ results[result_prefix + "_ilmcc_75"] = float(
278
+ np.array(stats[cgf1_micro_75_idx])
279
+ / np.array(stats[positive_micro_f1_75_idx])
280
+ )
281
+ results[result_prefix + "_positive_micro_f1_75"] = stats[
282
+ positive_micro_f1_75_idx
283
+ ]
284
+
285
+ self.extract_video_np_level_results(demoF1Eval, video_np_level_results)
286
+
287
+ return results, video_np_level_results
288
+
289
+ def extract_video_np_level_results(self, demoF1Eval, video_np_level_results):
290
+ """Aggregate statistics for video-level metrics."""
291
+ num_iou_thrs = len(demoF1Eval.params.iouThrs)
292
+ iou_50_index = int(np.where(demoF1Eval.params.iouThrs == 0.5)[0])
293
+ iou_75_index = int(np.where(demoF1Eval.params.iouThrs == 0.75)[0])
294
+
295
+ result_prefix = "mask" if demoF1Eval.params.iouType == "segm" else "bbox"
296
+
297
+ assert len(demoF1Eval.evalImgs) == len(demoF1Eval.cocoGt.dataset["images"])
298
+ for i, video in enumerate(demoF1Eval.cocoGt.dataset["images"]):
299
+ # the original video id and category id before remapping
300
+ video_id = video["orig_video_id"]
301
+ category_id = video["orig_category_id"]
302
+ eval_img_dict = demoF1Eval.evalImgs[i]
303
+
304
+ TPs = eval_img_dict.get("TPs", np.zeros(num_iou_thrs, dtype=np.int64))
305
+ FPs = eval_img_dict.get("FPs", np.zeros(num_iou_thrs, dtype=np.int64))
306
+ FNs = eval_img_dict.get("FNs", np.zeros(num_iou_thrs, dtype=np.int64))
307
+ assert len(TPs) == len(FPs) == len(FNs) == num_iou_thrs
308
+ # F1 = 2*TP / (2*TP + FP + FN), and we set F1 to 1.0 if denominator is 0
309
+ denominator = 2 * TPs + FPs + FNs
310
+ F1s = np.where(denominator > 0, 2 * TPs / np.maximum(denominator, 1), 1.0)
311
+ local_results = {
312
+ f"{result_prefix}_TP_50_95": float(TPs.mean()),
313
+ f"{result_prefix}_FP_50_95": float(FPs.mean()),
314
+ f"{result_prefix}_FN_50_95": float(FNs.mean()),
315
+ f"{result_prefix}_F1_50_95": float(F1s.mean()),
316
+ f"{result_prefix}_TP_50": float(TPs[iou_50_index]),
317
+ f"{result_prefix}_FP_50": float(FPs[iou_50_index]),
318
+ f"{result_prefix}_FN_50": float(FNs[iou_50_index]),
319
+ f"{result_prefix}_F1_50": float(F1s[iou_50_index]),
320
+ f"{result_prefix}_TP_75": float(TPs[iou_75_index]),
321
+ f"{result_prefix}_FP_75": float(FPs[iou_75_index]),
322
+ f"{result_prefix}_FN_75": float(FNs[iou_75_index]),
323
+ f"{result_prefix}_F1_75": float(F1s[iou_75_index]),
324
+ }
325
+ if (video_id, category_id) not in video_np_level_results:
326
+ video_np_level_results[(video_id, category_id)] = {}
327
+ video_np_level_results[(video_id, category_id)].update(local_results)
328
+
329
+
330
+ class VideoTetaEvaluator(BasePredFileEvaluator):
331
+ """Evaluate TETA metric using YouTubeVIS format prediction and GT files."""
332
+
333
+ def __init__(
334
+ self,
335
+ gt_ann_file: str,
336
+ dataset_name: str = "video",
337
+ tracker_name: str = "Sam3",
338
+ nms_threshold: float = 0.5,
339
+ nms_strategy: str = "none", # "track", "frame", or "none"
340
+ prob_thresh: float = 0.5,
341
+ is_exhaustive: bool = False,
342
+ use_mask: bool = False,
343
+ num_parallel_cores: int = 8,
344
+ ):
345
+ self.gt_ann_file = gt_ann_file
346
+ self.dataset_name = dataset_name
347
+ self.tracker_name = tracker_name
348
+ self.nms_threshold = nms_threshold
349
+ self.nms_strategy = nms_strategy.lower() # Convert to lowercase for consistency
350
+ self.prob_thresh = prob_thresh
351
+ self.metric_prefix = "TETA"
352
+ self.is_exhaustive = is_exhaustive
353
+ self.use_mask = use_mask
354
+ self.num_parallel_cores = num_parallel_cores
355
+
356
+ # Verify NMS strategy is valid
357
+ valid_strategies = ["track", "frame", "none"]
358
+ print("current nms_strategy:", self.nms_strategy)
359
+ if self.nms_strategy not in valid_strategies:
360
+ raise ValueError(
361
+ f"Invalid NMS strategy: {self.nms_strategy}. Must be one of {valid_strategies}"
362
+ )
363
+
364
+ print(f"Initialized VideoTetaEvaluator with NMS strategy: {self.nms_strategy}")
365
+ print(f"Probability threshold set to: {self.prob_thresh}")
366
+ print(f"Dataset exhaustivity set to: {self.is_exhaustive}")
367
+ print(f"Tracker name set to: {self.tracker_name}")
368
+ print(f"Dataset name set to: {self.dataset_name}")
369
+ print(f"Use mask set to: {self.use_mask}")
370
+
371
+ def process_predictions(self, pred_file: str, tmp_dir: str) -> str:
372
+ """Process predictions with selected NMS strategy"""
373
+ with open(pred_file, "r") as f:
374
+ raw_preds = json.load(f)
375
+ print(f"Processing predictions with {self.nms_strategy} NMS strategy")
376
+
377
+ # Filter by score threshold
378
+ if self.prob_thresh > 0:
379
+ raw_preds = [d for d in raw_preds if d["score"] >= self.prob_thresh]
380
+ print(
381
+ f"Filtered to {len(raw_preds)} predictions with score >= {self.prob_thresh}"
382
+ )
383
+ # Group predictions by video_id
384
+ video_groups = defaultdict(list)
385
+ for pred in raw_preds:
386
+ video_groups[pred["video_id"]].append(pred)
387
+ # Process based on NMS strategy
388
+ if self.nms_strategy == "track":
389
+ process_track_level_nms(video_groups, nms_threshold=self.nms_threshold)
390
+ elif self.nms_strategy == "frame":
391
+ process_frame_level_nms(video_groups, nms_threshold=self.nms_threshold)
392
+ elif self.nms_strategy == "none":
393
+ print("Skipping NMS processing as strategy is set to 'none'")
394
+ # No processing needed for "none" strategy
395
+ # Save processed predictions
396
+ processed_preds = [
397
+ track for tracks in video_groups.values() for track in tracks
398
+ ]
399
+ processed_path = os.path.join(tmp_dir, "processed_preds.json")
400
+ with open(processed_path, "w") as f:
401
+ json.dump(processed_preds, f)
402
+
403
+ print(f"Saved processed predictions to {processed_path}")
404
+ return processed_path
405
+
406
+ def evaluate(self, pred_file: str) -> Tuple[Dict[str, float], Dict]:
407
+ """Main evaluation method"""
408
+
409
+ print(f"Evaluating TETA Metric with {self.nms_strategy.upper()} NMS strategy")
410
+ with tempfile.TemporaryDirectory() as tmp_dir:
411
+ # Process predictions first
412
+ processed_pred_file = self.process_predictions(pred_file, tmp_dir)
413
+
414
+ # Convert GT to COCO-vid format
415
+ gt_dir = os.path.join(tmp_dir, "gt")
416
+ os.makedirs(gt_dir, exist_ok=True)
417
+ gt_coco_path = os.path.join(gt_dir, "annotations.json")
418
+ convert_ytbvis_to_cocovid_gt(self.gt_ann_file, gt_coco_path)
419
+
420
+ # Convert processed predictions to COCO-vid format
421
+ pred_dir = os.path.join(tmp_dir, "predictions")
422
+ tracker_dir = os.path.join(pred_dir, self.tracker_name)
423
+ os.makedirs(tracker_dir, exist_ok=True)
424
+ pred_coco_path = os.path.join(tracker_dir, "track_results_cocofmt.json")
425
+ convert_ytbvis_to_cocovid_pred(
426
+ youtubevis_pred_path=processed_pred_file,
427
+ converted_dataset_path=gt_coco_path,
428
+ output_path=pred_coco_path,
429
+ )
430
+ # Configure TETA evaluator
431
+ default_eval_config = config.get_default_eval_config()
432
+ default_eval_config["PRINT_ONLY_COMBINED"] = True
433
+ default_eval_config["DISPLAY_LESS_PROGRESS"] = True
434
+ default_eval_config["OUTPUT_TEMP_RAW_DATA"] = True
435
+ default_eval_config["NUM_PARALLEL_CORES"] = self.num_parallel_cores
436
+ default_dataset_config = config.get_default_dataset_config()
437
+ default_dataset_config["TRACKERS_TO_EVAL"] = [self.tracker_name]
438
+ default_dataset_config["GT_FOLDER"] = gt_dir
439
+ default_dataset_config["OUTPUT_FOLDER"] = pred_dir
440
+ default_dataset_config["TRACKER_SUB_FOLDER"] = tracker_dir
441
+ default_dataset_config["USE_MASK"] = self.use_mask
442
+
443
+ evaluator = Evaluator(default_eval_config)
444
+ if self.is_exhaustive:
445
+ dataset_list = [COCO(default_dataset_config)]
446
+ dataset_parsing_key = "COCO"
447
+ else:
448
+ dataset_list = [TAO(default_dataset_config)]
449
+ dataset_parsing_key = "TAO"
450
+
451
+ # Run evaluation
452
+ eval_results, _ = evaluator.evaluate(
453
+ dataset_list, [metrics.TETA(exhaustive=self.is_exhaustive)]
454
+ )
455
+
456
+ # Extract and format results
457
+ results = {
458
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_teta": float(
459
+ eval_results[dataset_parsing_key]["TETA"][0]
460
+ ),
461
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_a": float(
462
+ eval_results[dataset_parsing_key]["TETA"][1]
463
+ ),
464
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_a": float(
465
+ eval_results[dataset_parsing_key]["TETA"][2]
466
+ ),
467
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_a": float(
468
+ eval_results[dataset_parsing_key]["TETA"][3]
469
+ ),
470
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_re": float(
471
+ eval_results[dataset_parsing_key]["TETA"][4]
472
+ ),
473
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_pr": float(
474
+ eval_results[dataset_parsing_key]["TETA"][5]
475
+ ),
476
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_re": float(
477
+ eval_results[dataset_parsing_key]["TETA"][6]
478
+ ),
479
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_pr": float(
480
+ eval_results[dataset_parsing_key]["TETA"][7]
481
+ ),
482
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_re": float(
483
+ eval_results[dataset_parsing_key]["TETA"][8]
484
+ ),
485
+ f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_pr": float(
486
+ eval_results[dataset_parsing_key]["TETA"][9]
487
+ ),
488
+ }
489
+
490
+ # video-NP level results not supported for `VideoTetaEvaluator` yet
491
+ video_np_level_results = {}
492
+ return results, video_np_level_results
493
+
494
+
495
+ class VideoPhraseHotaEvaluator(BasePredFileEvaluator):
496
+ """Evaluate Video Phrase HOTA with YT-VIS format prediction and GT files."""
497
+
498
+ def __init__(
499
+ self,
500
+ gt_ann_file: str,
501
+ dataset_name: str = "video",
502
+ prob_thresh: float = 0.5,
503
+ iou_types: Optional[Sequence[str]] = None,
504
+ compute_video_mot_hota: bool = False,
505
+ ):
506
+ self.gt_ann_file = gt_ann_file
507
+ self.dataset_name = dataset_name
508
+ self.prob_thresh = prob_thresh
509
+ self.metric_prefix = "phrase"
510
+ # the list of metrics to collect from the HOTA evaluation results
511
+ self.metric_to_collect = [
512
+ "HOTA",
513
+ "DetA",
514
+ "AssA",
515
+ "DetRe",
516
+ "DetPr",
517
+ "AssRe",
518
+ "AssPr",
519
+ "LocA",
520
+ "OWTA",
521
+ ]
522
+ self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"]
523
+ assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
524
+
525
+ # If True, compute video MOT HOTA, aggregating predictions/GT from all categories.
526
+ self.compute_video_mot_hota = compute_video_mot_hota
527
+
528
+ def evaluate(self, pred_file: str) -> Dict[str, float]:
529
+ # use the YT-VIS evaluation toolkit in TrackEval
530
+
531
+ with open(self.gt_ann_file) as f:
532
+ gt = json.load(f)
533
+ with open(pred_file) as f:
534
+ dt = json.load(f)
535
+ # keep only predictions with score above the probability threshold
536
+ dt = [d for d in dt if d["score"] > self.prob_thresh]
537
+ for d in dt:
538
+ assert len(d["areas"]) == len(d["bboxes"])
539
+ assert len(d["areas"]) == len(d["segmentations"])
540
+ # remove empty boxes (otherwise they will count as false positives for during
541
+ # per-frame detection accuracy in HOTA evaluation)
542
+ for t in range(len(d["bboxes"])):
543
+ bbox = d["bboxes"][t]
544
+ if d["areas"][t] == 0 or bbox is None or all(x == 0 for x in bbox):
545
+ d["segmentations"][t] = None
546
+ d["bboxes"][t] = None
547
+ d["areas"][t] = None
548
+ # check that box occurence and mask occurence are consistent
549
+ for bbox, mask, area in zip(d["bboxes"], d["segmentations"], d["areas"]):
550
+ assert (area is None) == (bbox is None)
551
+ assert (area is None) == (mask is None)
552
+ # set all scores to 1.0 for HOTA evaluation (just like Demo F1, the exact score
553
+ # value is not used in HOTA metrics; it will be treated as a detection prediction
554
+ # as long as its score is above the threshold)
555
+ d["score"] = 1.0
556
+
557
+ # remap the GT and DT annotations for phrase HOTA evaluation
558
+ gt = _fill_in_ann_height_width(gt)
559
+ if not self.compute_video_mot_hota:
560
+ # remap the GT and DT annotations for phrase HOTA evaluation
561
+ gt, dt = self._remap_gt_dt(gt, dt)
562
+ else:
563
+ # Compute video-level MOT HOTA
564
+ # Apply track-level NMS
565
+ video_groups = defaultdict(list)
566
+ for pred in dt:
567
+ video_groups[pred["video_id"]].append(pred)
568
+ process_track_level_nms(video_groups, nms_threshold=0.5)
569
+ dt = [track for tracks in video_groups.values() for track in tracks]
570
+
571
+ # Remap GT track ids for class-agnostic HOTA
572
+ gt, dt = remap_gt_dt_class_agnostic(gt, dt)
573
+
574
+ # run the HOTA evaluation using TrackEval on the remapped (video_id, category_id) pairs
575
+ out_dict = {}
576
+ video_np_level_results = {}
577
+ for iou_type in self.iou_types:
578
+ output_res, _ = run_ytvis_eval(
579
+ args=[
580
+ "--METRICS",
581
+ "HOTA",
582
+ "--IOU_TYPE",
583
+ iou_type,
584
+ "--DATASET_NAME",
585
+ self.dataset_name,
586
+ "--USE_PARALLEL",
587
+ "True",
588
+ "--NUM_PARALLEL_CORES",
589
+ "8",
590
+ "--PLOT_CURVES",
591
+ "False",
592
+ "--LOG_ON_ERROR",
593
+ "None",
594
+ "--PRINT_ONLY_COMBINED",
595
+ "True",
596
+ "--OUTPUT_SUMMARY",
597
+ "False",
598
+ "--OUTPUT_DETAILED",
599
+ "False",
600
+ "--TIME_PROGRESS",
601
+ "False",
602
+ "--PRINT_CONFIG",
603
+ "False",
604
+ ],
605
+ gt_json=gt,
606
+ dt_json=dt,
607
+ )
608
+ self.extract_video_np_level_results(
609
+ iou_type=iou_type,
610
+ remapped_gt=gt,
611
+ raw_results=output_res[self.dataset_name]["tracker"],
612
+ video_np_level_results=video_np_level_results,
613
+ )
614
+
615
+ def _summarize_results(output_res, iou_type, field, suffix):
616
+ eval_res = output_res[self.dataset_name]["tracker"][field]
617
+ result_prefix = f"{self.dataset_name}_{'mask' if iou_type == 'segm' else 'bbox'}_{suffix}"
618
+ for metric_name in self.metric_to_collect:
619
+ eval_res_hota = eval_res["cls_comb_cls_av"]["HOTA"]
620
+ result_key = f"{result_prefix}_{self.metric_prefix}_{metric_name}"
621
+ result_value = float(np.mean(eval_res_hota[metric_name]))
622
+ out_dict[result_key] = result_value
623
+
624
+ _summarize_results(output_res, iou_type, "COMBINED_SEQ", "all")
625
+ if "COMBINED_SEQ_CHALLENGING" in output_res[self.dataset_name]["tracker"]:
626
+ _summarize_results(
627
+ output_res, iou_type, "COMBINED_SEQ_CHALLENGING", "challenging"
628
+ )
629
+
630
+ # video-NP level results not supported for `VideoPhraseHotaEvaluator` yet
631
+ return out_dict, video_np_level_results
632
+
633
+ def _remap_gt_dt(self, gt, dt):
634
+ # For phrase HOTA evaluation, we need to remap each pair of (video_id, category_id) to
635
+ # a new unique video_id, so that we don't mix detections from different categories
636
+ gt, dt = remap_video_category_pairs_to_unique_video_ids(gt, dt)
637
+ # We further map all the categories to category_id=1 in HOTA evaluation toolkit
638
+ # for phrase HOTA (similar to "useCat=False" for video phrase AP)
639
+ remapped_category_id = 1
640
+ gt["categories"] = [
641
+ {
642
+ "supercategory": "object",
643
+ "id": remapped_category_id,
644
+ "name": "_REMAPPED_FOR_PHRASE_METRICS_",
645
+ }
646
+ ]
647
+ for ann in gt["annotations"]:
648
+ ann["category_id"] = remapped_category_id
649
+ for d in dt:
650
+ d["category_id"] = remapped_category_id
651
+ # To be compatible with the TrackEval YT-VIS evaluation toolkit, we need to give
652
+ # unique filenames to each remapped video, so we add remapped video_id as prefix.
653
+ for video in gt["videos"]:
654
+ new_video_id = video["id"]
655
+ video["file_names"] = [
656
+ f"remapped_vid_{new_video_id:012d}/{name}"
657
+ for name in video["file_names"]
658
+ ]
659
+ return gt, dt
660
+
661
+ def extract_video_np_level_results(
662
+ self, iou_type, remapped_gt, raw_results, video_np_level_results
663
+ ):
664
+ """Aggregate statistics for video-level metrics."""
665
+ result_prefix = "mask" if iou_type == "segm" else "bbox"
666
+ for video in remapped_gt["videos"]:
667
+ # the original video id and category id before remapping
668
+ video_id = video["orig_video_id"]
669
+ category_id = video["orig_category_id"]
670
+ video_key = f"remapped_vid_{video['id']:012d}"
671
+ results = raw_results[video_key]["_REMAPPED_FOR_PHRASE_METRICS_"]["HOTA"]
672
+
673
+ local_results = {}
674
+ for metric_name in self.metric_to_collect:
675
+ result_key = f"{result_prefix}_{metric_name}"
676
+ local_results[result_key] = float(results[metric_name].mean())
677
+ if (video_id, category_id) not in video_np_level_results:
678
+ video_np_level_results[(video_id, category_id)] = {}
679
+ video_np_level_results[(video_id, category_id)].update(local_results)
680
+
681
+
682
+ class VideoClassBasedHotaEvaluator(VideoPhraseHotaEvaluator):
683
+ def __init__(
684
+ self,
685
+ gt_ann_file: str,
686
+ dataset_name: str = "video",
687
+ prob_thresh: float = 0.5,
688
+ ):
689
+ super().__init__(gt_ann_file, dataset_name, prob_thresh)
690
+ self.metric_prefix = "class"
691
+
692
+ def _remap_gt_dt(self, gt, dt):
693
+ return gt, dt # no remapping needed for class-based HOTA evaluation
694
+
695
+ def extract_video_np_level_results(self, *args, **kwargs):
696
+ pass # no video-NP level results for class-based HOTA evaluation
697
+
698
+
699
+ def _compress_rle(rle):
700
+ """Convert RLEs from uncompressed (integer list) to compressed (string) format."""
701
+ if rle is None:
702
+ return None
703
+ if isinstance(rle["counts"], list):
704
+ rle = pycocotools.mask.frPyObjects(rle, rle["size"][0], rle["size"][1])
705
+ rle["counts"] = rle["counts"].decode()
706
+ return rle
707
+
708
+
709
+ def remap_video_category_pairs_to_unique_video_ids(
710
+ gt_json, dt_json, add_negative_np_pairs=False
711
+ ):
712
+ """
713
+ Remap each pair of (video_id, category_id) to a new unique video_id. This is useful
714
+ for phrase AP and demo F1 evaluation on videos, where we have `useCat=False` and
715
+ rely on separating different NPs (from the same video) into different new video ids,
716
+ so that we don't mix detections from different categories in computeIoU under `useCat=False`.
717
+
718
+ This is consistent with how do we phrase AP and demo F1 evaluation on images, where we
719
+ use a remapped unique coco_image_id for each image-NP pair (based in its query["id"] in
720
+ CustomCocoDetectionAPI.load_queries in modulated_detection_api.py)
721
+ """
722
+ # collect the unique video_id-category_id pairs
723
+ video_id_to_video = {v["id"]: v for v in gt_json["videos"]}
724
+ video_id_category_id_pairs = set()
725
+ for pred in dt_json:
726
+ video_id_category_id_pairs.add((pred["video_id"], pred["category_id"]))
727
+ for ann in gt_json["annotations"]:
728
+ video_id_category_id_pairs.add((ann["video_id"], ann["category_id"]))
729
+
730
+ # assign the video_id-category_id pairs to unique video ids
731
+ video_id_category_id_pairs = sorted(video_id_category_id_pairs)
732
+ video_id_category_id_to_new_video_id = {
733
+ pair: (i + 1) for i, pair in enumerate(video_id_category_id_pairs)
734
+ }
735
+ # also map the negative NP pairs -- this is needed for IL_MCC and CG-F1 evaluation
736
+ if add_negative_np_pairs:
737
+ for vnp in gt_json["video_np_pairs"]:
738
+ pair = (vnp["video_id"], vnp["category_id"])
739
+ if pair not in video_id_category_id_to_new_video_id:
740
+ video_id_category_id_to_new_video_id[pair] = (
741
+ len(video_id_category_id_to_new_video_id) + 1
742
+ )
743
+
744
+ # map the "video_id" in predictions
745
+ for pred in dt_json:
746
+ pred["video_id"] = video_id_category_id_to_new_video_id[
747
+ (pred["video_id"], pred["category_id"])
748
+ ]
749
+ # map the "video_id" in gt_json["annotations"]
750
+ for ann in gt_json["annotations"]:
751
+ ann["video_id"] = video_id_category_id_to_new_video_id[
752
+ (ann["video_id"], ann["category_id"])
753
+ ]
754
+ # map and duplicate gt_json["videos"]
755
+ new_videos = []
756
+ for (
757
+ video_id,
758
+ category_id,
759
+ ), new_video_id in video_id_category_id_to_new_video_id.items():
760
+ video = video_id_to_video[video_id].copy()
761
+ video["id"] = new_video_id
762
+ # preserve the original video_id and category_id of each remapped video entry,
763
+ # so that we can associate sample-level eval metrics with the original video-NP pairs
764
+ video["orig_video_id"] = video_id
765
+ video["orig_category_id"] = category_id
766
+ new_videos.append(video)
767
+ gt_json["videos"] = new_videos
768
+
769
+ return gt_json, dt_json
770
+
771
+
772
+ def remap_gt_dt_class_agnostic(gt, dt):
773
+ """
774
+ For class-agnostic HOTA, merge all GT tracks for each video (across NPs),
775
+ ensure unique track_ids, and set all category_id to 1.
776
+ Also, add orig_video_id and orig_category_id for compatibility.
777
+ """
778
+ # 1. Remap all GT track_ids to be unique per video
779
+ gt_anns_by_video = defaultdict(list)
780
+ for ann in gt["annotations"]:
781
+ gt_anns_by_video[ann["video_id"]].append(ann)
782
+
783
+ # Ensure unique track ids across tracks of all videos
784
+ next_tid = 1
785
+ for _, anns in gt_anns_by_video.items():
786
+ # Map old track_ids to new unique ones
787
+ old_to_new_tid = {}
788
+ for ann in anns:
789
+ old_tid = ann["id"]
790
+ if old_tid not in old_to_new_tid:
791
+ old_to_new_tid[old_tid] = next_tid
792
+ next_tid += 1
793
+ ann["id"] = old_to_new_tid[old_tid]
794
+ # Set category_id to 1 for class-agnostic
795
+ ann["category_id"] = 1
796
+
797
+ # Set all GT categories to a single category
798
+ gt["categories"] = [
799
+ {
800
+ "supercategory": "object",
801
+ "id": 1,
802
+ "name": "_REMAPPED_FOR_PHRASE_METRICS_",
803
+ }
804
+ ]
805
+
806
+ # Add orig_video_id and orig_category_id to each video for compatibility
807
+ anns_by_video = defaultdict(list)
808
+ for ann in gt["annotations"]:
809
+ anns_by_video[ann["video_id"]].append(ann)
810
+ for video in gt["videos"]:
811
+ video["orig_video_id"] = video["id"]
812
+ # Use the first annotation's original category_id if available, else None
813
+ orig_cat = (
814
+ anns_by_video[video["id"]][0]["category_id"]
815
+ if anns_by_video[video["id"]]
816
+ else None
817
+ )
818
+ video["orig_category_id"] = orig_cat
819
+ video["file_names"] = [
820
+ f"remapped_vid_{video['id']:012d}/{name}" for name in video["file_names"]
821
+ ]
822
+
823
+ # Set all DT category_id to 1
824
+ for d in dt:
825
+ d["category_id"] = 1
826
+ return gt, dt
827
+
828
+
829
+ def _fill_in_ann_height_width(gt_json):
830
+ """Fill in missing height/width in GT annotations from its video info."""
831
+ video_id_to_video = {v["id"]: v for v in gt_json["videos"]}
832
+ for ann in gt_json["annotations"]:
833
+ if "height" not in ann or "width" not in ann:
834
+ video = video_id_to_video[ann["video_id"]]
835
+ if "height" not in ann:
836
+ ann["height"] = video["height"]
837
+ if "width" not in ann:
838
+ ann["width"] = video["width"]
839
+
840
+ return gt_json
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ from . import config, datasets, metrics, utils
7
+ from .eval import Evaluator
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/_timing.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ import inspect
7
+ from functools import wraps
8
+ from time import perf_counter
9
+
10
+ DO_TIMING = False
11
+ DISPLAY_LESS_PROGRESS = False
12
+ timer_dict = {}
13
+ counter = 0
14
+
15
+
16
+ def time(f):
17
+ @wraps(f)
18
+ def wrap(*args, **kw):
19
+ if DO_TIMING:
20
+ # Run function with timing
21
+ ts = perf_counter()
22
+ result = f(*args, **kw)
23
+ te = perf_counter()
24
+ tt = te - ts
25
+
26
+ # Get function name
27
+ arg_names = inspect.getfullargspec(f)[0]
28
+ if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS:
29
+ return result
30
+ elif arg_names[0] == "self":
31
+ method_name = type(args[0]).__name__ + "." + f.__name__
32
+ else:
33
+ method_name = f.__name__
34
+
35
+ # Record accumulative time in each function for analysis
36
+ if method_name in timer_dict.keys():
37
+ timer_dict[method_name] += tt
38
+ else:
39
+ timer_dict[method_name] = tt
40
+
41
+ # If code is finished, display timing summary
42
+ if method_name == "Evaluator.evaluate":
43
+ print("")
44
+ print("Timing analysis:")
45
+ for key, value in timer_dict.items():
46
+ print("%-70s %2.4f sec" % (key, value))
47
+ else:
48
+ # Get function argument values for printing special arguments of interest
49
+ arg_titles = ["tracker", "seq", "cls"]
50
+ arg_vals = []
51
+ for i, a in enumerate(arg_names):
52
+ if a in arg_titles:
53
+ arg_vals.append(args[i])
54
+ arg_text = "(" + ", ".join(arg_vals) + ")"
55
+
56
+ # Display methods and functions with different indentation.
57
+ if arg_names[0] == "self":
58
+ print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt))
59
+ elif arg_names[0] == "test":
60
+ pass
61
+ else:
62
+ global counter
63
+ counter += 1
64
+ print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
65
+
66
+ return result
67
+ else:
68
+ # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
69
+ return f(*args, **kw)
70
+
71
+ return wrap
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/config.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ """Config."""
7
+ import argparse
8
+ import os
9
+
10
+
11
+ def parse_configs():
12
+ """Parse command line."""
13
+ default_eval_config = get_default_eval_config()
14
+ default_eval_config["DISPLAY_LESS_PROGRESS"] = True
15
+ default_dataset_config = get_default_dataset_config()
16
+ default_metrics_config = {"METRICS": ["TETA"]}
17
+ config = {
18
+ **default_eval_config,
19
+ **default_dataset_config,
20
+ **default_metrics_config,
21
+ }
22
+ parser = argparse.ArgumentParser()
23
+ for setting in config.keys():
24
+ if type(config[setting]) == list or type(config[setting]) == type(None):
25
+ parser.add_argument("--" + setting, nargs="+")
26
+ else:
27
+ parser.add_argument("--" + setting)
28
+ args = parser.parse_args().__dict__
29
+ for setting in args.keys():
30
+ if args[setting] is not None:
31
+ if type(config[setting]) == type(True):
32
+ if args[setting] == "True":
33
+ x = True
34
+ elif args[setting] == "False":
35
+ x = False
36
+ else:
37
+ raise Exception(
38
+ f"Command line parameter {setting} must be True/False"
39
+ )
40
+ elif type(config[setting]) == type(1):
41
+ x = int(args[setting])
42
+ elif type(args[setting]) == type(None):
43
+ x = None
44
+ else:
45
+ x = args[setting]
46
+ config[setting] = x
47
+ eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()}
48
+ dataset_config = {
49
+ k: v for k, v in config.items() if k in default_dataset_config.keys()
50
+ }
51
+ metrics_config = {
52
+ k: v for k, v in config.items() if k in default_metrics_config.keys()
53
+ }
54
+
55
+ return eval_config, dataset_config, metrics_config
56
+
57
+
58
+ def get_default_eval_config():
59
+ """Returns the default config values for evaluation."""
60
+ code_path = get_code_path()
61
+ default_config = {
62
+ "USE_PARALLEL": True,
63
+ "NUM_PARALLEL_CORES": 8,
64
+ "BREAK_ON_ERROR": True,
65
+ "RETURN_ON_ERROR": False,
66
+ "LOG_ON_ERROR": os.path.join(code_path, "error_log.txt"),
67
+ "PRINT_RESULTS": True,
68
+ "PRINT_ONLY_COMBINED": True,
69
+ "PRINT_CONFIG": True,
70
+ "TIME_PROGRESS": True,
71
+ "DISPLAY_LESS_PROGRESS": True,
72
+ "OUTPUT_SUMMARY": True,
73
+ "OUTPUT_EMPTY_CLASSES": True,
74
+ "OUTPUT_TEM_RAW_DATA": True,
75
+ "OUTPUT_PER_SEQ_RES": True,
76
+ }
77
+ return default_config
78
+
79
+
80
+ def get_default_dataset_config():
81
+ """Default class config values"""
82
+ code_path = get_code_path()
83
+ default_config = {
84
+ "GT_FOLDER": os.path.join(
85
+ code_path, "data/gt/tao/tao_training"
86
+ ), # Location of GT data
87
+ "TRACKERS_FOLDER": os.path.join(
88
+ code_path, "data/trackers/tao/tao_training"
89
+ ), # Trackers location
90
+ "OUTPUT_FOLDER": None, # Where to save eval results (if None, same as TRACKERS_FOLDER)
91
+ "TRACKERS_TO_EVAL": ['TETer'], # Filenames of trackers to eval (if None, all in folder)
92
+ "CLASSES_TO_EVAL": None, # Classes to eval (if None, all classes)
93
+ "SPLIT_TO_EVAL": "training", # Valid: 'training', 'val'
94
+ "PRINT_CONFIG": True, # Whether to print current config
95
+ "TRACKER_SUB_FOLDER": "data", # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER
96
+ "OUTPUT_SUB_FOLDER": "", # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER
97
+ "TRACKER_DISPLAY_NAMES": None, # Names of trackers to display, if None: TRACKERS_TO_EVAL
98
+ "MAX_DETECTIONS": 0, # Number of maximal allowed detections per image (0 for unlimited)
99
+ "USE_MASK": False, # Whether to use mask data for evaluation
100
+ }
101
+ return default_config
102
+
103
+
104
+ def init_config(config, default_config, name=None):
105
+ """Initialize non-given config values with defaults."""
106
+ if config is None:
107
+ config = default_config
108
+ else:
109
+ for k in default_config.keys():
110
+ if k not in config.keys():
111
+ config[k] = default_config[k]
112
+ if name and config["PRINT_CONFIG"]:
113
+ print("\n%s Config:" % name)
114
+ for c in config.keys():
115
+ print("%-20s : %-30s" % (c, config[c]))
116
+ return config
117
+
118
+
119
+ def update_config(config):
120
+ """
121
+ Parse the arguments of a script and updates the config values for a given value if specified in the arguments.
122
+ :param config: the config to update
123
+ :return: the updated config
124
+ """
125
+ parser = argparse.ArgumentParser()
126
+ for setting in config.keys():
127
+ if type(config[setting]) == list or type(config[setting]) == type(None):
128
+ parser.add_argument("--" + setting, nargs="+")
129
+ else:
130
+ parser.add_argument("--" + setting)
131
+ args = parser.parse_args().__dict__
132
+ for setting in args.keys():
133
+ if args[setting] is not None:
134
+ if type(config[setting]) == type(True):
135
+ if args[setting] == "True":
136
+ x = True
137
+ elif args[setting] == "False":
138
+ x = False
139
+ else:
140
+ raise Exception(
141
+ "Command line parameter " + setting + "must be True or False"
142
+ )
143
+ elif type(config[setting]) == type(1):
144
+ x = int(args[setting])
145
+ elif type(args[setting]) == type(None):
146
+ x = None
147
+ else:
148
+ x = args[setting]
149
+ config[setting] = x
150
+ return config
151
+
152
+
153
+ def get_code_path():
154
+ """Get base path where code is"""
155
+ return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+ """Datasets."""
6
+ from .coco import COCO
7
+ from .tao import TAO
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/_base_dataset.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ import csv
7
+ import io
8
+ import os
9
+ import traceback
10
+ import zipfile
11
+ from abc import ABC, abstractmethod
12
+ from copy import deepcopy
13
+
14
+ import numpy as np
15
+
16
+ from .. import _timing
17
+ from ..utils import TrackEvalException
18
+
19
+
20
+ class _BaseDataset(ABC):
21
+ @abstractmethod
22
+ def __init__(self):
23
+ self.tracker_list = None
24
+ self.seq_list = None
25
+ self.class_list = None
26
+ self.output_fol = None
27
+ self.output_sub_fol = None
28
+ self.should_classes_combine = True
29
+ self.use_super_categories = False
30
+
31
+ # Functions to implement:
32
+
33
+ @abstractmethod
34
+ def _load_raw_file(self, tracker, seq, is_gt):
35
+ ...
36
+
37
+ @_timing.time
38
+ @abstractmethod
39
+ def get_preprocessed_seq_data(self, raw_data, cls):
40
+ ...
41
+
42
+ @abstractmethod
43
+ def _calculate_similarities(self, gt_dets_t, tracker_dets_t):
44
+ ...
45
+
46
+ # Helper functions for all datasets:
47
+
48
+ @classmethod
49
+ def get_class_name(cls):
50
+ return cls.__name__
51
+
52
+ def get_name(self):
53
+ return self.get_class_name()
54
+
55
+ def get_output_fol(self, tracker):
56
+ return os.path.join(self.output_fol, tracker, self.output_sub_fol)
57
+
58
+ def get_display_name(self, tracker):
59
+ """Can be overwritten if the trackers name (in files) is different to how it should be displayed.
60
+ By default this method just returns the trackers name as is.
61
+ """
62
+ return tracker
63
+
64
+ def get_eval_info(self):
65
+ """Return info about the dataset needed for the Evaluator"""
66
+ return self.tracker_list, self.seq_list, self.class_list
67
+
68
+ @_timing.time
69
+ def get_raw_seq_data(self, tracker, seq):
70
+ """Loads raw data (tracker and ground-truth) for a single tracker on a single sequence.
71
+ Raw data includes all of the information needed for both preprocessing and evaluation, for all classes.
72
+ A later function (get_processed_seq_data) will perform such preprocessing and extract relevant information for
73
+ the evaluation of each class.
74
+
75
+ This returns a dict which contains the fields:
76
+ [num_timesteps]: integer
77
+ [gt_ids, tracker_ids, gt_classes, tracker_classes, tracker_confidences]:
78
+ list (for each timestep) of 1D NDArrays (for each det).
79
+ [gt_dets, tracker_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections.
80
+ [similarity_scores]: list (for each timestep) of 2D NDArrays.
81
+ [gt_extras]: dict (for each extra) of lists (for each timestep) of 1D NDArrays (for each det).
82
+
83
+ gt_extras contains dataset specific information used for preprocessing such as occlusion and truncation levels.
84
+
85
+ Note that similarities are extracted as part of the dataset and not the metric, because almost all metrics are
86
+ independent of the exact method of calculating the similarity. However datasets are not (e.g. segmentation
87
+ masks vs 2D boxes vs 3D boxes).
88
+ We calculate the similarity before preprocessing because often both preprocessing and evaluation require it and
89
+ we don't wish to calculate this twice.
90
+ We calculate similarity between all gt and tracker classes (not just each class individually) to allow for
91
+ calculation of metrics such as class confusion matrices. Typically the impact of this on performance is low.
92
+ """
93
+ # Load raw data.
94
+ raw_gt_data = self._load_raw_file(tracker, seq, is_gt=True)
95
+ raw_tracker_data = self._load_raw_file(tracker, seq, is_gt=False)
96
+ raw_data = {**raw_tracker_data, **raw_gt_data} # Merges dictionaries
97
+
98
+ # Calculate similarities for each timestep.
99
+ similarity_scores = []
100
+ for _, (gt_dets_t, tracker_dets_t) in enumerate(
101
+ zip(raw_data["gt_dets"], raw_data["tk_dets"])
102
+ ):
103
+ ious = self._calculate_similarities(gt_dets_t, tracker_dets_t)
104
+ similarity_scores.append(ious)
105
+ raw_data["similarity_scores"] = similarity_scores
106
+ return raw_data
107
+
108
+ @staticmethod
109
+ def _load_simple_text_file(
110
+ file,
111
+ time_col=0,
112
+ id_col=None,
113
+ remove_negative_ids=False,
114
+ valid_filter=None,
115
+ crowd_ignore_filter=None,
116
+ convert_filter=None,
117
+ is_zipped=False,
118
+ zip_file=None,
119
+ force_delimiters=None,
120
+ ):
121
+ """Function that loads data which is in a commonly used text file format.
122
+ Assumes each det is given by one row of a text file.
123
+ There is no limit to the number or meaning of each column,
124
+ however one column needs to give the timestep of each det (time_col) which is default col 0.
125
+
126
+ The file dialect (deliminator, num cols, etc) is determined automatically.
127
+ This function automatically separates dets by timestep,
128
+ and is much faster than alternatives such as np.loadtext or pandas.
129
+
130
+ If remove_negative_ids is True and id_col is not None, dets with negative values in id_col are excluded.
131
+ These are not excluded from ignore data.
132
+
133
+ valid_filter can be used to only include certain classes.
134
+ It is a dict with ints as keys, and lists as values,
135
+ such that a row is included if "row[key].lower() is in value" for all key/value pairs in the dict.
136
+ If None, all classes are included.
137
+
138
+ crowd_ignore_filter can be used to read crowd_ignore regions separately. It has the same format as valid filter.
139
+
140
+ convert_filter can be used to convert value read to another format.
141
+ This is used most commonly to convert classes given as string to a class id.
142
+ This is a dict such that the key is the column to convert, and the value is another dict giving the mapping.
143
+
144
+ Optionally, input files could be a zip of multiple text files for storage efficiency.
145
+
146
+ Returns read_data and ignore_data.
147
+ Each is a dict (with keys as timesteps as strings) of lists (over dets) of lists (over column values).
148
+ Note that all data is returned as strings, and must be converted to float/int later if needed.
149
+ Note that timesteps will not be present in the returned dict keys if there are no dets for them
150
+ """
151
+
152
+ if remove_negative_ids and id_col is None:
153
+ raise TrackEvalException(
154
+ "remove_negative_ids is True, but id_col is not given."
155
+ )
156
+ if crowd_ignore_filter is None:
157
+ crowd_ignore_filter = {}
158
+ if convert_filter is None:
159
+ convert_filter = {}
160
+ try:
161
+ if is_zipped: # Either open file directly or within a zip.
162
+ if zip_file is None:
163
+ raise TrackEvalException(
164
+ "is_zipped set to True, but no zip_file is given."
165
+ )
166
+ archive = zipfile.ZipFile(os.path.join(zip_file), "r")
167
+ fp = io.TextIOWrapper(archive.open(file, "r"))
168
+ else:
169
+ fp = open(file)
170
+ read_data = {}
171
+ crowd_ignore_data = {}
172
+ fp.seek(0, os.SEEK_END)
173
+ # check if file is empty
174
+ if fp.tell():
175
+ fp.seek(0)
176
+ dialect = csv.Sniffer().sniff(
177
+ fp.readline(), delimiters=force_delimiters
178
+ ) # Auto determine structure.
179
+ dialect.skipinitialspace = (
180
+ True # Deal with extra spaces between columns
181
+ )
182
+ fp.seek(0)
183
+ reader = csv.reader(fp, dialect)
184
+ for row in reader:
185
+ try:
186
+ # Deal with extra trailing spaces at the end of rows
187
+ if row[-1] in "":
188
+ row = row[:-1]
189
+ timestep = str(int(float(row[time_col])))
190
+ # Read ignore regions separately.
191
+ is_ignored = False
192
+ for ignore_key, ignore_value in crowd_ignore_filter.items():
193
+ if row[ignore_key].lower() in ignore_value:
194
+ # Convert values in one column (e.g. string to id)
195
+ for (
196
+ convert_key,
197
+ convert_value,
198
+ ) in convert_filter.items():
199
+ row[convert_key] = convert_value[
200
+ row[convert_key].lower()
201
+ ]
202
+ # Save data separated by timestep.
203
+ if timestep in crowd_ignore_data.keys():
204
+ crowd_ignore_data[timestep].append(row)
205
+ else:
206
+ crowd_ignore_data[timestep] = [row]
207
+ is_ignored = True
208
+ if (
209
+ is_ignored
210
+ ): # if det is an ignore region, it cannot be a normal det.
211
+ continue
212
+ # Exclude some dets if not valid.
213
+ if valid_filter is not None:
214
+ for key, value in valid_filter.items():
215
+ if row[key].lower() not in value:
216
+ continue
217
+ if remove_negative_ids:
218
+ if int(float(row[id_col])) < 0:
219
+ continue
220
+ # Convert values in one column (e.g. string to id)
221
+ for convert_key, convert_value in convert_filter.items():
222
+ row[convert_key] = convert_value[row[convert_key].lower()]
223
+ # Save data separated by timestep.
224
+ if timestep in read_data.keys():
225
+ read_data[timestep].append(row)
226
+ else:
227
+ read_data[timestep] = [row]
228
+ except Exception:
229
+ exc_str_init = (
230
+ "In file %s the following line cannot be read correctly: \n"
231
+ % os.path.basename(file)
232
+ )
233
+ exc_str = " ".join([exc_str_init] + row)
234
+ raise TrackEvalException(exc_str)
235
+ fp.close()
236
+ except Exception:
237
+ print("Error loading file: %s, printing traceback." % file)
238
+ traceback.print_exc()
239
+ raise TrackEvalException(
240
+ "File %s cannot be read because it is either not present or invalidly formatted"
241
+ % os.path.basename(file)
242
+ )
243
+ return read_data, crowd_ignore_data
244
+
245
+ @staticmethod
246
+ def _calculate_mask_ious(masks1, masks2, is_encoded=False, do_ioa=False):
247
+ """Calculates the IOU (intersection over union) between two arrays of segmentation masks.
248
+ If is_encoded a run length encoding with pycocotools is assumed as input format, otherwise an input of numpy
249
+ arrays of the shape (num_masks, height, width) is assumed and the encoding is performed.
250
+ If do_ioa (intersection over area) , then calculates the intersection over the area of masks1 - this is commonly
251
+ used to determine if detections are within crowd ignore region.
252
+ :param masks1: first set of masks (numpy array of shape (num_masks, height, width) if not encoded,
253
+ else pycocotools rle encoded format)
254
+ :param masks2: second set of masks (numpy array of shape (num_masks, height, width) if not encoded,
255
+ else pycocotools rle encoded format)
256
+ :param is_encoded: whether the input is in pycocotools rle encoded format
257
+ :param do_ioa: whether to perform IoA computation
258
+ :return: the IoU/IoA scores
259
+ """
260
+
261
+ # Only loaded when run to reduce minimum requirements
262
+ from pycocotools import mask as mask_utils
263
+
264
+ # use pycocotools for run length encoding of masks
265
+ if not is_encoded:
266
+ masks1 = mask_utils.encode(
267
+ np.array(np.transpose(masks1, (1, 2, 0)), order="F")
268
+ )
269
+ masks2 = mask_utils.encode(
270
+ np.array(np.transpose(masks2, (1, 2, 0)), order="F")
271
+ )
272
+
273
+ # use pycocotools for iou computation of rle encoded masks
274
+ ious = mask_utils.iou(masks1, masks2, [do_ioa] * len(masks2))
275
+ if len(masks1) == 0 or len(masks2) == 0:
276
+ ious = np.asarray(ious).reshape(len(masks1), len(masks2))
277
+ assert (ious >= 0 - np.finfo("float").eps).all()
278
+ assert (ious <= 1 + np.finfo("float").eps).all()
279
+
280
+ return ious
281
+
282
+ @staticmethod
283
+ def _calculate_box_ious(bboxes1, bboxes2, box_format="xywh", do_ioa=False):
284
+ """Calculates the IOU (intersection over union) between two arrays of boxes.
285
+ Allows variable box formats ('xywh' and 'x0y0x1y1').
286
+ If do_ioa (intersection over area) , then calculates the intersection over the area of boxes1 - this is commonly
287
+ used to determine if detections are within crowd ignore region.
288
+ """
289
+ if box_format in "xywh":
290
+ # layout: (x0, y0, w, h)
291
+ bboxes1 = deepcopy(bboxes1)
292
+ bboxes2 = deepcopy(bboxes2)
293
+
294
+ bboxes1[:, 2] = bboxes1[:, 0] + bboxes1[:, 2]
295
+ bboxes1[:, 3] = bboxes1[:, 1] + bboxes1[:, 3]
296
+ bboxes2[:, 2] = bboxes2[:, 0] + bboxes2[:, 2]
297
+ bboxes2[:, 3] = bboxes2[:, 1] + bboxes2[:, 3]
298
+ elif box_format not in "x0y0x1y1":
299
+ raise (TrackEvalException("box_format %s is not implemented" % box_format))
300
+
301
+ # layout: (x0, y0, x1, y1)
302
+ min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :])
303
+ max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :])
304
+ intersection = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum(
305
+ min_[..., 3] - max_[..., 1], 0
306
+ )
307
+ area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (
308
+ bboxes1[..., 3] - bboxes1[..., 1]
309
+ )
310
+
311
+ if do_ioa:
312
+ ioas = np.zeros_like(intersection)
313
+ valid_mask = area1 > 0 + np.finfo("float").eps
314
+ ioas[valid_mask, :] = (
315
+ intersection[valid_mask, :] / area1[valid_mask][:, np.newaxis]
316
+ )
317
+
318
+ return ioas
319
+ else:
320
+ area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (
321
+ bboxes2[..., 3] - bboxes2[..., 1]
322
+ )
323
+ union = area1[:, np.newaxis] + area2[np.newaxis, :] - intersection
324
+ intersection[area1 <= 0 + np.finfo("float").eps, :] = 0
325
+ intersection[:, area2 <= 0 + np.finfo("float").eps] = 0
326
+ intersection[union <= 0 + np.finfo("float").eps] = 0
327
+ union[union <= 0 + np.finfo("float").eps] = 1
328
+ ious = intersection / union
329
+ return ious
330
+
331
+ @staticmethod
332
+ def _calculate_euclidean_similarity(dets1, dets2, zero_distance=2.0):
333
+ """Calculates the euclidean distance between two sets of detections, and then converts this into a similarity
334
+ measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance).
335
+ The default zero_distance of 2.0, corresponds to the default used in MOT15_3D, such that a 0.5 similarity
336
+ threshold corresponds to a 1m distance threshold for TPs.
337
+ """
338
+ dist = np.linalg.norm(dets1[:, np.newaxis] - dets2[np.newaxis, :], axis=2)
339
+ sim = np.maximum(0, 1 - dist / zero_distance)
340
+ return sim
341
+
342
+ @staticmethod
343
+ def _check_unique_ids(data, after_preproc=False):
344
+ """Check the requirement that the tracker_ids and gt_ids are unique per timestep"""
345
+ gt_ids = data["gt_ids"]
346
+ tracker_ids = data["tk_ids"]
347
+ for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(gt_ids, tracker_ids)):
348
+ if len(tracker_ids_t) > 0:
349
+ unique_ids, counts = np.unique(tracker_ids_t, return_counts=True)
350
+ if np.max(counts) != 1:
351
+ duplicate_ids = unique_ids[counts > 1]
352
+ exc_str_init = (
353
+ "Tracker predicts the same ID more than once in a single timestep "
354
+ "(seq: %s, frame: %i, ids:" % (data["seq"], t + 1)
355
+ )
356
+ exc_str = (
357
+ " ".join([exc_str_init] + [str(d) for d in duplicate_ids]) + ")"
358
+ )
359
+ if after_preproc:
360
+ exc_str_init += (
361
+ "\n Note that this error occurred after preprocessing (but not before), "
362
+ "so ids may not be as in file, and something seems wrong with preproc."
363
+ )
364
+ raise TrackEvalException(exc_str)
365
+ if len(gt_ids_t) > 0:
366
+ unique_ids, counts = np.unique(gt_ids_t, return_counts=True)
367
+ if np.max(counts) != 1:
368
+ duplicate_ids = unique_ids[counts > 1]
369
+ exc_str_init = (
370
+ "Ground-truth has the same ID more than once in a single timestep "
371
+ "(seq: %s, frame: %i, ids:" % (data["seq"], t + 1)
372
+ )
373
+ exc_str = (
374
+ " ".join([exc_str_init] + [str(d) for d in duplicate_ids]) + ")"
375
+ )
376
+ if after_preproc:
377
+ exc_str_init += (
378
+ "\n Note that this error occurred after preprocessing (but not before), "
379
+ "so ids may not be as in file, and something seems wrong with preproc."
380
+ )
381
+ raise TrackEvalException(exc_str)
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/coco.py ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ """COCO Dataset."""
7
+ import copy
8
+ import itertools
9
+ import json
10
+ import os
11
+ from collections import defaultdict
12
+
13
+ import numpy as np
14
+ from scipy.optimize import linear_sum_assignment
15
+
16
+ from .. import _timing, utils
17
+ from ..config import get_default_dataset_config, init_config
18
+ from ..utils import TrackEvalException
19
+ from ._base_dataset import _BaseDataset
20
+
21
+
22
+ class COCO(_BaseDataset):
23
+ """Tracking datasets in COCO format."""
24
+
25
+ def __init__(self, config=None):
26
+ """Initialize dataset, checking that all required files are present."""
27
+ super().__init__()
28
+ # Fill non-given config values with defaults
29
+ self.config = init_config(config, get_default_dataset_config(), self.get_name())
30
+ self.gt_fol = self.config["GT_FOLDER"]
31
+ self.tracker_fol = self.config["TRACKERS_FOLDER"]
32
+ self.should_classes_combine = True
33
+ self.use_super_categories = False
34
+ self.use_mask = self.config["USE_MASK"]
35
+
36
+ self.tracker_sub_fol = self.config["TRACKER_SUB_FOLDER"]
37
+ self.output_fol = self.config["OUTPUT_FOLDER"]
38
+ if self.output_fol is None:
39
+ self.output_fol = self.tracker_fol
40
+ self.output_sub_fol = self.config["OUTPUT_SUB_FOLDER"]
41
+
42
+ if self.gt_fol.endswith(".json"):
43
+ self.gt_data = json.load(open(self.gt_fol, "r"))
44
+ else:
45
+ gt_dir_files = [
46
+ file for file in os.listdir(self.gt_fol) if file.endswith(".json")
47
+ ]
48
+ if len(gt_dir_files) != 1:
49
+ raise TrackEvalException(
50
+ f"{self.gt_fol} does not contain exactly one json file."
51
+ )
52
+
53
+ with open(os.path.join(self.gt_fol, gt_dir_files[0])) as f:
54
+ self.gt_data = json.load(f)
55
+
56
+ # fill missing video ids
57
+ self._fill_video_ids_inplace(self.gt_data["annotations"])
58
+
59
+ # get sequences to eval and sequence information
60
+ self.seq_list = [
61
+ vid["name"].replace("/", "-") for vid in self.gt_data["videos"]
62
+ ]
63
+ self.seq_name2seqid = {
64
+ vid["name"].replace("/", "-"): vid["id"] for vid in self.gt_data["videos"]
65
+ }
66
+ # compute mappings from videos to annotation data
67
+ self.video2gt_track, self.video2gt_image = self._compute_vid_mappings(
68
+ self.gt_data["annotations"]
69
+ )
70
+ # compute sequence lengths
71
+ self.seq_lengths = {vid["id"]: 0 for vid in self.gt_data["videos"]}
72
+ for img in self.gt_data["images"]:
73
+ self.seq_lengths[img["video_id"]] += 1
74
+ self.seq2images2timestep = self._compute_image_to_timestep_mappings()
75
+ self.seq2cls = {
76
+ vid["id"]: {
77
+ "pos_cat_ids": list(
78
+ {track["category_id"] for track in self.video2gt_track[vid["id"]]}
79
+ ),
80
+ }
81
+ for vid in self.gt_data["videos"]
82
+ }
83
+
84
+ # Get classes to eval
85
+ considered_vid_ids = [self.seq_name2seqid[vid] for vid in self.seq_list]
86
+ seen_cats = set(
87
+ [
88
+ cat_id
89
+ for vid_id in considered_vid_ids
90
+ for cat_id in self.seq2cls[vid_id]["pos_cat_ids"]
91
+ ]
92
+ )
93
+ # only classes with ground truth are evaluated in TAO
94
+ self.valid_classes = [
95
+ cls["name"] for cls in self.gt_data["categories"] if cls["id"] in seen_cats
96
+ ]
97
+ cls_name2clsid_map = {
98
+ cls["name"]: cls["id"] for cls in self.gt_data["categories"]
99
+ }
100
+
101
+ if self.config["CLASSES_TO_EVAL"]:
102
+ self.class_list = [
103
+ cls.lower() if cls.lower() in self.valid_classes else None
104
+ for cls in self.config["CLASSES_TO_EVAL"]
105
+ ]
106
+ if not all(self.class_list):
107
+ valid_cls = ", ".join(self.valid_classes)
108
+ raise TrackEvalException(
109
+ "Attempted to evaluate an invalid class. Only classes "
110
+ f"{valid_cls} are valid (classes present in ground truth"
111
+ " data)."
112
+ )
113
+ else:
114
+ self.class_list = [cls for cls in self.valid_classes]
115
+ self.cls_name2clsid = {
116
+ k: v for k, v in cls_name2clsid_map.items() if k in self.class_list
117
+ }
118
+ self.clsid2cls_name = {
119
+ v: k for k, v in cls_name2clsid_map.items() if k in self.class_list
120
+ }
121
+ # get trackers to eval
122
+ if self.config["TRACKERS_TO_EVAL"] is None:
123
+ self.tracker_list = os.listdir(self.tracker_fol)
124
+ else:
125
+ self.tracker_list = self.config["TRACKERS_TO_EVAL"]
126
+
127
+ if self.config["TRACKER_DISPLAY_NAMES"] is None:
128
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list))
129
+ elif (self.config["TRACKERS_TO_EVAL"] is not None) and (
130
+ len(self.config["TK_DISPLAY_NAMES"]) == len(self.tracker_list)
131
+ ):
132
+ self.tracker_to_disp = dict(
133
+ zip(self.tracker_list, self.config["TK_DISPLAY_NAMES"])
134
+ )
135
+ else:
136
+ raise TrackEvalException(
137
+ "List of tracker files and tracker display names do not match."
138
+ )
139
+
140
+ self.tracker_data = {tracker: dict() for tracker in self.tracker_list}
141
+
142
+ for tracker in self.tracker_list:
143
+ if self.tracker_sub_fol.endswith(".json"):
144
+ with open(os.path.join(self.tracker_sub_fol)) as f:
145
+ curr_data = json.load(f)
146
+ else:
147
+ tr_dir = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol)
148
+ tr_dir_files = [
149
+ file for file in os.listdir(tr_dir) if file.endswith(".json")
150
+ ]
151
+ if len(tr_dir_files) != 1:
152
+ raise TrackEvalException(
153
+ f"{tr_dir} does not contain exactly one json file."
154
+ )
155
+ with open(os.path.join(tr_dir, tr_dir_files[0])) as f:
156
+ curr_data = json.load(f)
157
+
158
+ # limit detections if MAX_DETECTIONS > 0
159
+ if self.config["MAX_DETECTIONS"]:
160
+ curr_data = self._limit_dets_per_image(curr_data)
161
+
162
+ # fill missing video ids
163
+ self._fill_video_ids_inplace(curr_data)
164
+
165
+ # make track ids unique over whole evaluation set
166
+ self._make_tk_ids_unique(curr_data)
167
+
168
+ # get tracker sequence information
169
+ curr_vids2tracks, curr_vids2images = self._compute_vid_mappings(curr_data)
170
+ self.tracker_data[tracker]["vids_to_tracks"] = curr_vids2tracks
171
+ self.tracker_data[tracker]["vids_to_images"] = curr_vids2images
172
+
173
+ def get_display_name(self, tracker):
174
+ return self.tracker_to_disp[tracker]
175
+
176
+ def _load_raw_file(self, tracker, seq, is_gt):
177
+ """Load a file (gt or tracker) in the TAO format
178
+
179
+ If is_gt, this returns a dict which contains the fields:
180
+ [gt_ids, gt_classes]:
181
+ list (for each timestep) of 1D NDArrays (for each det).
182
+ [gt_dets]: list (for each timestep) of lists of detections.
183
+
184
+ if not is_gt, this returns a dict which contains the fields:
185
+ [tk_ids, tk_classes]:
186
+ list (for each timestep) of 1D NDArrays (for each det).
187
+ [tk_dets]: list (for each timestep) of lists of detections.
188
+ """
189
+ seq_id = self.seq_name2seqid[seq]
190
+ # file location
191
+ if is_gt:
192
+ imgs = self.video2gt_image[seq_id]
193
+ else:
194
+ imgs = self.tracker_data[tracker]["vids_to_images"][seq_id]
195
+
196
+ # convert data to required format
197
+ num_timesteps = self.seq_lengths[seq_id]
198
+ img_to_timestep = self.seq2images2timestep[seq_id]
199
+ data_keys = ["ids", "classes", "dets"]
200
+ # if not is_gt:
201
+ # data_keys += ["tk_confidences"]
202
+ raw_data = {key: [None] * num_timesteps for key in data_keys}
203
+ for img in imgs:
204
+ # some tracker data contains images without any ground truth info,
205
+ # these are ignored
206
+ if img["id"] not in img_to_timestep:
207
+ continue
208
+ t = img_to_timestep[img["id"]]
209
+ anns = img["annotations"]
210
+ tk_str = utils.get_track_id_str(anns[0])
211
+
212
+ if self.use_mask:
213
+ # When using mask, extract segmentation data
214
+ raw_data["dets"][t] = [ann.get("segmentation") for ann in anns]
215
+ else:
216
+ # When using bbox, extract bbox data
217
+ raw_data["dets"][t] = np.atleast_2d([ann["bbox"] for ann in anns]).astype(
218
+ float
219
+ )
220
+ raw_data["ids"][t] = np.atleast_1d([ann[tk_str] for ann in anns]).astype(
221
+ int
222
+ )
223
+ raw_data["classes"][t] = np.atleast_1d(
224
+ [ann["category_id"] for ann in anns]
225
+ ).astype(int)
226
+ # if not is_gt:
227
+ # raw_data["tk_confidences"][t] = np.atleast_1d(
228
+ # [ann["score"] for ann in anns]
229
+ # ).astype(float)
230
+
231
+ for t, d in enumerate(raw_data["dets"]):
232
+ if d is None:
233
+ raw_data["dets"][t] = np.empty((0, 4)).astype(float)
234
+ raw_data["ids"][t] = np.empty(0).astype(int)
235
+ raw_data["classes"][t] = np.empty(0).astype(int)
236
+ # if not is_gt:
237
+ # raw_data["tk_confidences"][t] = np.empty(0)
238
+
239
+ if is_gt:
240
+ key_map = {"ids": "gt_ids", "classes": "gt_classes", "dets": "gt_dets"}
241
+ else:
242
+ key_map = {"ids": "tk_ids", "classes": "tk_classes", "dets": "tk_dets"}
243
+ for k, v in key_map.items():
244
+ raw_data[v] = raw_data.pop(k)
245
+
246
+ raw_data["num_timesteps"] = num_timesteps
247
+ raw_data["seq"] = seq
248
+ return raw_data
249
+
250
+ def get_preprocessed_seq_data_thr(self, raw_data, cls, assignment=None):
251
+ """Preprocess data for a single sequence for a single class.
252
+
253
+ Inputs:
254
+ raw_data: dict containing the data for the sequence already
255
+ read in by get_raw_seq_data().
256
+ cls: class to be evaluated.
257
+ Outputs:
258
+ gt_ids:
259
+ list (for each timestep) of ids of GT tracks
260
+ tk_ids:
261
+ list (for each timestep) of ids of predicted tracks (all for TP
262
+ matching (Det + AssocA))
263
+ tk_overlap_ids:
264
+ list (for each timestep) of ids of predicted tracks that overlap
265
+ with GTs
266
+ tk_dets:
267
+ list (for each timestep) of lists of detections that
268
+ corresponding to the tk_ids
269
+ tk_classes:
270
+ list (for each timestep) of lists of classes that corresponding
271
+ to the tk_ids
272
+ tk_confidences:
273
+ list (for each timestep) of lists of classes that corresponding
274
+ to the tk_ids
275
+ sim_scores:
276
+ similarity score between gt_ids and tk_ids.
277
+ """
278
+ if cls != "all":
279
+ cls_id = self.cls_name2clsid[cls]
280
+
281
+ data_keys = [
282
+ "gt_ids",
283
+ "tk_ids",
284
+ "gt_id_map",
285
+ "tk_id_map",
286
+ "gt_dets",
287
+ "gt_classes",
288
+ "gt_class_name",
289
+ "tk_overlap_classes",
290
+ "tk_overlap_ids",
291
+ "tk_class_eval_tk_ids",
292
+ "tk_dets",
293
+ "tk_classes",
294
+ # "tk_confidences",
295
+ "tk_exh_ids",
296
+ "sim_scores",
297
+ ]
298
+ data = {key: [None] * raw_data["num_timesteps"] for key in data_keys}
299
+ unique_gt_ids = []
300
+ unique_tk_ids = []
301
+ num_gt_dets = 0
302
+ num_tk_cls_dets = 0
303
+ num_tk_overlap_dets = 0
304
+ overlap_ious_thr = 0.5
305
+ loc_and_asso_tk_ids = []
306
+ exh_class_tk_ids = []
307
+
308
+ for t in range(raw_data["num_timesteps"]):
309
+ # only extract relevant dets for this class for preproc and eval
310
+ if cls == "all":
311
+ gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool)
312
+ else:
313
+ gt_class_mask = np.atleast_1d(
314
+ raw_data["gt_classes"][t] == cls_id
315
+ ).astype(bool)
316
+
317
+ # select GT that is not in the evaluating classes
318
+ if assignment is not None and assignment:
319
+ all_gt_ids = list(assignment[t].keys())
320
+ gt_ids_in = raw_data["gt_ids"][t][gt_class_mask]
321
+ gt_ids_out = set(all_gt_ids) - set(gt_ids_in)
322
+ tk_ids_out = set([assignment[t][key] for key in list(gt_ids_out)])
323
+
324
+ # compute overlapped tracks and add their ids to overlap_tk_ids
325
+ sim_scores = raw_data["similarity_scores"]
326
+ overlap_ids_masks = (sim_scores[t][gt_class_mask] >= overlap_ious_thr).any(
327
+ axis=0
328
+ )
329
+ overlap_tk_ids_t = raw_data["tk_ids"][t][overlap_ids_masks]
330
+ if assignment is not None and assignment:
331
+ data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t) - tk_ids_out)
332
+ else:
333
+ data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t))
334
+
335
+ loc_and_asso_tk_ids += data["tk_overlap_ids"][t]
336
+
337
+ data["tk_exh_ids"][t] = []
338
+ if cls == "all":
339
+ continue
340
+
341
+ # add the track ids of exclusive annotated class to exh_class_tk_ids
342
+ tk_exh_mask = np.atleast_1d(raw_data["tk_classes"][t] == cls_id)
343
+ tk_exh_mask = tk_exh_mask.astype(bool)
344
+ exh_class_tk_ids_t = raw_data["tk_ids"][t][tk_exh_mask]
345
+ exh_class_tk_ids.append(exh_class_tk_ids_t)
346
+ data["tk_exh_ids"][t] = exh_class_tk_ids_t
347
+
348
+ # remove tk_ids that has been assigned to GT belongs to other classes.
349
+ loc_and_asso_tk_ids = list(set(loc_and_asso_tk_ids))
350
+
351
+ # remove all unwanted unmatched tracker detections
352
+ for t in range(raw_data["num_timesteps"]):
353
+ # add gt to the data
354
+ if cls == "all":
355
+ gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool)
356
+ else:
357
+ gt_class_mask = np.atleast_1d(
358
+ raw_data["gt_classes"][t] == cls_id
359
+ ).astype(bool)
360
+ data["gt_classes"][t] = cls_id
361
+ data["gt_class_name"][t] = cls
362
+
363
+ gt_ids = raw_data["gt_ids"][t][gt_class_mask]
364
+ if self.use_mask:
365
+ gt_dets = [raw_data['gt_dets'][t][ind] for ind in range(len(gt_class_mask)) if gt_class_mask[ind]]
366
+ else:
367
+ gt_dets = raw_data["gt_dets"][t][gt_class_mask]
368
+ data["gt_ids"][t] = gt_ids
369
+ data["gt_dets"][t] = gt_dets
370
+
371
+ # filter pred and only keep those that highly overlap with GTs
372
+ tk_mask = np.isin(
373
+ raw_data["tk_ids"][t], np.array(loc_and_asso_tk_ids), assume_unique=True
374
+ )
375
+ tk_overlap_mask = np.isin(
376
+ raw_data["tk_ids"][t],
377
+ np.array(data["tk_overlap_ids"][t]),
378
+ assume_unique=True,
379
+ )
380
+
381
+ tk_ids = raw_data["tk_ids"][t][tk_mask]
382
+ if self.use_mask:
383
+ tk_dets = [raw_data['tk_dets'][t][ind] for ind in range(len(tk_mask)) if
384
+ tk_mask[ind]]
385
+ else:
386
+ tk_dets = raw_data["tk_dets"][t][tk_mask]
387
+
388
+ tracker_classes = raw_data["tk_classes"][t][tk_mask]
389
+
390
+ # add overlap classes for computing the FP for Cls term
391
+ tracker_overlap_classes = raw_data["tk_classes"][t][tk_overlap_mask]
392
+ # tracker_confidences = raw_data["tk_confidences"][t][tk_mask]
393
+ sim_scores_masked = sim_scores[t][gt_class_mask, :][:, tk_mask]
394
+
395
+ # add filtered prediction to the data
396
+ data["tk_classes"][t] = tracker_classes
397
+ data["tk_overlap_classes"][t] = tracker_overlap_classes
398
+ data["tk_ids"][t] = tk_ids
399
+ data["tk_dets"][t] = tk_dets
400
+ # data["tk_confidences"][t] = tracker_confidences
401
+ data["sim_scores"][t] = sim_scores_masked
402
+ data["tk_class_eval_tk_ids"][t] = set(
403
+ list(data["tk_overlap_ids"][t]) + list(data["tk_exh_ids"][t])
404
+ )
405
+
406
+ # count total number of detections
407
+ unique_gt_ids += list(np.unique(data["gt_ids"][t]))
408
+ # the unique track ids are for association.
409
+ unique_tk_ids += list(np.unique(data["tk_ids"][t]))
410
+
411
+ num_tk_overlap_dets += len(data["tk_overlap_ids"][t])
412
+ num_tk_cls_dets += len(data["tk_class_eval_tk_ids"][t])
413
+ num_gt_dets += len(data["gt_ids"][t])
414
+
415
+ # re-label IDs such that there are no empty IDs
416
+ if len(unique_gt_ids) > 0:
417
+ unique_gt_ids = np.unique(unique_gt_ids)
418
+ gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1))
419
+ gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids))
420
+ data["gt_id_map"] = {}
421
+ for gt_id in unique_gt_ids:
422
+ new_gt_id = gt_id_map[gt_id].astype(int)
423
+ data["gt_id_map"][new_gt_id] = gt_id
424
+
425
+ for t in range(raw_data["num_timesteps"]):
426
+ if len(data["gt_ids"][t]) > 0:
427
+ data["gt_ids"][t] = gt_id_map[data["gt_ids"][t]].astype(int)
428
+
429
+ if len(unique_tk_ids) > 0:
430
+ unique_tk_ids = np.unique(unique_tk_ids)
431
+ tk_id_map = np.nan * np.ones((np.max(unique_tk_ids) + 1))
432
+ tk_id_map[unique_tk_ids] = np.arange(len(unique_tk_ids))
433
+
434
+ data["tk_id_map"] = {}
435
+ for track_id in unique_tk_ids:
436
+ new_track_id = tk_id_map[track_id].astype(int)
437
+ data["tk_id_map"][new_track_id] = track_id
438
+
439
+ for t in range(raw_data["num_timesteps"]):
440
+ if len(data["tk_ids"][t]) > 0:
441
+ data["tk_ids"][t] = tk_id_map[data["tk_ids"][t]].astype(int)
442
+ if len(data["tk_overlap_ids"][t]) > 0:
443
+ data["tk_overlap_ids"][t] = tk_id_map[
444
+ data["tk_overlap_ids"][t]
445
+ ].astype(int)
446
+
447
+ # record overview statistics.
448
+ data["num_tk_cls_dets"] = num_tk_cls_dets
449
+ data["num_tk_overlap_dets"] = num_tk_overlap_dets
450
+ data["num_gt_dets"] = num_gt_dets
451
+ data["num_tk_ids"] = len(unique_tk_ids)
452
+ data["num_gt_ids"] = len(unique_gt_ids)
453
+ data["num_timesteps"] = raw_data["num_timesteps"]
454
+ data["seq"] = raw_data["seq"]
455
+
456
+ self._check_unique_ids(data)
457
+
458
+ return data
459
+
460
+ @_timing.time
461
+ def get_preprocessed_seq_data(
462
+ self, raw_data, cls, assignment=None, thresholds=[50, 75]
463
+ ):
464
+ """Preprocess data for a single sequence for a single class."""
465
+ data = {}
466
+ if thresholds is None:
467
+ thresholds = [50, 75]
468
+ elif isinstance(thresholds, int):
469
+ thresholds = [thresholds]
470
+
471
+ for thr in thresholds:
472
+ assignment_thr = None
473
+ if assignment is not None:
474
+ assignment_thr = assignment[thr]
475
+ data[thr] = self.get_preprocessed_seq_data_thr(
476
+ raw_data, cls, assignment_thr
477
+ )
478
+
479
+ return data
480
+
481
+ def _calculate_similarities(self, gt_dets_t, tk_dets_t):
482
+ """Compute similarity scores."""
483
+ if self.use_mask:
484
+ similarity_scores = self._calculate_mask_ious(gt_dets_t, tk_dets_t, is_encoded=True, do_ioa=False)
485
+ else:
486
+ similarity_scores = self._calculate_box_ious(gt_dets_t, tk_dets_t)
487
+ return similarity_scores
488
+
489
+ def _compute_vid_mappings(self, annotations):
490
+ """Computes mappings from videos to corresponding tracks and images."""
491
+ vids_to_tracks = {}
492
+ vids_to_imgs = {}
493
+ vid_ids = [vid["id"] for vid in self.gt_data["videos"]]
494
+
495
+ # compute an mapping from image IDs to images
496
+ images = {}
497
+ for image in self.gt_data["images"]:
498
+ images[image["id"]] = image
499
+
500
+ tk_str = utils.get_track_id_str(annotations[0])
501
+ for ann in annotations:
502
+ ann["area"] = ann["bbox"][2] * ann["bbox"][3]
503
+
504
+ vid = ann["video_id"]
505
+ if ann["video_id"] not in vids_to_tracks.keys():
506
+ vids_to_tracks[ann["video_id"]] = list()
507
+ if ann["video_id"] not in vids_to_imgs.keys():
508
+ vids_to_imgs[ann["video_id"]] = list()
509
+
510
+ # fill in vids_to_tracks
511
+ tid = ann[tk_str]
512
+ exist_tids = [track["id"] for track in vids_to_tracks[vid]]
513
+ try:
514
+ index1 = exist_tids.index(tid)
515
+ except ValueError:
516
+ index1 = -1
517
+ if tid not in exist_tids:
518
+ curr_track = {
519
+ "id": tid,
520
+ "category_id": ann["category_id"],
521
+ "video_id": vid,
522
+ "annotations": [ann],
523
+ }
524
+ vids_to_tracks[vid].append(curr_track)
525
+ else:
526
+ vids_to_tracks[vid][index1]["annotations"].append(ann)
527
+
528
+ # fill in vids_to_imgs
529
+ img_id = ann["image_id"]
530
+ exist_img_ids = [img["id"] for img in vids_to_imgs[vid]]
531
+ try:
532
+ index2 = exist_img_ids.index(img_id)
533
+ except ValueError:
534
+ index2 = -1
535
+ if index2 == -1:
536
+ curr_img = {"id": img_id, "annotations": [ann]}
537
+ vids_to_imgs[vid].append(curr_img)
538
+ else:
539
+ vids_to_imgs[vid][index2]["annotations"].append(ann)
540
+
541
+ # sort annotations by frame index and compute track area
542
+ for vid, tracks in vids_to_tracks.items():
543
+ for track in tracks:
544
+ track["annotations"] = sorted(
545
+ track["annotations"],
546
+ key=lambda x: images[x["image_id"]]["frame_id"],
547
+ )
548
+ # compute average area
549
+ track["area"] = sum(x["area"] for x in track["annotations"]) / len(
550
+ track["annotations"]
551
+ )
552
+
553
+ # ensure all videos are present
554
+ for vid_id in vid_ids:
555
+ if vid_id not in vids_to_tracks.keys():
556
+ vids_to_tracks[vid_id] = []
557
+ if vid_id not in vids_to_imgs.keys():
558
+ vids_to_imgs[vid_id] = []
559
+
560
+ return vids_to_tracks, vids_to_imgs
561
+
562
+ def _compute_image_to_timestep_mappings(self):
563
+ """Computes a mapping from images to timestep in sequence."""
564
+ images = {}
565
+ for image in self.gt_data["images"]:
566
+ images[image["id"]] = image
567
+
568
+ seq_to_imgs_to_timestep = {vid["id"]: dict() for vid in self.gt_data["videos"]}
569
+ for vid in seq_to_imgs_to_timestep:
570
+ curr_imgs = [img["id"] for img in self.video2gt_image[vid]]
571
+ curr_imgs = sorted(curr_imgs, key=lambda x: images[x]["frame_id"])
572
+ seq_to_imgs_to_timestep[vid] = {
573
+ curr_imgs[i]: i for i in range(len(curr_imgs))
574
+ }
575
+
576
+ return seq_to_imgs_to_timestep
577
+
578
+ def _limit_dets_per_image(self, annotations):
579
+ """Limits the number of detections for each image.
580
+
581
+ Adapted from https://github.com/TAO-Dataset/.
582
+ """
583
+ max_dets = self.config["MAX_DETECTIONS"]
584
+ img_ann = defaultdict(list)
585
+ for ann in annotations:
586
+ img_ann[ann["image_id"]].append(ann)
587
+
588
+ for img_id, _anns in img_ann.items():
589
+ if len(_anns) <= max_dets:
590
+ continue
591
+ _anns = sorted(_anns, key=lambda x: x["score"], reverse=True)
592
+ img_ann[img_id] = _anns[:max_dets]
593
+
594
+ return [ann for anns in img_ann.values() for ann in anns]
595
+
596
+ def _fill_video_ids_inplace(self, annotations):
597
+ """Fills in missing video IDs inplace.
598
+
599
+ Adapted from https://github.com/TAO-Dataset/.
600
+ """
601
+ missing_video_id = [x for x in annotations if "video_id" not in x]
602
+ if missing_video_id:
603
+ image_id_to_video_id = {
604
+ x["id"]: x["video_id"] for x in self.gt_data["images"]
605
+ }
606
+ for x in missing_video_id:
607
+ x["video_id"] = image_id_to_video_id[x["image_id"]]
608
+
609
+ @staticmethod
610
+ def _make_tk_ids_unique(annotations):
611
+ """Makes track IDs unqiue over the whole annotation set.
612
+
613
+ Adapted from https://github.com/TAO-Dataset/.
614
+ """
615
+ track_id_videos = {}
616
+ track_ids_to_update = set()
617
+ max_track_id = 0
618
+
619
+ tk_str = utils.get_track_id_str(annotations[0])
620
+ for ann in annotations:
621
+ t = int(ann[tk_str])
622
+ if t not in track_id_videos:
623
+ track_id_videos[t] = ann["video_id"]
624
+
625
+ if ann["video_id"] != track_id_videos[t]:
626
+ # track id is assigned to multiple videos
627
+ track_ids_to_update.add(t)
628
+ max_track_id = max(max_track_id, t)
629
+
630
+ if track_ids_to_update:
631
+ print("true")
632
+ next_id = itertools.count(max_track_id + 1)
633
+ new_tk_ids = defaultdict(lambda: next(next_id))
634
+ for ann in annotations:
635
+ t = ann[tk_str]
636
+ v = ann["video_id"]
637
+ if t in track_ids_to_update:
638
+ ann[tk_str] = new_tk_ids[t, v]
639
+ return len(track_ids_to_update)
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/datasets/tao.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ """TAO Dataset."""
7
+ import copy
8
+ import itertools
9
+ import json
10
+ import os
11
+ from collections import defaultdict
12
+
13
+ import numpy as np
14
+
15
+ from .. import _timing
16
+ from ..config import get_default_dataset_config, init_config
17
+ from ..utils import TrackEvalException
18
+ from ._base_dataset import _BaseDataset
19
+
20
+
21
+ class TAO(_BaseDataset):
22
+ """Dataset class for TAO tracking"""
23
+
24
+ def __init__(self, config=None):
25
+ """Initialize dataset, checking that all required files are present."""
26
+ super().__init__()
27
+ # Fill non-given config values with defaults
28
+ self.config = init_config(config, get_default_dataset_config(), self.get_name())
29
+ self.gt_fol = self.config["GT_FOLDER"]
30
+ self.tracker_fol = self.config["TRACKERS_FOLDER"]
31
+ self.should_classes_combine = True
32
+ self.use_super_categories = False
33
+ self.use_mask = self.config["USE_MASK"]
34
+
35
+
36
+ self.tracker_sub_fol = self.config["TRACKER_SUB_FOLDER"]
37
+ self.output_fol = self.config["OUTPUT_FOLDER"]
38
+ if self.output_fol is None:
39
+ self.output_fol = self.tracker_fol
40
+ self.output_sub_fol = self.config["OUTPUT_SUB_FOLDER"]
41
+
42
+ if self.gt_fol.endswith(".json"):
43
+ self.gt_data = json.load(open(self.gt_fol, "r"))
44
+ else:
45
+ gt_dir_files = [
46
+ file for file in os.listdir(self.gt_fol) if file.endswith(".json")
47
+ ]
48
+ if len(gt_dir_files) != 1:
49
+ raise TrackEvalException(
50
+ f"{self.gt_fol} does not contain exactly one json file."
51
+ )
52
+
53
+ with open(os.path.join(self.gt_fol, gt_dir_files[0])) as f:
54
+ self.gt_data = json.load(f)
55
+
56
+ # merge categories marked with a merged tag in TAO dataset
57
+ self._merge_categories(self.gt_data["annotations"] + self.gt_data["tracks"])
58
+
59
+ # get sequences to eval and sequence information
60
+ self.seq_list = [
61
+ vid["name"].replace("/", "-") for vid in self.gt_data["videos"]
62
+ ]
63
+ self.seq_name2seqid = {
64
+ vid["name"].replace("/", "-"): vid["id"] for vid in self.gt_data["videos"]
65
+ }
66
+ # compute mappings from videos to annotation data
67
+ self.video2gt_track, self.video2gt_image = self._compute_vid_mappings(
68
+ self.gt_data["annotations"]
69
+ )
70
+ # compute sequence lengths
71
+ self.seq_lengths = {vid["id"]: 0 for vid in self.gt_data["videos"]}
72
+ for img in self.gt_data["images"]:
73
+ self.seq_lengths[img["video_id"]] += 1
74
+ self.seq2images2timestep = self._compute_image_to_timestep_mappings()
75
+ self.seq2cls = {
76
+ vid["id"]: {
77
+ "pos_cat_ids": list(
78
+ {track["category_id"] for track in self.video2gt_track[vid["id"]]}
79
+ ),
80
+ "neg_cat_ids": vid["neg_category_ids"],
81
+ "not_exh_labeled_cat_ids": vid["not_exhaustive_category_ids"],
82
+ }
83
+ for vid in self.gt_data["videos"]
84
+ }
85
+
86
+ # Get classes to eval
87
+ considered_vid_ids = [self.seq_name2seqid[vid] for vid in self.seq_list]
88
+ seen_cats = set(
89
+ [
90
+ cat_id
91
+ for vid_id in considered_vid_ids
92
+ for cat_id in self.seq2cls[vid_id]["pos_cat_ids"]
93
+ ]
94
+ )
95
+ # only classes with ground truth are evaluated in TAO
96
+ self.valid_classes = [
97
+ cls["name"] for cls in self.gt_data["categories"] if cls["id"] in seen_cats
98
+ ]
99
+ cls_name2clsid_map = {
100
+ cls["name"]: cls["id"] for cls in self.gt_data["categories"]
101
+ }
102
+
103
+ if self.config["CLASSES_TO_EVAL"]:
104
+ self.class_list = [
105
+ cls.lower() if cls.lower() in self.valid_classes else None
106
+ for cls in self.config["CLASSES_TO_EVAL"]
107
+ ]
108
+ if not all(self.class_list):
109
+ valid_cls = ", ".join(self.valid_classes)
110
+ raise TrackEvalException(
111
+ "Attempted to evaluate an invalid class. Only classes "
112
+ f"{valid_cls} are valid (classes present in ground truth"
113
+ " data)."
114
+ )
115
+ else:
116
+ self.class_list = [cls for cls in self.valid_classes]
117
+ self.cls_name2clsid = {
118
+ k: v for k, v in cls_name2clsid_map.items() if k in self.class_list
119
+ }
120
+ self.clsid2cls_name = {
121
+ v: k for k, v in cls_name2clsid_map.items() if k in self.class_list
122
+ }
123
+ # get trackers to eval
124
+ print(self.config["TRACKERS_TO_EVAL"] )
125
+ if self.config["TRACKERS_TO_EVAL"] is None:
126
+ self.tracker_list = os.listdir(self.tracker_fol)
127
+ else:
128
+ self.tracker_list = self.config["TRACKERS_TO_EVAL"]
129
+
130
+ if self.config["TRACKER_DISPLAY_NAMES"] is None:
131
+ self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list))
132
+ elif (self.config["TRACKERS_TO_EVAL"] is not None) and (
133
+ len(self.config["TK_DISPLAY_NAMES"]) == len(self.tracker_list)
134
+ ):
135
+ self.tracker_to_disp = dict(
136
+ zip(self.tracker_list, self.config["TK_DISPLAY_NAMES"])
137
+ )
138
+ else:
139
+ raise TrackEvalException(
140
+ "List of tracker files and tracker display names do not match."
141
+ )
142
+
143
+ self.tracker_data = {tracker: dict() for tracker in self.tracker_list}
144
+
145
+ for tracker in self.tracker_list:
146
+ if self.tracker_sub_fol.endswith(".json"):
147
+ with open(os.path.join(self.tracker_sub_fol)) as f:
148
+ curr_data = json.load(f)
149
+ else:
150
+ tr_dir = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol)
151
+ tr_dir_files = [
152
+ file for file in os.listdir(tr_dir) if file.endswith(".json")
153
+ ]
154
+ if len(tr_dir_files) != 1:
155
+ raise TrackEvalException(
156
+ f"{tr_dir} does not contain exactly one json file."
157
+ )
158
+ with open(os.path.join(tr_dir, tr_dir_files[0])) as f:
159
+ curr_data = json.load(f)
160
+
161
+ # limit detections if MAX_DETECTIONS > 0
162
+ if self.config["MAX_DETECTIONS"]:
163
+ curr_data = self._limit_dets_per_image(curr_data)
164
+
165
+ # fill missing video ids
166
+ self._fill_video_ids_inplace(curr_data)
167
+
168
+ # make track ids unique over whole evaluation set
169
+ self._make_tk_ids_unique(curr_data)
170
+
171
+ # merge categories marked with a merged tag in TAO dataset
172
+ self._merge_categories(curr_data)
173
+
174
+ # get tracker sequence information
175
+ curr_vids2tracks, curr_vids2images = self._compute_vid_mappings(curr_data)
176
+ self.tracker_data[tracker]["vids_to_tracks"] = curr_vids2tracks
177
+ self.tracker_data[tracker]["vids_to_images"] = curr_vids2images
178
+
179
+ def get_display_name(self, tracker):
180
+ return self.tracker_to_disp[tracker]
181
+
182
+ def _load_raw_file(self, tracker, seq, is_gt):
183
+ """Load a file (gt or tracker) in the TAO format
184
+
185
+ If is_gt, this returns a dict which contains the fields:
186
+ [gt_ids, gt_classes]:
187
+ list (for each timestep) of 1D NDArrays (for each det).
188
+ [gt_dets]: list (for each timestep) of lists of detections.
189
+
190
+ if not is_gt, this returns a dict which contains the fields:
191
+ [tk_ids, tk_classes, tk_confidences]:
192
+ list (for each timestep) of 1D NDArrays (for each det).
193
+ [tk_dets]: list (for each timestep) of lists of detections.
194
+ """
195
+ seq_id = self.seq_name2seqid[seq]
196
+ # file location
197
+ if is_gt:
198
+ imgs = self.video2gt_image[seq_id]
199
+ else:
200
+ imgs = self.tracker_data[tracker]["vids_to_images"][seq_id]
201
+
202
+ # convert data to required format
203
+ num_timesteps = self.seq_lengths[seq_id]
204
+ img_to_timestep = self.seq2images2timestep[seq_id]
205
+ data_keys = ["ids", "classes", "dets"]
206
+ if not is_gt:
207
+ data_keys += ["tk_confidences"]
208
+ raw_data = {key: [None] * num_timesteps for key in data_keys}
209
+ for img in imgs:
210
+ # some tracker data contains images without any ground truth info,
211
+ # these are ignored
212
+ if img["id"] not in img_to_timestep:
213
+ continue
214
+ t = img_to_timestep[img["id"]]
215
+ anns = img["annotations"]
216
+ if self.use_mask:
217
+ # When using mask, extract segmentation data
218
+ raw_data["dets"][t] = [ann.get("segmentation") for ann in anns]
219
+ else:
220
+ # When using bbox, extract bbox data
221
+ raw_data["dets"][t] = np.atleast_2d([ann["bbox"] for ann in anns]).astype(
222
+ float
223
+ )
224
+ raw_data["ids"][t] = np.atleast_1d(
225
+ [ann["track_id"] for ann in anns]
226
+ ).astype(int)
227
+ raw_data["classes"][t] = np.atleast_1d(
228
+ [ann["category_id"] for ann in anns]
229
+ ).astype(int)
230
+ if not is_gt:
231
+ raw_data["tk_confidences"][t] = np.atleast_1d(
232
+ [ann["score"] for ann in anns]
233
+ ).astype(float)
234
+
235
+ for t, d in enumerate(raw_data["dets"]):
236
+ if d is None:
237
+ raw_data["dets"][t] = np.empty((0, 4)).astype(float)
238
+ raw_data["ids"][t] = np.empty(0).astype(int)
239
+ raw_data["classes"][t] = np.empty(0).astype(int)
240
+ if not is_gt:
241
+ raw_data["tk_confidences"][t] = np.empty(0)
242
+
243
+ if is_gt:
244
+ key_map = {"ids": "gt_ids", "classes": "gt_classes", "dets": "gt_dets"}
245
+ else:
246
+ key_map = {"ids": "tk_ids", "classes": "tk_classes", "dets": "tk_dets"}
247
+ for k, v in key_map.items():
248
+ raw_data[v] = raw_data.pop(k)
249
+
250
+ raw_data["num_timesteps"] = num_timesteps
251
+ raw_data["neg_cat_ids"] = self.seq2cls[seq_id]["neg_cat_ids"]
252
+ raw_data["not_exh_labeled_cls"] = self.seq2cls[seq_id][
253
+ "not_exh_labeled_cat_ids"
254
+ ]
255
+ raw_data["seq"] = seq
256
+ return raw_data
257
+
258
+ def get_preprocessed_seq_data_thr(self, raw_data, cls, assignment=None):
259
+ """Preprocess data for a single sequence for a single class.
260
+
261
+ Inputs:
262
+ raw_data: dict containing the data for the sequence already
263
+ read in by get_raw_seq_data().
264
+ cls: class to be evaluated.
265
+ Outputs:
266
+ gt_ids:
267
+ list (for each timestep) of ids of GT tracks
268
+ tk_ids:
269
+ list (for each timestep) of ids of predicted tracks (all for TP
270
+ matching (Det + AssocA))
271
+ tk_overlap_ids:
272
+ list (for each timestep) of ids of predicted tracks that overlap
273
+ with GTs
274
+ tk_neg_ids:
275
+ list (for each timestep) of ids of predicted tracks that with
276
+ the class id on the negative list for the current sequence.
277
+ tk_exh_ids:
278
+ list (for each timestep) of ids of predicted tracks that do not
279
+ overlap with existing GTs but have the class id on the
280
+ exhaustive annotated class list for the current sequence.
281
+ tk_dets:
282
+ list (for each timestep) of lists of detections that
283
+ corresponding to the tk_ids
284
+ tk_classes:
285
+ list (for each timestep) of lists of classes that corresponding
286
+ to the tk_ids
287
+ tk_confidences:
288
+ list (for each timestep) of lists of classes that corresponding
289
+ to the tk_ids
290
+ sim_scores:
291
+ similarity score between gt_ids and tk_ids.
292
+ """
293
+ if cls != "all":
294
+ cls_id = self.cls_name2clsid[cls]
295
+
296
+ data_keys = [
297
+ "gt_ids",
298
+ "tk_ids",
299
+ "gt_id_map",
300
+ "tk_id_map",
301
+ "gt_dets",
302
+ "gt_classes",
303
+ "gt_class_name",
304
+ "tk_overlap_classes",
305
+ "tk_overlap_ids",
306
+ "tk_neg_ids",
307
+ "tk_exh_ids",
308
+ "tk_class_eval_tk_ids",
309
+ "tk_dets",
310
+ "tk_classes",
311
+ "tk_confidences",
312
+ "sim_scores",
313
+ ]
314
+ data = {key: [None] * raw_data["num_timesteps"] for key in data_keys}
315
+ unique_gt_ids = []
316
+ unique_tk_ids = []
317
+ num_gt_dets = 0
318
+ num_tk_cls_dets = 0
319
+ num_tk_overlap_dets = 0
320
+ overlap_ious_thr = 0.5
321
+ loc_and_asso_tk_ids = []
322
+
323
+ for t in range(raw_data["num_timesteps"]):
324
+ # only extract relevant dets for this class for preproc and eval
325
+ if cls == "all":
326
+ gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool)
327
+ else:
328
+ gt_class_mask = np.atleast_1d(
329
+ raw_data["gt_classes"][t] == cls_id
330
+ ).astype(bool)
331
+
332
+ # select GT that is not in the evaluating classes
333
+ if assignment is not None and assignment:
334
+ all_gt_ids = list(assignment[t].keys())
335
+ gt_ids_in = raw_data["gt_ids"][t][gt_class_mask]
336
+ gt_ids_out = set(all_gt_ids) - set(gt_ids_in)
337
+ tk_ids_out = set([assignment[t][key] for key in list(gt_ids_out)])
338
+
339
+ # compute overlapped tracks and add their ids to overlap_tk_ids
340
+ sim_scores = raw_data["similarity_scores"]
341
+ overlap_ids_masks = (sim_scores[t][gt_class_mask] >= overlap_ious_thr).any(
342
+ axis=0
343
+ )
344
+ overlap_tk_ids_t = raw_data["tk_ids"][t][overlap_ids_masks]
345
+ if assignment is not None and assignment:
346
+ data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t) - tk_ids_out)
347
+ else:
348
+ data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t))
349
+
350
+ loc_and_asso_tk_ids += data["tk_overlap_ids"][t]
351
+
352
+ data["tk_exh_ids"][t] = []
353
+ data["tk_neg_ids"][t] = []
354
+
355
+ if cls == "all":
356
+ continue
357
+
358
+ # remove tk_ids that has been assigned to GT belongs to other classes.
359
+ loc_and_asso_tk_ids = list(set(loc_and_asso_tk_ids))
360
+
361
+ # remove all unwanted unmatched tracker detections
362
+ for t in range(raw_data["num_timesteps"]):
363
+ # add gt to the data
364
+ if cls == "all":
365
+ gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool)
366
+ else:
367
+ gt_class_mask = np.atleast_1d(
368
+ raw_data["gt_classes"][t] == cls_id
369
+ ).astype(bool)
370
+ data["gt_classes"][t] = cls_id
371
+ data["gt_class_name"][t] = cls
372
+
373
+ gt_ids = raw_data["gt_ids"][t][gt_class_mask]
374
+ if self.use_mask:
375
+ gt_dets = [raw_data['gt_dets'][t][ind] for ind in range(len(gt_class_mask)) if gt_class_mask[ind]]
376
+ else:
377
+ gt_dets = raw_data["gt_dets"][t][gt_class_mask]
378
+ data["gt_ids"][t] = gt_ids
379
+ data["gt_dets"][t] = gt_dets
380
+
381
+ # filter pred and only keep those that highly overlap with GTs
382
+ tk_mask = np.isin(
383
+ raw_data["tk_ids"][t], np.array(loc_and_asso_tk_ids), assume_unique=True
384
+ )
385
+ tk_overlap_mask = np.isin(
386
+ raw_data["tk_ids"][t],
387
+ np.array(data["tk_overlap_ids"][t]),
388
+ assume_unique=True,
389
+ )
390
+
391
+ tk_ids = raw_data["tk_ids"][t][tk_mask]
392
+ if self.use_mask:
393
+ tk_dets = [raw_data['tk_dets'][t][ind] for ind in range(len(tk_mask)) if
394
+ tk_mask[ind]]
395
+ else:
396
+ tk_dets = raw_data["tk_dets"][t][tk_mask]
397
+ tracker_classes = raw_data["tk_classes"][t][tk_mask]
398
+
399
+ # add overlap classes for computing the FP for Cls term
400
+ tracker_overlap_classes = raw_data["tk_classes"][t][tk_overlap_mask]
401
+ tracker_confidences = raw_data["tk_confidences"][t][tk_mask]
402
+ sim_scores_masked = sim_scores[t][gt_class_mask, :][:, tk_mask]
403
+
404
+ # add filtered prediction to the data
405
+ data["tk_classes"][t] = tracker_classes
406
+ data["tk_overlap_classes"][t] = tracker_overlap_classes
407
+ data["tk_ids"][t] = tk_ids
408
+ data["tk_dets"][t] = tk_dets
409
+ data["tk_confidences"][t] = tracker_confidences
410
+ data["sim_scores"][t] = sim_scores_masked
411
+ data["tk_class_eval_tk_ids"][t] = set(
412
+ list(data["tk_overlap_ids"][t])
413
+ + list(data["tk_neg_ids"][t])
414
+ + list(data["tk_exh_ids"][t])
415
+ )
416
+
417
+ # count total number of detections
418
+ unique_gt_ids += list(np.unique(data["gt_ids"][t]))
419
+ # the unique track ids are for association.
420
+ unique_tk_ids += list(np.unique(data["tk_ids"][t]))
421
+
422
+ num_tk_overlap_dets += len(data["tk_overlap_ids"][t])
423
+ num_tk_cls_dets += len(data["tk_class_eval_tk_ids"][t])
424
+ num_gt_dets += len(data["gt_ids"][t])
425
+
426
+ # re-label IDs such that there are no empty IDs
427
+ if len(unique_gt_ids) > 0:
428
+ unique_gt_ids = np.unique(unique_gt_ids)
429
+ gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1))
430
+ gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids))
431
+ data["gt_id_map"] = {}
432
+ for gt_id in unique_gt_ids:
433
+ new_gt_id = gt_id_map[gt_id].astype(int)
434
+ data["gt_id_map"][new_gt_id] = gt_id
435
+
436
+ for t in range(raw_data["num_timesteps"]):
437
+ if len(data["gt_ids"][t]) > 0:
438
+ data["gt_ids"][t] = gt_id_map[data["gt_ids"][t]].astype(int)
439
+
440
+ if len(unique_tk_ids) > 0:
441
+ unique_tk_ids = np.unique(unique_tk_ids)
442
+ tk_id_map = np.nan * np.ones((np.max(unique_tk_ids) + 1))
443
+ tk_id_map[unique_tk_ids] = np.arange(len(unique_tk_ids))
444
+
445
+ data["tk_id_map"] = {}
446
+ for track_id in unique_tk_ids:
447
+ new_track_id = tk_id_map[track_id].astype(int)
448
+ data["tk_id_map"][new_track_id] = track_id
449
+
450
+ for t in range(raw_data["num_timesteps"]):
451
+ if len(data["tk_ids"][t]) > 0:
452
+ data["tk_ids"][t] = tk_id_map[data["tk_ids"][t]].astype(int)
453
+ if len(data["tk_overlap_ids"][t]) > 0:
454
+ data["tk_overlap_ids"][t] = tk_id_map[
455
+ data["tk_overlap_ids"][t]
456
+ ].astype(int)
457
+
458
+ # record overview statistics.
459
+ data["num_tk_cls_dets"] = num_tk_cls_dets
460
+ data["num_tk_overlap_dets"] = num_tk_overlap_dets
461
+ data["num_gt_dets"] = num_gt_dets
462
+ data["num_tk_ids"] = len(unique_tk_ids)
463
+ data["num_gt_ids"] = len(unique_gt_ids)
464
+ data["num_timesteps"] = raw_data["num_timesteps"]
465
+ data["seq"] = raw_data["seq"]
466
+
467
+ self._check_unique_ids(data)
468
+
469
+ return data
470
+
471
+ @_timing.time
472
+ def get_preprocessed_seq_data(
473
+ self, raw_data, cls, assignment=None, thresholds=[50, 75]
474
+ ):
475
+ """Preprocess data for a single sequence for a single class."""
476
+ data = {}
477
+ if thresholds is None:
478
+ thresholds = [50]
479
+ elif isinstance(thresholds, int):
480
+ thresholds = [thresholds]
481
+
482
+ for thr in thresholds:
483
+ assignment_thr = None
484
+ if assignment is not None:
485
+ assignment_thr = assignment[thr]
486
+ data[thr] = self.get_preprocessed_seq_data_thr(
487
+ raw_data, cls, assignment_thr
488
+ )
489
+
490
+ return data
491
+
492
+ def _calculate_similarities(self, gt_dets_t, tk_dets_t):
493
+ """Compute similarity scores."""
494
+ if self.use_mask:
495
+ similarity_scores = self._calculate_mask_ious(gt_dets_t, tk_dets_t, is_encoded=True, do_ioa=False)
496
+ else:
497
+ similarity_scores = self._calculate_box_ious(gt_dets_t, tk_dets_t)
498
+ return similarity_scores
499
+
500
+ def _merge_categories(self, annotations):
501
+ """Merges categories with a merged tag.
502
+
503
+ Adapted from https://github.com/TAO-Dataset.
504
+ """
505
+ merge_map = {}
506
+ for category in self.gt_data["categories"]:
507
+ if "merged" in category:
508
+ for to_merge in category["merged"]:
509
+ merge_map[to_merge["id"]] = category["id"]
510
+
511
+ for ann in annotations:
512
+ ann["category_id"] = merge_map.get(ann["category_id"], ann["category_id"])
513
+
514
+ def _compute_vid_mappings(self, annotations):
515
+ """Computes mappings from videos to corresponding tracks and images."""
516
+ vids_to_tracks = {}
517
+ vids_to_imgs = {}
518
+ vid_ids = [vid["id"] for vid in self.gt_data["videos"]]
519
+
520
+ # compute an mapping from image IDs to images
521
+ images = {}
522
+ for image in self.gt_data["images"]:
523
+ images[image["id"]] = image
524
+
525
+ for ann in annotations:
526
+ ann["area"] = ann["bbox"][2] * ann["bbox"][3]
527
+
528
+ vid = ann["video_id"]
529
+ if ann["video_id"] not in vids_to_tracks.keys():
530
+ vids_to_tracks[ann["video_id"]] = list()
531
+ if ann["video_id"] not in vids_to_imgs.keys():
532
+ vids_to_imgs[ann["video_id"]] = list()
533
+
534
+ # fill in vids_to_tracks
535
+ tid = ann["track_id"]
536
+ exist_tids = [track["id"] for track in vids_to_tracks[vid]]
537
+ try:
538
+ index1 = exist_tids.index(tid)
539
+ except ValueError:
540
+ index1 = -1
541
+ if tid not in exist_tids:
542
+ curr_track = {
543
+ "id": tid,
544
+ "category_id": ann["category_id"],
545
+ "video_id": vid,
546
+ "annotations": [ann],
547
+ }
548
+ vids_to_tracks[vid].append(curr_track)
549
+ else:
550
+ vids_to_tracks[vid][index1]["annotations"].append(ann)
551
+
552
+ # fill in vids_to_imgs
553
+ img_id = ann["image_id"]
554
+ exist_img_ids = [img["id"] for img in vids_to_imgs[vid]]
555
+ try:
556
+ index2 = exist_img_ids.index(img_id)
557
+ except ValueError:
558
+ index2 = -1
559
+ if index2 == -1:
560
+ curr_img = {"id": img_id, "annotations": [ann]}
561
+ vids_to_imgs[vid].append(curr_img)
562
+ else:
563
+ vids_to_imgs[vid][index2]["annotations"].append(ann)
564
+
565
+ # sort annotations by frame index and compute track area
566
+ for vid, tracks in vids_to_tracks.items():
567
+ for track in tracks:
568
+ track["annotations"] = sorted(
569
+ track["annotations"],
570
+ key=lambda x: images[x["image_id"]]["frame_index"],
571
+ )
572
+ # compute average area
573
+ track["area"] = sum(x["area"] for x in track["annotations"]) / len(
574
+ track["annotations"]
575
+ )
576
+
577
+ # ensure all videos are present
578
+ for vid_id in vid_ids:
579
+ if vid_id not in vids_to_tracks.keys():
580
+ vids_to_tracks[vid_id] = []
581
+ if vid_id not in vids_to_imgs.keys():
582
+ vids_to_imgs[vid_id] = []
583
+
584
+ return vids_to_tracks, vids_to_imgs
585
+
586
+ def _compute_image_to_timestep_mappings(self):
587
+ """Computes a mapping from images to timestep in sequence."""
588
+ images = {}
589
+ for image in self.gt_data["images"]:
590
+ images[image["id"]] = image
591
+
592
+ seq_to_imgs_to_timestep = {vid["id"]: dict() for vid in self.gt_data["videos"]}
593
+ for vid in seq_to_imgs_to_timestep:
594
+ curr_imgs = [img["id"] for img in self.video2gt_image[vid]]
595
+ curr_imgs = sorted(curr_imgs, key=lambda x: images[x]["frame_index"])
596
+ seq_to_imgs_to_timestep[vid] = {
597
+ curr_imgs[i]: i for i in range(len(curr_imgs))
598
+ }
599
+
600
+ return seq_to_imgs_to_timestep
601
+
602
+ def _limit_dets_per_image(self, annotations):
603
+ """Limits the number of detections for each image.
604
+
605
+ Adapted from https://github.com/TAO-Dataset/.
606
+ """
607
+ max_dets = self.config["MAX_DETECTIONS"]
608
+ img_ann = defaultdict(list)
609
+ for ann in annotations:
610
+ img_ann[ann["image_id"]].append(ann)
611
+
612
+ for img_id, _anns in img_ann.items():
613
+ if len(_anns) <= max_dets:
614
+ continue
615
+ _anns = sorted(_anns, key=lambda x: x["score"], reverse=True)
616
+ img_ann[img_id] = _anns[:max_dets]
617
+
618
+ return [ann for anns in img_ann.values() for ann in anns]
619
+
620
+ def _fill_video_ids_inplace(self, annotations):
621
+ """Fills in missing video IDs inplace.
622
+
623
+ Adapted from https://github.com/TAO-Dataset/.
624
+ """
625
+ missing_video_id = [x for x in annotations if "video_id" not in x]
626
+ if missing_video_id:
627
+ image_id_to_video_id = {
628
+ x["id"]: x["video_id"] for x in self.gt_data["images"]
629
+ }
630
+ for x in missing_video_id:
631
+ x["video_id"] = image_id_to_video_id[x["image_id"]]
632
+
633
+ @staticmethod
634
+ def _make_tk_ids_unique(annotations):
635
+ """Makes track IDs unqiue over the whole annotation set.
636
+
637
+ Adapted from https://github.com/TAO-Dataset/.
638
+ """
639
+ track_id_videos = {}
640
+ track_ids_to_update = set()
641
+ max_track_id = 0
642
+ for ann in annotations:
643
+ t = ann["track_id"]
644
+ if t not in track_id_videos:
645
+ track_id_videos[t] = ann["video_id"]
646
+
647
+ if ann["video_id"] != track_id_videos[t]:
648
+ # track id is assigned to multiple videos
649
+ track_ids_to_update.add(t)
650
+ max_track_id = max(max_track_id, t)
651
+
652
+ if track_ids_to_update:
653
+ print("true")
654
+ next_id = itertools.count(max_track_id + 1)
655
+ new_tk_ids = defaultdict(lambda: next(next_id))
656
+ for ann in annotations:
657
+ t = ann["track_id"]
658
+ v = ann["video_id"]
659
+ if t in track_ids_to_update:
660
+ ann["track_id"] = new_tk_ids[t, v]
661
+ return len(track_ids_to_update)
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/eval.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ import copy
7
+ import os
8
+ import pickle
9
+ import time
10
+ import traceback
11
+ from functools import partial
12
+ from multiprocessing.pool import Pool
13
+
14
+ import numpy as np
15
+
16
+ from . import _timing, utils
17
+ from .config import get_default_eval_config, init_config
18
+ from .utils import TrackEvalException
19
+
20
+
21
+ class Evaluator:
22
+ """Evaluator class for evaluating different metrics for each datasets."""
23
+
24
+ def __init__(self, config=None):
25
+ """Initialize the evaluator with a config file."""
26
+ self.config = init_config(config, get_default_eval_config(), "Eval")
27
+ # Only run timing analysis if not run in parallel.
28
+ if self.config["TIME_PROGRESS"] and not self.config["USE_PARALLEL"]:
29
+ _timing.DO_TIMING = True
30
+ if self.config["DISPLAY_LESS_PROGRESS"]:
31
+ _timing.DISPLAY_LESS_PROGRESS = True
32
+
33
+ @_timing.time
34
+ def evaluate(self, dataset_list, metrics_list):
35
+ """Evaluate a set of metrics on a set of datasets."""
36
+ config = self.config
37
+ metrics_list = metrics_list
38
+ metric_names = utils.validate_metrics_list(metrics_list)
39
+ dataset_names = [dataset.get_name() for dataset in dataset_list]
40
+ output_res = {}
41
+ output_msg = {}
42
+
43
+ for dataset, dname in zip(dataset_list, dataset_names):
44
+ # Get dataset info about what to evaluate
45
+ output_res[dname] = {}
46
+ output_msg[dname] = {}
47
+ tracker_list, seq_list, class_list = dataset.get_eval_info()
48
+ print(
49
+ f"\nEvaluating {len(tracker_list)} tracker(s) on "
50
+ f"{len(seq_list)} sequence(s) for {len(class_list)} class(es)"
51
+ f" on {dname} dataset using the following "
52
+ f'metrics: {", ".join(metric_names)}\n'
53
+ )
54
+
55
+ # Evaluate each tracker
56
+ for tracker in tracker_list:
57
+ try:
58
+ output_res, output_msg = self.evaluate_tracker(
59
+ tracker,
60
+ dataset,
61
+ dname,
62
+ class_list,
63
+ metrics_list,
64
+ metric_names,
65
+ seq_list,
66
+ output_res,
67
+ output_msg,
68
+ )
69
+ except Exception as err:
70
+ output_res[dname][tracker] = None
71
+ if type(err) == TrackEvalException:
72
+ output_msg[dname][tracker] = str(err)
73
+ else:
74
+ output_msg[dname][tracker] = "Unknown error occurred."
75
+ print("Tracker %s was unable to be evaluated." % tracker)
76
+ print(err)
77
+ traceback.print_exc()
78
+ if config["LOG_ON_ERROR"] is not None:
79
+ with open(config["LOG_ON_ERROR"], "a") as f:
80
+ print(dname, file=f)
81
+ print(tracker, file=f)
82
+ print(traceback.format_exc(), file=f)
83
+ print("\n\n\n", file=f)
84
+ if config["BREAK_ON_ERROR"]:
85
+ raise err
86
+ elif config["RETURN_ON_ERROR"]:
87
+ return output_res, output_msg
88
+
89
+ return output_res, output_msg
90
+
91
+ def evaluate_tracker(
92
+ self,
93
+ tracker,
94
+ dataset,
95
+ dname,
96
+ class_list,
97
+ metrics_list,
98
+ metric_names,
99
+ seq_list,
100
+ output_res,
101
+ output_msg,
102
+ ):
103
+ """Evaluate each sequence in parallel or in series."""
104
+ print("\nEvaluating %s\n" % tracker)
105
+ time_start = time.time()
106
+ config = self.config
107
+ if config["USE_PARALLEL"]:
108
+ with Pool(config["NUM_PARALLEL_CORES"]) as pool:
109
+ _eval_sequence = partial(
110
+ eval_sequence,
111
+ dataset=dataset,
112
+ tracker=tracker,
113
+ class_list=class_list,
114
+ metrics_list=metrics_list,
115
+ metric_names=metric_names,
116
+ )
117
+ results = pool.map(_eval_sequence, seq_list)
118
+ res = dict(zip(seq_list, results))
119
+ else:
120
+ res = {}
121
+ for curr_seq in sorted(seq_list):
122
+ res[curr_seq] = eval_sequence(
123
+ curr_seq, dataset, tracker, class_list, metrics_list, metric_names
124
+ )
125
+
126
+
127
+ # collecting combined cls keys (cls averaged, det averaged, super classes)
128
+ cls_keys = []
129
+ res["COMBINED_SEQ"] = {}
130
+ # combine sequences for each class
131
+ for c_cls in class_list:
132
+ res["COMBINED_SEQ"][c_cls] = {}
133
+ for metric, mname in zip(metrics_list, metric_names):
134
+ curr_res = {
135
+ seq_key: seq_value[c_cls][mname]
136
+ for seq_key, seq_value in res.items()
137
+ if seq_key != "COMBINED_SEQ"
138
+ }
139
+ # combine results over all sequences and then over all classes
140
+ res["COMBINED_SEQ"][c_cls][mname] = metric.combine_sequences(curr_res)
141
+
142
+ # combine classes
143
+ if dataset.should_classes_combine:
144
+ if config["OUTPUT_PER_SEQ_RES"]:
145
+ video_keys = res.keys()
146
+ else:
147
+ video_keys = ["COMBINED_SEQ"]
148
+ for v_key in video_keys:
149
+ cls_keys += ["average"]
150
+ res[v_key]["average"] = {}
151
+ for metric, mname in zip(metrics_list, metric_names):
152
+ cls_res = {
153
+ cls_key: cls_value[mname]
154
+ for cls_key, cls_value in res[v_key].items()
155
+ if cls_key not in cls_keys
156
+ }
157
+ res[v_key]["average"][
158
+ mname
159
+ ] = metric.combine_classes_class_averaged(
160
+ cls_res, ignore_empty=True
161
+ )
162
+
163
+ # combine classes to super classes
164
+ if dataset.use_super_categories:
165
+ for cat, sub_cats in dataset.super_categories.items():
166
+ cls_keys.append(cat)
167
+ res["COMBINED_SEQ"][cat] = {}
168
+ for metric, mname in zip(metrics_list, metric_names):
169
+ cat_res = {
170
+ cls_key: cls_value[mname]
171
+ for cls_key, cls_value in res["COMBINED_SEQ"].items()
172
+ if cls_key in sub_cats
173
+ }
174
+ res["COMBINED_SEQ"][cat][
175
+ mname
176
+ ] = metric.combine_classes_det_averaged(cat_res)
177
+ # Print and output results in various formats
178
+ if config["TIME_PROGRESS"]:
179
+ print(
180
+ f"\nAll sequences for {tracker} finished in"
181
+ f" {time.time() - time_start} seconds"
182
+ )
183
+ output_fol = dataset.get_output_fol(tracker)
184
+ os.makedirs(output_fol, exist_ok=True)
185
+
186
+ # take a mean of each field of each thr
187
+ if config["OUTPUT_PER_SEQ_RES"]:
188
+ all_res = copy.deepcopy(res)
189
+ summary_keys = res.keys()
190
+ else:
191
+ all_res = copy.deepcopy(res["COMBINED_SEQ"])
192
+ summary_keys = ["COMBINED_SEQ"]
193
+ thr_key_list = [50]
194
+ for s_key in summary_keys:
195
+ for metric, mname in zip(metrics_list, metric_names):
196
+ if mname != "TETA":
197
+ if s_key == "COMBINED_SEQ":
198
+ metric.print_table(
199
+ {"COMBINED_SEQ": res["COMBINED_SEQ"][cls_keys[0]][mname]},
200
+ tracker,
201
+ cls_keys[0],
202
+ )
203
+ continue
204
+
205
+ for c_cls in res[s_key].keys():
206
+ for thr in thr_key_list:
207
+ all_res[s_key][c_cls][mname][thr] = metric._summary_row(
208
+ res[s_key][c_cls][mname][thr]
209
+ )
210
+ x = (
211
+ np.array(list(all_res[s_key][c_cls]["TETA"].values()))
212
+ .astype("float")
213
+ .mean(axis=0)
214
+ )
215
+ all_res_summary = list(x.round(decimals=2).astype("str"))
216
+ all_res[s_key][c_cls][mname]["ALL"] = all_res_summary
217
+ if config["OUTPUT_SUMMARY"] and s_key == "COMBINED_SEQ":
218
+ for t in thr_key_list:
219
+ metric.print_summary_table(
220
+ all_res[s_key][cls_keys[0]][mname][t],
221
+ t,
222
+ tracker,
223
+ cls_keys[0],
224
+ )
225
+
226
+ if config["OUTPUT_TEM_RAW_DATA"]:
227
+ out_file = os.path.join(output_fol, "teta_summary_results.pth")
228
+ pickle.dump(all_res, open(out_file, "wb"))
229
+ print("Saved the TETA summary results.")
230
+
231
+ # output
232
+ output_res[dname][mname] = all_res[s_key][cls_keys[0]][mname][t]
233
+ output_msg[dname][tracker] = "Success"
234
+
235
+ return output_res, output_msg
236
+
237
+
238
+ @_timing.time
239
+ def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names):
240
+ """Function for evaluating a single sequence."""
241
+ raw_data = dataset.get_raw_seq_data(tracker, seq)
242
+ seq_res = {}
243
+
244
+ if "TETA" in metric_names:
245
+ thresholds = [50]
246
+ data_all_class = dataset.get_preprocessed_seq_data(
247
+ raw_data, "all", thresholds=thresholds
248
+ )
249
+ teta = metrics_list[metric_names.index("TETA")]
250
+ assignment = teta.compute_global_assignment(data_all_class)
251
+
252
+ # create a dict to save Cls_FP for each class in different thr.
253
+ cls_fp = {
254
+ key: {
255
+ cls: np.zeros((len(np.arange(0.5, 0.99, 0.05)))) for cls in class_list
256
+ }
257
+ for key in thresholds
258
+ }
259
+
260
+ for cls in class_list:
261
+ seq_res[cls] = {}
262
+ data = dataset.get_preprocessed_seq_data(raw_data, cls, assignment, thresholds)
263
+
264
+ for metric, mname in zip(metrics_list, metric_names):
265
+ if mname == "TETA":
266
+ seq_res[cls][mname], cls_fp, _ = metric.eval_sequence(
267
+ data, cls, dataset.clsid2cls_name, cls_fp
268
+ )
269
+ else:
270
+ seq_res[cls][mname] = metric.eval_sequence(data)
271
+
272
+ if "TETA" in metric_names:
273
+ for thr in thresholds:
274
+ for cls in class_list:
275
+ seq_res[cls]["TETA"][thr]["Cls_FP"] += cls_fp[thr][cls]
276
+
277
+ return seq_res
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ from .teta import TETA
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ from abc import ABC, abstractmethod
7
+
8
+ import numpy as np
9
+
10
+ from .. import _timing
11
+ from ..utils import TrackEvalException
12
+
13
+
14
+ class _BaseMetric(ABC):
15
+ @abstractmethod
16
+ def __init__(self):
17
+ self.plottable = False
18
+ self.integer_fields = []
19
+ self.float_fields = []
20
+ self.array_labels = []
21
+ self.integer_array_fields = []
22
+ self.float_array_fields = []
23
+ self.fields = []
24
+ self.summary_fields = []
25
+ self.registered = False
26
+
27
+ #####################################################################
28
+ # Abstract functions for subclasses to implement
29
+
30
+ @_timing.time
31
+ @abstractmethod
32
+ def eval_sequence(self, data):
33
+ ...
34
+
35
+ @abstractmethod
36
+ def combine_sequences(self, all_res):
37
+ ...
38
+
39
+ @abstractmethod
40
+ def combine_classes_class_averaged(self, all_res, ignore_empty=False):
41
+ ...
42
+
43
+ @abstractmethod
44
+ def combine_classes_det_averaged(self, all_res):
45
+ ...
46
+
47
+ def plot_single_tracker_results(self, all_res, tracker, output_folder, cls):
48
+ """Plot results, only valid for metrics with self.plottable."""
49
+ if self.plottable:
50
+ raise NotImplementedError(
51
+ f"plot_results is not implemented for metric {self.get_name()}"
52
+ )
53
+ else:
54
+ pass
55
+
56
+ #####################################################################
57
+ # Helper functions which are useful for all metrics:
58
+
59
+ @classmethod
60
+ def get_name(cls):
61
+ return cls.__name__
62
+
63
+ @staticmethod
64
+ def _combine_sum(all_res, field):
65
+ """Combine sequence results via sum"""
66
+ return sum([all_res[k][field] for k in all_res.keys()])
67
+
68
+ @staticmethod
69
+ def _combine_weighted_av(all_res, field, comb_res, weight_field):
70
+ """Combine sequence results via weighted average."""
71
+ return sum(
72
+ [all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()]
73
+ ) / np.maximum(1.0, comb_res[weight_field])
74
+
75
+ def print_table(self, table_res, tracker, cls):
76
+ """Print table of results for all sequences."""
77
+ print("")
78
+ metric_name = self.get_name()
79
+ self._row_print(
80
+ [metric_name + ": " + tracker + "-" + cls] + self.summary_fields
81
+ )
82
+ for seq, results in sorted(table_res.items()):
83
+ if seq == "COMBINED_SEQ":
84
+ continue
85
+ summary_res = self._summary_row(results)
86
+ self._row_print([seq] + summary_res)
87
+ summary_res = self._summary_row(table_res["COMBINED_SEQ"])
88
+ self._row_print(["COMBINED"] + summary_res)
89
+
90
+ def _summary_row(self, results_):
91
+ vals = []
92
+ for h in self.summary_fields:
93
+ if h in self.float_array_fields:
94
+ vals.append("{0:1.5g}".format(100 * np.mean(results_[h])))
95
+ elif h in self.float_fields:
96
+ vals.append("{0:1.5g}".format(100 * float(results_[h])))
97
+ elif h in self.integer_fields:
98
+ vals.append("{0:d}".format(int(results_[h])))
99
+ else:
100
+ raise NotImplementedError(
101
+ "Summary function not implemented for this field type."
102
+ )
103
+ return vals
104
+
105
+ @staticmethod
106
+ def _row_print(*argv):
107
+ """Print results in evenly spaced rows, with more space in first row."""
108
+ if len(argv) == 1:
109
+ argv = argv[0]
110
+ to_print = "%-35s" % argv[0]
111
+ for v in argv[1:]:
112
+ to_print += "%-10s" % str(v)
113
+ print(to_print)
114
+
115
+ def summary_results(self, table_res):
116
+ """Return a simple summary of final results for a tracker."""
117
+ return dict(
118
+ zip(self.summary_fields, self._summary_row(table_res["COMBINED_SEQ"]),)
119
+ )
120
+
121
+ def detailed_results(self, table_res):
122
+ """Return detailed final results for a tracker."""
123
+ # Get detailed field information
124
+ detailed_fields = self.float_fields + self.integer_fields
125
+ for h in self.float_array_fields + self.integer_array_fields:
126
+ for alpha in [int(100 * x) for x in self.array_labels]:
127
+ detailed_fields.append(h + "___" + str(alpha))
128
+ detailed_fields.append(h + "___AUC")
129
+
130
+ # Get detailed results
131
+ detailed_results = {}
132
+ for seq, res in table_res.items():
133
+ detailed_row = self._detailed_row(res)
134
+ if len(detailed_row) != len(detailed_fields):
135
+ raise TrackEvalException(
136
+ f"Field names and data have different sizes "
137
+ f"({len(detailed_row)} and {len(detailed_fields)})"
138
+ )
139
+ detailed_results[seq] = dict(zip(detailed_fields, detailed_row))
140
+ return detailed_results
141
+
142
+ def _detailed_row(self, res):
143
+ detailed_row = []
144
+ for h in self.float_fields + self.integer_fields:
145
+ detailed_row.append(res[h])
146
+ for h in self.float_array_fields + self.integer_array_fields:
147
+ for i, _ in enumerate([int(100 * x) for x in self.array_labels]):
148
+ detailed_row.append(res[h][i])
149
+ detailed_row.append(np.mean(res[h]))
150
+ return detailed_row
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/metrics/teta.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ """Track Every Thing Accuracy metric."""
7
+
8
+ import numpy as np
9
+ from scipy.optimize import linear_sum_assignment
10
+
11
+ from .. import _timing
12
+ from ._base_metric import _BaseMetric
13
+
14
+ EPS = np.finfo("float").eps # epsilon
15
+
16
+
17
+ class TETA(_BaseMetric):
18
+ """TETA metric."""
19
+
20
+ def __init__(self, exhaustive=False, config=None):
21
+ """Initialize metric."""
22
+ super().__init__()
23
+ self.plottable = True
24
+ self.array_labels = np.arange(0.0, 0.99, 0.05)
25
+ self.cls_array_labels = np.arange(0.5, 0.99, 0.05)
26
+
27
+ self.integer_array_fields = [
28
+ "Loc_TP",
29
+ "Loc_FN",
30
+ "Loc_FP",
31
+ "Cls_TP",
32
+ "Cls_FN",
33
+ "Cls_FP",
34
+ ]
35
+ self.float_array_fields = (
36
+ ["TETA", "LocA", "AssocA", "ClsA"]
37
+ + ["LocRe", "LocPr"]
38
+ + ["AssocRe", "AssocPr"]
39
+ + ["ClsRe", "ClsPr"]
40
+ )
41
+ self.fields = self.float_array_fields + self.integer_array_fields
42
+ self.summary_fields = self.float_array_fields
43
+ self.exhaustive = exhaustive
44
+
45
+ def compute_global_assignment(self, data_thr, alpha=0.5):
46
+ """Compute global assignment of TP."""
47
+ res = {
48
+ thr: {t: {} for t in range(data_thr[thr]["num_timesteps"])}
49
+ for thr in data_thr
50
+ }
51
+
52
+ for thr in data_thr:
53
+ data = data_thr[thr]
54
+ # return empty result if tracker or gt sequence is empty
55
+ if data["num_tk_overlap_dets"] == 0 or data["num_gt_dets"] == 0:
56
+ return res
57
+
58
+ # global alignment score
59
+ ga_score, _, _ = self.compute_global_alignment_score(data)
60
+
61
+ # calculate scores for each timestep
62
+ for t, (gt_ids_t, tk_ids_t) in enumerate(
63
+ zip(data["gt_ids"], data["tk_ids"])
64
+ ):
65
+ # get matches optimizing for TETA
66
+ amatch_rows, amatch_cols = self.compute_matches(
67
+ data, t, ga_score, gt_ids_t, tk_ids_t, alpha=alpha
68
+ )
69
+ gt_ids = [data["gt_id_map"][tid] for tid in gt_ids_t[amatch_rows[0]]]
70
+ matched_ids = [
71
+ data["tk_id_map"][tid] for tid in tk_ids_t[amatch_cols[0]]
72
+ ]
73
+ res[thr][t] = dict(zip(gt_ids, matched_ids))
74
+
75
+ return res
76
+
77
+ def eval_sequence_single_thr(self, data, cls, cid2clsname, cls_fp_thr, thr):
78
+ """Computes TETA metric for one threshold for one sequence."""
79
+ res = {}
80
+ class_info_list = []
81
+ for field in self.float_array_fields + self.integer_array_fields:
82
+ if field.startswith("Cls"):
83
+ res[field] = np.zeros(len(self.cls_array_labels), dtype=float)
84
+ else:
85
+ res[field] = np.zeros((len(self.array_labels)), dtype=float)
86
+
87
+ # return empty result if tracker or gt sequence is empty
88
+ if data["num_tk_overlap_dets"] == 0:
89
+ res["Loc_FN"] = data["num_gt_dets"] * np.ones(
90
+ (len(self.array_labels)), dtype=float
91
+ )
92
+ if self.exhaustive:
93
+ cls_fp_thr[cls] = data["num_tk_cls_dets"] * np.ones(
94
+ (len(self.cls_array_labels)), dtype=float
95
+ )
96
+ res = self._compute_final_fields(res)
97
+ return res, cls_fp_thr, class_info_list
98
+
99
+ if data["num_gt_dets"] == 0:
100
+ if self.exhaustive:
101
+ cls_fp_thr[cls] = data["num_tk_cls_dets"] * np.ones(
102
+ (len(self.cls_array_labels)), dtype=float
103
+ )
104
+ res = self._compute_final_fields(res)
105
+ return res, cls_fp_thr, class_info_list
106
+
107
+ # global alignment score
108
+ ga_score, gt_id_count, tk_id_count = self.compute_global_alignment_score(data)
109
+ matches_counts = [np.zeros_like(ga_score) for _ in self.array_labels]
110
+
111
+ # calculate scores for each timestep
112
+ for t, (gt_ids_t, tk_ids_t, tk_overlap_ids_t, tk_cls_ids_t) in enumerate(
113
+ zip(
114
+ data["gt_ids"],
115
+ data["tk_ids"],
116
+ data["tk_overlap_ids"],
117
+ data["tk_class_eval_tk_ids"],
118
+ )
119
+ ):
120
+ # deal with the case that there are no gt_det/tk_det in a timestep
121
+ if len(gt_ids_t) == 0:
122
+ if self.exhaustive:
123
+ cls_fp_thr[cls] += len(tk_cls_ids_t)
124
+ continue
125
+
126
+ # get matches optimizing for TETA
127
+ amatch_rows, amatch_cols = self.compute_matches(
128
+ data, t, ga_score, gt_ids_t, tk_ids_t, list(self.array_labels)
129
+ )
130
+
131
+ # map overlap_ids to original ids.
132
+ if len(tk_overlap_ids_t) != 0:
133
+ sorter = np.argsort(tk_ids_t)
134
+ indexes = sorter[
135
+ np.searchsorted(tk_ids_t, tk_overlap_ids_t, sorter=sorter)
136
+ ]
137
+ sim_t = data["sim_scores"][t][:, indexes]
138
+ fpl_candidates = tk_overlap_ids_t[(sim_t >= (thr / 100)).any(axis=0)]
139
+ fpl_candidates_ori_ids_t = np.array(
140
+ [data["tk_id_map"][tid] for tid in fpl_candidates]
141
+ )
142
+ else:
143
+ fpl_candidates_ori_ids_t = []
144
+
145
+ if self.exhaustive:
146
+ cls_fp_thr[cls] += len(tk_cls_ids_t) - len(tk_overlap_ids_t)
147
+
148
+ # calculate and accumulate basic statistics
149
+ for a, alpha in enumerate(self.array_labels):
150
+ match_row, match_col = amatch_rows[a], amatch_cols[a]
151
+ num_matches = len(match_row)
152
+ matched_ori_ids = set(
153
+ [data["tk_id_map"][tid] for tid in tk_ids_t[match_col]]
154
+ )
155
+ match_tk_cls = data["tk_classes"][t][match_col]
156
+ wrong_tk_cls = match_tk_cls[match_tk_cls != data["gt_classes"][t]]
157
+
158
+ num_class_and_det_matches = np.sum(
159
+ match_tk_cls == data["gt_classes"][t]
160
+ )
161
+
162
+ if alpha >= 0.5:
163
+ for cid in wrong_tk_cls:
164
+ if cid in cid2clsname:
165
+ cname = cid2clsname[cid]
166
+ cls_fp_thr[cname][a - 10] += 1
167
+ res["Cls_TP"][a - 10] += num_class_and_det_matches
168
+ res["Cls_FN"][a - 10] += num_matches - num_class_and_det_matches
169
+
170
+ res["Loc_TP"][a] += num_matches
171
+ res["Loc_FN"][a] += len(gt_ids_t) - num_matches
172
+ res["Loc_FP"][a] += len(set(fpl_candidates_ori_ids_t) - matched_ori_ids)
173
+
174
+ if num_matches > 0:
175
+ matches_counts[a][gt_ids_t[match_row], tk_ids_t[match_col]] += 1
176
+
177
+ # calculate AssocA, AssocRe, AssocPr
178
+ self.compute_association_scores(res, matches_counts, gt_id_count, tk_id_count)
179
+
180
+ # calculate final scores
181
+ res = self._compute_final_fields(res)
182
+ return res, cls_fp_thr, class_info_list
183
+
184
+ def compute_global_alignment_score(self, data):
185
+ """Computes global alignment score."""
186
+ num_matches = np.zeros((data["num_gt_ids"], data["num_tk_ids"]))
187
+ gt_id_count = np.zeros((data["num_gt_ids"], 1))
188
+ tk_id_count = np.zeros((1, data["num_tk_ids"]))
189
+
190
+ # loop through each timestep and accumulate global track info.
191
+ for t, (gt_ids_t, tk_ids_t) in enumerate(zip(data["gt_ids"], data["tk_ids"])):
192
+ # count potential matches between ids in each time step
193
+ # these are normalized, weighted by match similarity
194
+ sim = data["sim_scores"][t]
195
+ sim_iou_denom = sim.sum(0, keepdims=True) + sim.sum(1, keepdims=True) - sim
196
+ sim_iou = np.zeros_like(sim)
197
+ mask = sim_iou_denom > (0 + EPS)
198
+ sim_iou[mask] = sim[mask] / sim_iou_denom[mask]
199
+ num_matches[gt_ids_t[:, None], tk_ids_t[None, :]] += sim_iou
200
+
201
+ # calculate total number of dets for each gt_id and tk_id.
202
+ gt_id_count[gt_ids_t] += 1
203
+ tk_id_count[0, tk_ids_t] += 1
204
+
205
+ # Calculate overall Jaccard alignment score between IDs
206
+ ga_score = num_matches / (gt_id_count + tk_id_count - num_matches)
207
+ return ga_score, gt_id_count, tk_id_count
208
+
209
+ def compute_matches(self, data, t, ga_score, gt_ids, tk_ids, alpha):
210
+ """Compute matches based on alignment score."""
211
+ sim = data["sim_scores"][t]
212
+ score_mat = ga_score[gt_ids[:, None], tk_ids[None, :]] * sim
213
+ # Hungarian algorithm to find best matches
214
+ match_rows, match_cols = linear_sum_assignment(-score_mat)
215
+
216
+ if not isinstance(alpha, list):
217
+ alpha = [alpha]
218
+ alpha_match_rows, alpha_match_cols = [], []
219
+ for a in alpha:
220
+ matched_mask = sim[match_rows, match_cols] >= a - EPS
221
+ alpha_match_rows.append(match_rows[matched_mask])
222
+ alpha_match_cols.append(match_cols[matched_mask])
223
+ return alpha_match_rows, alpha_match_cols
224
+
225
+ def compute_association_scores(self, res, matches_counts, gt_id_count, tk_id_count):
226
+ """Calculate association scores for each alpha.
227
+
228
+ First calculate scores per gt_id/tk_id combo,
229
+ and then average over the number of detections.
230
+ """
231
+ for a, _ in enumerate(self.array_labels):
232
+ matches_count = matches_counts[a]
233
+ ass_a = matches_count / np.maximum(
234
+ 1, gt_id_count + tk_id_count - matches_count
235
+ )
236
+ res["AssocA"][a] = np.sum(matches_count * ass_a) / np.maximum(
237
+ 1, res["Loc_TP"][a]
238
+ )
239
+ ass_re = matches_count / np.maximum(1, gt_id_count)
240
+ res["AssocRe"][a] = np.sum(matches_count * ass_re) / np.maximum(
241
+ 1, res["Loc_TP"][a]
242
+ )
243
+ ass_pr = matches_count / np.maximum(1, tk_id_count)
244
+ res["AssocPr"][a] = np.sum(matches_count * ass_pr) / np.maximum(
245
+ 1, res["Loc_TP"][a]
246
+ )
247
+
248
+ @_timing.time
249
+ def eval_sequence(self, data, cls, cls_id_name_mapping, cls_fp):
250
+ """Evaluate a single sequence across all thresholds."""
251
+ res = {}
252
+ class_info_dict = {}
253
+
254
+ for thr in data:
255
+ res[thr], cls_fp[thr], cls_info = self.eval_sequence_single_thr(
256
+ data[thr], cls, cls_id_name_mapping, cls_fp[thr], thr
257
+ )
258
+ class_info_dict[thr] = cls_info
259
+
260
+ return res, cls_fp, class_info_dict
261
+
262
+ def combine_sequences(self, all_res):
263
+ """Combines metrics across all sequences."""
264
+ data = {}
265
+ res = {}
266
+
267
+ if all_res:
268
+ thresholds = list(list(all_res.values())[0].keys())
269
+ else:
270
+ thresholds = [50]
271
+ for thr in thresholds:
272
+ data[thr] = {}
273
+ for seq_key in all_res:
274
+ data[thr][seq_key] = all_res[seq_key][thr]
275
+ for thr in thresholds:
276
+ res[thr] = self._combine_sequences_thr(data[thr])
277
+
278
+ return res
279
+
280
+ def _combine_sequences_thr(self, all_res):
281
+ """Combines sequences over each threshold."""
282
+ res = {}
283
+ for field in self.integer_array_fields:
284
+ res[field] = self._combine_sum(all_res, field)
285
+ for field in ["AssocRe", "AssocPr", "AssocA"]:
286
+ res[field] = self._combine_weighted_av(
287
+ all_res, field, res, weight_field="Loc_TP"
288
+ )
289
+ res = self._compute_final_fields(res)
290
+ return res
291
+
292
+ def combine_classes_class_averaged(self, all_res, ignore_empty=False):
293
+ """Combines metrics across all classes by averaging over classes.
294
+
295
+ If 'ignore_empty' is True, then it only sums over classes
296
+ with at least one gt or predicted detection.
297
+ """
298
+ data = {}
299
+ res = {}
300
+ if all_res:
301
+ thresholds = list(list(all_res.values())[0].keys())
302
+ else:
303
+ thresholds = [50]
304
+ for thr in thresholds:
305
+ data[thr] = {}
306
+ for cls_key in all_res:
307
+ data[thr][cls_key] = all_res[cls_key][thr]
308
+ for thr in data:
309
+ res[thr] = self._combine_classes_class_averaged_thr(
310
+ data[thr], ignore_empty=ignore_empty
311
+ )
312
+ return res
313
+
314
+ def _combine_classes_class_averaged_thr(self, all_res, ignore_empty=False):
315
+ """Combines classes over each threshold."""
316
+ res = {}
317
+
318
+ def check_empty(val):
319
+ """Returns True if empty."""
320
+ return not (val["Loc_TP"] + val["Loc_FN"] + val["Loc_FP"] > 0 + EPS).any()
321
+
322
+ for field in self.integer_array_fields:
323
+ if ignore_empty:
324
+ res_field = {k: v for k, v in all_res.items() if not check_empty(v)}
325
+ else:
326
+ res_field = {k: v for k, v in all_res.items()}
327
+ res[field] = self._combine_sum(res_field, field)
328
+
329
+ for field in self.float_array_fields:
330
+ if ignore_empty:
331
+ res_field = [v[field] for v in all_res.values() if not check_empty(v)]
332
+ else:
333
+ res_field = [v[field] for v in all_res.values()]
334
+ res[field] = np.mean(res_field, axis=0)
335
+ return res
336
+
337
+ def combine_classes_det_averaged(self, all_res):
338
+ """Combines metrics across all classes by averaging over detections."""
339
+ data = {}
340
+ res = {}
341
+ if all_res:
342
+ thresholds = list(list(all_res.values())[0].keys())
343
+ else:
344
+ thresholds = [50]
345
+ for thr in thresholds:
346
+ data[thr] = {}
347
+ for cls_key in all_res:
348
+ data[thr][cls_key] = all_res[cls_key][thr]
349
+ for thr in data:
350
+ res[thr] = self._combine_classes_det_averaged_thr(data[thr])
351
+ return res
352
+
353
+ def _combine_classes_det_averaged_thr(self, all_res):
354
+ """Combines detections over each threshold."""
355
+ res = {}
356
+ for field in self.integer_array_fields:
357
+ res[field] = self._combine_sum(all_res, field)
358
+ for field in ["AssocRe", "AssocPr", "AssocA"]:
359
+ res[field] = self._combine_weighted_av(
360
+ all_res, field, res, weight_field="Loc_TP"
361
+ )
362
+ res = self._compute_final_fields(res)
363
+ return res
364
+
365
+ @staticmethod
366
+ def _compute_final_fields(res):
367
+ """Calculate final metric values.
368
+
369
+ This function is used both for both per-sequence calculation,
370
+ and in combining values across sequences.
371
+ """
372
+ # LocA
373
+ res["LocRe"] = res["Loc_TP"] / np.maximum(1, res["Loc_TP"] + res["Loc_FN"])
374
+ res["LocPr"] = res["Loc_TP"] / np.maximum(1, res["Loc_TP"] + res["Loc_FP"])
375
+ res["LocA"] = res["Loc_TP"] / np.maximum(
376
+ 1, res["Loc_TP"] + res["Loc_FN"] + res["Loc_FP"]
377
+ )
378
+
379
+ # ClsA
380
+ res["ClsRe"] = res["Cls_TP"] / np.maximum(1, res["Cls_TP"] + res["Cls_FN"])
381
+ res["ClsPr"] = res["Cls_TP"] / np.maximum(1, res["Cls_TP"] + res["Cls_FP"])
382
+ res["ClsA"] = res["Cls_TP"] / np.maximum(
383
+ 1, res["Cls_TP"] + res["Cls_FN"] + res["Cls_FP"]
384
+ )
385
+
386
+ res["ClsRe"] = np.mean(res["ClsRe"])
387
+ res["ClsPr"] = np.mean(res["ClsPr"])
388
+ res["ClsA"] = np.mean(res["ClsA"])
389
+
390
+ res["TETA"] = (res["LocA"] + res["AssocA"] + res["ClsA"]) / 3
391
+
392
+ return res
393
+
394
+ def print_summary_table(self, thr_res, thr, tracker, cls):
395
+ """Prints summary table of results."""
396
+ print("")
397
+ metric_name = self.get_name()
398
+ self._row_print(
399
+ [f"{metric_name}{str(thr)}: {tracker}-{cls}"] + self.summary_fields
400
+ )
401
+ self._row_print(["COMBINED"] + thr_res)
third_party/GraspGen/sam3/sam3/eval/teta_eval_toolkit/utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fmt: off
2
+ # flake8: noqa
3
+
4
+ # pyre-unsafe
5
+
6
+ import csv
7
+ import os
8
+ from collections import OrderedDict
9
+
10
+
11
+ def validate_metrics_list(metrics_list):
12
+ """Get names of metric class and ensures they are unique, further checks that the fields within each metric class
13
+ do not have overlapping names.
14
+ """
15
+ metric_names = [metric.get_name() for metric in metrics_list]
16
+ # check metric names are unique
17
+ if len(metric_names) != len(set(metric_names)):
18
+ raise TrackEvalException(
19
+ "Code being run with multiple metrics of the same name"
20
+ )
21
+ fields = []
22
+ for m in metrics_list:
23
+ fields += m.fields
24
+ # check metric fields are unique
25
+ if len(fields) != len(set(fields)):
26
+ raise TrackEvalException(
27
+ "Code being run with multiple metrics with fields of the same name"
28
+ )
29
+ return metric_names
30
+
31
+
32
+ def get_track_id_str(ann):
33
+ """Get name of track ID in annotation."""
34
+ if "track_id" in ann:
35
+ tk_str = "track_id"
36
+ elif "instance_id" in ann:
37
+ tk_str = "instance_id"
38
+ elif "scalabel_id" in ann:
39
+ tk_str = "scalabel_id"
40
+ else:
41
+ assert False, "No track/instance ID."
42
+ return tk_str
43
+
44
+
45
+ class TrackEvalException(Exception):
46
+ """Custom exception for catching expected errors."""
47
+
48
+ ...
third_party/GraspGen/sam3/sam3/eval/ytvis_coco_wrapper.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ # (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
3
+
4
+ # pyre-unsafe
5
+
6
+ import copy
7
+ import json
8
+ import logging
9
+
10
+ import numpy as np
11
+ import pycocotools.mask as mask_util
12
+ from pycocotools.coco import COCO
13
+ from typing_extensions import override
14
+
15
+
16
+ class YTVIS(COCO):
17
+ """
18
+ Helper class for reading YT-VIS annotations
19
+ """
20
+
21
+ @override
22
+ def __init__(self, annotation_file: str = None, ignore_gt_cats: bool = True):
23
+ """
24
+ Args:
25
+ annotation_file: Path to the annotation file
26
+ ignore_gt_cats: If True, we ignore the ground truth categories and replace them with a dummy "object" category. This is useful for Phrase AP evaluation.
27
+ """
28
+ self.ignore_gt_cats = ignore_gt_cats
29
+ super().__init__(annotation_file=annotation_file)
30
+
31
+ @override
32
+ def createIndex(self):
33
+ # We rename some keys to match the COCO format before creating the index.
34
+ if "annotations" in self.dataset:
35
+ for ann in self.dataset["annotations"]:
36
+ if "video_id" in ann:
37
+ ann["image_id"] = int(ann.pop("video_id"))
38
+ if self.ignore_gt_cats:
39
+ ann["category_id"] = -1
40
+ else:
41
+ ann["category_id"] = int(ann["category_id"])
42
+ if "bboxes" in ann:
43
+ # note that in some datasets we load under this YTVIS class,
44
+ # some "bboxes" could be None for when the GT object is invisible,
45
+ # so we replace them with [0, 0, 0, 0]
46
+ ann["bboxes"] = [
47
+ bbox if bbox is not None else [0, 0, 0, 0]
48
+ for bbox in ann["bboxes"]
49
+ ]
50
+ if "areas" in ann:
51
+ # similar to "bboxes", some areas could be None for when the GT
52
+ # object is invisible, so we replace them with 0
53
+ areas = [a if a is not None else 0 for a in ann["areas"]]
54
+ # Compute average area of tracklet
55
+ ann["area"] = np.mean(areas)
56
+ if "videos" in self.dataset:
57
+ for vid in self.dataset["videos"]:
58
+ vid["id"] = int(vid["id"])
59
+ self.dataset["images"] = self.dataset.pop("videos")
60
+
61
+ if self.ignore_gt_cats:
62
+ self.dataset["categories"] = [
63
+ {"supercategory": "object", "id": -1, "name": "object"}
64
+ ]
65
+ else:
66
+ for cat in self.dataset["categories"]:
67
+ cat["id"] = int(cat["id"])
68
+ super().createIndex()
69
+
70
+ @override
71
+ def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
72
+ if len(areaRng) > 0:
73
+ logging.warning(
74
+ "Note that we filter out objects based on their *average* area across the video, not per frame area"
75
+ )
76
+
77
+ return super().getAnnIds(imgIds=imgIds, catIds=catIds, iscrowd=iscrowd)
78
+
79
+ @override
80
+ def showAnns(self, anns, draw_bbox=False):
81
+ raise NotImplementedError("Showing annotations is not supported")
82
+
83
+ @override
84
+ def loadRes(self, resFile):
85
+ # Adapted from COCO.loadRes to support tracklets/masklets
86
+ res = YTVIS(ignore_gt_cats=self.ignore_gt_cats)
87
+ res.dataset["images"] = [img for img in self.dataset["images"]]
88
+
89
+ if type(resFile) == str:
90
+ with open(resFile) as f:
91
+ anns = json.load(f)
92
+ elif type(resFile) == np.ndarray:
93
+ anns = self.loadNumpyAnnotations(resFile)
94
+ else:
95
+ anns = resFile
96
+ assert type(anns) == list, "results is not an array of objects"
97
+ annsImgIds = [ann["image_id"] for ann in anns]
98
+ assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
99
+ "Results do not correspond to current coco set"
100
+ )
101
+ if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
102
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
103
+ for id, ann in enumerate(anns):
104
+ bbs = [(bb if bb is not None else [0, 0, 0, 0]) for bb in ann["bboxes"]]
105
+ xxyy = [[bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]] for bb in bbs]
106
+ if not "segmentations" in ann:
107
+ ann["segmentations"] = [
108
+ [[x1, y1, x1, y2, x2, y2, x2, y1]] for (x1, x2, y1, y2) in xxyy
109
+ ]
110
+ ann["areas"] = [bb[2] * bb[3] for bb in bbs]
111
+ # NOTE: We also compute average area of a tracklet across video, allowing us to compute area based mAP.
112
+ ann["area"] = np.mean(ann["areas"])
113
+ ann["id"] = id + 1
114
+ ann["iscrowd"] = 0
115
+ elif "segmentations" in anns[0]:
116
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
117
+ for id, ann in enumerate(anns):
118
+ ann["bboxes"] = [
119
+ mask_util.toBbox(segm) for segm in ann["segmentations"]
120
+ ]
121
+ if "areas" not in ann:
122
+ ann["areas"] = [
123
+ mask_util.area(segm) for segm in ann["segmentations"]
124
+ ]
125
+ # NOTE: We also compute average area of a tracklet across video, allowing us to compute area based mAP.
126
+ ann["area"] = np.mean(ann["areas"])
127
+ ann["id"] = id + 1
128
+ ann["iscrowd"] = 0
129
+
130
+ res.dataset["annotations"] = anns
131
+ res.createIndex()
132
+ return res
133
+
134
+ @override
135
+ def download(self, tarDir=None, imgIds=[]):
136
+ raise NotImplementedError
137
+
138
+ @override
139
+ def loadNumpyAnnotations(self, data):
140
+ raise NotImplementedError("We don't support numpy annotations for now")
141
+
142
+ @override
143
+ def annToRLE(self, ann):
144
+ raise NotImplementedError("We expect masks to be already in RLE format")
145
+
146
+ @override
147
+ def annToMask(self, ann):
148
+ raise NotImplementedError("We expect masks to be already in RLE format")
third_party/GraspGen/sam3/sam3/model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
third_party/GraspGen/sam3/sam3/model/act_ckpt_utils.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import inspect
6
+ from functools import wraps
7
+ from typing import Callable, TypeVar, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint as checkpoint
12
+ from torch.utils._pytree import tree_map_only
13
+
14
+ # Type variables for better type hinting
15
+ T = TypeVar("T")
16
+ Module = TypeVar("Module", bound=nn.Module)
17
+
18
+
19
+ def activation_ckpt_wrapper(module: Union[nn.Module, Callable]) -> Callable:
20
+ """
21
+ Wraps a given module to enable or disable activation checkpointing.
22
+
23
+ Activation checkpointing (gradient checkpointing) trades compute for memory by
24
+ recomputing intermediate activations during the backward pass instead of storing
25
+ them in memory during the forward pass.
26
+
27
+ When activation checkpointing is enabled, the wrapper expects only keyword arguments,
28
+ and it maps these to positional arguments based on the module's signature.
29
+
30
+ Args:
31
+ module: The module or function to wrap with activation checkpointing
32
+
33
+ Returns:
34
+ A wrapped callable that supports activation checkpointing
35
+
36
+ Usage:
37
+ The returned wrapper function can be called with the same arguments as the
38
+ original module, with an additional `act_ckpt_enable` keyword argument to control
39
+ activation checkpointing and optional `use_reentrant` parameter.
40
+
41
+ Example:
42
+ ```python
43
+ wrapped_module = activation_ckpt_wrapper(my_module)
44
+ output = wrapped_module(x=input_tensor, y=another_tensor, act_ckpt_enable=True)
45
+ ```
46
+ """
47
+
48
+ @wraps(module)
49
+ def act_ckpt_wrapper(
50
+ *args, act_ckpt_enable: bool = True, use_reentrant: bool = False, **kwargs
51
+ ):
52
+ if act_ckpt_enable:
53
+ if len(args) > 0:
54
+ raise ValueError(
55
+ "This wrapper expects keyword arguments only when `act_ckpt_enable=True`"
56
+ )
57
+ # Get the signature of the target function/module
58
+ callable_fn = module.forward if isinstance(module, nn.Module) else module
59
+ sig = inspect.signature(callable_fn)
60
+ # Create a mapping of parameter names to their default values
61
+ param_defaults = {
62
+ name: param.default for name, param in sig.parameters.items()
63
+ }
64
+ args = []
65
+ for p_name in param_defaults.keys():
66
+ if p_name in kwargs:
67
+ args.append(kwargs.pop(p_name))
68
+ elif param_defaults[p_name] is not inspect.Parameter.empty:
69
+ # Set arg to default value if it's not in kwargs. Useful for primitive types or args that default to None
70
+ args.append(param_defaults[p_name])
71
+ elif (
72
+ sig.parameters[p_name].kind is not inspect.Parameter.VAR_KEYWORD
73
+ ): # Skip **kwargs parameter
74
+ raise ValueError(f"Missing positional argument: {p_name}")
75
+
76
+ # Scan remaining kwargs for torch.Tensor
77
+ remaining_keys = list(kwargs.keys())
78
+ for key in remaining_keys:
79
+ if isinstance(kwargs[key], torch.Tensor):
80
+ # Remove the tensor from kwargs, assuming it's not required by the module.
81
+ # If it is required, the module's signature should be modified to accept it as a positional or keyword argument.
82
+ kwargs[key] = "_REMOVED_BY_ACT_CKPT_WRAPPER_"
83
+
84
+ ret = checkpoint.checkpoint(
85
+ module, *args, use_reentrant=use_reentrant, **kwargs
86
+ )
87
+ else:
88
+ ret = module(*args, **kwargs)
89
+
90
+ return ret
91
+
92
+ return act_ckpt_wrapper
93
+
94
+
95
+ def clone_output_wrapper(f: Callable[..., T]) -> Callable[..., T]:
96
+ """
97
+ Clone the CUDA output tensors of a function to avoid in-place operations.
98
+
99
+ This wrapper is useful when working with torch.compile to prevent errors
100
+ related to in-place operations on tensors.
101
+
102
+ Args:
103
+ f: The function whose CUDA tensor outputs should be cloned
104
+
105
+ Returns:
106
+ A wrapped function that clones any CUDA tensor outputs
107
+ """
108
+
109
+ @wraps(f)
110
+ def wrapped(*args, **kwargs):
111
+ outputs = f(*args, **kwargs)
112
+ return tree_map_only(
113
+ torch.Tensor, lambda t: t.clone() if t.is_cuda else t, outputs
114
+ )
115
+
116
+ return wrapped
third_party/GraspGen/sam3/sam3/model/box_ops.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ """
5
+ Utilities for bounding box manipulation and GIoU.
6
+ """
7
+
8
+ from typing import Tuple
9
+
10
+ import torch
11
+
12
+
13
+ def box_cxcywh_to_xyxy(x):
14
+ x_c, y_c, w, h = x.unbind(-1)
15
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
16
+ return torch.stack(b, dim=-1)
17
+
18
+
19
+ def box_cxcywh_to_xywh(x):
20
+ x_c, y_c, w, h = x.unbind(-1)
21
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (w), (h)]
22
+ return torch.stack(b, dim=-1)
23
+
24
+
25
+ def box_xywh_to_xyxy(x):
26
+ x, y, w, h = x.unbind(-1)
27
+ b = [(x), (y), (x + w), (y + h)]
28
+ return torch.stack(b, dim=-1)
29
+
30
+
31
+ def box_xywh_to_cxcywh(x):
32
+ x, y, w, h = x.unbind(-1)
33
+ b = [(x + 0.5 * w), (y + 0.5 * h), (w), (h)]
34
+ return torch.stack(b, dim=-1)
35
+
36
+
37
+ def box_xyxy_to_xywh(x):
38
+ x, y, X, Y = x.unbind(-1)
39
+ b = [(x), (y), (X - x), (Y - y)]
40
+ return torch.stack(b, dim=-1)
41
+
42
+
43
+ def box_xyxy_to_cxcywh(x):
44
+ x0, y0, x1, y1 = x.unbind(-1)
45
+ b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
46
+ return torch.stack(b, dim=-1)
47
+
48
+
49
+ def box_area(boxes):
50
+ """
51
+ Batched version of box area. Boxes should be in [x0, y0, x1, y1] format.
52
+
53
+ Inputs:
54
+ - boxes: Tensor of shape (..., 4)
55
+
56
+ Returns:
57
+ - areas: Tensor of shape (...,)
58
+ """
59
+ x0, y0, x1, y1 = boxes.unbind(-1)
60
+ return (x1 - x0) * (y1 - y0)
61
+
62
+
63
+ def masks_to_boxes(masks):
64
+ """Compute the bounding boxes around the provided masks
65
+
66
+ The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
67
+
68
+ Returns a [N, 4] tensors, with the boxes in xyxy format
69
+ """
70
+ if masks.numel() == 0:
71
+ return torch.zeros((0, 4), device=masks.device)
72
+
73
+ h, w = masks.shape[-2:]
74
+
75
+ y = torch.arange(0, h, dtype=torch.float, device=masks.device)
76
+ x = torch.arange(0, w, dtype=torch.float, device=masks.device)
77
+ y, x = torch.meshgrid(y, x)
78
+
79
+ x_mask = masks * x.unsqueeze(0)
80
+ x_max = x_mask.flatten(1).max(-1)[0] + 1
81
+ x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
82
+
83
+ y_mask = masks * y.unsqueeze(0)
84
+ y_max = y_mask.flatten(1).max(-1)[0] + 1
85
+ y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
86
+
87
+ boxes = torch.stack([x_min, y_min, x_max, y_max], 1)
88
+ # Invalidate boxes corresponding to empty masks.
89
+ boxes = boxes * masks.flatten(-2).any(-1)
90
+ return boxes
91
+
92
+
93
+ def box_iou(boxes1, boxes2):
94
+ """
95
+ Batched version of box_iou. Boxes should be in [x0, y0, x1, y1] format.
96
+
97
+ Inputs:
98
+ - boxes1: Tensor of shape (..., N, 4)
99
+ - boxes2: Tensor of shape (..., M, 4)
100
+
101
+ Returns:
102
+ - iou, union: Tensors of shape (..., N, M)
103
+ """
104
+ area1 = box_area(boxes1)
105
+ area2 = box_area(boxes2)
106
+
107
+ # boxes1: (..., N, 4) -> (..., N, 1, 2)
108
+ # boxes2: (..., M, 4) -> (..., 1, M, 2)
109
+ lt = torch.max(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
110
+ rb = torch.min(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
111
+
112
+ wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
113
+ inter = wh[..., 0] * wh[..., 1] # (..., N, M)
114
+
115
+ union = area1[..., None] + area2[..., None, :] - inter
116
+
117
+ iou = inter / union
118
+ return iou, union
119
+
120
+
121
+ def generalized_box_iou(boxes1, boxes2):
122
+ """
123
+ Batched version of Generalized IoU from https://giou.stanford.edu/
124
+
125
+ Boxes should be in [x0, y0, x1, y1] format
126
+
127
+ Inputs:
128
+ - boxes1: Tensor of shape (..., N, 4)
129
+ - boxes2: Tensor of shape (..., M, 4)
130
+
131
+ Returns:
132
+ - giou: Tensor of shape (..., N, M)
133
+ """
134
+ iou, union = box_iou(boxes1, boxes2)
135
+
136
+ # boxes1: (..., N, 4) -> (..., N, 1, 2)
137
+ # boxes2: (..., M, 4) -> (..., 1, M, 2)
138
+ lt = torch.min(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
139
+ rb = torch.max(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
140
+
141
+ wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
142
+ area = wh[..., 0] * wh[..., 1] # (..., N, M)
143
+
144
+ return iou - (area - union) / area
145
+
146
+
147
+ @torch.jit.script
148
+ def fast_diag_generalized_box_iou(boxes1, boxes2):
149
+ assert len(boxes1) == len(boxes2)
150
+ box1_xy = boxes1[:, 2:]
151
+ box1_XY = boxes1[:, :2]
152
+ box2_xy = boxes2[:, 2:]
153
+ box2_XY = boxes2[:, :2]
154
+ # assert (box1_xy >= box1_XY).all()
155
+ # assert (box2_xy >= box2_XY).all()
156
+ area1 = (box1_xy - box1_XY).prod(-1)
157
+ area2 = (box2_xy - box2_XY).prod(-1)
158
+
159
+ lt = torch.max(box1_XY, box2_XY) # [N,2]
160
+ lt2 = torch.min(box1_XY, box2_XY)
161
+ rb = torch.min(box1_xy, box2_xy) # [N,2]
162
+ rb2 = torch.max(box1_xy, box2_xy)
163
+
164
+ inter = (rb - lt).clamp(min=0).prod(-1)
165
+ tot_area = (rb2 - lt2).clamp(min=0).prod(-1)
166
+
167
+ union = area1 + area2 - inter
168
+
169
+ iou = inter / union
170
+
171
+ return iou - (tot_area - union) / tot_area
172
+
173
+
174
+ @torch.jit.script
175
+ def fast_diag_box_iou(boxes1, boxes2):
176
+ assert len(boxes1) == len(boxes2)
177
+ box1_xy = boxes1[:, 2:]
178
+ box1_XY = boxes1[:, :2]
179
+ box2_xy = boxes2[:, 2:]
180
+ box2_XY = boxes2[:, :2]
181
+ # assert (box1_xy >= box1_XY).all()
182
+ # assert (box2_xy >= box2_XY).all()
183
+ area1 = (box1_xy - box1_XY).prod(-1)
184
+ area2 = (box2_xy - box2_XY).prod(-1)
185
+
186
+ lt = torch.max(box1_XY, box2_XY) # [N,2]
187
+ rb = torch.min(box1_xy, box2_xy) # [N,2]
188
+
189
+ inter = (rb - lt).clamp(min=0).prod(-1)
190
+
191
+ union = area1 + area2 - inter
192
+
193
+ iou = inter / union
194
+
195
+ return iou
196
+
197
+
198
+ def box_xywh_inter_union(
199
+ boxes1: torch.Tensor, boxes2: torch.Tensor
200
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
201
+ # Asuumes boxes in xywh format
202
+ assert boxes1.size(-1) == 4 and boxes2.size(-1) == 4
203
+ boxes1 = box_xywh_to_xyxy(boxes1)
204
+ boxes2 = box_xywh_to_xyxy(boxes2)
205
+ box1_tl_xy = boxes1[..., :2]
206
+ box1_br_xy = boxes1[..., 2:]
207
+ box2_tl_xy = boxes2[..., :2]
208
+ box2_br_xy = boxes2[..., 2:]
209
+ area1 = (box1_br_xy - box1_tl_xy).prod(-1)
210
+ area2 = (box2_br_xy - box2_tl_xy).prod(-1)
211
+
212
+ assert (area1 >= 0).all() and (area2 >= 0).all()
213
+ tl = torch.max(box1_tl_xy, box2_tl_xy)
214
+ br = torch.min(box1_br_xy, box2_br_xy)
215
+
216
+ inter = (br - tl).clamp(min=0).prod(-1)
217
+ union = area1 + area2 - inter
218
+
219
+ return inter, union
third_party/GraspGen/sam3/sam3/model/data_misc.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ """
5
+ Misc functions, including distributed helpers.
6
+ """
7
+
8
+ import collections
9
+ import re
10
+ from dataclasses import dataclass, field as field_ptr_behaviour, fields, is_dataclass
11
+ from typing import Any, get_args, get_origin, List, Mapping, Optional, Sequence, Union
12
+
13
+ import torch
14
+
15
+
16
+ MyTensor = Union[torch.Tensor, List[Any]]
17
+
18
+
19
+ def interpolate(
20
+ input, size=None, scale_factor=None, mode="nearest", align_corners=None
21
+ ):
22
+ # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
23
+ """
24
+ Equivalent to nn.functional.interpolate, but with support for empty channel sizes.
25
+ """
26
+ if input.numel() > 0:
27
+ return torch.nn.functional.interpolate(
28
+ input, size, scale_factor, mode, align_corners
29
+ )
30
+
31
+ assert input.shape[0] != 0 or input.shape[1] != 0, (
32
+ "At least one of the two first dimensions must be non zero"
33
+ )
34
+
35
+ if input.shape[1] == 0:
36
+ # Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim
37
+ return torch.nn.functional.interpolate(
38
+ input.transpose(0, 1), size, scale_factor, mode, align_corners
39
+ ).transpose(0, 1)
40
+
41
+ # empty batch dimension is now supported in pytorch
42
+ return torch.nn.functional.interpolate(
43
+ input, size, scale_factor, mode, align_corners
44
+ )
45
+
46
+
47
+ @dataclass
48
+ class BatchedPointer:
49
+ stage_ids: MyTensor
50
+ stage_ids__type = torch.long
51
+ query_ids: MyTensor
52
+ query_ids__type = torch.long
53
+ object_ids: MyTensor
54
+ object_ids__type = torch.long
55
+ ptr_mask: MyTensor
56
+ ptr_mask__type = torch.bool
57
+ ptr_types: MyTensor
58
+ ptr_types__type = torch.long
59
+
60
+
61
+ @dataclass
62
+ class FindStage:
63
+ img_ids: MyTensor
64
+ img_ids__type = torch.long
65
+ text_ids: MyTensor
66
+ text_ids__type = torch.long
67
+
68
+ input_boxes: MyTensor
69
+ input_boxes__type = torch.float
70
+ input_boxes_mask: MyTensor
71
+ input_boxes_mask__type = torch.bool
72
+ input_boxes_label: MyTensor
73
+ input_boxes_label__type = torch.long
74
+
75
+ input_points: MyTensor
76
+ input_points__type = torch.float
77
+ input_points_mask: MyTensor
78
+ input_points_mask__type = torch.bool
79
+
80
+ # We track the object ids referred to by this query.
81
+ # This is beneficial for tracking in videos without the need for pointers.
82
+ object_ids: Optional[List[List]] = None # List of objects per query
83
+
84
+
85
+ @dataclass
86
+ class BatchedFindTarget:
87
+ # The number of boxes in each find query
88
+ num_boxes: MyTensor
89
+ num_boxes__type = torch.long
90
+
91
+ # Target boxes in normalized CxCywh format
92
+ boxes: MyTensor
93
+ boxes__type = torch.float
94
+ # Target boxes in normalized CxCywh format but in padded representation
95
+ # as used in BinaryHungarianMatcherV2 (unlike the packed ones in `boxes`)
96
+ boxes_padded: MyTensor
97
+ boxes_padded__type = torch.float
98
+
99
+ # For hybrid matching, we repeat the boxes
100
+ repeated_boxes: MyTensor
101
+ repeated_boxes__type = torch.float
102
+
103
+ # Target Segmentation masks
104
+ segments: Optional[MyTensor]
105
+ segments__type = torch.bool
106
+
107
+ # Target Semantic Segmentation masks
108
+ semantic_segments: Optional[MyTensor]
109
+ semantic_segments__type = torch.bool
110
+
111
+ is_valid_segment: Optional[MyTensor]
112
+ is_valid_segment__type = torch.bool
113
+
114
+ # Whether annotations are exhaustive for each query
115
+ is_exhaustive: MyTensor
116
+ is_exhaustive__type = torch.bool
117
+
118
+ # The object id for each ground-truth box, in both packed and padded representations
119
+ object_ids: MyTensor
120
+ object_ids__type = torch.long
121
+ object_ids_padded: MyTensor
122
+ object_ids_padded__type = torch.long
123
+
124
+
125
+ @dataclass
126
+ class BatchedInferenceMetadata:
127
+ """All metadata required to post-process a find stage"""
128
+
129
+ # Coco id that corresponds to the "image" for evaluation by the coco evaluator
130
+ coco_image_id: MyTensor
131
+ coco_image_id__type = torch.long
132
+
133
+ # id in the original dataset, such that we can use the original evaluator
134
+ original_image_id: MyTensor
135
+ original_image_id__type = torch.long
136
+
137
+ # Original category id (if we want to use the original evaluator)
138
+ original_category_id: MyTensor
139
+ original_category_id__type = torch.int
140
+
141
+ # Size of the raw image (height, width)
142
+ original_size: MyTensor
143
+ original_size__type = torch.long
144
+
145
+ # id of the object in the media (track_id for a video)
146
+ object_id: MyTensor
147
+ object_id__type = torch.long
148
+
149
+ # index of the frame in the media (0 in the case of a single-frame media)
150
+ frame_index: MyTensor
151
+ frame_index__type = torch.long
152
+
153
+ # Adding for relations inference
154
+ # get_text_input: List[Optional[str]]
155
+
156
+ # Adding for TA conditional inference
157
+ is_conditioning_only: List[Optional[bool]]
158
+
159
+
160
+ @dataclass
161
+ class BatchedDatapoint:
162
+ img_batch: torch.Tensor
163
+ find_text_batch: List[str]
164
+ find_inputs: List[FindStage]
165
+ find_targets: List[BatchedFindTarget]
166
+ find_metadatas: List[BatchedInferenceMetadata]
167
+ raw_images: Optional[List[Any]] = None
168
+
169
+
170
+ def convert_my_tensors(obj):
171
+ def is_optional_field(field) -> bool:
172
+ return get_origin(field) is Union and type(None) in get_args(field)
173
+
174
+ for field in fields(obj):
175
+ if is_dataclass(getattr(obj, field.name)):
176
+ convert_my_tensors(getattr(obj, field.name))
177
+ continue
178
+
179
+ field_type = field.type
180
+ if is_optional_field(field.type):
181
+ field_type = Union[get_args(field.type)[:-1]] # Get the Optional field type
182
+
183
+ if field_type != MyTensor or getattr(obj, field.name) is None:
184
+ continue
185
+
186
+ elif len(getattr(obj, field.name)) and isinstance(
187
+ getattr(obj, field.name)[0], torch.Tensor
188
+ ):
189
+ stack_dim = 0
190
+ if field.name in [
191
+ "input_boxes",
192
+ "input_boxes_label",
193
+ ]:
194
+ stack_dim = 1
195
+ setattr(
196
+ obj,
197
+ field.name,
198
+ torch.stack(getattr(obj, field.name), dim=stack_dim).to(
199
+ getattr(obj, field.name + "__type")
200
+ ),
201
+ )
202
+ else:
203
+ setattr(
204
+ obj,
205
+ field.name,
206
+ torch.as_tensor(
207
+ getattr(obj, field.name), dtype=getattr(obj, field.name + "__type")
208
+ ),
209
+ )
210
+ return obj
third_party/GraspGen/sam3/sam3/model/decoder.py ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ """
5
+ Transformer decoder.
6
+ Inspired from Pytorch's version, adds the pre-norm variant
7
+ """
8
+
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ import numpy as np
12
+ import torch
13
+ from sam3.sam.transformer import RoPEAttention
14
+ from torch import nn, Tensor
15
+ from torchvision.ops.roi_align import RoIAlign
16
+
17
+ from .act_ckpt_utils import activation_ckpt_wrapper
18
+ from .box_ops import box_cxcywh_to_xyxy
19
+ from .model_misc import (
20
+ gen_sineembed_for_position,
21
+ get_activation_fn,
22
+ get_clones,
23
+ inverse_sigmoid,
24
+ MLP,
25
+ )
26
+
27
+
28
+ class TransformerDecoderLayer(nn.Module):
29
+ def __init__(
30
+ self,
31
+ activation: str,
32
+ d_model: int,
33
+ dim_feedforward: int,
34
+ dropout: float,
35
+ cross_attention: nn.Module,
36
+ n_heads: int,
37
+ use_text_cross_attention: bool = False,
38
+ ):
39
+ super().__init__()
40
+
41
+ # cross attention
42
+ self.cross_attn = cross_attention
43
+ self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
44
+ self.norm1 = nn.LayerNorm(d_model)
45
+
46
+ # cross attention text
47
+ self.use_text_cross_attention = use_text_cross_attention
48
+ if use_text_cross_attention:
49
+ self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
50
+ self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
51
+ self.catext_norm = nn.LayerNorm(d_model)
52
+
53
+ # self attention
54
+ self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
55
+ self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
56
+ self.norm2 = nn.LayerNorm(d_model)
57
+
58
+ # ffn
59
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
60
+ self.activation = get_activation_fn(activation)
61
+ self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
62
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
63
+ self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
64
+ self.norm3 = nn.LayerNorm(d_model)
65
+
66
+ @staticmethod
67
+ def with_pos_embed(tensor, pos):
68
+ return tensor if pos is None else tensor + pos
69
+
70
+ def forward_ffn(self, tgt):
71
+ with torch.amp.autocast(device_type="cuda", enabled=False):
72
+ tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
73
+ tgt = tgt + self.dropout4(tgt2)
74
+ tgt = self.norm3(tgt)
75
+ return tgt
76
+
77
+ def forward(
78
+ self,
79
+ # for tgt
80
+ tgt: Optional[Tensor], # nq, bs, d_model
81
+ tgt_query_pos: Optional[Tensor] = None, # pos for query. MLP(Sine(pos))
82
+ tgt_query_sine_embed: Optional[Tensor] = None, # pos for query. Sine(pos)
83
+ tgt_key_padding_mask: Optional[Tensor] = None,
84
+ tgt_reference_points: Optional[Tensor] = None, # nq, bs, 4
85
+ memory_text: Optional[Tensor] = None, # num_token, bs, d_model
86
+ text_attention_mask: Optional[Tensor] = None, # bs, num_token
87
+ # for memory
88
+ memory: Optional[Tensor] = None, # hw, bs, d_model
89
+ memory_key_padding_mask: Optional[Tensor] = None,
90
+ memory_level_start_index: Optional[Tensor] = None, # num_levels
91
+ memory_spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
92
+ memory_pos: Optional[Tensor] = None, # pos for memory
93
+ # sa
94
+ self_attn_mask: Optional[Tensor] = None, # mask used for self-attention
95
+ cross_attn_mask: Optional[Tensor] = None, # mask used for cross-attention
96
+ # dac
97
+ dac=False,
98
+ dac_use_selfatt_ln=True,
99
+ presence_token=None,
100
+ # skip inside deformable attn
101
+ identity=0.0,
102
+ **kwargs, # additional kwargs for compatibility
103
+ ):
104
+ """
105
+ Input:
106
+ - tgt/tgt_query_pos: nq, bs, d_model
107
+ -
108
+ """
109
+ # self attention
110
+ if self.self_attn is not None:
111
+ if dac:
112
+ # we only apply self attention to the first half of the queries
113
+ assert tgt.shape[0] % 2 == 0
114
+ num_o2o_queries = tgt.shape[0] // 2
115
+ tgt_o2o = tgt[:num_o2o_queries]
116
+ tgt_query_pos_o2o = tgt_query_pos[:num_o2o_queries]
117
+ tgt_o2m = tgt[num_o2o_queries:]
118
+ else:
119
+ tgt_o2o = tgt
120
+ tgt_query_pos_o2o = tgt_query_pos
121
+
122
+ if presence_token is not None:
123
+ tgt_o2o = torch.cat([presence_token, tgt_o2o], dim=0)
124
+ tgt_query_pos_o2o = torch.cat(
125
+ [torch.zeros_like(presence_token), tgt_query_pos_o2o], dim=0
126
+ )
127
+ tgt_query_pos = torch.cat(
128
+ [torch.zeros_like(presence_token), tgt_query_pos], dim=0
129
+ )
130
+
131
+ q = k = self.with_pos_embed(tgt_o2o, tgt_query_pos_o2o)
132
+ tgt2 = self.self_attn(q, k, tgt_o2o, attn_mask=self_attn_mask)[0]
133
+ tgt_o2o = tgt_o2o + self.dropout2(tgt2)
134
+ if dac:
135
+ if not dac_use_selfatt_ln:
136
+ tgt_o2o = self.norm2(tgt_o2o)
137
+ tgt = torch.cat((tgt_o2o, tgt_o2m), dim=0) # Recombine
138
+ if dac_use_selfatt_ln:
139
+ tgt = self.norm2(tgt)
140
+ else:
141
+ tgt = tgt_o2o
142
+ tgt = self.norm2(tgt)
143
+
144
+ if self.use_text_cross_attention:
145
+ tgt2 = self.ca_text(
146
+ self.with_pos_embed(tgt, tgt_query_pos),
147
+ memory_text,
148
+ memory_text,
149
+ key_padding_mask=text_attention_mask,
150
+ )[0]
151
+ tgt = tgt + self.catext_dropout(tgt2)
152
+ tgt = self.catext_norm(tgt)
153
+
154
+ if presence_token is not None:
155
+ presence_token_mask = torch.zeros_like(cross_attn_mask[:, :1, :])
156
+ cross_attn_mask = torch.cat(
157
+ [presence_token_mask, cross_attn_mask], dim=1
158
+ ) # (bs*nheads, 1+nq, hw)
159
+
160
+ # Cross attention to image
161
+ tgt2 = self.cross_attn(
162
+ query=self.with_pos_embed(tgt, tgt_query_pos),
163
+ key=self.with_pos_embed(memory, memory_pos),
164
+ value=memory,
165
+ attn_mask=cross_attn_mask,
166
+ key_padding_mask=(
167
+ memory_key_padding_mask.transpose(0, 1)
168
+ if memory_key_padding_mask is not None
169
+ else None
170
+ ),
171
+ )[0]
172
+
173
+ tgt = tgt + self.dropout1(tgt2)
174
+ tgt = self.norm1(tgt)
175
+
176
+ # ffn
177
+ tgt = self.forward_ffn(tgt)
178
+
179
+ presence_token_out = None
180
+ if presence_token is not None:
181
+ presence_token_out = tgt[:1]
182
+ tgt = tgt[1:]
183
+
184
+ return tgt, presence_token_out
185
+
186
+
187
+ class TransformerDecoder(nn.Module):
188
+ def __init__(
189
+ self,
190
+ d_model: int,
191
+ frozen: bool,
192
+ interaction_layer,
193
+ layer,
194
+ num_layers: int,
195
+ num_queries: int,
196
+ return_intermediate: bool,
197
+ box_refine: bool = False,
198
+ num_o2m_queries: int = 0,
199
+ dac: bool = False,
200
+ boxRPB: str = "none",
201
+ # Experimental: An object query for SAM 2 tasks
202
+ instance_query: bool = False,
203
+ # Defines the number of additional instance queries,
204
+ # 1 or 4 are the most likely for single vs multi mask support
205
+ num_instances: int = 1, # Irrelevant if instance_query is False
206
+ dac_use_selfatt_ln: bool = True,
207
+ use_act_checkpoint: bool = False,
208
+ compile_mode=None,
209
+ presence_token: bool = False,
210
+ clamp_presence_logits: bool = True,
211
+ clamp_presence_logit_max_val: float = 10.0,
212
+ use_normed_output_consistently: bool = True,
213
+ separate_box_head_instance: bool = False,
214
+ separate_norm_instance: bool = False,
215
+ resolution: Optional[int] = None,
216
+ stride: Optional[int] = None,
217
+ ):
218
+ super().__init__()
219
+ self.d_model = d_model
220
+ self.layers = get_clones(layer, num_layers)
221
+ self.fine_layers = (
222
+ get_clones(interaction_layer, num_layers)
223
+ if interaction_layer is not None
224
+ else [None] * num_layers
225
+ )
226
+ self.num_layers = num_layers
227
+ self.num_queries = num_queries
228
+ self.dac = dac
229
+ if dac:
230
+ self.num_o2m_queries = num_queries
231
+ tot_num_queries = num_queries
232
+ else:
233
+ self.num_o2m_queries = num_o2m_queries
234
+ tot_num_queries = num_queries + num_o2m_queries
235
+ self.norm = nn.LayerNorm(d_model)
236
+ self.return_intermediate = return_intermediate
237
+ self.bbox_embed = MLP(d_model, d_model, 4, 3)
238
+ self.query_embed = nn.Embedding(tot_num_queries, d_model)
239
+ self.instance_query_embed = None
240
+ self.instance_query_reference_points = None
241
+ self.use_instance_query = instance_query
242
+ self.num_instances = num_instances
243
+ self.use_normed_output_consistently = use_normed_output_consistently
244
+
245
+ self.instance_norm = nn.LayerNorm(d_model) if separate_norm_instance else None
246
+ self.instance_bbox_embed = None
247
+ if separate_box_head_instance:
248
+ self.instance_bbox_embed = MLP(d_model, d_model, 4, 3)
249
+ if instance_query:
250
+ self.instance_query_embed = nn.Embedding(num_instances, d_model)
251
+ self.box_refine = box_refine
252
+ if box_refine:
253
+ nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
254
+ nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
255
+
256
+ self.reference_points = nn.Embedding(num_queries, 4)
257
+ if instance_query:
258
+ self.instance_reference_points = nn.Embedding(num_instances, 4)
259
+
260
+ assert boxRPB in ["none", "log", "linear", "both"]
261
+ self.boxRPB = boxRPB
262
+ if boxRPB != "none":
263
+ try:
264
+ nheads = self.layers[0].cross_attn_image.num_heads
265
+ except AttributeError:
266
+ nheads = self.layers[0].cross_attn.num_heads
267
+
268
+ n_input = 4 if boxRPB == "both" else 2
269
+ self.boxRPB_embed_x = MLP(n_input, d_model, nheads, 2)
270
+ self.boxRPB_embed_y = MLP(n_input, d_model, nheads, 2)
271
+ self.compilable_cord_cache = None
272
+ self.compilable_stored_size = None
273
+ self.coord_cache = {}
274
+
275
+ if resolution is not None and stride is not None:
276
+ feat_size = resolution // stride
277
+ coords_h, coords_w = self._get_coords(
278
+ feat_size, feat_size, device="cuda"
279
+ )
280
+ self.compilable_cord_cache = (coords_h, coords_w)
281
+ self.compilable_stored_size = (feat_size, feat_size)
282
+
283
+ self.roi_pooler = (
284
+ RoIAlign(output_size=7, spatial_scale=1, sampling_ratio=-1, aligned=True)
285
+ if interaction_layer is not None
286
+ else None
287
+ )
288
+ if frozen:
289
+ for p in self.parameters():
290
+ p.requires_grad_(False)
291
+
292
+ self.presence_token = None
293
+ self.clamp_presence_logits = clamp_presence_logits
294
+ self.clamp_presence_logit_max_val = clamp_presence_logit_max_val
295
+ if presence_token:
296
+ self.presence_token = nn.Embedding(1, d_model)
297
+ self.presence_token_head = MLP(d_model, d_model, 1, 3)
298
+ self.presence_token_out_norm = nn.LayerNorm(d_model)
299
+
300
+ self.ref_point_head = MLP(2 * self.d_model, self.d_model, self.d_model, 2)
301
+ self.dac_use_selfatt_ln = dac_use_selfatt_ln
302
+ self.use_act_checkpoint = use_act_checkpoint
303
+
304
+ nn.init.normal_(self.query_embed.weight.data)
305
+ if self.instance_query_embed is not None:
306
+ nn.init.normal_(self.instance_query_embed.weight.data)
307
+
308
+ assert self.roi_pooler is None
309
+ assert self.return_intermediate, "support return_intermediate only"
310
+ assert self.box_refine, "support box refine only"
311
+
312
+ self.compile_mode = compile_mode
313
+ self.compiled = False
314
+ # We defer compilation till after the first forward, to first warm-up the boxRPB cache
315
+
316
+ # assign layer index to each layer so that some layers can decide what to do
317
+ # based on which layer index they are (e.g. cross attention to memory bank only
318
+ # in selected layers)
319
+ for layer_idx, layer in enumerate(self.layers):
320
+ layer.layer_idx = layer_idx
321
+
322
+ @staticmethod
323
+ def _get_coords(H, W, device):
324
+ coords_h = torch.arange(0, H, device=device, dtype=torch.float32) / H
325
+ coords_w = torch.arange(0, W, device=device, dtype=torch.float32) / W
326
+ return coords_h, coords_w
327
+
328
+ def _get_rpb_matrix(self, reference_boxes, feat_size):
329
+ H, W = feat_size
330
+ boxes_xyxy = box_cxcywh_to_xyxy(reference_boxes).transpose(0, 1)
331
+ bs, num_queries, _ = boxes_xyxy.shape
332
+ if self.compilable_cord_cache is None:
333
+ self.compilable_cord_cache = self._get_coords(H, W, reference_boxes.device)
334
+ self.compilable_stored_size = (H, W)
335
+
336
+ if torch.compiler.is_dynamo_compiling() or self.compilable_stored_size == (
337
+ H,
338
+ W,
339
+ ):
340
+ # good, hitting the cache, will be compilable
341
+ coords_h, coords_w = self.compilable_cord_cache
342
+ else:
343
+ # cache miss, will create compilation issue
344
+ # In case we're not compiling, we'll still rely on the dict-based cache
345
+ if feat_size not in self.coord_cache:
346
+ self.coord_cache[feat_size] = self._get_coords(
347
+ H, W, reference_boxes.device
348
+ )
349
+ coords_h, coords_w = self.coord_cache[feat_size]
350
+
351
+ assert coords_h.shape == (H,)
352
+ assert coords_w.shape == (W,)
353
+
354
+ deltas_y = coords_h.view(1, -1, 1) - boxes_xyxy.reshape(-1, 1, 4)[:, :, 1:4:2]
355
+ deltas_y = deltas_y.view(bs, num_queries, -1, 2)
356
+ deltas_x = coords_w.view(1, -1, 1) - boxes_xyxy.reshape(-1, 1, 4)[:, :, 0:3:2]
357
+ deltas_x = deltas_x.view(bs, num_queries, -1, 2)
358
+
359
+ if self.boxRPB in ["log", "both"]:
360
+ deltas_x_log = deltas_x * 8 # normalize to -8, 8
361
+ deltas_x_log = (
362
+ torch.sign(deltas_x_log)
363
+ * torch.log2(torch.abs(deltas_x_log) + 1.0)
364
+ / np.log2(8)
365
+ )
366
+
367
+ deltas_y_log = deltas_y * 8 # normalize to -8, 8
368
+ deltas_y_log = (
369
+ torch.sign(deltas_y_log)
370
+ * torch.log2(torch.abs(deltas_y_log) + 1.0)
371
+ / np.log2(8)
372
+ )
373
+ if self.boxRPB == "log":
374
+ deltas_x = deltas_x_log
375
+ deltas_y = deltas_y_log
376
+ else:
377
+ deltas_x = torch.cat([deltas_x, deltas_x_log], dim=-1)
378
+ deltas_y = torch.cat([deltas_y, deltas_y_log], dim=-1)
379
+
380
+ if self.training:
381
+ assert self.use_act_checkpoint, "activation ckpt not enabled in decoder"
382
+ deltas_x = activation_ckpt_wrapper(self.boxRPB_embed_x)(
383
+ x=deltas_x,
384
+ act_ckpt_enable=self.training and self.use_act_checkpoint,
385
+ ) # bs, num_queries, W, n_heads
386
+ deltas_y = activation_ckpt_wrapper(self.boxRPB_embed_y)(
387
+ x=deltas_y,
388
+ act_ckpt_enable=self.training and self.use_act_checkpoint,
389
+ ) # bs, num_queries, H, n_heads
390
+
391
+ if not torch.compiler.is_dynamo_compiling():
392
+ assert deltas_x.shape[:3] == (bs, num_queries, W)
393
+ assert deltas_y.shape[:3] == (bs, num_queries, H)
394
+
395
+ B = deltas_y.unsqueeze(3) + deltas_x.unsqueeze(
396
+ 2
397
+ ) # bs, num_queries, H, W, n_heads
398
+ if not torch.compiler.is_dynamo_compiling():
399
+ assert B.shape[:4] == (bs, num_queries, H, W)
400
+ B = B.flatten(2, 3) # bs, num_queries, H*W, n_heads
401
+ B = B.permute(0, 3, 1, 2) # bs, n_heads, num_queries, H*W
402
+ B = B.contiguous() # memeff attn likes ordered strides
403
+ if not torch.compiler.is_dynamo_compiling():
404
+ assert B.shape[2:] == (num_queries, H * W)
405
+ return B
406
+
407
+ def forward(
408
+ self,
409
+ tgt,
410
+ memory,
411
+ tgt_mask: Optional[Tensor] = None,
412
+ memory_mask: Optional[Tensor] = None,
413
+ tgt_key_padding_mask: Optional[Tensor] = None,
414
+ memory_key_padding_mask: Optional[Tensor] = None,
415
+ pos: Optional[Tensor] = None,
416
+ reference_boxes: Optional[Tensor] = None, # num_queries, bs, 4
417
+ # for memory
418
+ level_start_index: Optional[Tensor] = None, # num_levels
419
+ spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
420
+ valid_ratios: Optional[Tensor] = None,
421
+ # for text
422
+ memory_text: Optional[Tensor] = None,
423
+ text_attention_mask: Optional[Tensor] = None,
424
+ # if `apply_dac` is None, it will default to `self.dac`
425
+ apply_dac: Optional[bool] = None,
426
+ is_instance_prompt=False,
427
+ decoder_extra_kwargs: Optional[Dict] = None,
428
+ # ROI memory bank
429
+ obj_roi_memory_feat=None,
430
+ obj_roi_memory_mask=None,
431
+ box_head_trk=None,
432
+ ):
433
+ """
434
+ Input:
435
+ - tgt: nq, bs, d_model
436
+ - memory: \\sum{hw}, bs, d_model
437
+ - pos: \\sum{hw}, bs, d_model
438
+ - reference_boxes: nq, bs, 4 (after sigmoid)
439
+ - valid_ratios/spatial_shapes: bs, nlevel, 2
440
+ """
441
+ if memory_mask is not None:
442
+ assert self.boxRPB == "none", (
443
+ "inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
444
+ )
445
+
446
+ apply_dac = apply_dac if apply_dac is not None else self.dac
447
+ if apply_dac:
448
+ assert (tgt.shape[0] == self.num_queries) or (
449
+ self.use_instance_query
450
+ and (tgt.shape[0] == self.instance_query_embed.num_embeddings)
451
+ )
452
+
453
+ tgt = tgt.repeat(2, 1, 1)
454
+ # note that we don't tile tgt_mask, since DAC doesn't
455
+ # use self-attention in o2m queries
456
+ if reference_boxes is not None:
457
+ assert (reference_boxes.shape[0] == self.num_queries) or (
458
+ self.use_instance_query
459
+ and (
460
+ reference_boxes.shape[0]
461
+ == self.instance_query_embed.num_embeddings
462
+ )
463
+ )
464
+ reference_boxes = reference_boxes.repeat(2, 1, 1)
465
+
466
+ bs = tgt.shape[1]
467
+ intermediate = []
468
+ intermediate_presence_logits = []
469
+ presence_feats = None
470
+
471
+ if self.box_refine:
472
+ if reference_boxes is None:
473
+ # In this case, we're in a one-stage model, so we generate the reference boxes
474
+ reference_boxes = self.reference_points.weight.unsqueeze(1)
475
+ reference_boxes = (
476
+ reference_boxes.repeat(2, bs, 1)
477
+ if apply_dac
478
+ else reference_boxes.repeat(1, bs, 1)
479
+ )
480
+ reference_boxes = reference_boxes.sigmoid()
481
+ intermediate_ref_boxes = [reference_boxes]
482
+ else:
483
+ reference_boxes = None
484
+ intermediate_ref_boxes = None
485
+
486
+ output = tgt
487
+ presence_out = None
488
+ if self.presence_token is not None and is_instance_prompt is False:
489
+ # expand to batch dim
490
+ presence_out = self.presence_token.weight[None].expand(1, bs, -1)
491
+
492
+ box_head = self.bbox_embed
493
+ if is_instance_prompt and self.instance_bbox_embed is not None:
494
+ box_head = self.instance_bbox_embed
495
+
496
+ out_norm = self.norm
497
+ if is_instance_prompt and self.instance_norm is not None:
498
+ out_norm = self.instance_norm
499
+
500
+ for layer_idx, layer in enumerate(self.layers):
501
+ reference_points_input = (
502
+ reference_boxes[:, :, None]
503
+ * torch.cat([valid_ratios, valid_ratios], -1)[None, :]
504
+ ) # nq, bs, nlevel, 4
505
+
506
+ query_sine_embed = gen_sineembed_for_position(
507
+ reference_points_input[:, :, 0, :], self.d_model
508
+ ) # nq, bs, d_model*2
509
+
510
+ # conditional query
511
+ query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
512
+
513
+ if self.boxRPB != "none" and reference_boxes is not None:
514
+ assert spatial_shapes.shape[0] == 1, (
515
+ "only single scale support implemented"
516
+ )
517
+ memory_mask = self._get_rpb_matrix(
518
+ reference_boxes,
519
+ (spatial_shapes[0, 0], spatial_shapes[0, 1]),
520
+ )
521
+ memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
522
+ if self.training:
523
+ assert self.use_act_checkpoint, (
524
+ "Activation checkpointing not enabled in the decoder"
525
+ )
526
+ output, presence_out = activation_ckpt_wrapper(layer)(
527
+ tgt=output,
528
+ tgt_query_pos=query_pos,
529
+ tgt_query_sine_embed=query_sine_embed,
530
+ tgt_key_padding_mask=tgt_key_padding_mask,
531
+ tgt_reference_points=reference_points_input,
532
+ memory_text=memory_text,
533
+ text_attention_mask=text_attention_mask,
534
+ memory=memory,
535
+ memory_key_padding_mask=memory_key_padding_mask,
536
+ memory_level_start_index=level_start_index,
537
+ memory_spatial_shapes=spatial_shapes,
538
+ memory_pos=pos,
539
+ self_attn_mask=tgt_mask,
540
+ cross_attn_mask=memory_mask,
541
+ dac=apply_dac,
542
+ dac_use_selfatt_ln=self.dac_use_selfatt_ln,
543
+ presence_token=presence_out,
544
+ **(decoder_extra_kwargs or {}),
545
+ act_ckpt_enable=self.training and self.use_act_checkpoint,
546
+ # ROI memory bank
547
+ obj_roi_memory_feat=obj_roi_memory_feat,
548
+ obj_roi_memory_mask=obj_roi_memory_mask,
549
+ )
550
+
551
+ # iter update
552
+ if self.box_refine:
553
+ reference_before_sigmoid = inverse_sigmoid(reference_boxes)
554
+ if box_head_trk is None:
555
+ # delta_unsig = self.bbox_embed(output)
556
+ if not self.use_normed_output_consistently:
557
+ delta_unsig = box_head(output)
558
+ else:
559
+ delta_unsig = box_head(out_norm(output))
560
+ else:
561
+ # box_head_trk use a separate box head for tracking queries
562
+ Q_det = decoder_extra_kwargs["Q_det"]
563
+ assert output.size(0) >= Q_det
564
+ delta_unsig_det = self.bbox_embed(output[:Q_det])
565
+ delta_unsig_trk = box_head_trk(output[Q_det:])
566
+ delta_unsig = torch.cat([delta_unsig_det, delta_unsig_trk], dim=0)
567
+ outputs_unsig = delta_unsig + reference_before_sigmoid
568
+ new_reference_points = outputs_unsig.sigmoid()
569
+
570
+ reference_boxes = new_reference_points.detach()
571
+ if layer_idx != self.num_layers - 1:
572
+ intermediate_ref_boxes.append(new_reference_points)
573
+ else:
574
+ raise NotImplementedError("not implemented yet")
575
+
576
+ intermediate.append(out_norm(output))
577
+ if self.presence_token is not None and is_instance_prompt is False:
578
+ # norm, mlp head
579
+ intermediate_layer_presence_logits = self.presence_token_head(
580
+ self.presence_token_out_norm(presence_out)
581
+ ).squeeze(-1)
582
+
583
+ # clamp to mitigate numerical issues
584
+ if self.clamp_presence_logits:
585
+ intermediate_layer_presence_logits.clamp(
586
+ min=-self.clamp_presence_logit_max_val,
587
+ max=self.clamp_presence_logit_max_val,
588
+ )
589
+
590
+ intermediate_presence_logits.append(intermediate_layer_presence_logits)
591
+ presence_feats = presence_out.clone()
592
+
593
+ if not self.compiled and self.compile_mode is not None:
594
+ self.forward = torch.compile(
595
+ self.forward, mode=self.compile_mode, fullgraph=True
596
+ )
597
+ self.compiled = True
598
+
599
+ return (
600
+ torch.stack(intermediate),
601
+ torch.stack(intermediate_ref_boxes),
602
+ (
603
+ torch.stack(intermediate_presence_logits)
604
+ if self.presence_token is not None and is_instance_prompt is False
605
+ else None
606
+ ),
607
+ presence_feats,
608
+ )
609
+
610
+
611
+ class TransformerEncoderCrossAttention(nn.Module):
612
+ def __init__(
613
+ self,
614
+ d_model: int,
615
+ frozen: bool,
616
+ pos_enc_at_input: bool,
617
+ layer,
618
+ num_layers: int,
619
+ use_act_checkpoint: bool = False,
620
+ batch_first: bool = False, # Do layers expect batch first input?
621
+ # which layers to exclude cross attention? default: None, means all
622
+ # layers use cross attention
623
+ remove_cross_attention_layers: Optional[list] = None,
624
+ ):
625
+ super().__init__()
626
+ self.d_model = d_model
627
+ self.layers = get_clones(layer, num_layers)
628
+ self.num_layers = num_layers
629
+ self.norm = nn.LayerNorm(d_model)
630
+ self.pos_enc_at_input = pos_enc_at_input
631
+ self.use_act_checkpoint = use_act_checkpoint
632
+
633
+ if frozen:
634
+ for p in self.parameters():
635
+ p.requires_grad_(False)
636
+
637
+ self.batch_first = batch_first
638
+
639
+ # remove cross attention layers if specified
640
+ self.remove_cross_attention_layers = [False] * self.num_layers
641
+ if remove_cross_attention_layers is not None:
642
+ for i in remove_cross_attention_layers:
643
+ self.remove_cross_attention_layers[i] = True
644
+ assert len(self.remove_cross_attention_layers) == len(self.layers)
645
+
646
+ for i, remove_cross_attention in enumerate(self.remove_cross_attention_layers):
647
+ if remove_cross_attention:
648
+ self.layers[i].cross_attn_image = None
649
+ self.layers[i].norm2 = None
650
+ self.layers[i].dropout2 = None
651
+
652
+ def forward(
653
+ self,
654
+ src, # self-attention inputs
655
+ prompt, # cross-attention inputs
656
+ src_mask: Optional[Tensor] = None, # att.mask for self-attention inputs
657
+ prompt_mask: Optional[Tensor] = None, # att.mask for cross-attention inputs
658
+ src_key_padding_mask: Optional[Tensor] = None,
659
+ prompt_key_padding_mask: Optional[Tensor] = None,
660
+ src_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
661
+ prompt_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
662
+ feat_sizes: Optional[list] = None,
663
+ num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
664
+ ):
665
+ if isinstance(src, list):
666
+ assert isinstance(src_key_padding_mask, list) and isinstance(src_pos, list)
667
+ assert len(src) == len(src_key_padding_mask) == len(src_pos) == 1
668
+ src, src_key_padding_mask, src_pos = (
669
+ src[0],
670
+ src_key_padding_mask[0],
671
+ src_pos[0],
672
+ )
673
+
674
+ assert src.shape[1] == prompt.shape[1], (
675
+ "Batch size must be the same for src and prompt"
676
+ )
677
+
678
+ output = src
679
+
680
+ if self.pos_enc_at_input and src_pos is not None:
681
+ output = output + 0.1 * src_pos
682
+
683
+ if self.batch_first:
684
+ # Convert to batch first
685
+ output = output.transpose(0, 1)
686
+ src_pos = src_pos.transpose(0, 1)
687
+ prompt = prompt.transpose(0, 1)
688
+ prompt_pos = prompt_pos.transpose(0, 1)
689
+
690
+ for layer in self.layers:
691
+ kwds = {}
692
+ if isinstance(layer.cross_attn_image, RoPEAttention):
693
+ kwds = {"num_k_exclude_rope": num_obj_ptr_tokens}
694
+
695
+ output = activation_ckpt_wrapper(layer)(
696
+ tgt=output,
697
+ memory=prompt,
698
+ tgt_mask=src_mask,
699
+ memory_mask=prompt_mask,
700
+ tgt_key_padding_mask=src_key_padding_mask,
701
+ memory_key_padding_mask=prompt_key_padding_mask,
702
+ pos=prompt_pos,
703
+ query_pos=src_pos,
704
+ dac=False,
705
+ attn_bias=None,
706
+ act_ckpt_enable=self.training and self.use_act_checkpoint,
707
+ **kwds,
708
+ )
709
+ normed_output = self.norm(output)
710
+
711
+ if self.batch_first:
712
+ # Convert back to seq first
713
+ normed_output = normed_output.transpose(0, 1)
714
+ src_pos = src_pos.transpose(0, 1)
715
+
716
+ return {
717
+ "memory": normed_output,
718
+ "pos_embed": src_pos,
719
+ "padding_mask": src_key_padding_mask,
720
+ }
721
+
722
+
723
+ class TransformerDecoderLayerv1(nn.Module):
724
+ def __init__(
725
+ self,
726
+ activation: str,
727
+ cross_attention: nn.Module,
728
+ d_model: int,
729
+ dim_feedforward: int,
730
+ dropout: float,
731
+ pos_enc_at_attn: bool,
732
+ pos_enc_at_cross_attn_keys: bool,
733
+ pos_enc_at_cross_attn_queries: bool,
734
+ pre_norm: bool,
735
+ self_attention: nn.Module,
736
+ ):
737
+ super().__init__()
738
+ self.d_model = d_model
739
+ self.dim_feedforward = dim_feedforward
740
+ self.dropout_value = dropout
741
+ self.self_attn = self_attention
742
+ self.cross_attn_image = cross_attention
743
+
744
+ # Implementation of Feedforward model
745
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
746
+ self.dropout = nn.Dropout(dropout)
747
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
748
+
749
+ self.norm1 = nn.LayerNorm(d_model)
750
+ self.norm2 = nn.LayerNorm(d_model)
751
+ self.norm3 = nn.LayerNorm(d_model)
752
+ self.dropout1 = nn.Dropout(dropout)
753
+ self.dropout2 = nn.Dropout(dropout)
754
+ self.dropout3 = nn.Dropout(dropout)
755
+
756
+ self.activation_str = activation
757
+ self.activation = get_activation_fn(activation)
758
+ self.pre_norm = pre_norm
759
+
760
+ self.pos_enc_at_attn = pos_enc_at_attn
761
+ self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
762
+ self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
763
+
764
+ def forward_post(
765
+ self,
766
+ tgt,
767
+ memory,
768
+ tgt_mask: Optional[Tensor] = None,
769
+ memory_mask: Optional[Tensor] = None,
770
+ tgt_key_padding_mask: Optional[Tensor] = None,
771
+ memory_key_padding_mask: Optional[Tensor] = None,
772
+ pos: Optional[Tensor] = None,
773
+ query_pos: Optional[Tensor] = None,
774
+ **kwargs,
775
+ ):
776
+ q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
777
+
778
+ # Self attention
779
+ tgt2 = self.self_attn(
780
+ q,
781
+ k,
782
+ value=tgt,
783
+ attn_mask=tgt_mask,
784
+ key_padding_mask=tgt_key_padding_mask,
785
+ )[0]
786
+ tgt = tgt + self.dropout1(tgt2)
787
+ tgt = self.norm1(tgt)
788
+
789
+ # Cross attention to image
790
+ tgt2 = self.cross_attn_image(
791
+ query=tgt + query_pos if self.pos_enc_at_cross_attn_queries else tgt,
792
+ key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
793
+ value=memory,
794
+ attn_mask=memory_mask,
795
+ key_padding_mask=memory_key_padding_mask,
796
+ )[0]
797
+ tgt = tgt + self.dropout2(tgt2)
798
+ tgt = self.norm2(tgt)
799
+
800
+ # FFN
801
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
802
+ tgt = tgt + self.dropout3(tgt2)
803
+ tgt = self.norm3(tgt)
804
+ return tgt
805
+
806
+ def forward_pre(
807
+ self,
808
+ tgt,
809
+ memory,
810
+ dac: bool = False,
811
+ tgt_mask: Optional[Tensor] = None,
812
+ memory_mask: Optional[Tensor] = None,
813
+ tgt_key_padding_mask: Optional[Tensor] = None,
814
+ memory_key_padding_mask: Optional[Tensor] = None,
815
+ pos: Optional[Tensor] = None,
816
+ query_pos: Optional[Tensor] = None,
817
+ attn_bias: Optional[Tensor] = None,
818
+ **kwargs,
819
+ ):
820
+ if dac:
821
+ # we only apply self attention to the first half of the queries
822
+ assert tgt.shape[0] % 2 == 0
823
+ other_tgt = tgt[tgt.shape[0] // 2 :]
824
+ tgt = tgt[: tgt.shape[0] // 2]
825
+ tgt2 = self.norm1(tgt)
826
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
827
+ tgt2 = self.self_attn(
828
+ q,
829
+ k,
830
+ value=tgt2,
831
+ attn_mask=tgt_mask,
832
+ key_padding_mask=tgt_key_padding_mask,
833
+ )[0]
834
+ tgt = tgt + self.dropout1(tgt2)
835
+ if dac:
836
+ # Recombine
837
+ tgt = torch.cat((tgt, other_tgt), dim=0)
838
+ tgt2 = self.norm2(tgt)
839
+ tgt2 = self.cross_attn_image(
840
+ query=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
841
+ key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
842
+ value=memory,
843
+ attn_mask=memory_mask,
844
+ key_padding_mask=memory_key_padding_mask,
845
+ attn_bias=attn_bias,
846
+ )[0]
847
+ tgt = tgt + self.dropout2(tgt2)
848
+ tgt2 = self.norm3(tgt)
849
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
850
+ tgt = tgt + self.dropout3(tgt2)
851
+ return tgt
852
+
853
+ def forward(
854
+ self,
855
+ tgt,
856
+ memory,
857
+ dac: bool = False,
858
+ tgt_mask: Optional[Tensor] = None,
859
+ memory_mask: Optional[Tensor] = None,
860
+ tgt_key_padding_mask: Optional[Tensor] = None,
861
+ memory_key_padding_mask: Optional[Tensor] = None,
862
+ pos: Optional[Tensor] = None,
863
+ query_pos: Optional[Tensor] = None,
864
+ attn_bias: Optional[Tensor] = None,
865
+ **kwds: Any,
866
+ ) -> torch.Tensor:
867
+ fwd_fn = self.forward_pre if self.pre_norm else self.forward_post
868
+ return fwd_fn(
869
+ tgt,
870
+ memory,
871
+ dac=dac,
872
+ tgt_mask=tgt_mask,
873
+ memory_mask=memory_mask,
874
+ tgt_key_padding_mask=tgt_key_padding_mask,
875
+ memory_key_padding_mask=memory_key_padding_mask,
876
+ pos=pos,
877
+ query_pos=query_pos,
878
+ attn_bias=attn_bias,
879
+ **kwds,
880
+ )
881
+
882
+
883
+ class TransformerDecoderLayerv2(TransformerDecoderLayerv1):
884
+ def __init__(self, cross_attention_first=False, *args: Any, **kwds: Any):
885
+ super().__init__(*args, **kwds)
886
+ self.cross_attention_first = cross_attention_first
887
+
888
+ def _forward_sa(self, tgt, query_pos):
889
+ # Self-Attention
890
+ tgt2 = self.norm1(tgt)
891
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
892
+ tgt2 = self.self_attn(q, k, v=tgt2)
893
+ tgt = tgt + self.dropout1(tgt2)
894
+ return tgt
895
+
896
+ def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0):
897
+ if self.cross_attn_image is None:
898
+ return tgt
899
+
900
+ kwds = {}
901
+ if num_k_exclude_rope > 0:
902
+ assert isinstance(self.cross_attn_image, RoPEAttention)
903
+ kwds = {"num_k_exclude_rope": num_k_exclude_rope}
904
+
905
+ # Cross-Attention
906
+ tgt2 = self.norm2(tgt)
907
+ tgt2 = self.cross_attn_image(
908
+ q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
909
+ k=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
910
+ v=memory,
911
+ **kwds,
912
+ )
913
+ tgt = tgt + self.dropout2(tgt2)
914
+ return tgt
915
+
916
+ def forward_pre(
917
+ self,
918
+ tgt,
919
+ memory,
920
+ dac: bool,
921
+ tgt_mask: Optional[Tensor] = None,
922
+ memory_mask: Optional[Tensor] = None,
923
+ tgt_key_padding_mask: Optional[Tensor] = None,
924
+ memory_key_padding_mask: Optional[Tensor] = None,
925
+ pos: Optional[Tensor] = None,
926
+ query_pos: Optional[Tensor] = None,
927
+ attn_bias: Optional[Tensor] = None,
928
+ num_k_exclude_rope: int = 0,
929
+ ):
930
+ assert dac is False
931
+ assert tgt_mask is None
932
+ assert memory_mask is None
933
+ assert tgt_key_padding_mask is None
934
+ assert memory_key_padding_mask is None
935
+ assert attn_bias is None
936
+
937
+ if self.cross_attention_first:
938
+ tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope)
939
+ tgt = self._forward_sa(tgt, query_pos)
940
+ else:
941
+ tgt = self._forward_sa(tgt, query_pos)
942
+ tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope)
943
+
944
+ # MLP
945
+ tgt2 = self.norm3(tgt)
946
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
947
+ tgt = tgt + self.dropout3(tgt2)
948
+ return tgt
949
+
950
+ def forward(self, *args: Any, **kwds: Any) -> torch.Tensor:
951
+ if self.pre_norm:
952
+ return self.forward_pre(*args, **kwds)
953
+ raise NotImplementedError
third_party/GraspGen/sam3/sam3/model/edt.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Triton kernel for euclidean distance transform (EDT)"""
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ """
12
+ Disclaimer: This implementation is not meant to be extremely efficient. A CUDA kernel would likely be more efficient.
13
+ Even in Triton, there may be more suitable algorithms.
14
+
15
+ The goal of this kernel is to mimic cv2.distanceTransform(input, cv2.DIST_L2, 0).
16
+ Recall that the euclidean distance transform (EDT) calculates the L2 distance to the closest zero pixel for each pixel of the source image.
17
+
18
+ For images of size NxN, the naive algorithm would be to compute pairwise distances between every pair of points, leading to a O(N^4) algorithm, which is obviously impractical.
19
+ One can do better using the following approach:
20
+ - First, compute the distance to the closest point in the same row. We can write it as Row_EDT[i,j] = min_k (sqrt((k-j)^2) if input[i,k]==0 else +infinity). With a naive implementation, this step has a O(N^3) complexity
21
+ - Then, because of triangular inequality, we notice that the EDT for a given location [i,j] is the min of the row EDTs in the same column. EDT[i,j] = min_k Row_EDT[k, j]. This is also O(N^3)
22
+
23
+ Overall, this algorithm is quite amenable to parallelization, and has a complexity O(N^3). Can we do better?
24
+
25
+ It turns out that we can leverage the structure of the L2 distance (nice and convex) to find the minimum in a more efficient way.
26
+ We follow the algorithm from "Distance Transforms of Sampled Functions" (https://cs.brown.edu/people/pfelzens/papers/dt-final.pdf), which is also what's implemented in opencv
27
+
28
+ For a single dimension EDT, we can compute the EDT of an arbitrary function F, that we discretize over the grid. Note that for the binary EDT that we're interested in, we can set F(i,j) = 0 if input[i,j]==0 else +infinity
29
+ For now, we'll compute the EDT squared, and will take the sqrt only at the very end.
30
+ The basic idea is that each point at location i spawns a parabola around itself, with a bias equal to F(i). So specifically, we're looking at the parabola (x - i)^2 + F(i)
31
+ When we're looking for the row EDT at location j, we're effectively looking for min_i (x-i)^2 + F(i). In other word we want to find the lowest parabola at location j.
32
+
33
+ To do this efficiently, we need to maintain the lower envelope of the union of parabolas. This can be constructed on the fly using a sort of stack approach:
34
+ - every time we want to add a new parabola, we check if it may be covering the current right-most parabola. If so, then that parabola was useless, so we can pop it from the stack
35
+ - repeat until we can't find any more parabola to pop. Then push the new one.
36
+
37
+ This algorithm runs in O(N) for a single row, so overall O(N^2) when applied to all rows
38
+ Similarly as before, we notice that we can decompose the algorithm for rows and columns, leading to an overall run-time of O(N^2)
39
+
40
+ This algorithm is less suited for to GPUs, since the one-dimensional EDT computation is quite sequential in nature. However, we can parallelize over batch and row dimensions.
41
+ In Triton, things are particularly bad at the moment, since there is no support for reading/writing to the local memory at a specific index (a local gather is coming soon, see https://github.com/triton-lang/triton/issues/974, but no mention of writing, ie scatter)
42
+ One could emulate these operations with masking, but in initial tests, it proved to be worst than naively reading and writing to the global memory. My guess is that the cache is compensating somewhat for the repeated single-point accesses.
43
+
44
+
45
+ The timing obtained on a H100 for a random batch of masks of dimension 256 x 1024 x 1024 are as follows:
46
+ - OpenCV: 1780ms (including round-trip to cpu, but discounting the fact that it introduces a synchronization point)
47
+ - triton, O(N^3) algo: 627ms
48
+ - triton, O(N^2) algo: 322ms
49
+
50
+ Overall, despite being quite naive, this implementation is roughly 5.5x faster than the openCV cpu implem
51
+
52
+ """
53
+
54
+
55
+ @triton.jit
56
+ def edt_kernel(inputs_ptr, outputs_ptr, v, z, height, width, horizontal: tl.constexpr):
57
+ # This is a somewhat verbatim implementation of the efficient 1D EDT algorithm described above
58
+ # It can be applied horizontally or vertically depending if we're doing the first or second stage.
59
+ # It's parallelized across batch+row (or batch+col if horizontal=False)
60
+ # TODO: perhaps the implementation can be revisited if/when local gather/scatter become available in triton
61
+ batch_id = tl.program_id(axis=0)
62
+ if horizontal:
63
+ row_id = tl.program_id(axis=1)
64
+ block_start = (batch_id * height * width) + row_id * width
65
+ length = width
66
+ stride = 1
67
+ else:
68
+ col_id = tl.program_id(axis=1)
69
+ block_start = (batch_id * height * width) + col_id
70
+ length = height
71
+ stride = width
72
+
73
+ # This will be the index of the right most parabola in the envelope ("the top of the stack")
74
+ k = 0
75
+ for q in range(1, length):
76
+ # Read the function value at the current location. Note that we're doing a singular read, not very efficient
77
+ cur_input = tl.load(inputs_ptr + block_start + (q * stride))
78
+ # location of the parabola on top of the stack
79
+ r = tl.load(v + block_start + (k * stride))
80
+ # associated boundary
81
+ z_k = tl.load(z + block_start + (k * stride))
82
+ # value of the function at the parabola location
83
+ previous_input = tl.load(inputs_ptr + block_start + (r * stride))
84
+ # intersection between the two parabolas
85
+ s = (cur_input - previous_input + q * q - r * r) / (q - r) / 2
86
+
87
+ # we'll pop as many parabolas as required
88
+ while s <= z_k and k - 1 >= 0:
89
+ k = k - 1
90
+ r = tl.load(v + block_start + (k * stride))
91
+ z_k = tl.load(z + block_start + (k * stride))
92
+ previous_input = tl.load(inputs_ptr + block_start + (r * stride))
93
+ s = (cur_input - previous_input + q * q - r * r) / (q - r) / 2
94
+
95
+ # Store the new one
96
+ k = k + 1
97
+ tl.store(v + block_start + (k * stride), q)
98
+ tl.store(z + block_start + (k * stride), s)
99
+ if k + 1 < length:
100
+ tl.store(z + block_start + ((k + 1) * stride), 1e9)
101
+
102
+ # Last step, we read the envelope to find the min in every location
103
+ k = 0
104
+ for q in range(length):
105
+ while (
106
+ k + 1 < length
107
+ and tl.load(
108
+ z + block_start + ((k + 1) * stride), mask=(k + 1) < length, other=q
109
+ )
110
+ < q
111
+ ):
112
+ k += 1
113
+ r = tl.load(v + block_start + (k * stride))
114
+ d = q - r
115
+ old_value = tl.load(inputs_ptr + block_start + (r * stride))
116
+ tl.store(outputs_ptr + block_start + (q * stride), old_value + d * d)
117
+
118
+
119
+ def edt_triton(data: torch.Tensor):
120
+ """
121
+ Computes the Euclidean Distance Transform (EDT) of a batch of binary images.
122
+
123
+ Args:
124
+ data: A tensor of shape (B, H, W) representing a batch of binary images.
125
+
126
+ Returns:
127
+ A tensor of the same shape as data containing the EDT.
128
+ It should be equivalent to a batched version of cv2.distanceTransform(input, cv2.DIST_L2, 0)
129
+ """
130
+ assert data.dim() == 3
131
+ assert data.is_cuda
132
+ B, H, W = data.shape
133
+ data = data.contiguous()
134
+
135
+ # Allocate the "function" tensor. Implicitly the function is 0 if data[i,j]==0 else +infinity
136
+ output = torch.where(data, 1e18, 0.0)
137
+ assert output.is_contiguous()
138
+
139
+ # Scratch tensors for the parabola stacks
140
+ parabola_loc = torch.zeros(B, H, W, dtype=torch.uint32, device=data.device)
141
+ parabola_inter = torch.empty(B, H, W, dtype=torch.float, device=data.device)
142
+ parabola_inter[:, :, 0] = -1e18
143
+ parabola_inter[:, :, 1] = 1e18
144
+
145
+ # Grid size (number of blocks)
146
+ grid = (B, H)
147
+
148
+ # Launch initialization kernel
149
+ edt_kernel[grid](
150
+ output.clone(),
151
+ output,
152
+ parabola_loc,
153
+ parabola_inter,
154
+ H,
155
+ W,
156
+ horizontal=True,
157
+ )
158
+
159
+ # reset the parabola stacks
160
+ parabola_loc.zero_()
161
+ parabola_inter[:, :, 0] = -1e18
162
+ parabola_inter[:, :, 1] = 1e18
163
+
164
+ grid = (B, W)
165
+ edt_kernel[grid](
166
+ output.clone(),
167
+ output,
168
+ parabola_loc,
169
+ parabola_inter,
170
+ H,
171
+ W,
172
+ horizontal=False,
173
+ )
174
+ # don't forget to take sqrt at the end
175
+ return output.sqrt()
third_party/GraspGen/sam3/sam3/model/encoder.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ # Based on https://github.com/IDEA-Research/GroundingDINO
3
+
4
+ # pyre-unsafe
5
+
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ import torch
9
+ from torch import nn, Tensor
10
+
11
+ from .act_ckpt_utils import activation_ckpt_wrapper
12
+ from .model_misc import get_activation_fn, get_clones, get_valid_ratio
13
+
14
+
15
+ class TransformerEncoderLayer(nn.Module):
16
+ """
17
+ Transformer encoder layer that performs self-attention followed by cross-attention.
18
+
19
+ This layer was previously called TransformerDecoderLayer but was renamed to better
20
+ reflect its role in the architecture. It processes input sequences through self-attention
21
+ and then cross-attention with another input (typically image features).
22
+
23
+ The layer supports both pre-norm and post-norm configurations, as well as
24
+ positional encoding at different stages of the attention mechanism.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ activation: str,
30
+ cross_attention: nn.Module,
31
+ d_model: int,
32
+ dim_feedforward: int,
33
+ dropout: float,
34
+ pos_enc_at_attn: bool,
35
+ pos_enc_at_cross_attn_keys: bool,
36
+ pos_enc_at_cross_attn_queries: bool,
37
+ pre_norm: bool,
38
+ self_attention: nn.Module,
39
+ ):
40
+ """
41
+ Initialize a transformer encoder layer.
42
+
43
+ Args:
44
+ activation: Activation function to use in the feedforward network
45
+ cross_attention: Cross-attention module for attending to image features
46
+ d_model: Model dimension/hidden size
47
+ dim_feedforward: Dimension of the feedforward network
48
+ dropout: Dropout probability
49
+ pos_enc_at_attn: Whether to add positional encodings at self-attention
50
+ pos_enc_at_cross_attn_keys: Whether to add positional encodings to keys in cross-attention
51
+ pos_enc_at_cross_attn_queries: Whether to add positional encodings to queries in cross-attention
52
+ pre_norm: Whether to use pre-norm (True) or post-norm (False) architecture
53
+ self_attention: Self-attention module
54
+ """
55
+ super().__init__()
56
+ self.d_model = d_model
57
+ self.dim_feedforward = dim_feedforward
58
+ self.dropout_value = dropout
59
+ self.self_attn = self_attention
60
+ self.cross_attn_image = cross_attention
61
+
62
+ # Implementation of Feedforward model
63
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
64
+ self.dropout = nn.Dropout(dropout)
65
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
66
+
67
+ self.norm1 = nn.LayerNorm(d_model)
68
+ self.norm2 = nn.LayerNorm(d_model)
69
+ self.norm3 = nn.LayerNorm(d_model)
70
+ self.dropout1 = nn.Dropout(dropout)
71
+ self.dropout2 = nn.Dropout(dropout)
72
+ self.dropout3 = nn.Dropout(dropout)
73
+
74
+ self.activation_str = activation
75
+ self.activation = get_activation_fn(activation)
76
+ self.pre_norm = pre_norm
77
+
78
+ self.pos_enc_at_attn = pos_enc_at_attn
79
+ self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
80
+ self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
81
+
82
+ self.layer_idx = None
83
+
84
+ def forward_post(
85
+ self,
86
+ tgt: Tensor,
87
+ memory: Tensor,
88
+ tgt_mask: Optional[Tensor] = None,
89
+ memory_mask: Optional[Tensor] = None,
90
+ tgt_key_padding_mask: Optional[Tensor] = None,
91
+ memory_key_padding_mask: Optional[Tensor] = None,
92
+ pos: Optional[Tensor] = None,
93
+ query_pos: Optional[Tensor] = None,
94
+ **kwargs,
95
+ ) -> Tensor:
96
+ """
97
+ Forward pass for post-norm architecture.
98
+
99
+ In post-norm architecture, normalization is applied after attention and feedforward operations.
100
+
101
+ Args:
102
+ tgt: Input tensor to be processed
103
+ memory: Memory tensor for cross-attention
104
+ tgt_mask: Mask for self-attention
105
+ memory_mask: Mask for cross-attention
106
+ tgt_key_padding_mask: Key padding mask for self-attention
107
+ memory_key_padding_mask: Key padding mask for cross-attention
108
+ pos: Positional encoding for memory
109
+ query_pos: Positional encoding for query
110
+ **kwargs: Additional keyword arguments
111
+
112
+ Returns:
113
+ Processed tensor
114
+ """
115
+ q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
116
+
117
+ # Self attention
118
+ tgt2 = self.self_attn(
119
+ q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask
120
+ )[0]
121
+ tgt = tgt + self.dropout1(tgt2)
122
+ tgt = self.norm1(tgt)
123
+
124
+ # Cross attention to image
125
+ tgt2 = self.cross_attn_image(
126
+ query=tgt + query_pos if self.pos_enc_at_cross_attn_queries else tgt,
127
+ key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
128
+ value=memory,
129
+ attn_mask=memory_mask,
130
+ key_padding_mask=memory_key_padding_mask,
131
+ )[0]
132
+ tgt = tgt + self.dropout2(tgt2)
133
+ tgt = self.norm2(tgt)
134
+
135
+ # FFN
136
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
137
+ tgt = tgt + self.dropout3(tgt2)
138
+ tgt = self.norm3(tgt)
139
+ return tgt
140
+
141
+ def forward_pre(
142
+ self,
143
+ tgt: Tensor,
144
+ memory: Tensor,
145
+ dac: bool = False,
146
+ tgt_mask: Optional[Tensor] = None,
147
+ memory_mask: Optional[Tensor] = None,
148
+ tgt_key_padding_mask: Optional[Tensor] = None,
149
+ memory_key_padding_mask: Optional[Tensor] = None,
150
+ pos: Optional[Tensor] = None,
151
+ query_pos: Optional[Tensor] = None,
152
+ # attn_bias: Optional[Tensor] = None,
153
+ # **kwargs,
154
+ ) -> Tensor:
155
+ """
156
+ Forward pass for pre-norm architecture.
157
+
158
+ In pre-norm architecture, normalization is applied before attention and feedforward operations.
159
+
160
+ Args:
161
+ tgt: Input tensor to be processed
162
+ memory: Memory tensor for cross-attention
163
+ dac: Whether to use Divide-and-Conquer attention
164
+ tgt_mask: Mask for self-attention
165
+ memory_mask: Mask for cross-attention
166
+ tgt_key_padding_mask: Key padding mask for self-attention
167
+ memory_key_padding_mask: Key padding mask for cross-attention
168
+ pos: Positional encoding for memory
169
+ query_pos: Positional encoding for query
170
+ attn_bias: Optional attention bias tensor
171
+ **kwargs: Additional keyword arguments
172
+
173
+ Returns:
174
+ Processed tensor
175
+ """
176
+ if dac:
177
+ # we only apply self attention to the first half of the queries
178
+ assert tgt.shape[0] % 2 == 0
179
+ other_tgt = tgt[tgt.shape[0] // 2 :]
180
+ tgt = tgt[: tgt.shape[0] // 2]
181
+ tgt2 = self.norm1(tgt)
182
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
183
+ tgt2 = self.self_attn(
184
+ q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask
185
+ )[0]
186
+ tgt = tgt + self.dropout1(tgt2)
187
+ if dac:
188
+ # Recombine
189
+ tgt = torch.cat((tgt, other_tgt), dim=0)
190
+ tgt2 = self.norm2(tgt)
191
+ tgt2 = self.cross_attn_image(
192
+ query=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
193
+ key=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
194
+ value=memory,
195
+ attn_mask=memory_mask,
196
+ key_padding_mask=memory_key_padding_mask,
197
+ # attn_bias=attn_bias,
198
+ )[0]
199
+ tgt = tgt + self.dropout2(tgt2)
200
+ tgt2 = self.norm3(tgt)
201
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
202
+ tgt = tgt + self.dropout3(tgt2)
203
+ return tgt
204
+
205
+ def forward(
206
+ self,
207
+ tgt: Tensor,
208
+ memory: Tensor,
209
+ dac: bool = False,
210
+ tgt_mask: Optional[Tensor] = None,
211
+ memory_mask: Optional[Tensor] = None,
212
+ tgt_key_padding_mask: Optional[Tensor] = None,
213
+ memory_key_padding_mask: Optional[Tensor] = None,
214
+ pos: Optional[Tensor] = None,
215
+ query_pos: Optional[Tensor] = None,
216
+ # attn_bias: Optional[Tensor] = None,
217
+ # **kwds: Any,
218
+ ) -> torch.Tensor:
219
+ """
220
+ Forward pass for the transformer encoder layer.
221
+
222
+ Args:
223
+ tgt: Input tensor to be processed
224
+ memory: Memory tensor (e.g., image features) for cross-attention
225
+ dac: Whether to use Divide-and-Conquer attention (only apply self-attention to first half)
226
+ tgt_mask: Mask for self-attention
227
+ memory_mask: Mask for cross-attention
228
+ tgt_key_padding_mask: Key padding mask for self-attention
229
+ memory_key_padding_mask: Key padding mask for cross-attention
230
+ pos: Positional encoding for memory
231
+ query_pos: Positional encoding for query
232
+ attn_bias: Optional attention bias tensor
233
+ **kwds: Additional keyword arguments
234
+
235
+ Returns:
236
+ Processed tensor after self-attention, cross-attention, and feedforward network
237
+ """
238
+ fwd_fn = self.forward_pre if self.pre_norm else self.forward_post
239
+ return fwd_fn(
240
+ tgt,
241
+ memory,
242
+ dac=dac,
243
+ tgt_mask=tgt_mask,
244
+ memory_mask=memory_mask,
245
+ tgt_key_padding_mask=tgt_key_padding_mask,
246
+ memory_key_padding_mask=memory_key_padding_mask,
247
+ pos=pos,
248
+ query_pos=query_pos,
249
+ # attn_bias=attn_bias,
250
+ # **kwds,
251
+ )
252
+
253
+
254
+ class TransformerEncoder(nn.Module):
255
+ """
256
+ Transformer encoder that processes multi-level features.
257
+
258
+ This encoder takes multi-level features (e.g., from a backbone network) and processes
259
+ them through a stack of transformer encoder layers. It supports features from multiple
260
+ levels (e.g., different resolutions) and can apply activation checkpointing for memory
261
+ efficiency during training.
262
+
263
+ Args:
264
+ layer: The encoder layer to be stacked multiple times
265
+ num_layers: Number of encoder layers to stack
266
+ d_model: Model dimension/hidden size
267
+ num_feature_levels: Number of feature levels to process
268
+ frozen: Whether to freeze the parameters of this module
269
+ use_act_checkpoint: Whether to use activation checkpointing during training
270
+ """
271
+
272
+ def __init__(
273
+ self,
274
+ layer: nn.Module,
275
+ num_layers: int,
276
+ d_model: int,
277
+ num_feature_levels: int,
278
+ frozen: bool = False,
279
+ use_act_checkpoint: bool = False,
280
+ ):
281
+ super().__init__()
282
+ self.layers = get_clones(layer, num_layers)
283
+ self.num_layers = num_layers
284
+
285
+ self.num_feature_levels = num_feature_levels
286
+ self.level_embed = None
287
+ if num_feature_levels > 1:
288
+ self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
289
+
290
+ if frozen:
291
+ for p in self.parameters():
292
+ p.requires_grad_(False)
293
+
294
+ self.use_act_checkpoint = use_act_checkpoint
295
+
296
+ # assign layer index to each layer so that some layers can decide what to do
297
+ # based on which layer index they are (e.g. cross attention to memory bank only
298
+ # in selected layers)
299
+ for layer_idx, layer in enumerate(self.layers):
300
+ layer.layer_idx = layer_idx
301
+
302
+ @staticmethod
303
+ def get_reference_points(spatial_shapes, valid_ratios, device):
304
+ with torch.no_grad():
305
+ reference_points_list = []
306
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
307
+ ref_y, ref_x = torch.meshgrid(
308
+ torch.linspace(
309
+ 0.5, H_ - 0.5, H_, dtype=torch.float32, device=device
310
+ ),
311
+ torch.linspace(
312
+ 0.5, W_ - 0.5, W_, dtype=torch.float32, device=device
313
+ ),
314
+ )
315
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_)
316
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_)
317
+ ref = torch.stack((ref_x, ref_y), -1)
318
+ reference_points_list.append(ref)
319
+ reference_points = torch.cat(reference_points_list, 1)
320
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
321
+
322
+ return reference_points
323
+
324
+ def _prepare_multilevel_features(self, srcs, masks, pos_embeds):
325
+ assert len(srcs) == self.num_feature_levels, (
326
+ "mismatch between expected and received # of feature levels"
327
+ )
328
+
329
+ src_flatten = []
330
+ mask_flatten = []
331
+ lvl_pos_embed_flatten = []
332
+ spatial_shapes = []
333
+ has_mask = masks is not None and masks[0] is not None
334
+ for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
335
+ bs, c, h, w = src.shape
336
+ spatial_shape = (h, w)
337
+ spatial_shapes.append(spatial_shape)
338
+
339
+ src = src.flatten(2).transpose(1, 2) # bs, hw, c
340
+ if has_mask:
341
+ mask = mask.flatten(1)
342
+ pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c
343
+ if self.level_embed is not None:
344
+ lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1)
345
+ else:
346
+ lvl_pos_embed = pos_embed
347
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
348
+ src_flatten.append(src)
349
+ if has_mask:
350
+ mask_flatten.append(mask)
351
+ src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c
352
+ mask_flatten = torch.cat(mask_flatten, 1) if has_mask else None # bs, \sum{hxw}
353
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c
354
+ spatial_shapes = torch.tensor(
355
+ spatial_shapes, dtype=torch.long, device=src_flatten.device
356
+ )
357
+ level_start_index = torch.cat(
358
+ (
359
+ spatial_shapes.new_zeros((1,)),
360
+ spatial_shapes.prod(1).cumsum(0)[:-1],
361
+ )
362
+ )
363
+ if has_mask:
364
+ valid_ratios = torch.stack([get_valid_ratio(m) for m in masks], 1)
365
+ else:
366
+ valid_ratios = torch.ones(
367
+ (src_flatten.shape[0], self.num_feature_levels, 2),
368
+ device=src_flatten.device,
369
+ )
370
+
371
+ return (
372
+ src_flatten,
373
+ mask_flatten,
374
+ lvl_pos_embed_flatten,
375
+ level_start_index,
376
+ valid_ratios,
377
+ spatial_shapes,
378
+ )
379
+
380
+ def forward(
381
+ self,
382
+ src: List[Tensor],
383
+ src_key_padding_masks: Optional[List[Tensor]] = None,
384
+ pos: Optional[List[Tensor]] = None,
385
+ prompt: Optional[Tensor] = None,
386
+ prompt_key_padding_mask: Optional[Tensor] = None,
387
+ encoder_extra_kwargs: Optional[Dict] = None,
388
+ ) -> Tuple[Tensor, Optional[Tensor], Tensor, Tensor, Tensor, Tensor]:
389
+ """
390
+ Process multi-level features through the transformer encoder.
391
+
392
+ Args:
393
+ src: List of multi-level features, each with shape (batch_size, channels, height, width)
394
+ src_key_padding_masks: List of padding masks for each feature level, each with shape (batch_size, height, width)
395
+ pos: List of positional embeddings for each feature level, each with shape (batch_size, channels, height, width)
396
+ prompt: Optional text/prompt features to attend to, with shape (seq_len, batch_size, d_model)
397
+ prompt_key_padding_mask: Optional padding mask for prompt, with shape (batch_size, seq_len)
398
+ encoder_extra_kwargs: Optional additional arguments to pass to each encoder layer
399
+
400
+ Returns:
401
+ A tuple containing:
402
+ - output: Processed features with shape (seq_len, batch_size, d_model)
403
+ - key_padding_masks_flatten: Flattened padding masks
404
+ - lvl_pos_embed_flatten: Flattened positional embeddings
405
+ - level_start_index: Starting indices for each feature level
406
+ - spatial_shapes: Spatial dimensions of each feature level
407
+ - valid_ratios: Valid ratios for each feature level
408
+ """
409
+ assert len(src) == self.num_feature_levels, (
410
+ "must be equal to num_feature_levels"
411
+ )
412
+ if src_key_padding_masks is not None:
413
+ assert len(src_key_padding_masks) == self.num_feature_levels
414
+ if pos is not None:
415
+ assert len(pos) == self.num_feature_levels
416
+ # Flatten multilevel feats and add level pos embeds
417
+ (
418
+ src_flatten,
419
+ key_padding_masks_flatten,
420
+ lvl_pos_embed_flatten,
421
+ level_start_index,
422
+ valid_ratios,
423
+ spatial_shapes,
424
+ ) = self._prepare_multilevel_features(src, src_key_padding_masks, pos)
425
+
426
+ reference_points = self.get_reference_points(
427
+ spatial_shapes, valid_ratios, device=src_flatten.device
428
+ )
429
+
430
+ output = src_flatten
431
+ for layer in self.layers:
432
+ layer_kwargs = {}
433
+
434
+ assert isinstance(layer, TransformerEncoderLayer)
435
+ layer_kwargs["memory"] = prompt
436
+ layer_kwargs["memory_key_padding_mask"] = prompt_key_padding_mask
437
+ layer_kwargs["query_pos"] = lvl_pos_embed_flatten
438
+ layer_kwargs["tgt"] = output
439
+ layer_kwargs["tgt_key_padding_mask"] = key_padding_masks_flatten
440
+
441
+ if self.training:
442
+ assert self.use_act_checkpoint, "activation ckpt not enabled in encoder"
443
+ if encoder_extra_kwargs is not None:
444
+ layer_kwargs.update(encoder_extra_kwargs)
445
+ output = activation_ckpt_wrapper(layer)(
446
+ **layer_kwargs,
447
+ act_ckpt_enable=self.training and self.use_act_checkpoint,
448
+ )
449
+ # return as seq first
450
+ return (
451
+ output.transpose(0, 1),
452
+ (
453
+ key_padding_masks_flatten.transpose(0, 1)
454
+ if key_padding_masks_flatten is not None
455
+ else None
456
+ ),
457
+ lvl_pos_embed_flatten.transpose(0, 1),
458
+ level_start_index,
459
+ spatial_shapes,
460
+ valid_ratios,
461
+ )
462
+
463
+
464
+ class TransformerEncoderFusion(TransformerEncoder):
465
+ """
466
+ Transformer encoder that fuses text and image features.
467
+
468
+ This encoder extends TransformerEncoder to handle both text and image features,
469
+ with the ability to add pooled text features to image features for better
470
+ cross-modal fusion. It supports torch.compile for performance optimization.
471
+
472
+ Args:
473
+ layer: The encoder layer to be stacked multiple times
474
+ num_layers: Number of encoder layers to stack
475
+ d_model: Model dimension/hidden size
476
+ num_feature_levels: Number of feature levels to process
477
+ add_pooled_text_to_img_feat: Whether to add pooled text features to image features
478
+ pool_text_with_mask: Whether to use the mask when pooling text features
479
+ compile_mode: Mode for torch.compile, or None to disable compilation
480
+ **kwargs: Additional arguments to pass to the parent class
481
+ """
482
+
483
+ def __init__(
484
+ self,
485
+ layer: nn.Module,
486
+ num_layers: int,
487
+ d_model: int,
488
+ num_feature_levels: int,
489
+ add_pooled_text_to_img_feat: bool = True,
490
+ pool_text_with_mask: bool = False,
491
+ compile_mode: Optional[str] = None,
492
+ **kwargs,
493
+ ):
494
+ super().__init__(
495
+ layer,
496
+ num_layers,
497
+ d_model,
498
+ num_feature_levels,
499
+ **kwargs,
500
+ )
501
+ self.add_pooled_text_to_img_feat = add_pooled_text_to_img_feat
502
+ if self.add_pooled_text_to_img_feat:
503
+ self.text_pooling_proj = nn.Linear(d_model, d_model)
504
+ self.pool_text_with_mask = pool_text_with_mask
505
+ if compile_mode is not None:
506
+ self.forward = torch.compile(
507
+ self.forward, mode=compile_mode, fullgraph=True
508
+ )
509
+
510
+ @staticmethod
511
+ def get_reference_points(spatial_shapes, valid_ratios, device):
512
+ # Not needed here
513
+ return None
514
+
515
+ def forward(
516
+ self,
517
+ src: List[Tensor],
518
+ prompt: Tensor,
519
+ src_key_padding_mask: Optional[List[Tensor]] = None,
520
+ src_pos: Optional[List[Tensor]] = None,
521
+ prompt_key_padding_mask: Optional[Tensor] = None,
522
+ prompt_pos: Optional[Tensor] = None,
523
+ feat_sizes: Optional[List[int]] = None,
524
+ encoder_extra_kwargs: Optional[Dict] = None,
525
+ ):
526
+ # Restore spatial shapes of vision
527
+ bs = src[0].shape[1] # seq first
528
+ if feat_sizes is not None:
529
+ assert len(feat_sizes) == len(src)
530
+ if src_key_padding_mask is None:
531
+ src_key_padding_mask = [None] * len(src)
532
+ for i, (h, w) in enumerate(feat_sizes):
533
+ src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
534
+ src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1)
535
+ src_key_padding_mask[i] = (
536
+ src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1)
537
+ if src_key_padding_mask[i] is not None
538
+ else None
539
+ )
540
+ else:
541
+ assert all(x.dim == 4 for x in src), (
542
+ "expected list of (bs, c, h, w) tensors"
543
+ )
544
+
545
+ if self.add_pooled_text_to_img_feat:
546
+ # Fusion: Add mean pooled text to image features
547
+ pooled_text = pool_text_feat(
548
+ prompt, prompt_key_padding_mask, self.pool_text_with_mask
549
+ )
550
+ pooled_text = self.text_pooling_proj(pooled_text)[
551
+ ..., None, None
552
+ ] # prompt is seq first
553
+ src = [x.add_(pooled_text) for x in src]
554
+
555
+ (
556
+ out,
557
+ key_padding_masks_flatten,
558
+ lvl_pos_embed_flatten,
559
+ level_start_index,
560
+ spatial_shapes,
561
+ valid_ratios,
562
+ ) = super().forward(
563
+ src,
564
+ src_key_padding_masks=src_key_padding_mask,
565
+ pos=src_pos,
566
+ prompt=prompt.transpose(0, 1),
567
+ prompt_key_padding_mask=prompt_key_padding_mask,
568
+ encoder_extra_kwargs=encoder_extra_kwargs,
569
+ )
570
+
571
+ return {
572
+ "memory": out,
573
+ "padding_mask": key_padding_masks_flatten,
574
+ "pos_embed": lvl_pos_embed_flatten,
575
+ "memory_text": prompt,
576
+ "level_start_index": level_start_index,
577
+ "spatial_shapes": spatial_shapes,
578
+ "valid_ratios": valid_ratios,
579
+ }
580
+
581
+
582
+ def pool_text_feat(prompt, prompt_mask, pool_with_mask):
583
+ # prompt has shape (seq, bs, dim)
584
+ if not pool_with_mask:
585
+ return prompt.mean(dim=0)
586
+
587
+ # prompt_mask has shape (bs, seq), where False is valid and True is padding
588
+ assert prompt_mask.dim() == 2
589
+ # is_valid has shape (seq, bs, 1), where 1 is valid and 0 is padding
590
+ is_valid = (~prompt_mask).float().permute(1, 0)[..., None]
591
+ # num_valid has shape (bs, 1)
592
+ num_valid = torch.clamp(torch.sum(is_valid, dim=0), min=1.0)
593
+
594
+ # mean pool over all the valid tokens
595
+ pooled_text = (prompt * is_valid).sum(dim=0) / num_valid
596
+ return pooled_text
third_party/GraspGen/sam3/sam3/model/geometry_encoders.py ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ from typing import Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torchvision
10
+ from typing_extensions import override
11
+
12
+ from .act_ckpt_utils import activation_ckpt_wrapper
13
+ from .box_ops import box_cxcywh_to_xyxy
14
+ from .model_misc import get_clones
15
+
16
+
17
+ def is_right_padded(mask):
18
+ """Given a padding mask (following pytorch convention, 1s for padded values),
19
+ returns whether the padding is on the right or not."""
20
+ return (mask.long() == torch.sort(mask.long(), dim=-1)[0]).all()
21
+
22
+
23
+ def concat_padded_sequences(seq1, mask1, seq2, mask2, return_index: bool = False):
24
+ """
25
+ Concatenates two right-padded sequences, such that the resulting sequence
26
+ is contiguous and also right-padded.
27
+
28
+ Following pytorch's convention, tensors are sequence first, and the mask are
29
+ batch first, with 1s for padded values.
30
+
31
+ :param seq1: A tensor of shape (seq1_length, batch_size, hidden_size).
32
+ :param mask1: A tensor of shape (batch_size, seq1_length).
33
+ :param seq2: A tensor of shape (seq2_length, batch_size, hidden_size).
34
+ :param mask2: A tensor of shape (batch_size, seq2_length).
35
+ :param return_index: If True, also returns the index of the ids of the element of seq2
36
+ in the concatenated sequence. This can be used to retrieve the elements of seq2
37
+ :return: A tuple (concatenated_sequence, concatenated_mask) if return_index is False,
38
+ otherwise (concatenated_sequence, concatenated_mask, index).
39
+ """
40
+ seq1_length, batch_size, hidden_size = seq1.shape
41
+ seq2_length, batch_size, hidden_size = seq2.shape
42
+
43
+ assert batch_size == seq1.size(1) == seq2.size(1) == mask1.size(0) == mask2.size(0)
44
+ assert hidden_size == seq1.size(2) == seq2.size(2)
45
+ assert seq1_length == mask1.size(1)
46
+ assert seq2_length == mask2.size(1)
47
+
48
+ torch._assert_async(is_right_padded(mask1))
49
+ torch._assert_async(is_right_padded(mask2))
50
+
51
+ actual_seq1_lengths = (~mask1).sum(dim=-1)
52
+ actual_seq2_lengths = (~mask2).sum(dim=-1)
53
+
54
+ final_lengths = actual_seq1_lengths + actual_seq2_lengths
55
+ max_length = seq1_length + seq2_length
56
+ concatenated_mask = (
57
+ torch.arange(max_length, device=seq2.device)[None].repeat(batch_size, 1)
58
+ >= final_lengths[:, None]
59
+ )
60
+
61
+ # (max_len, batch_size, hidden_size)
62
+ concatenated_sequence = torch.zeros(
63
+ (max_length, batch_size, hidden_size), device=seq2.device, dtype=seq2.dtype
64
+ )
65
+ concatenated_sequence[:seq1_length, :, :] = seq1
66
+
67
+ # At this point, the element of seq1 are in the right place
68
+ # We just need to shift the elements of seq2
69
+
70
+ index = torch.arange(seq2_length, device=seq2.device)[:, None].repeat(1, batch_size)
71
+ index = index + actual_seq1_lengths[None]
72
+
73
+ concatenated_sequence = concatenated_sequence.scatter(
74
+ 0, index[:, :, None].expand(-1, -1, hidden_size), seq2
75
+ )
76
+
77
+ if return_index:
78
+ return concatenated_sequence, concatenated_mask, index
79
+
80
+ return concatenated_sequence, concatenated_mask
81
+
82
+
83
+ class Prompt:
84
+ """Utility class to manipulate geometric prompts.
85
+
86
+ We expect the sequences in pytorch convention, that is sequence first, batch second
87
+ The dimensions are expected as follows:
88
+ box_embeddings shape: N_boxes x B x C_box
89
+ box_mask shape: B x N_boxes. Can be None if nothing is masked out
90
+ point_embeddings shape: N_points x B x C_point
91
+ point_mask shape: B x N_points. Can be None if nothing is masked out
92
+ mask_embeddings shape: N_masks x B x 1 x H_mask x W_mask
93
+ mask_mask shape: B x N_masks. Can be None if nothing is masked out
94
+
95
+ We also store positive/negative labels. These tensors are also stored batch-first
96
+ If they are None, we'll assume positive labels everywhere
97
+ box_labels: long tensor of shape N_boxes x B
98
+ point_labels: long tensor of shape N_points x B
99
+ mask_labels: long tensor of shape N_masks x B
100
+ """
101
+
102
+ def __init__(
103
+ self,
104
+ box_embeddings=None,
105
+ box_mask=None,
106
+ point_embeddings=None,
107
+ point_mask=None,
108
+ box_labels=None,
109
+ point_labels=None,
110
+ mask_embeddings=None,
111
+ mask_mask=None, # Attention mask for mask prompt
112
+ mask_labels=None,
113
+ ):
114
+ # Check for null prompt
115
+ if (
116
+ box_embeddings is None
117
+ and point_embeddings is None
118
+ and mask_embeddings is None
119
+ ):
120
+ self.box_embeddings = None
121
+ self.box_labels = None
122
+ self.box_mask = None
123
+ self.point_embeddings = None
124
+ self.point_labels = None
125
+ self.point_mask = None
126
+ self.mask_embeddings = None
127
+ self.mask_mask = None
128
+ # Masks are assumed positive only for now.
129
+ self.mask_labels = None
130
+ return
131
+ # Get sequence lengths and device
132
+ box_seq_len, point_seq_len, mask_seq_len, bs, device = (
133
+ self._init_seq_len_and_device(
134
+ box_embeddings, point_embeddings, mask_embeddings
135
+ )
136
+ )
137
+
138
+ # Initialize embeds, labels, attention masks.
139
+ box_embeddings, box_labels, box_mask = self._init_box(
140
+ box_embeddings, box_labels, box_mask, box_seq_len, bs, device
141
+ )
142
+ point_embeddings, point_labels, point_mask = self._init_point(
143
+ point_embeddings, point_labels, point_mask, point_seq_len, bs, device
144
+ )
145
+ mask_embeddings, mask_labels, mask_mask = self._init_mask(
146
+ mask_embeddings, mask_labels, mask_mask, mask_seq_len, bs, device
147
+ )
148
+
149
+ # Dimension checks
150
+ assert box_embeddings is not None and list(box_embeddings.shape[:2]) == [
151
+ box_seq_len,
152
+ bs,
153
+ ], (
154
+ f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
155
+ )
156
+ assert box_mask is not None and list(box_mask.shape) == [
157
+ bs,
158
+ box_seq_len,
159
+ ], (
160
+ f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
161
+ )
162
+ assert point_embeddings is not None and list(point_embeddings.shape[:2]) == [
163
+ point_seq_len,
164
+ bs,
165
+ ], (
166
+ f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
167
+ )
168
+ assert point_mask is not None and list(point_mask.shape) == [
169
+ bs,
170
+ point_seq_len,
171
+ ], (
172
+ f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
173
+ )
174
+ assert box_labels is not None and list(box_labels.shape) == [
175
+ box_seq_len,
176
+ bs,
177
+ ], (
178
+ f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
179
+ )
180
+ assert point_labels is not None and list(point_labels.shape) == [
181
+ point_seq_len,
182
+ bs,
183
+ ], (
184
+ f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_labels.shape}"
185
+ )
186
+ assert (
187
+ # Allowed to be None, we leave it to the encoder to check for validity before encoding.
188
+ mask_embeddings is None
189
+ or list(mask_embeddings.shape[:2])
190
+ == [
191
+ mask_seq_len,
192
+ bs,
193
+ ]
194
+ ), (
195
+ f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
196
+ )
197
+ assert mask_mask is None or list(mask_mask.shape) == [
198
+ bs,
199
+ mask_seq_len,
200
+ ], (
201
+ f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
202
+ )
203
+
204
+ # Device checks
205
+ assert box_embeddings is not None and box_embeddings.device == device, (
206
+ f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
207
+ )
208
+ assert box_mask is not None and box_mask.device == device, (
209
+ f"Expected box mask to be on device {device}, got {box_mask.device}"
210
+ )
211
+ assert box_labels is not None and box_labels.device == device, (
212
+ f"Expected box labels to be on device {device}, got {box_labels.device}"
213
+ )
214
+ assert point_embeddings is not None and point_embeddings.device == device, (
215
+ f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
216
+ )
217
+ assert point_mask is not None and point_mask.device == device, (
218
+ f"Expected point mask to be on device {device}, got {point_mask.device}"
219
+ )
220
+ assert point_labels is not None and point_labels.device == device, (
221
+ f"Expected point labels to be on device {device}, got {point_labels.device}"
222
+ )
223
+ assert mask_embeddings is None or mask_embeddings.device == device, (
224
+ f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
225
+ )
226
+ assert mask_mask is None or mask_mask.device == device, (
227
+ f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
228
+ )
229
+
230
+ self.box_embeddings = box_embeddings
231
+ self.point_embeddings = point_embeddings
232
+ self.box_mask = box_mask
233
+ self.point_mask = point_mask
234
+ self.box_labels = box_labels
235
+ self.point_labels = point_labels
236
+ self.mask_embeddings = mask_embeddings
237
+ self.mask_labels = mask_labels
238
+ self.mask_mask = mask_mask
239
+
240
+ def _init_seq_len_and_device(
241
+ self, box_embeddings, point_embeddings, mask_embeddings
242
+ ):
243
+ box_seq_len = point_seq_len = mask_seq_len = 0
244
+ bs = None
245
+ device = None
246
+ if box_embeddings is not None:
247
+ bs = box_embeddings.shape[1]
248
+ box_seq_len = box_embeddings.shape[0]
249
+ device = box_embeddings.device
250
+
251
+ if point_embeddings is not None:
252
+ point_seq_len = point_embeddings.shape[0]
253
+ if bs is not None:
254
+ assert bs == point_embeddings.shape[1], (
255
+ f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
256
+ )
257
+ else:
258
+ bs = point_embeddings.shape[1]
259
+ if device is not None:
260
+ assert device == point_embeddings.device, (
261
+ "Device mismatch between box and point embeddings"
262
+ )
263
+ else:
264
+ device = point_embeddings.device
265
+
266
+ if mask_embeddings is not None:
267
+ mask_seq_len = mask_embeddings.shape[0]
268
+ if bs is not None:
269
+ assert bs == mask_embeddings.shape[1], (
270
+ f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
271
+ )
272
+ else:
273
+ bs = mask_embeddings.shape[1]
274
+ if device is not None:
275
+ assert device == mask_embeddings.device, (
276
+ "Device mismatch between box/point and mask embeddings."
277
+ )
278
+ else:
279
+ device = mask_embeddings.device
280
+
281
+ return box_seq_len, point_seq_len, mask_seq_len, bs, device
282
+
283
+ def _init_box(self, box_embeddings, box_labels, box_mask, box_seq_len, bs, device):
284
+ if box_embeddings is None:
285
+ box_embeddings = torch.zeros(box_seq_len, bs, 4, device=device)
286
+ if box_labels is None:
287
+ box_labels = torch.ones(box_seq_len, bs, device=device, dtype=torch.long)
288
+ if box_mask is None:
289
+ box_mask = torch.zeros(bs, box_seq_len, device=device, dtype=torch.bool)
290
+ return box_embeddings, box_labels, box_mask
291
+
292
+ def _init_point(
293
+ self, point_embeddings, point_labels, point_mask, point_seq_len, bs, device
294
+ ):
295
+ """
296
+ Identical to _init_box. Except that C=2 for points (vs. 4 for boxes).
297
+ """
298
+ if point_embeddings is None:
299
+ point_embeddings = torch.zeros(point_seq_len, bs, 2, device=device)
300
+ if point_labels is None:
301
+ point_labels = torch.ones(
302
+ point_seq_len, bs, device=device, dtype=torch.long
303
+ )
304
+ if point_mask is None:
305
+ point_mask = torch.zeros(bs, point_seq_len, device=device, dtype=torch.bool)
306
+ return point_embeddings, point_labels, point_mask
307
+
308
+ def _init_mask(
309
+ self, mask_embeddings, mask_labels, mask_mask, mask_seq_len, bs, device
310
+ ):
311
+ # NOTE: Mask embeddings can be of arbitrary resolution, so we don't initialize it here.
312
+ # In case we append new mask, we check that its resolution matches exisiting ones (if any).
313
+ # In case mask_embeddings is None, we should never encode it.
314
+ if mask_labels is None:
315
+ mask_labels = torch.ones(mask_seq_len, bs, device=device, dtype=torch.long)
316
+ if mask_mask is None:
317
+ mask_mask = torch.zeros(bs, mask_seq_len, device=device, dtype=torch.bool)
318
+ return mask_embeddings, mask_labels, mask_mask
319
+
320
+ def append_boxes(self, boxes, labels, mask=None):
321
+ if self.box_embeddings is None:
322
+ self.box_embeddings = boxes
323
+ self.box_labels = labels
324
+ self.box_mask = mask
325
+ return
326
+
327
+ bs = self.box_embeddings.shape[1]
328
+ assert boxes.shape[1] == labels.shape[1] == bs
329
+ assert list(boxes.shape[:2]) == list(labels.shape[:2])
330
+ if mask is None:
331
+ mask = torch.zeros(
332
+ bs, boxes.shape[0], dtype=torch.bool, device=boxes.device
333
+ )
334
+
335
+ self.box_labels, _ = concat_padded_sequences(
336
+ self.box_labels.unsqueeze(-1), self.box_mask, labels.unsqueeze(-1), mask
337
+ )
338
+ self.box_labels = self.box_labels.squeeze(-1)
339
+ self.box_embeddings, self.box_mask = concat_padded_sequences(
340
+ self.box_embeddings, self.box_mask, boxes, mask
341
+ )
342
+
343
+ def append_points(self, points, labels, mask=None):
344
+ if self.point_embeddings is None:
345
+ self.point_embeddings = points
346
+ self.point_labels = labels
347
+ self.point_mask = mask
348
+ return
349
+
350
+ bs = self.point_embeddings.shape[1]
351
+ assert points.shape[1] == labels.shape[1] == bs
352
+ assert list(points.shape[:2]) == list(labels.shape[:2])
353
+ if mask is None:
354
+ mask = torch.zeros(
355
+ bs, points.shape[0], dtype=torch.bool, device=points.device
356
+ )
357
+
358
+ self.point_labels, _ = concat_padded_sequences(
359
+ self.point_labels.unsqueeze(-1), self.point_mask, labels.unsqueeze(-1), mask
360
+ )
361
+ self.point_labels = self.point_labels.squeeze(-1)
362
+ self.point_embeddings, self.point_mask = concat_padded_sequences(
363
+ self.point_embeddings, self.point_mask, points, mask
364
+ )
365
+
366
+ def append_masks(self, masks, labels=None, attn_mask=None):
367
+ if labels is not None:
368
+ assert list(masks.shape[:2]) == list(labels.shape[:2])
369
+ if self.mask_embeddings is None:
370
+ self.mask_embeddings = masks
371
+ mask_seq_len, bs = masks.shape[:2]
372
+ if labels is None:
373
+ self.mask_labels = torch.ones(
374
+ mask_seq_len, bs, device=masks.device, dtype=torch.long
375
+ )
376
+ else:
377
+ self.mask_labels = labels
378
+ if attn_mask is None:
379
+ self.mask_mask = torch.zeros(
380
+ bs, mask_seq_len, device=masks.device, dtype=torch.bool
381
+ )
382
+ else:
383
+ self.mask_mask = attn_mask
384
+ else:
385
+ raise NotImplementedError("Only one mask per prompt is supported.")
386
+
387
+ def clone(self):
388
+ return Prompt(
389
+ box_embeddings=(
390
+ None if self.box_embeddings is None else self.box_embeddings.clone()
391
+ ),
392
+ box_mask=None if self.box_mask is None else self.box_mask.clone(),
393
+ point_embeddings=(
394
+ None if self.point_embeddings is None else self.point_embeddings.clone()
395
+ ),
396
+ point_mask=None if self.point_mask is None else self.point_mask.clone(),
397
+ box_labels=None if self.box_labels is None else self.box_labels.clone(),
398
+ point_labels=(
399
+ None if self.point_labels is None else self.point_labels.clone()
400
+ ),
401
+ )
402
+
403
+
404
+ class MaskEncoder(nn.Module):
405
+ """
406
+ Base class for mask encoders.
407
+ """
408
+
409
+ def __init__(
410
+ self,
411
+ mask_downsampler: nn.Module,
412
+ position_encoding: nn.Module,
413
+ ):
414
+ super().__init__()
415
+ self.mask_downsampler = mask_downsampler
416
+ self.position_encoding = position_encoding
417
+
418
+ def forward(self, masks, *args, **kwargs) -> Tuple[torch.Tensor, torch.Tensor]:
419
+ masks = self.mask_downsampler(masks)
420
+ masks_pos = self.position_encoding(masks).to(masks.dtype)
421
+
422
+ return masks, masks_pos
423
+
424
+
425
+ class FusedMaskEncoder(MaskEncoder):
426
+ """
427
+ Identical to memory.SimpleMaskEncoder but follows the interface of geometry_encoders.MaskEncoder.
428
+ We also remove the `skip_mask_sigmoid` option (to be handled outside the MaskEncoder).
429
+ Fuses backbone image features with mask features.
430
+ """
431
+
432
+ def __init__(
433
+ self,
434
+ mask_downsampler: nn.Module,
435
+ position_encoding: nn.Module,
436
+ fuser: nn.Module,
437
+ in_dim: int = 256,
438
+ out_dim: int = 256,
439
+ ):
440
+ super().__init__(mask_downsampler, position_encoding)
441
+ self.fuser = fuser
442
+ self.out_proj = nn.Identity()
443
+ if out_dim != in_dim:
444
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
445
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
446
+
447
+ @override
448
+ def forward(
449
+ self,
450
+ masks: torch.Tensor,
451
+ pix_feat: torch.Tensor,
452
+ **kwargs,
453
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
454
+ masks = self.mask_downsampler(masks)
455
+
456
+ ## Fuse pix_feats and downsampled masks
457
+ # in case the visual features are on CPU, cast them to CUDA
458
+ pix_feat = pix_feat.to(masks.device)
459
+
460
+ x = self.pix_feat_proj(pix_feat)
461
+ x = x + masks
462
+ x = self.fuser(x)
463
+ x = self.out_proj(x)
464
+
465
+ pos = self.position_encoding(x).to(x.dtype)
466
+
467
+ return x, pos
468
+
469
+
470
+ class SequenceGeometryEncoder(nn.Module):
471
+ """
472
+ This a fully fledged encoder for geometric prompts.
473
+ It assumes boxes are passed in the "normalized CxCyWH" format, and points in normalized xy
474
+ This allows flexibility in how to encode the features (eg do pooling)
475
+
476
+ Points and boxes can be encoded with any of the three possibilities:
477
+ - direct projection: we just compute a linear from coordinate space to d_model
478
+ - pooling: pool features from the backbone in the requested location.
479
+ For boxes, it's a roi align
480
+ For points it's a grid sample
481
+ - pos encoder: Take the position encoding of the point or box center
482
+
483
+ These three options are mutually compatible. If several are selected, we'll take a simple addition
484
+
485
+ As an alternative, we offer the possibility to encode points only.
486
+ In that case, the boxes are converted to two points for the top left and bottom right corners (with appropriate labels)
487
+
488
+ On top of these encodings, we offer the possibility to further encode the prompt sequence with a transformer.
489
+ """
490
+
491
+ def __init__(
492
+ self,
493
+ encode_boxes_as_points: bool,
494
+ points_direct_project: bool,
495
+ points_pool: bool,
496
+ points_pos_enc: bool,
497
+ boxes_direct_project: bool,
498
+ boxes_pool: bool,
499
+ boxes_pos_enc: bool,
500
+ d_model: int,
501
+ pos_enc,
502
+ num_layers: int,
503
+ layer: nn.Module,
504
+ roi_size: int = 7, # for boxes pool
505
+ add_cls: bool = True,
506
+ add_post_encode_proj: bool = True,
507
+ mask_encoder: MaskEncoder = None,
508
+ add_mask_label: bool = False,
509
+ use_act_ckpt: bool = False,
510
+ ):
511
+ super().__init__()
512
+
513
+ self.d_model = d_model
514
+ self.pos_enc = pos_enc
515
+ self.encode_boxes_as_points = encode_boxes_as_points
516
+ self.roi_size = roi_size
517
+ # There usually are two labels: positive and negatives.
518
+ # If we encode boxes as points, we have 3 types of points: regular, top left, bottom right
519
+ # These 3 types can be positives or negatives, hence 2*3 = 6 labels
520
+ num_labels = 6 if self.encode_boxes_as_points else 2
521
+ self.label_embed = torch.nn.Embedding(num_labels, self.d_model)
522
+
523
+ # This is a cls token, can be used for pooling if need be.
524
+ # It also ensures that the encoded sequences are always non-empty
525
+ self.cls_embed = None
526
+ if add_cls:
527
+ self.cls_embed = torch.nn.Embedding(1, self.d_model)
528
+
529
+ assert points_direct_project or points_pos_enc or points_pool, (
530
+ "Error: need at least one way to encode points"
531
+ )
532
+ assert (
533
+ encode_boxes_as_points
534
+ or boxes_direct_project
535
+ or boxes_pos_enc
536
+ or boxes_pool
537
+ ), "Error: need at least one way to encode boxes"
538
+
539
+ self.points_direct_project = None
540
+ if points_direct_project:
541
+ self.points_direct_project = nn.Linear(2, self.d_model)
542
+ self.points_pool_project = None
543
+ if points_pool:
544
+ self.points_pool_project = nn.Linear(self.d_model, self.d_model)
545
+ self.points_pos_enc_project = None
546
+ if points_pos_enc:
547
+ self.points_pos_enc_project = nn.Linear(self.d_model, self.d_model)
548
+
549
+ self.boxes_direct_project = None
550
+ self.boxes_pool_project = None
551
+ self.boxes_pos_enc_project = None
552
+ if not encode_boxes_as_points:
553
+ if boxes_direct_project:
554
+ self.boxes_direct_project = nn.Linear(4, self.d_model)
555
+ if boxes_pool:
556
+ self.boxes_pool_project = nn.Conv2d(
557
+ self.d_model, self.d_model, self.roi_size
558
+ )
559
+ if boxes_pos_enc:
560
+ self.boxes_pos_enc_project = nn.Linear(self.d_model + 2, self.d_model)
561
+
562
+ self.final_proj = None
563
+ if add_post_encode_proj:
564
+ self.final_proj = nn.Linear(self.d_model, self.d_model)
565
+ self.norm = nn.LayerNorm(self.d_model)
566
+
567
+ self.img_pre_norm = nn.Identity()
568
+ if self.points_pool_project is not None or self.boxes_pool_project is not None:
569
+ self.img_pre_norm = nn.LayerNorm(self.d_model)
570
+
571
+ self.encode = None
572
+ if num_layers > 0:
573
+ assert add_cls, (
574
+ "It's currently highly recommended to add a CLS when using a transformer"
575
+ )
576
+ self.encode = get_clones(layer, num_layers)
577
+ self.encode_norm = nn.LayerNorm(self.d_model)
578
+
579
+ if mask_encoder is not None:
580
+ assert isinstance(mask_encoder, MaskEncoder), (
581
+ f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
582
+ )
583
+ if add_mask_label:
584
+ self.mask_label_embed = torch.nn.Embedding(2, self.d_model)
585
+ self.add_mask_label = add_mask_label
586
+ self.mask_encoder = mask_encoder
587
+ self.use_act_ckpt = use_act_ckpt
588
+
589
+ def _encode_points(self, points, points_mask, points_labels, img_feats):
590
+ points_embed = None
591
+ n_points, bs = points.shape[:2]
592
+
593
+ if self.points_direct_project is not None:
594
+ proj = self.points_direct_project(points)
595
+ assert points_embed is None
596
+ points_embed = proj
597
+
598
+ if self.points_pool_project is not None:
599
+ # points are [Num_points, bs, 2], normalized in [0, 1]
600
+ # the grid needs to be [Bs, H_out, W_out, 2] normalized in [-1,1]
601
+ # Will take H_out = num_points, w_out = 1
602
+ grid = points.transpose(0, 1).unsqueeze(2)
603
+ # re normalize to [-1, 1]
604
+ grid = (grid * 2) - 1
605
+ sampled = torch.nn.functional.grid_sample(
606
+ img_feats, grid, align_corners=False
607
+ )
608
+ assert list(sampled.shape) == [bs, self.d_model, n_points, 1]
609
+ sampled = sampled.squeeze(-1).permute(2, 0, 1)
610
+ proj = self.points_pool_project(sampled)
611
+ if points_embed is None:
612
+ points_embed = proj
613
+ else:
614
+ points_embed = points_embed + proj
615
+
616
+ if self.points_pos_enc_project is not None:
617
+ x, y = points.unbind(-1)
618
+ enc_x, enc_y = self.pos_enc._encode_xy(x.flatten(), y.flatten())
619
+ enc_x = enc_x.view(n_points, bs, enc_x.shape[-1])
620
+ enc_y = enc_y.view(n_points, bs, enc_y.shape[-1])
621
+ enc = torch.cat([enc_x, enc_y], -1)
622
+
623
+ proj = self.points_pos_enc_project(enc)
624
+ if points_embed is None:
625
+ points_embed = proj
626
+ else:
627
+ points_embed = points_embed + proj
628
+
629
+ type_embed = self.label_embed(points_labels.long())
630
+ return type_embed + points_embed, points_mask
631
+
632
+ def _encode_boxes(self, boxes, boxes_mask, boxes_labels, img_feats):
633
+ boxes_embed = None
634
+ n_boxes, bs = boxes.shape[:2]
635
+
636
+ if self.boxes_direct_project is not None:
637
+ proj = self.boxes_direct_project(boxes)
638
+ assert boxes_embed is None
639
+ boxes_embed = proj
640
+
641
+ if self.boxes_pool_project is not None:
642
+ H, W = img_feats.shape[-2:]
643
+
644
+ # boxes are [Num_boxes, bs, 4], normalized in [0, 1]
645
+ # We need to denormalize, and convert to [x, y, x, y]
646
+ boxes_xyxy = box_cxcywh_to_xyxy(boxes)
647
+ scale = torch.tensor([W, H, W, H], dtype=boxes_xyxy.dtype)
648
+ scale = scale.pin_memory().to(device=boxes_xyxy.device, non_blocking=True)
649
+ scale = scale.view(1, 1, 4)
650
+ boxes_xyxy = boxes_xyxy * scale
651
+ sampled = torchvision.ops.roi_align(
652
+ img_feats, boxes_xyxy.float().transpose(0, 1).unbind(0), self.roi_size
653
+ )
654
+ assert list(sampled.shape) == [
655
+ bs * n_boxes,
656
+ self.d_model,
657
+ self.roi_size,
658
+ self.roi_size,
659
+ ]
660
+ proj = self.boxes_pool_project(sampled)
661
+ proj = proj.view(bs, n_boxes, self.d_model).transpose(0, 1)
662
+ if boxes_embed is None:
663
+ boxes_embed = proj
664
+ else:
665
+ boxes_embed = boxes_embed + proj
666
+
667
+ if self.boxes_pos_enc_project is not None:
668
+ cx, cy, w, h = boxes.unbind(-1)
669
+ enc = self.pos_enc.encode_boxes(
670
+ cx.flatten(), cy.flatten(), w.flatten(), h.flatten()
671
+ )
672
+ enc = enc.view(boxes.shape[0], boxes.shape[1], enc.shape[-1])
673
+
674
+ proj = self.boxes_pos_enc_project(enc)
675
+ if boxes_embed is None:
676
+ boxes_embed = proj
677
+ else:
678
+ boxes_embed = boxes_embed + proj
679
+
680
+ type_embed = self.label_embed(boxes_labels.long())
681
+ return type_embed + boxes_embed, boxes_mask
682
+
683
+ def _encode_masks(
684
+ self,
685
+ masks: torch.Tensor,
686
+ attn_mask: torch.Tensor,
687
+ mask_labels: torch.Tensor,
688
+ img_feats: torch.Tensor = None,
689
+ ):
690
+ n_masks, bs = masks.shape[:2]
691
+ assert n_masks == 1, (
692
+ "We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
693
+ )
694
+ assert list(attn_mask.shape) == [
695
+ bs,
696
+ n_masks,
697
+ ], (
698
+ f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
699
+ )
700
+ masks, pos = self.mask_encoder(
701
+ masks=masks.flatten(0, 1).float(),
702
+ pix_feat=img_feats,
703
+ )
704
+ H, W = masks.shape[-2:]
705
+ n_tokens_per_mask = H * W
706
+ # NOTE: We directly add pos enc here as we usually don't keep track of pos encoding for the concatenated prompt (text, other geometric prompts). Might need to do some refactoring for more flexibility.
707
+ masks = masks + pos
708
+ masks = masks.view(n_masks, bs, *masks.shape[1:]).flatten(
709
+ -2
710
+ ) # n_masks x bs x C x H*W
711
+ masks = masks.permute(0, 3, 1, 2).flatten(0, 1) # n_masks * H*W x bs x C
712
+ attn_mask = attn_mask.repeat_interleave(n_tokens_per_mask, dim=1)
713
+ if self.add_mask_label:
714
+ masks = masks + self.mask_label_embed(mask_labels.long())
715
+ return masks, attn_mask
716
+
717
+ def forward(self, geo_prompt: Prompt, img_feats, img_sizes, img_pos_embeds=None):
718
+ points = geo_prompt.point_embeddings
719
+ points_mask = geo_prompt.point_mask
720
+ points_labels = geo_prompt.point_labels
721
+ boxes = geo_prompt.box_embeddings
722
+ boxes_mask = geo_prompt.box_mask
723
+ boxes_labels = geo_prompt.box_labels
724
+ masks = geo_prompt.mask_embeddings
725
+ masks_mask = geo_prompt.mask_mask
726
+ masks_labels = geo_prompt.mask_labels
727
+ seq_first_img_feats = img_feats[-1] # [H*W, B, C]
728
+ seq_first_img_pos_embeds = (
729
+ img_pos_embeds[-1]
730
+ if img_pos_embeds is not None
731
+ else torch.zeros_like(seq_first_img_feats)
732
+ )
733
+
734
+ if self.points_pool_project or self.boxes_pool_project:
735
+ assert len(img_feats) == len(img_sizes)
736
+ cur_img_feat = img_feats[-1]
737
+ cur_img_feat = self.img_pre_norm(cur_img_feat)
738
+ H, W = img_sizes[-1]
739
+ assert cur_img_feat.shape[0] == H * W
740
+ N, C = cur_img_feat.shape[-2:]
741
+ # Put back in NxCxHxW
742
+ cur_img_feat = cur_img_feat.permute(1, 2, 0)
743
+ cur_img_feat = cur_img_feat.view(N, C, H, W)
744
+ img_feats = cur_img_feat
745
+
746
+ if self.encode_boxes_as_points:
747
+ assert boxes is not None
748
+ assert geo_prompt.box_mask is not None
749
+ assert geo_prompt.box_labels is not None
750
+ assert boxes.shape[-1] == 4
751
+
752
+ boxes_xyxy = box_cxcywh_to_xyxy(boxes)
753
+ top_left, bottom_right = boxes_xyxy.split(split_size=2, dim=-1)
754
+
755
+ labels_tl = geo_prompt.box_labels + 2
756
+ labels_br = geo_prompt.box_labels + 4
757
+
758
+ # Append to the existing points
759
+ points, _ = concat_padded_sequences(
760
+ points, points_mask, top_left, boxes_mask
761
+ )
762
+ points_labels, points_mask = concat_padded_sequences(
763
+ points_labels.unsqueeze(-1),
764
+ points_mask,
765
+ labels_tl.unsqueeze(-1),
766
+ boxes_mask,
767
+ )
768
+ points_labels = points_labels.squeeze(-1)
769
+
770
+ points, _ = concat_padded_sequences(
771
+ points, points_mask, bottom_right, boxes_mask
772
+ )
773
+ points_labels, points_mask = concat_padded_sequences(
774
+ points_labels.unsqueeze(-1),
775
+ points_mask,
776
+ labels_br.unsqueeze(-1),
777
+ boxes_mask,
778
+ )
779
+ points_labels = points_labels.squeeze(-1)
780
+
781
+ final_embeds, final_mask = self._encode_points(
782
+ points=points,
783
+ points_mask=points_mask,
784
+ points_labels=points_labels,
785
+ img_feats=img_feats,
786
+ )
787
+
788
+ if not self.encode_boxes_as_points:
789
+ boxes_embeds, boxes_mask = self._encode_boxes(
790
+ boxes=boxes,
791
+ boxes_mask=boxes_mask,
792
+ boxes_labels=boxes_labels,
793
+ img_feats=img_feats,
794
+ )
795
+
796
+ final_embeds, final_mask = concat_padded_sequences(
797
+ final_embeds, final_mask, boxes_embeds, boxes_mask
798
+ )
799
+
800
+ if masks is not None and self.mask_encoder is not None:
801
+ masks_embed, masks_mask = self._encode_masks(
802
+ masks=masks,
803
+ attn_mask=masks_mask,
804
+ mask_labels=masks_labels,
805
+ img_feats=img_feats,
806
+ )
807
+ if points.size(0) == boxes.size(0) == 0:
808
+ return masks_embed, masks_mask
809
+ bs = final_embeds.shape[1]
810
+ assert final_mask.shape[0] == bs
811
+ if self.cls_embed is not None:
812
+ cls = self.cls_embed.weight.view(1, 1, self.d_model).repeat(1, bs, 1)
813
+ cls_mask = torch.zeros(
814
+ bs, 1, dtype=final_mask.dtype, device=final_mask.device
815
+ )
816
+ final_embeds, final_mask = concat_padded_sequences(
817
+ final_embeds, final_mask, cls, cls_mask
818
+ )
819
+
820
+ if self.final_proj is not None:
821
+ final_embeds = self.norm(self.final_proj(final_embeds))
822
+
823
+ if self.encode is not None:
824
+ for lay in self.encode:
825
+ final_embeds = activation_ckpt_wrapper(lay)(
826
+ tgt=final_embeds,
827
+ memory=seq_first_img_feats,
828
+ tgt_key_padding_mask=final_mask,
829
+ pos=seq_first_img_pos_embeds,
830
+ act_ckpt_enable=self.training and self.use_act_ckpt,
831
+ )
832
+ final_embeds = self.encode_norm(final_embeds)
833
+ # Finally, concat mask embeddings if any
834
+ if masks is not None and self.mask_encoder is not None:
835
+ final_embeds, final_mask = concat_padded_sequences(
836
+ final_embeds, final_mask, masks_embed, masks_mask
837
+ )
838
+ return final_embeds, final_mask
third_party/GraspGen/sam3/sam3/model/io_utils.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import contextlib
6
+ import os
7
+ import queue
8
+ import re
9
+ import time
10
+ from threading import Condition, get_ident, Lock, Thread
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms.functional as TF
16
+ from PIL import Image
17
+ from sam3.logger import get_logger
18
+ from tqdm import tqdm
19
+
20
+ logger = get_logger(__name__)
21
+
22
+ IS_MAIN_PROCESS = os.getenv("IS_MAIN_PROCESS", "1") == "1"
23
+ RANK = int(os.getenv("RANK", "0"))
24
+
25
+ IMAGE_EXTS = [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp"]
26
+ VIDEO_EXTS = [".mp4", ".mov", ".avi", ".mkv", ".webm"]
27
+
28
+
29
+ def load_resource_as_video_frames(
30
+ resource_path,
31
+ image_size,
32
+ offload_video_to_cpu,
33
+ img_mean=(0.5, 0.5, 0.5),
34
+ img_std=(0.5, 0.5, 0.5),
35
+ async_loading_frames=False,
36
+ video_loader_type="cv2",
37
+ ):
38
+ """
39
+ Load video frames from either a video or an image (as a single-frame video).
40
+ Alternatively, if input is a list of PIL images, convert its format
41
+ """
42
+ if isinstance(resource_path, list):
43
+ img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
44
+ img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
45
+ assert all(isinstance(img_pil, Image.Image) for img_pil in resource_path)
46
+ assert len(resource_path) is not None
47
+ orig_height, orig_width = resource_path[0].size
48
+ orig_height, orig_width = (
49
+ orig_width,
50
+ orig_height,
51
+ ) # For some reason, this method returns these swapped
52
+ images = []
53
+ for img_pil in resource_path:
54
+ img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
55
+ assert img_np.dtype == np.uint8, "np.uint8 is expected for JPEG images"
56
+ img_np = img_np / 255.0
57
+ img = torch.from_numpy(img_np).permute(2, 0, 1)
58
+ # float16 precision should be sufficient for image tensor storage
59
+ img = img.to(dtype=torch.float16)
60
+ # normalize by mean and std
61
+ img -= img_mean
62
+ img /= img_std
63
+ images.append(img)
64
+ images = torch.stack(images)
65
+ if not offload_video_to_cpu:
66
+ images = images.cuda()
67
+ return images, orig_height, orig_width
68
+
69
+ is_image = (
70
+ isinstance(resource_path, str)
71
+ and os.path.splitext(resource_path)[-1].lower() in IMAGE_EXTS
72
+ )
73
+ if is_image:
74
+ return load_image_as_single_frame_video(
75
+ image_path=resource_path,
76
+ image_size=image_size,
77
+ offload_video_to_cpu=offload_video_to_cpu,
78
+ img_mean=img_mean,
79
+ img_std=img_std,
80
+ )
81
+ else:
82
+ return load_video_frames(
83
+ video_path=resource_path,
84
+ image_size=image_size,
85
+ offload_video_to_cpu=offload_video_to_cpu,
86
+ img_mean=img_mean,
87
+ img_std=img_std,
88
+ async_loading_frames=async_loading_frames,
89
+ video_loader_type=video_loader_type,
90
+ )
91
+
92
+
93
+ def load_image_as_single_frame_video(
94
+ image_path,
95
+ image_size,
96
+ offload_video_to_cpu,
97
+ img_mean=(0.5, 0.5, 0.5),
98
+ img_std=(0.5, 0.5, 0.5),
99
+ ):
100
+ """Load an image as a single-frame video."""
101
+ images, image_height, image_width = _load_img_as_tensor(image_path, image_size)
102
+ images = images.unsqueeze(0).half()
103
+
104
+ img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
105
+ img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
106
+ if not offload_video_to_cpu:
107
+ images = images.cuda()
108
+ img_mean = img_mean.cuda()
109
+ img_std = img_std.cuda()
110
+ # normalize by mean and std
111
+ images -= img_mean
112
+ images /= img_std
113
+ return images, image_height, image_width
114
+
115
+
116
+ def load_video_frames(
117
+ video_path,
118
+ image_size,
119
+ offload_video_to_cpu,
120
+ img_mean=(0.5, 0.5, 0.5),
121
+ img_std=(0.5, 0.5, 0.5),
122
+ async_loading_frames=False,
123
+ video_loader_type="cv2",
124
+ ):
125
+ """
126
+ Load the video frames from video_path. The frames are resized to image_size as in
127
+ the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo.
128
+ """
129
+ assert isinstance(video_path, str)
130
+ if video_path.startswith("<load-dummy-video"):
131
+ # Check for pattern <load-dummy-video-N> where N is an integer
132
+ match = re.match(r"<load-dummy-video-(\d+)>", video_path)
133
+ num_frames = int(match.group(1)) if match else 60
134
+ return load_dummy_video(image_size, offload_video_to_cpu, num_frames=num_frames)
135
+ elif os.path.isdir(video_path):
136
+ return load_video_frames_from_image_folder(
137
+ image_folder=video_path,
138
+ image_size=image_size,
139
+ offload_video_to_cpu=offload_video_to_cpu,
140
+ img_mean=img_mean,
141
+ img_std=img_std,
142
+ async_loading_frames=async_loading_frames,
143
+ )
144
+ elif os.path.splitext(video_path)[-1].lower() in VIDEO_EXTS:
145
+ return load_video_frames_from_video_file(
146
+ video_path=video_path,
147
+ image_size=image_size,
148
+ offload_video_to_cpu=offload_video_to_cpu,
149
+ img_mean=img_mean,
150
+ img_std=img_std,
151
+ async_loading_frames=async_loading_frames,
152
+ video_loader_type=video_loader_type,
153
+ )
154
+ else:
155
+ raise NotImplementedError("Only video files and image folders are supported")
156
+
157
+
158
+ def load_video_frames_from_image_folder(
159
+ image_folder,
160
+ image_size,
161
+ offload_video_to_cpu,
162
+ img_mean,
163
+ img_std,
164
+ async_loading_frames,
165
+ ):
166
+ """
167
+ Load the video frames from a directory of image files ("<frame_index>.<img_ext>" format)
168
+ """
169
+ frame_names = [
170
+ p
171
+ for p in os.listdir(image_folder)
172
+ if os.path.splitext(p)[-1].lower() in IMAGE_EXTS
173
+ ]
174
+ try:
175
+ frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
176
+ except ValueError:
177
+ # fallback to lexicographic sort if the format is not "<frame_index>.<img_ext>"
178
+ logger.warning(
179
+ f'frame names are not in "<frame_index>.<img_ext>" format: {frame_names[:5]=}, '
180
+ f"falling back to lexicographic sort."
181
+ )
182
+ frame_names.sort()
183
+ num_frames = len(frame_names)
184
+ if num_frames == 0:
185
+ raise RuntimeError(f"no images found in {image_folder}")
186
+ img_paths = [os.path.join(image_folder, frame_name) for frame_name in frame_names]
187
+ img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
188
+ img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
189
+
190
+ if async_loading_frames:
191
+ lazy_images = AsyncImageFrameLoader(
192
+ img_paths, image_size, offload_video_to_cpu, img_mean, img_std
193
+ )
194
+ return lazy_images, lazy_images.video_height, lazy_images.video_width
195
+
196
+ # float16 precision should be sufficient for image tensor storage
197
+ images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float16)
198
+ video_height, video_width = None, None
199
+ for n, img_path in enumerate(
200
+ tqdm(img_paths, desc=f"frame loading (image folder) [rank={RANK}]")
201
+ ):
202
+ images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
203
+ if not offload_video_to_cpu:
204
+ images = images.cuda()
205
+ img_mean = img_mean.cuda()
206
+ img_std = img_std.cuda()
207
+ # normalize by mean and std
208
+ images -= img_mean
209
+ images /= img_std
210
+ return images, video_height, video_width
211
+
212
+
213
+ def load_video_frames_from_video_file(
214
+ video_path,
215
+ image_size,
216
+ offload_video_to_cpu,
217
+ img_mean,
218
+ img_std,
219
+ async_loading_frames,
220
+ gpu_acceleration=False,
221
+ gpu_device=None,
222
+ video_loader_type="cv2",
223
+ ):
224
+ """Load the video frames from a video file."""
225
+ if video_loader_type == "cv2":
226
+ return load_video_frames_from_video_file_using_cv2(
227
+ video_path=video_path,
228
+ image_size=image_size,
229
+ img_mean=img_mean,
230
+ img_std=img_std,
231
+ offload_video_to_cpu=offload_video_to_cpu,
232
+ )
233
+ elif video_loader_type == "torchcodec":
234
+ logger.info("Using torchcodec to load video file")
235
+ lazy_images = AsyncVideoFileLoaderWithTorchCodec(
236
+ video_path=video_path,
237
+ image_size=image_size,
238
+ offload_video_to_cpu=offload_video_to_cpu,
239
+ img_mean=img_mean,
240
+ img_std=img_std,
241
+ gpu_acceleration=gpu_acceleration,
242
+ gpu_device=gpu_device,
243
+ )
244
+ # The `AsyncVideoFileLoaderWithTorchCodec` class always loads the videos asynchronously,
245
+ # so we just wait for its loading thread to finish if async_loading_frames=False.
246
+ if not async_loading_frames:
247
+ async_thread = lazy_images.thread
248
+ if async_thread is not None:
249
+ async_thread.join()
250
+ return lazy_images, lazy_images.video_height, lazy_images.video_width
251
+ else:
252
+ raise RuntimeError("video_loader_type must be either 'cv2' or 'torchcodec'")
253
+
254
+
255
+ def load_video_frames_from_video_file_using_cv2(
256
+ video_path: str,
257
+ image_size: int,
258
+ img_mean: tuple = (0.5, 0.5, 0.5),
259
+ img_std: tuple = (0.5, 0.5, 0.5),
260
+ offload_video_to_cpu: bool = False,
261
+ ) -> torch.Tensor:
262
+ """
263
+ Load video from path, convert to normalized tensor with specified preprocessing
264
+
265
+ Args:
266
+ video_path: Path to video file
267
+ image_size: Target size for square frames (height and width)
268
+ img_mean: Normalization mean (RGB)
269
+ img_std: Normalization standard deviation (RGB)
270
+
271
+ Returns:
272
+ torch.Tensor: Preprocessed video tensor in shape (T, C, H, W) with float16 dtype
273
+ """
274
+ import cv2 # delay OpenCV import to avoid unnecessary dependency
275
+
276
+ # Initialize video capture
277
+ cap = cv2.VideoCapture(video_path)
278
+ if not cap.isOpened():
279
+ raise ValueError(f"Could not open video: {video_path}")
280
+
281
+ original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
282
+ original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
283
+ num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
284
+ num_frames = num_frames if num_frames > 0 else None
285
+
286
+ frames = []
287
+ pbar = tqdm(desc=f"frame loading (OpenCV) [rank={RANK}]", total=num_frames)
288
+ while True:
289
+ ret, frame = cap.read()
290
+ if not ret:
291
+ break
292
+
293
+ # Convert BGR to RGB and resize
294
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
295
+ frame_resized = cv2.resize(
296
+ frame_rgb, (image_size, image_size), interpolation=cv2.INTER_CUBIC
297
+ )
298
+ frames.append(frame_resized)
299
+ pbar.update(1)
300
+ cap.release()
301
+ pbar.close()
302
+
303
+ if len(frames) == 0:
304
+ raise RuntimeError(
305
+ f"No frames could be decoded from video: {video_path}. "
306
+ f"The file may be corrupted, empty, or encoded with an unsupported codec."
307
+ )
308
+
309
+ # Convert to tensor
310
+ frames_np = np.stack(frames, axis=0).astype(np.float32) # (T, H, W, C)
311
+ video_tensor = torch.from_numpy(frames_np).permute(0, 3, 1, 2) # (T, C, H, W)
312
+
313
+ img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1)
314
+ img_std = torch.tensor(img_std, dtype=torch.float16).view(1, 3, 1, 1)
315
+ if not offload_video_to_cpu:
316
+ video_tensor = video_tensor.cuda()
317
+ img_mean = img_mean.cuda()
318
+ img_std = img_std.cuda()
319
+ # normalize by mean and std
320
+ video_tensor -= img_mean
321
+ video_tensor /= img_std
322
+ return video_tensor, original_height, original_width
323
+
324
+
325
+ def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60):
326
+ """
327
+ Load a dummy video with random frames for testing and compilation warmup purposes.
328
+ """
329
+ video_height, video_width = 480, 640 # dummy original video sizes
330
+ images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
331
+ if not offload_video_to_cpu:
332
+ images = images.cuda()
333
+ return images, video_height, video_width
334
+
335
+
336
+ def _load_img_as_tensor(img_path, image_size):
337
+ """Load and resize an image and convert it into a PyTorch tensor."""
338
+ img = Image.open(img_path).convert("RGB")
339
+ orig_width, orig_height = img.width, img.height
340
+ img = TF.resize(img, size=(image_size, image_size))
341
+ img = TF.to_tensor(img)
342
+ return img, orig_height, orig_width
343
+
344
+
345
+ class AsyncImageFrameLoader:
346
+ """
347
+ A list of video frames to be load asynchronously without blocking session start.
348
+ """
349
+
350
+ def __init__(self, img_paths, image_size, offload_video_to_cpu, img_mean, img_std):
351
+ self.img_paths = img_paths
352
+ self.image_size = image_size
353
+ self.offload_video_to_cpu = offload_video_to_cpu
354
+ self.img_mean = img_mean
355
+ self.img_std = img_std
356
+ # items in `self._images` will be loaded asynchronously
357
+ self.images = [None] * len(img_paths)
358
+ # catch and raise any exceptions in the async loading thread
359
+ self.exception = None
360
+ # video_height and video_width be filled when loading the first image
361
+ self.video_height = None
362
+ self.video_width = None
363
+
364
+ # load the first frame to fill video_height and video_width and also
365
+ # to cache it (since it's most likely where the user will click)
366
+ self.__getitem__(0)
367
+
368
+ # load the rest of frames asynchronously without blocking the session start
369
+ def _load_frames():
370
+ try:
371
+ for n in tqdm(
372
+ range(len(self.images)),
373
+ desc=f"frame loading (image folder) [rank={RANK}]",
374
+ ):
375
+ self.__getitem__(n)
376
+ except Exception as e:
377
+ self.exception = e
378
+
379
+ self.thread = Thread(target=_load_frames, daemon=True)
380
+ self.thread.start()
381
+
382
+ def __getitem__(self, index):
383
+ if self.exception is not None:
384
+ raise RuntimeError("Failure in frame loading thread") from self.exception
385
+
386
+ img = self.images[index]
387
+ if img is not None:
388
+ return img
389
+
390
+ img, video_height, video_width = _load_img_as_tensor(
391
+ self.img_paths[index], self.image_size
392
+ )
393
+ self.video_height = video_height
394
+ self.video_width = video_width
395
+ # float16 precision should be sufficient for image tensor storage
396
+ img = img.to(dtype=torch.float16)
397
+ # normalize by mean and std
398
+ img -= self.img_mean
399
+ img /= self.img_std
400
+ if not self.offload_video_to_cpu:
401
+ img = img.cuda()
402
+ self.images[index] = img
403
+ return img
404
+
405
+ def __len__(self):
406
+ return len(self.images)
407
+
408
+
409
+ class TorchCodecDecoder:
410
+ """
411
+ A wrapper to support GPU device and num_threads in TorchCodec decoder,
412
+ which are not supported by `torchcodec.decoders.SimpleVideoDecoder` yet.
413
+ """
414
+
415
+ def __init__(self, source, dimension_order="NCHW", device="cpu", num_threads=1):
416
+ from torchcodec import _core as core
417
+
418
+ self._source = source # hold a reference to the source to prevent it from GC
419
+ if isinstance(source, str):
420
+ self._decoder = core.create_from_file(source, "exact")
421
+ elif isinstance(source, bytes):
422
+ self._decoder = core.create_from_bytes(source, "exact")
423
+ else:
424
+ raise TypeError(f"Unknown source type: {type(source)}.")
425
+ assert dimension_order in ("NCHW", "NHWC")
426
+
427
+ device_string = str(device)
428
+ core.scan_all_streams_to_update_metadata(self._decoder)
429
+ core.add_video_stream(
430
+ self._decoder,
431
+ dimension_order=dimension_order,
432
+ device=device_string,
433
+ num_threads=(1 if "cuda" in device_string else num_threads),
434
+ )
435
+ video_metadata = core.get_container_metadata(self._decoder)
436
+ best_stream_index = video_metadata.best_video_stream_index
437
+ assert best_stream_index is not None
438
+ self.metadata = video_metadata.streams[best_stream_index]
439
+ assert self.metadata.num_frames_from_content is not None
440
+ self._num_frames = self.metadata.num_frames_from_content
441
+
442
+ def __len__(self) -> int:
443
+ return self._num_frames
444
+
445
+ def __getitem__(self, key: int):
446
+ from torchcodec import _core as core
447
+
448
+ if key < 0:
449
+ key += self._num_frames
450
+ if key >= self._num_frames or key < 0:
451
+ raise IndexError(
452
+ f"Index {key} is out of bounds; length is {self._num_frames}"
453
+ )
454
+ frame_data, *_ = core.get_frame_at_index(
455
+ self._decoder,
456
+ frame_index=key,
457
+ )
458
+ return frame_data
459
+
460
+
461
+ class FIFOLock:
462
+ """A lock that ensures FIFO ordering of lock acquisitions."""
463
+
464
+ def __init__(self):
465
+ self._lock = Lock()
466
+ self._waiters = queue.Queue()
467
+ self._condition = Condition()
468
+
469
+ def acquire(self):
470
+ ident = get_ident()
471
+ with self._condition:
472
+ self._waiters.put(ident)
473
+ while self._waiters.queue[0] != ident or not self._lock.acquire(
474
+ blocking=False
475
+ ):
476
+ self._condition.wait()
477
+ # got the lock and it's our turn
478
+
479
+ def release(self):
480
+ with self._condition:
481
+ self._lock.release()
482
+ self._waiters.get()
483
+ self._condition.notify_all()
484
+
485
+ def __enter__(self):
486
+ self.acquire()
487
+
488
+ def __exit__(self, t, v, tb):
489
+ self.release()
490
+
491
+
492
+ class AsyncVideoFileLoaderWithTorchCodec:
493
+ """
494
+ Loading frames from video files asynchronously without blocking session start.
495
+
496
+ Unlike `AsyncVideoFileLoader`, this class uses PyTorch's offical TorchCodec library
497
+ for video decoding, which is more efficient and supports more video formats.
498
+ """
499
+
500
+ def __init__(
501
+ self,
502
+ video_path,
503
+ image_size,
504
+ offload_video_to_cpu,
505
+ img_mean,
506
+ img_std,
507
+ gpu_acceleration=True,
508
+ gpu_device=None,
509
+ use_rand_seek_in_loading=False,
510
+ ):
511
+ # Check and possibly infer the output device (and also get its GPU id when applicable)
512
+ assert gpu_device is None or gpu_device.type == "cuda"
513
+ gpu_id = (
514
+ gpu_device.index
515
+ if gpu_device is not None and gpu_device.index is not None
516
+ else torch.cuda.current_device()
517
+ )
518
+ if offload_video_to_cpu:
519
+ out_device = torch.device("cpu")
520
+ else:
521
+ out_device = torch.device("cuda") if gpu_device is None else gpu_device
522
+ self.out_device = out_device
523
+ self.gpu_acceleration = gpu_acceleration
524
+ self.gpu_id = gpu_id
525
+ self.image_size = image_size
526
+ self.offload_video_to_cpu = offload_video_to_cpu
527
+ if not isinstance(img_mean, torch.Tensor):
528
+ img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
529
+ self.img_mean = img_mean
530
+ if not isinstance(img_std, torch.Tensor):
531
+ img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
532
+ self.img_std = img_std
533
+
534
+ if gpu_acceleration:
535
+ self.img_mean = self.img_mean.to(f"cuda:{self.gpu_id}")
536
+ self.img_std = self.img_std.to(f"cuda:{self.gpu_id}")
537
+ decoder_option = {"device": f"cuda:{self.gpu_id}"}
538
+ else:
539
+ self.img_mean = self.img_mean.cpu()
540
+ self.img_std = self.img_std.cpu()
541
+ decoder_option = {"num_threads": 1} # use a single thread to save memory
542
+
543
+ self.rank = int(os.environ.get("RANK", "0"))
544
+ self.world_size = int(os.environ.get("WORLD_SIZE", "1"))
545
+ self.async_reader = TorchCodecDecoder(video_path, **decoder_option)
546
+
547
+ # `num_frames_from_content` is the true number of frames in the video content
548
+ # from the scan operation (rather than from the metadata, which could be wrong)
549
+ self.num_frames = self.async_reader.metadata.num_frames_from_content
550
+ self.video_height = self.async_reader.metadata.height
551
+ self.video_width = self.async_reader.metadata.width
552
+
553
+ # items in `self._images` will be loaded asynchronously
554
+ self.images_loaded = [False] * self.num_frames
555
+ self.images = torch.zeros(
556
+ self.num_frames,
557
+ 3,
558
+ self.image_size,
559
+ self.image_size,
560
+ dtype=torch.float16,
561
+ device=self.out_device,
562
+ )
563
+ # catch and raise any exceptions in the async loading thread
564
+ self.exception = None
565
+ self.use_rand_seek_in_loading = use_rand_seek_in_loading
566
+ self.rand_seek_idx_queue = queue.Queue()
567
+ # use a lock to avoid race condition between concurrent access to torchcodec
568
+ # libs (which are not thread-safe); the lock is replaced with a nullcontext
569
+ # when the video is fully loaded
570
+ self.torchcodec_access_lock = FIFOLock()
571
+ self._start_video_loading()
572
+
573
+ def _load_one_frame(self, idx):
574
+ frame_resized = self._transform_frame(self.async_reader[idx])
575
+ return frame_resized
576
+
577
+ @torch.inference_mode()
578
+ def _start_video_loading(self):
579
+ desc = f"frame loading (TorchCodec w/ {'GPU' if self.gpu_acceleration else 'CPU'}) [rank={RANK}]"
580
+ pbar = tqdm(desc=desc, total=self.num_frames)
581
+ self.num_loaded_frames = 0
582
+ # load the first frame synchronously to cache it before the session is opened
583
+ idx = self.num_loaded_frames
584
+ self.images[idx] = self._load_one_frame(idx)
585
+ self.images_loaded[idx] = True
586
+ self.num_loaded_frames += 1
587
+ pbar.update(n=1)
588
+ self.all_frames_loaded = self.num_loaded_frames == self.num_frames
589
+
590
+ # load the frames asynchronously without blocking the session start
591
+ def _load_frames():
592
+ finished = self.all_frames_loaded
593
+ chunk_size = 16
594
+ while not finished:
595
+ # asynchronously load `chunk_size` frames each time we acquire the lock
596
+ with self.torchcodec_access_lock, torch.inference_mode():
597
+ for _ in range(chunk_size):
598
+ try:
599
+ idx = self.num_loaded_frames
600
+ self.images[idx] = self._load_one_frame(idx)
601
+ self.images_loaded[idx] = True
602
+ self.num_loaded_frames += 1
603
+ pbar.update(n=1)
604
+ if self.num_loaded_frames >= self.num_frames:
605
+ finished = True
606
+ break
607
+ except Exception as e:
608
+ self.exception = e
609
+ raise
610
+
611
+ # also read the frame that is being randomly seeked to
612
+ while True:
613
+ try:
614
+ idx = self.rand_seek_idx_queue.get_nowait()
615
+ if not self.images_loaded[idx]:
616
+ self.images[idx] = self._load_one_frame(idx)
617
+ self.images_loaded[idx] = True
618
+ except queue.Empty:
619
+ break
620
+ except Exception as e:
621
+ self.exception = e
622
+ raise
623
+
624
+ # finished -- check whether we have loaded the total number of frames
625
+ if self.num_loaded_frames != self.num_frames:
626
+ raise RuntimeError(
627
+ f"There are {self.num_frames} frames in the video, but only "
628
+ f"{self.num_loaded_frames} frames can be loaded successfully."
629
+ )
630
+ else:
631
+ self.all_frames_loaded = True
632
+ pbar.close()
633
+ with self.torchcodec_access_lock:
634
+ import gc
635
+
636
+ # all frames have been loaded, so we can release the readers and free their memory
637
+ # also remove pbar and thread (which shouldn't be a part of session saving)
638
+ reader = self.async_reader
639
+ if reader is not None:
640
+ reader._source = None
641
+ self.async_reader = None
642
+ self.pbar = None
643
+ self.thread = None
644
+ self.rand_seek_idx_queue = None
645
+ gc.collect()
646
+ # remove the lock (replace it with nullcontext) when the video is fully loaded
647
+ self.torchcodec_access_lock = contextlib.nullcontext()
648
+
649
+ self.thread = Thread(target=_load_frames, daemon=True)
650
+ self.thread.start()
651
+
652
+ def _transform_frame(self, frame):
653
+ frame = frame.clone() # make a copy to avoid modifying the original frame bytes
654
+ frame = frame.float() # convert to float32 before interpolation
655
+ frame_resized = F.interpolate(
656
+ frame[None, :],
657
+ size=(self.image_size, self.image_size),
658
+ mode="bicubic",
659
+ align_corners=False,
660
+ )[0]
661
+ # float16 precision should be sufficient for image tensor storage
662
+ frame_resized = frame_resized.half() # uint8 -> float16
663
+ frame_resized /= 255
664
+ frame_resized -= self.img_mean
665
+ frame_resized /= self.img_std
666
+ if self.offload_video_to_cpu:
667
+ frame_resized = frame_resized.cpu()
668
+ elif frame_resized.device != self.out_device:
669
+ frame_resized = frame_resized.to(device=self.out_device, non_blocking=True)
670
+ return frame_resized
671
+
672
+ def __getitem__(self, index):
673
+ if self.exception is not None:
674
+ raise RuntimeError("Failure in frame loading thread") from self.exception
675
+
676
+ max_tries = 1200
677
+ for _ in range(max_tries):
678
+ # use a lock to avoid race condition between concurrent access to torchcodec
679
+ # libs (which are not thread-safe); the lock is replaced with a nullcontext
680
+ # when the video is fully loaded
681
+ with self.torchcodec_access_lock:
682
+ if self.images_loaded[index]:
683
+ return self.images[index]
684
+
685
+ if self.use_rand_seek_in_loading:
686
+ # async loading hasn't reached this frame yet, so we load this frame individually
687
+ # (it will be loaded by in _load_frames thread and added to self.images[index])
688
+ self.rand_seek_idx_queue.put(index)
689
+
690
+ time.sleep(0.1)
691
+
692
+ raise RuntimeError(f"Failed to load frame {index} after {max_tries} tries")
693
+
694
+ def __len__(self):
695
+ return len(self.images)
696
+
697
+ def __getstate__(self):
698
+ """
699
+ Remove a few attributes during pickling, so that this async video loader can be
700
+ saved and loaded as a part of the model session.
701
+ """
702
+ # wait for async video loading to finish before pickling
703
+ async_thread = self.thread
704
+ if async_thread is not None:
705
+ async_thread.join()
706
+ # release a few objects that cannot be pickled
707
+ reader = self.async_reader
708
+ if reader is not None:
709
+ reader._source = None
710
+ self.async_reader = None
711
+ self.pbar = None
712
+ self.thread = None
713
+ self.rand_seek_idx_queue = None
714
+ self.torchcodec_access_lock = contextlib.nullcontext()
715
+ return self.__dict__.copy()
third_party/GraspGen/sam3/sam3/model/maskformer_segmentation.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import math
6
+ from typing import Dict, List, Optional
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint as checkpoint
12
+
13
+ from .model_misc import MLP
14
+
15
+
16
+ class LinearPresenceHead(nn.Sequential):
17
+ def __init__(self, d_model):
18
+ # a hack to make `LinearPresenceHead` compatible with old checkpoints
19
+ super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1))
20
+
21
+ def forward(self, hs, prompt, prompt_mask):
22
+ return super().forward(hs)
23
+
24
+
25
+ class MaskPredictor(nn.Module):
26
+ def __init__(self, hidden_dim, mask_dim):
27
+ super().__init__()
28
+ self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3)
29
+
30
+ def forward(self, obj_queries, pixel_embed):
31
+ if len(obj_queries.shape) == 3:
32
+ if pixel_embed.ndim == 3:
33
+ # batch size was omitted
34
+ mask_preds = torch.einsum(
35
+ "bqc,chw->bqhw", self.mask_embed(obj_queries), pixel_embed
36
+ )
37
+ else:
38
+ mask_preds = torch.einsum(
39
+ "bqc,bchw->bqhw", self.mask_embed(obj_queries), pixel_embed
40
+ )
41
+ else:
42
+ # Assumed to have aux masks
43
+ if pixel_embed.ndim == 3:
44
+ # batch size was omitted
45
+ mask_preds = torch.einsum(
46
+ "lbqc,chw->lbqhw", self.mask_embed(obj_queries), pixel_embed
47
+ )
48
+ else:
49
+ mask_preds = torch.einsum(
50
+ "lbqc,bchw->lbqhw", self.mask_embed(obj_queries), pixel_embed
51
+ )
52
+
53
+ return mask_preds
54
+
55
+
56
+ class SegmentationHead(nn.Module):
57
+ def __init__(
58
+ self,
59
+ hidden_dim,
60
+ upsampling_stages,
61
+ use_encoder_inputs=False,
62
+ aux_masks=False,
63
+ no_dec=False,
64
+ pixel_decoder=None,
65
+ act_ckpt=False,
66
+ shared_conv=False,
67
+ compile_mode_pixel_decoder=None,
68
+ ):
69
+ super().__init__()
70
+ self.use_encoder_inputs = use_encoder_inputs
71
+ self.aux_masks = aux_masks
72
+ if pixel_decoder is not None:
73
+ self.pixel_decoder = pixel_decoder
74
+ else:
75
+ self.pixel_decoder = PixelDecoder(
76
+ hidden_dim,
77
+ upsampling_stages,
78
+ shared_conv=shared_conv,
79
+ compile_mode=compile_mode_pixel_decoder,
80
+ )
81
+ self.no_dec = no_dec
82
+ if no_dec:
83
+ self.mask_predictor = nn.Conv2d(
84
+ hidden_dim, 1, kernel_size=3, stride=1, padding=1
85
+ )
86
+ else:
87
+ self.mask_predictor = MaskPredictor(hidden_dim, mask_dim=hidden_dim)
88
+
89
+ self.act_ckpt = act_ckpt
90
+
91
+ # used to update the output dictionary
92
+ self.instance_keys = ["pred_masks"]
93
+
94
+ @property
95
+ def device(self):
96
+ self._device = getattr(self, "_device", None) or next(self.parameters()).device
97
+ return self._device
98
+
99
+ def to(self, *args, **kwargs):
100
+ # clear cached _device in case the model is moved to a different device
101
+ self._device = None
102
+ return super().to(*args, **kwargs)
103
+
104
+ def _embed_pixels(
105
+ self,
106
+ backbone_feats: List[torch.Tensor],
107
+ image_ids,
108
+ encoder_hidden_states,
109
+ ) -> torch.Tensor:
110
+ feature_device = backbone_feats[0].device # features could be on CPU
111
+ model_device = self.device
112
+ image_ids_ = image_ids.to(feature_device)
113
+ if self.use_encoder_inputs:
114
+ if backbone_feats[0].shape[0] > 1:
115
+ # For bs > 1, we construct the per query backbone features
116
+ backbone_visual_feats = []
117
+ for feat in backbone_feats:
118
+ # Copy the img features per query (pixel decoder won't share img feats)
119
+ backbone_visual_feats.append(feat[image_ids_, ...].to(model_device))
120
+ else:
121
+ # Bs=1, we rely on broadcasting for query-based processing
122
+ backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats]
123
+ # Extract visual embeddings
124
+ encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0)
125
+ spatial_dim = math.prod(backbone_feats[-1].shape[-2:])
126
+ encoder_visual_embed = encoder_hidden_states[..., :spatial_dim].reshape(
127
+ -1, *backbone_feats[-1].shape[1:]
128
+ )
129
+
130
+ backbone_visual_feats[-1] = encoder_visual_embed
131
+ if self.act_ckpt:
132
+ pixel_embed = checkpoint.checkpoint(
133
+ self.pixel_decoder, backbone_visual_feats, use_reentrant=False
134
+ )
135
+ else:
136
+ pixel_embed = self.pixel_decoder(backbone_visual_feats)
137
+ else:
138
+ backbone_feats = [x.to(model_device) for x in backbone_feats]
139
+ pixel_embed = self.pixel_decoder(backbone_feats)
140
+ if pixel_embed.shape[0] == 1:
141
+ # For batch_size=1 training, we can avoid the indexing to save memory
142
+ pixel_embed = pixel_embed.squeeze(0)
143
+ else:
144
+ pixel_embed = pixel_embed[image_ids, ...]
145
+ return pixel_embed
146
+
147
+ def forward(
148
+ self,
149
+ backbone_feats: List[torch.Tensor],
150
+ obj_queries: torch.Tensor,
151
+ image_ids,
152
+ encoder_hidden_states: Optional[torch.Tensor] = None,
153
+ **kwargs,
154
+ ) -> Dict[str, torch.Tensor]:
155
+ if self.use_encoder_inputs:
156
+ assert encoder_hidden_states is not None
157
+
158
+ pixel_embed = self._embed_pixels(
159
+ backbone_feats=backbone_feats,
160
+ image_ids=image_ids,
161
+ encoder_hidden_states=encoder_hidden_states,
162
+ )
163
+
164
+ if self.no_dec:
165
+ mask_pred = self.mask_predictor(pixel_embed)
166
+ elif self.aux_masks:
167
+ mask_pred = self.mask_predictor(obj_queries, pixel_embed)
168
+ else:
169
+ mask_pred = self.mask_predictor(obj_queries[-1], pixel_embed)
170
+
171
+ return {"pred_masks": mask_pred}
172
+
173
+
174
+ class PixelDecoder(nn.Module):
175
+ def __init__(
176
+ self,
177
+ hidden_dim,
178
+ num_upsampling_stages,
179
+ interpolation_mode="nearest",
180
+ shared_conv=False,
181
+ compile_mode=None,
182
+ ):
183
+ super().__init__()
184
+ self.hidden_dim = hidden_dim
185
+ self.num_upsampling_stages = num_upsampling_stages
186
+ self.interpolation_mode = interpolation_mode
187
+ conv_layers = []
188
+ norms = []
189
+ num_convs = 1 if shared_conv else num_upsampling_stages
190
+ for _ in range(num_convs):
191
+ conv_layers.append(nn.Conv2d(self.hidden_dim, self.hidden_dim, 3, 1, 1))
192
+ norms.append(nn.GroupNorm(8, self.hidden_dim))
193
+
194
+ self.conv_layers = nn.ModuleList(conv_layers)
195
+ self.norms = nn.ModuleList(norms)
196
+ self.shared_conv = shared_conv
197
+ self.out_dim = self.conv_layers[-1].out_channels
198
+ if compile_mode is not None:
199
+ self.forward = torch.compile(
200
+ self.forward, mode=compile_mode, dynamic=True, fullgraph=True
201
+ )
202
+ # Needed to make checkpointing happy. But we don't know if the module is checkpointed, so we disable it by default.
203
+ torch._dynamo.config.optimize_ddp = False
204
+
205
+ def forward(self, backbone_feats: List[torch.Tensor]):
206
+ # Assumes backbone features are already projected (C == hidden dim)
207
+
208
+ prev_fpn = backbone_feats[-1]
209
+ fpn_feats = backbone_feats[:-1]
210
+ for layer_idx, bb_feat in enumerate(fpn_feats[::-1]):
211
+ curr_fpn = bb_feat
212
+ prev_fpn = curr_fpn + F.interpolate(
213
+ prev_fpn, size=curr_fpn.shape[-2:], mode=self.interpolation_mode
214
+ )
215
+ if self.shared_conv:
216
+ # only one conv layer
217
+ layer_idx = 0
218
+ prev_fpn = self.conv_layers[layer_idx](prev_fpn)
219
+ prev_fpn = F.relu(self.norms[layer_idx](prev_fpn))
220
+
221
+ return prev_fpn
222
+
223
+
224
+ class UniversalSegmentationHead(SegmentationHead):
225
+ """This module handles semantic+instance segmentation"""
226
+
227
+ def __init__(
228
+ self,
229
+ hidden_dim,
230
+ upsampling_stages,
231
+ pixel_decoder,
232
+ aux_masks=False,
233
+ no_dec=False,
234
+ act_ckpt=False,
235
+ presence_head: bool = False,
236
+ dot_product_scorer=None,
237
+ cross_attend_prompt=None,
238
+ ):
239
+ super().__init__(
240
+ hidden_dim=hidden_dim,
241
+ upsampling_stages=upsampling_stages,
242
+ use_encoder_inputs=True,
243
+ aux_masks=aux_masks,
244
+ no_dec=no_dec,
245
+ pixel_decoder=pixel_decoder,
246
+ act_ckpt=act_ckpt,
247
+ )
248
+ self.d_model = hidden_dim
249
+
250
+ if dot_product_scorer is not None:
251
+ assert presence_head, (
252
+ "Specifying a dot product scorer without a presence head is likely a mistake"
253
+ )
254
+
255
+ self.presence_head = None
256
+ if presence_head:
257
+ self.presence_head = (
258
+ dot_product_scorer
259
+ if dot_product_scorer is not None
260
+ else LinearPresenceHead(self.d_model)
261
+ )
262
+
263
+ self.cross_attend_prompt = cross_attend_prompt
264
+ if self.cross_attend_prompt is not None:
265
+ self.cross_attn_norm = nn.LayerNorm(self.d_model)
266
+
267
+ self.semantic_seg_head = nn.Conv2d(self.pixel_decoder.out_dim, 1, kernel_size=1)
268
+ self.instance_seg_head = nn.Conv2d(
269
+ self.pixel_decoder.out_dim, self.d_model, kernel_size=1
270
+ )
271
+
272
+ def forward(
273
+ self,
274
+ backbone_feats: List[torch.Tensor],
275
+ obj_queries: torch.Tensor,
276
+ image_ids,
277
+ encoder_hidden_states: Optional[torch.Tensor] = None,
278
+ prompt: Optional[torch.Tensor] = None,
279
+ prompt_mask: Optional[torch.Tensor] = None,
280
+ **kwargs,
281
+ ) -> Dict[str, Optional[torch.Tensor]]:
282
+ assert encoder_hidden_states is not None
283
+ bs = encoder_hidden_states.shape[1]
284
+
285
+ if self.cross_attend_prompt is not None:
286
+ tgt2 = self.cross_attn_norm(encoder_hidden_states)
287
+ tgt2 = self.cross_attend_prompt(
288
+ query=tgt2,
289
+ key=prompt,
290
+ value=prompt,
291
+ key_padding_mask=prompt_mask,
292
+ )[0]
293
+ encoder_hidden_states = tgt2 + encoder_hidden_states
294
+
295
+ presence_logit = None
296
+ if self.presence_head is not None:
297
+ pooled_enc = encoder_hidden_states.mean(0)
298
+ presence_logit = (
299
+ self.presence_head(
300
+ pooled_enc.view(1, bs, 1, self.d_model),
301
+ prompt=prompt,
302
+ prompt_mask=prompt_mask,
303
+ )
304
+ .squeeze(0)
305
+ .squeeze(1)
306
+ )
307
+
308
+ pixel_embed = self._embed_pixels(
309
+ backbone_feats=backbone_feats,
310
+ image_ids=image_ids,
311
+ encoder_hidden_states=encoder_hidden_states,
312
+ )
313
+
314
+ instance_embeds = self.instance_seg_head(pixel_embed)
315
+
316
+ if self.no_dec:
317
+ mask_pred = self.mask_predictor(instance_embeds)
318
+ elif self.aux_masks:
319
+ mask_pred = self.mask_predictor(obj_queries, instance_embeds)
320
+ else:
321
+ mask_pred = self.mask_predictor(obj_queries[-1], instance_embeds)
322
+
323
+ return {
324
+ "pred_masks": mask_pred,
325
+ "semantic_seg": self.semantic_seg_head(pixel_embed),
326
+ "presence_logit": presence_logit,
327
+ }
third_party/GraspGen/sam3/sam3/model/memory.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import math
6
+ from typing import Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+
12
+ try:
13
+ from timm.layers import DropPath
14
+ except ModuleNotFoundError:
15
+ # compatibility for older timm versions
16
+ from timm.models.layers import DropPath
17
+
18
+ from .model_misc import get_clones, LayerNorm2d
19
+
20
+
21
+ class SimpleMaskDownSampler(nn.Module):
22
+ """
23
+ Progressively downsample a mask by total_stride, each time by stride.
24
+ Note that LayerNorm is applied per *token*, like in ViT.
25
+
26
+ With each downsample (by a factor stride**2), channel capacity increases by the same factor.
27
+ In the end, we linearly project to embed_dim channels.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ embed_dim=256,
33
+ kernel_size=4,
34
+ stride=4,
35
+ padding=0,
36
+ total_stride=16,
37
+ activation=nn.GELU,
38
+ # Option to interpolate the input mask first before downsampling using convs. In that case, the total_stride is assumed to be after interpolation.
39
+ # If set to input resolution or None, we don't interpolate. We default to None to be safe (for older configs or if not explicitly set)
40
+ interpol_size=None,
41
+ ):
42
+ super().__init__()
43
+ num_layers = int(math.log2(total_stride) // math.log2(stride))
44
+ assert stride**num_layers == total_stride
45
+ self.encoder = nn.Sequential()
46
+ mask_in_chans, mask_out_chans = 1, 1
47
+ for _ in range(num_layers):
48
+ mask_out_chans = mask_in_chans * (stride**2)
49
+ self.encoder.append(
50
+ nn.Conv2d(
51
+ mask_in_chans,
52
+ mask_out_chans,
53
+ kernel_size=kernel_size,
54
+ stride=stride,
55
+ padding=padding,
56
+ )
57
+ )
58
+ self.encoder.append(LayerNorm2d(mask_out_chans))
59
+ self.encoder.append(activation())
60
+ mask_in_chans = mask_out_chans
61
+
62
+ self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
63
+ self.interpol_size = interpol_size
64
+ if self.interpol_size is not None:
65
+ assert isinstance(self.interpol_size, (list, tuple)), (
66
+ f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
67
+ )
68
+ self.interpol_size = list(interpol_size)
69
+ assert len(self.interpol_size) == 2
70
+
71
+ def forward(self, x: torch.Tensor):
72
+ if self.interpol_size is not None and self.interpol_size != list(x.shape[-2:]):
73
+ x = F.interpolate(
74
+ x.float(),
75
+ size=self.interpol_size,
76
+ align_corners=False,
77
+ mode="bilinear",
78
+ antialias=True,
79
+ )
80
+ return self.encoder(x)
81
+
82
+
83
+ # Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
84
+ class CXBlock(nn.Module):
85
+ r"""ConvNeXt Block. There are two equivalent implementations:
86
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
87
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
88
+ We use (2) as we find it slightly faster in PyTorch
89
+
90
+ Args:
91
+ dim (int): Number of input channels.
92
+ drop_path (float): Stochastic depth rate. Default: 0.0
93
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ dim,
99
+ kernel_size=7,
100
+ padding=3,
101
+ drop_path=0.0,
102
+ layer_scale_init_value=1e-6,
103
+ use_dwconv=True,
104
+ ):
105
+ super().__init__()
106
+ self.dwconv = nn.Conv2d(
107
+ dim,
108
+ dim,
109
+ kernel_size=kernel_size,
110
+ padding=padding,
111
+ groups=dim if use_dwconv else 1,
112
+ ) # depthwise conv
113
+ self.norm = LayerNorm2d(dim, eps=1e-6)
114
+ self.pwconv1 = nn.Linear(
115
+ dim, 4 * dim
116
+ ) # pointwise/1x1 convs, implemented with linear layers
117
+ self.act = nn.GELU()
118
+ self.pwconv2 = nn.Linear(4 * dim, dim)
119
+ self.gamma = (
120
+ nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
121
+ if layer_scale_init_value > 0
122
+ else None
123
+ )
124
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
125
+
126
+ def forward(self, x):
127
+ input = x
128
+ x = self.dwconv(x)
129
+ x = self.norm(x)
130
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
131
+ x = self.pwconv1(x)
132
+ x = self.act(x)
133
+ x = self.pwconv2(x)
134
+ if self.gamma is not None:
135
+ x = self.gamma * x
136
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
137
+
138
+ x = input + self.drop_path(x)
139
+ return x
140
+
141
+
142
+ class SimpleFuser(nn.Module):
143
+ def __init__(self, layer, num_layers, dim=None, input_projection=False):
144
+ super().__init__()
145
+ self.proj = nn.Identity()
146
+ self.layers = get_clones(layer, num_layers)
147
+
148
+ if input_projection:
149
+ assert dim is not None
150
+ self.proj = nn.Conv2d(dim, dim, kernel_size=1)
151
+
152
+ def forward(self, x):
153
+ # normally x: (N, C, H, W)
154
+ x = self.proj(x)
155
+ for layer in self.layers:
156
+ x = layer(x)
157
+ return x
158
+
159
+
160
+ class SimpleMaskEncoder(nn.Module):
161
+ def __init__(
162
+ self,
163
+ out_dim,
164
+ mask_downsampler,
165
+ fuser,
166
+ position_encoding,
167
+ in_dim=256, # in_dim of pix_feats
168
+ ):
169
+ super().__init__()
170
+
171
+ self.mask_downsampler = mask_downsampler
172
+
173
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
174
+ self.fuser = fuser
175
+ self.position_encoding = position_encoding
176
+ self.out_proj = nn.Identity()
177
+ if out_dim != in_dim:
178
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
179
+
180
+ def forward(
181
+ self,
182
+ pix_feat: torch.Tensor,
183
+ masks: torch.Tensor,
184
+ skip_mask_sigmoid: bool = False,
185
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
186
+ ## Process masks
187
+ # sigmoid, so that less domain shift from gt masks which are bool
188
+ if not skip_mask_sigmoid:
189
+ masks = F.sigmoid(masks)
190
+ masks = self.mask_downsampler(masks)
191
+
192
+ ## Fuse pix_feats and downsampled masks
193
+ # in case the visual features are on CPU, cast them to CUDA
194
+ pix_feat = pix_feat.to(masks.device)
195
+
196
+ x = self.pix_feat_proj(pix_feat)
197
+ x = x + masks
198
+ x = self.fuser(x)
199
+ x = self.out_proj(x)
200
+
201
+ pos = self.position_encoding(x).to(x.dtype)
202
+
203
+ return {"vision_features": x, "vision_pos_enc": [pos]}
third_party/GraspGen/sam3/sam3/model/model_misc.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Various utility models"""
6
+
7
+ import copy
8
+ import math
9
+ import weakref
10
+ from collections.abc import Iterator
11
+ from contextlib import AbstractContextManager
12
+ from enum import auto, Enum
13
+ from typing import Dict, List, Optional, Union
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn, Tensor
19
+ from typing_extensions import override
20
+
21
+
22
+ def inverse_sigmoid(x, eps=1e-3):
23
+ """
24
+ The inverse function for sigmoid activation function.
25
+ Note: It might face numberical issues with fp16 small eps.
26
+ """
27
+ x = x.clamp(min=0, max=1)
28
+ x1 = x.clamp(min=eps)
29
+ x2 = (1 - x).clamp(min=eps)
30
+ return torch.log(x1 / x2)
31
+
32
+
33
+ class MultiheadAttentionWrapper(nn.MultiheadAttention):
34
+ def forward(self, *args, **kwargs):
35
+ kwargs["need_weights"] = False
36
+ return super().forward(*args, **kwargs)
37
+
38
+
39
+ class DotProductScoring(torch.nn.Module):
40
+ def __init__(
41
+ self,
42
+ d_model,
43
+ d_proj,
44
+ prompt_mlp=None,
45
+ clamp_logits=True,
46
+ clamp_max_val=12.0,
47
+ ):
48
+ super().__init__()
49
+ self.d_proj = d_proj
50
+ assert isinstance(prompt_mlp, torch.nn.Module) or prompt_mlp is None
51
+ self.prompt_mlp = prompt_mlp # an optional MLP projection for prompt
52
+ self.prompt_proj = torch.nn.Linear(d_model, d_proj)
53
+ self.hs_proj = torch.nn.Linear(d_model, d_proj)
54
+ self.scale = float(1.0 / np.sqrt(d_proj))
55
+ self.clamp_logits = clamp_logits
56
+ if self.clamp_logits:
57
+ self.clamp_max_val = clamp_max_val
58
+
59
+ def mean_pool_text(self, prompt, prompt_mask):
60
+ # is_valid has shape (seq, bs, 1), where 1 is valid and 0 is padding
61
+ is_valid = (~prompt_mask).float().permute(1, 0)[..., None]
62
+ # num_valid has shape (bs, 1)
63
+ num_valid = torch.clamp(torch.sum(is_valid, dim=0), min=1.0)
64
+ # mean pool over all the valid tokens -- pooled_prompt has shape (bs, proj_dim)
65
+ pooled_prompt = (prompt * is_valid).sum(dim=0) / num_valid
66
+ return pooled_prompt
67
+
68
+ def forward(self, hs, prompt, prompt_mask):
69
+ # hs has shape (num_layer, bs, num_query, d_model)
70
+ # prompt has shape (seq, bs, d_model)
71
+ # prompt_mask has shape (bs, seq), where 1 is valid and 0 is padding
72
+ assert hs.dim() == 4 and prompt.dim() == 3 and prompt_mask.dim() == 2
73
+
74
+ # apply MLP on prompt if specified
75
+ if self.prompt_mlp is not None:
76
+ prompt = self.prompt_mlp(prompt)
77
+
78
+ # first, get the mean-pooled version of the prompt
79
+ pooled_prompt = self.mean_pool_text(prompt, prompt_mask)
80
+
81
+ # then, project pooled_prompt and hs to d_proj dimensions
82
+ proj_pooled_prompt = self.prompt_proj(pooled_prompt) # (bs, d_proj)
83
+ proj_hs = self.hs_proj(hs) # (num_layer, bs, num_query, d_proj)
84
+
85
+ # finally, get dot-product scores of shape (num_layer, bs, num_query, 1)
86
+ scores = torch.matmul(proj_hs, proj_pooled_prompt.unsqueeze(-1))
87
+ scores *= self.scale
88
+
89
+ # clamp scores to a max value to avoid numerical issues in loss or matcher
90
+ if self.clamp_logits:
91
+ scores.clamp_(min=-self.clamp_max_val, max=self.clamp_max_val)
92
+
93
+ return scores
94
+
95
+
96
+ class LayerScale(nn.Module):
97
+ def __init__(
98
+ self,
99
+ dim: int,
100
+ init_values: Union[float, Tensor] = 1e-5,
101
+ inplace: bool = False,
102
+ ) -> None:
103
+ super().__init__()
104
+ self.inplace = inplace
105
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
106
+
107
+ def forward(self, x: Tensor) -> Tensor:
108
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
109
+
110
+
111
+ class LayerNorm2d(nn.Module):
112
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
113
+ super().__init__()
114
+ self.weight = nn.Parameter(torch.ones(num_channels))
115
+ self.bias = nn.Parameter(torch.zeros(num_channels))
116
+ self.eps = eps
117
+
118
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
119
+ u = x.mean(1, keepdim=True)
120
+ s = (x - u).pow(2).mean(1, keepdim=True)
121
+ x = (x - u) / torch.sqrt(s + self.eps)
122
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
123
+ return x
124
+
125
+
126
+ class TransformerWrapper(nn.Module):
127
+ def __init__(
128
+ self,
129
+ encoder,
130
+ decoder,
131
+ d_model: int,
132
+ two_stage_type="none", # ["none"] only for now
133
+ pos_enc_at_input_dec=True,
134
+ ):
135
+ super().__init__()
136
+
137
+ self.encoder = encoder
138
+ self.decoder = decoder
139
+ self.num_queries = decoder.num_queries if decoder is not None else None
140
+ self.pos_enc_at_input_dec = pos_enc_at_input_dec
141
+
142
+ # for two stage
143
+ assert two_stage_type in ["none"], "unknown param {} of two_stage_type".format(
144
+ two_stage_type
145
+ )
146
+ self.two_stage_type = two_stage_type
147
+
148
+ self._reset_parameters()
149
+ self.d_model = d_model
150
+
151
+ def _reset_parameters(self):
152
+ for n, p in self.named_parameters():
153
+ if p.dim() > 1:
154
+ if (
155
+ "box_embed" not in n
156
+ and "query_embed" not in n
157
+ and "reference_points" not in n
158
+ ):
159
+ nn.init.xavier_uniform_(p)
160
+
161
+
162
+ class MLP(nn.Module):
163
+ """Very simple multi-layer perceptron (also called FFN)"""
164
+
165
+ def __init__(
166
+ self,
167
+ input_dim: int,
168
+ hidden_dim: int,
169
+ output_dim: int,
170
+ num_layers: int,
171
+ dropout: float = 0.0,
172
+ residual: bool = False,
173
+ out_norm: Optional[nn.Module] = None,
174
+ ):
175
+ super().__init__()
176
+ self.num_layers = num_layers
177
+ h = [hidden_dim] * (num_layers - 1)
178
+ self.layers = nn.ModuleList(
179
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
180
+ )
181
+ self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
182
+ # whether to add the output as a residual connection to the input
183
+ if residual and input_dim != output_dim:
184
+ raise ValueError("residual is only supported if input_dim == output_dim")
185
+ self.residual = residual
186
+ # whether to apply a normalization layer to the output
187
+ assert isinstance(out_norm, nn.Module) or out_norm is None
188
+ self.out_norm = out_norm or nn.Identity()
189
+
190
+ def forward(self, x):
191
+ orig_x = x
192
+ for i, layer in enumerate(self.layers):
193
+ x = self.drop(F.relu(layer(x))) if i < self.num_layers - 1 else layer(x)
194
+ if self.residual:
195
+ x = x + orig_x
196
+ x = self.out_norm(x)
197
+ return x
198
+
199
+
200
+ def get_clones(module, N):
201
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
202
+
203
+
204
+ def get_clones_seq(module, N):
205
+ return nn.Sequential(*[copy.deepcopy(module) for i in range(N)])
206
+
207
+
208
+ def get_activation_fn(activation):
209
+ """Return an activation function given a string"""
210
+ if activation == "relu":
211
+ return F.relu
212
+ if activation == "gelu":
213
+ return F.gelu
214
+ if activation == "glu":
215
+ return F.glu
216
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
217
+
218
+
219
+ def get_activation_module(activation):
220
+ """Return an activation function given a string"""
221
+ if activation == "relu":
222
+ return nn.ReLU
223
+ if activation == "gelu":
224
+ return nn.GELU
225
+ if activation == "glu":
226
+ return nn.GLU
227
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
228
+
229
+
230
+ def get_valid_ratio(mask):
231
+ _, H, W = mask.shape
232
+ valid_H = torch.sum(~mask[:, :, 0], 1)
233
+ valid_W = torch.sum(~mask[:, 0, :], 1)
234
+ valid_ratio_h = valid_H.float() / H
235
+ valid_ratio_w = valid_W.float() / W
236
+ valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
237
+ return valid_ratio
238
+
239
+
240
+ def gen_sineembed_for_position(pos_tensor, num_feats=256):
241
+ assert num_feats % 2 == 0
242
+ num_feats = num_feats // 2
243
+ # n_query, bs, _ = pos_tensor.size()
244
+ # sineembed_tensor = torch.zeros(n_query, bs, 256)
245
+ scale = 2 * math.pi
246
+ dim_t = torch.arange(num_feats, dtype=torch.float32, device=pos_tensor.device)
247
+ dim_t = 10000 ** (2 * (torch.div(dim_t, 2, rounding_mode="floor")) / num_feats)
248
+ x_embed = pos_tensor[:, :, 0] * scale
249
+ y_embed = pos_tensor[:, :, 1] * scale
250
+ pos_x = x_embed[:, :, None] / dim_t
251
+ pos_y = y_embed[:, :, None] / dim_t
252
+ pos_x = torch.stack(
253
+ (pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3
254
+ ).flatten(2)
255
+ pos_y = torch.stack(
256
+ (pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3
257
+ ).flatten(2)
258
+ if pos_tensor.size(-1) == 2:
259
+ pos = torch.cat((pos_y, pos_x), dim=2)
260
+ elif pos_tensor.size(-1) == 4:
261
+ w_embed = pos_tensor[:, :, 2] * scale
262
+ pos_w = w_embed[:, :, None] / dim_t
263
+ pos_w = torch.stack(
264
+ (pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3
265
+ ).flatten(2)
266
+
267
+ h_embed = pos_tensor[:, :, 3] * scale
268
+ pos_h = h_embed[:, :, None] / dim_t
269
+ pos_h = torch.stack(
270
+ (pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3
271
+ ).flatten(2)
272
+
273
+ pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
274
+ else:
275
+ raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1)))
276
+ return pos
277
+
278
+
279
+ class SAM3Output(list):
280
+ """
281
+ A class representing the output of a SAM3 model.
282
+ It provides an iterable interface that supports different iteration modes, including iterating over all steps per stage,
283
+ last step per stage, and flattened output.
284
+ Attributes:
285
+ output: The output of the SAM3 model, represented as a list of lists.
286
+ iter_mode: The current iteration mode.
287
+ Example:
288
+ >>> output = [[1, 2], [3, 4], [5, 6]]
289
+ >>> sam3_output = SAM3Output(output)
290
+ >>> for step in sam3_output:
291
+ ... print(step)
292
+ [1, 2]
293
+ [3, 4]
294
+ [5, 6]
295
+ >>> with SAM3Output.iteration_mode(SAM3Output.IterMode.LAST_STEP_PER_STAGE) as sam3_last_step_out:
296
+ ... for step in sam3_last_step_out:
297
+ ... print(step)
298
+ [2]
299
+ [4]
300
+ [6]
301
+ >>> with SAM3Output.iteration_mode(SAM3Output.IterMode.FLATTENED) as sam3_flattened_out:
302
+ ... for step in sam3_flattened_out:
303
+ ... print(step)
304
+ 1
305
+ 2
306
+ 3
307
+ 4
308
+ 5
309
+ 6
310
+ """
311
+
312
+ class IterMode(Enum):
313
+ # Defines the type of iterator over ouptuts.
314
+ ALL_STEPS_PER_STAGE = auto()
315
+ LAST_STEP_PER_STAGE = auto()
316
+ FLATTENED = auto() # Returns each interactivity step as if it is a separate stage (this is used in SAM3Image model)
317
+
318
+ def __init__(
319
+ self,
320
+ output: List[List[Dict]] = None,
321
+ iter_mode: IterMode = IterMode.ALL_STEPS_PER_STAGE,
322
+ loss_stages: Optional[List[int]] = None,
323
+ ):
324
+ if output is not None:
325
+ assert (
326
+ isinstance(output, list)
327
+ and len(output) > 0
328
+ and isinstance(output[0], list)
329
+ ), "Expected output to be a list of lists"
330
+ self.output = output
331
+ else:
332
+ self.output = []
333
+ assert isinstance(iter_mode, SAM3Output.IterMode), (
334
+ f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
335
+ )
336
+
337
+ self.iter_mode = iter_mode
338
+ # We create a weak reference to self to be used in the lambda functions.
339
+ # This is to avoid cyclic references and let SAM3Output be garabge collected.
340
+ self_ref = weakref.ref(self)
341
+ self._mode2iter = {
342
+ SAM3Output.IterMode.ALL_STEPS_PER_STAGE: lambda: iter(self_ref().output),
343
+ SAM3Output.IterMode.LAST_STEP_PER_STAGE: lambda: (
344
+ inner_list[-1] for inner_list in self_ref().output
345
+ ),
346
+ SAM3Output.IterMode.FLATTENED: lambda: (
347
+ element for inner_list in self_ref().output for element in inner_list
348
+ ),
349
+ }
350
+ self.loss_stages = loss_stages
351
+
352
+ @override
353
+ def __iter__(self) -> Iterator:
354
+ return self._mode2iter[self.iter_mode]()
355
+
356
+ def __getitem__(self, index):
357
+ """
358
+ Returns the item at the specified index.
359
+ Args:
360
+ index (int): The index of the item to return.
361
+ Returns:
362
+ list or element: The item at the specified index.
363
+ """
364
+ assert isinstance(index, int), f"index should be an integer. Got {type(index)}"
365
+ if self.iter_mode == SAM3Output.IterMode.ALL_STEPS_PER_STAGE:
366
+ return self.output[index]
367
+ elif self.iter_mode == SAM3Output.IterMode.LAST_STEP_PER_STAGE:
368
+ return self.output[index][-1]
369
+ elif self.iter_mode == SAM3Output.IterMode.FLATTENED:
370
+ if index == -1:
371
+ return self.self.output[-1][-1]
372
+ else:
373
+ flattened_output = sum(self.output, [])
374
+ return flattened_output[index]
375
+
376
+ class _IterationMode(AbstractContextManager):
377
+ """
378
+ A context manager that temporarily changes the iteration mode of a SAM3Output object.
379
+ This class is used internally by the SAM3Output.iteration_mode method.
380
+ """
381
+
382
+ def __init__(
383
+ self, model_output: "SAM3Output", iter_mode: "SAM3Output.IterMode"
384
+ ):
385
+ self._model_output = model_output
386
+ self._orig_iter_mode = model_output.iter_mode
387
+ self._new_iter_mode = iter_mode
388
+
389
+ @override
390
+ def __enter__(self) -> "SAM3Output":
391
+ self._model_output.iter_mode = self._new_iter_mode
392
+ return self._model_output
393
+
394
+ @override
395
+ def __exit__(self, exc_type, exc_value, traceback):
396
+ self._model_output.iter_mode = self._orig_iter_mode
397
+ return super().__exit__(exc_type, exc_value, traceback)
398
+
399
+ @staticmethod
400
+ def iteration_mode(
401
+ model_output: "SAM3Output", iter_mode: IterMode
402
+ ) -> _IterationMode:
403
+ """
404
+ Returns a context manager that allows you to temporarily change the iteration mode of the SAM3Output object.
405
+ Args:
406
+ model_output: The SAM3Output object.
407
+ iter_mode: The new iteration mode.
408
+ Returns:
409
+ SAM3Output._IterationMode: A context manager that changes the iteration mode of the SAM3Output object.
410
+ """
411
+ return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode)
412
+
413
+ def append(self, item: list):
414
+ assert isinstance(item, list), (
415
+ f"Only list items are supported. Got {type(item)}"
416
+ )
417
+ self.output.append(item)
418
+
419
+ def __repr__(self):
420
+ return self.output.__repr__()
421
+
422
+ def __len__(self):
423
+ if self.iter_mode in [
424
+ SAM3Output.IterMode.ALL_STEPS_PER_STAGE,
425
+ SAM3Output.IterMode.LAST_STEP_PER_STAGE,
426
+ ]:
427
+ return len(self.output)
428
+ elif self.iter_mode == SAM3Output.IterMode.FLATTENED:
429
+ flattened_output = sum(self.output, [])
430
+ return len(flattened_output)
third_party/GraspGen/sam3/sam3/model/necks.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Necks are the interface between a vision backbone and the rest of the detection model"""
6
+
7
+ from copy import deepcopy
8
+ from typing import List, Optional, Tuple
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+
13
+
14
+ class Sam3DualViTDetNeck(nn.Module):
15
+ def __init__(
16
+ self,
17
+ trunk: nn.Module,
18
+ position_encoding: nn.Module,
19
+ d_model: int,
20
+ scale_factors=(4.0, 2.0, 1.0, 0.5),
21
+ add_sam2_neck: bool = False,
22
+ ):
23
+ """
24
+ SimpleFPN neck a la ViTDet
25
+ (From detectron2, very lightly adapted)
26
+ It supports a "dual neck" setting, where we have two identical necks (for SAM3 and SAM2), with different weights
27
+
28
+ :param trunk: the backbone
29
+ :param position_encoding: the positional encoding to use
30
+ :param d_model: the dimension of the model
31
+ """
32
+ super().__init__()
33
+ self.trunk = trunk
34
+ self.position_encoding = position_encoding
35
+ self.convs = nn.ModuleList()
36
+
37
+ self.scale_factors = scale_factors
38
+ use_bias = True
39
+ dim: int = self.trunk.channel_list[-1]
40
+
41
+ for _, scale in enumerate(scale_factors):
42
+ current = nn.Sequential()
43
+
44
+ if scale == 4.0:
45
+ current.add_module(
46
+ "dconv_2x2_0",
47
+ nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
48
+ )
49
+ current.add_module(
50
+ "gelu",
51
+ nn.GELU(),
52
+ )
53
+ current.add_module(
54
+ "dconv_2x2_1",
55
+ nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
56
+ )
57
+ out_dim = dim // 4
58
+ elif scale == 2.0:
59
+ current.add_module(
60
+ "dconv_2x2",
61
+ nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
62
+ )
63
+ out_dim = dim // 2
64
+ elif scale == 1.0:
65
+ out_dim = dim
66
+ elif scale == 0.5:
67
+ current.add_module(
68
+ "maxpool_2x2",
69
+ nn.MaxPool2d(kernel_size=2, stride=2),
70
+ )
71
+ out_dim = dim
72
+ else:
73
+ raise NotImplementedError(f"scale_factor={scale} is not supported yet.")
74
+
75
+ current.add_module(
76
+ "conv_1x1",
77
+ nn.Conv2d(
78
+ in_channels=out_dim,
79
+ out_channels=d_model,
80
+ kernel_size=1,
81
+ bias=use_bias,
82
+ ),
83
+ )
84
+ current.add_module(
85
+ "conv_3x3",
86
+ nn.Conv2d(
87
+ in_channels=d_model,
88
+ out_channels=d_model,
89
+ kernel_size=3,
90
+ padding=1,
91
+ bias=use_bias,
92
+ ),
93
+ )
94
+ self.convs.append(current)
95
+
96
+ self.sam2_convs = None
97
+ if add_sam2_neck:
98
+ # Assumes sam2 neck is just a clone of the original neck
99
+ self.sam2_convs = deepcopy(self.convs)
100
+
101
+ def forward(
102
+ self, tensor_list: List[torch.Tensor]
103
+ ) -> Tuple[
104
+ List[torch.Tensor],
105
+ List[torch.Tensor],
106
+ Optional[List[torch.Tensor]],
107
+ Optional[List[torch.Tensor]],
108
+ ]:
109
+ xs = self.trunk(tensor_list)
110
+ sam3_out, sam3_pos = [], []
111
+ sam2_out, sam2_pos = None, None
112
+ if self.sam2_convs is not None:
113
+ sam2_out, sam2_pos = [], []
114
+ x = xs[-1] # simpleFPN
115
+ for i in range(len(self.convs)):
116
+ sam3_x_out = self.convs[i](x)
117
+ sam3_pos_out = self.position_encoding(sam3_x_out).to(sam3_x_out.dtype)
118
+ sam3_out.append(sam3_x_out)
119
+ sam3_pos.append(sam3_pos_out)
120
+
121
+ if self.sam2_convs is not None:
122
+ sam2_x_out = self.sam2_convs[i](x)
123
+ sam2_pos_out = self.position_encoding(sam2_x_out).to(sam2_x_out.dtype)
124
+ sam2_out.append(sam2_x_out)
125
+ sam2_pos.append(sam2_pos_out)
126
+ return sam3_out, sam3_pos, sam2_out, sam2_pos
third_party/GraspGen/sam3/sam3/model/position_encoding.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import math
6
+ from typing import Optional
7
+
8
+ import torch
9
+ from torch import nn
10
+
11
+
12
+ class PositionEmbeddingSine(nn.Module):
13
+ """
14
+ This is a more standard version of the position embedding, very similar to the one
15
+ used by the Attention is all you need paper, generalized to work on images.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ num_pos_feats,
21
+ temperature: int = 10000,
22
+ normalize: bool = True,
23
+ scale: Optional[float] = None,
24
+ precompute_resolution: Optional[int] = None,
25
+ ):
26
+ super().__init__()
27
+ assert num_pos_feats % 2 == 0, "Expecting even model width"
28
+ self.num_pos_feats = num_pos_feats // 2
29
+ self.temperature = temperature
30
+ self.normalize = normalize
31
+ if scale is not None and normalize is False:
32
+ raise ValueError("normalize should be True if scale is passed")
33
+ if scale is None:
34
+ scale = 2 * math.pi
35
+ self.scale = scale
36
+
37
+ self.cache = {}
38
+ # Precompute positional encodings under `precompute_resolution` to fill the cache
39
+ # and avoid symbolic shape tracing errors in torch.compile in PyTorch 2.4 nightly.
40
+ if precompute_resolution is not None:
41
+ # We precompute pos enc for stride 4, 8, 16 and 32 to fill `self.cache`.
42
+ precompute_sizes = [
43
+ (precompute_resolution // 4, precompute_resolution // 4),
44
+ (precompute_resolution // 8, precompute_resolution // 8),
45
+ (precompute_resolution // 16, precompute_resolution // 16),
46
+ (precompute_resolution // 32, precompute_resolution // 32),
47
+ ]
48
+ for size in precompute_sizes:
49
+ tensors = torch.zeros((1, 1) + size, device="cuda")
50
+ self.forward(tensors)
51
+ # further clone and detach it in the cache (just to be safe)
52
+ self.cache[size] = self.cache[size].clone().detach()
53
+
54
+ def _encode_xy(self, x, y):
55
+ # The positions are expected to be normalized
56
+ assert len(x) == len(y) and x.ndim == y.ndim == 1
57
+ x_embed = x * self.scale
58
+ y_embed = y * self.scale
59
+
60
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
61
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
62
+
63
+ pos_x = x_embed[:, None] / dim_t
64
+ pos_y = y_embed[:, None] / dim_t
65
+ pos_x = torch.stack(
66
+ (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2
67
+ ).flatten(1)
68
+ pos_y = torch.stack(
69
+ (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2
70
+ ).flatten(1)
71
+ return pos_x, pos_y
72
+
73
+ @torch.no_grad()
74
+ def encode_boxes(self, x, y, w, h):
75
+ pos_x, pos_y = self._encode_xy(x, y)
76
+ pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1)
77
+ return pos
78
+
79
+ encode = encode_boxes # Backwards compatibility
80
+
81
+ @torch.no_grad()
82
+ def encode_points(self, x, y, labels):
83
+ (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape
84
+ assert bx == by and nx == ny and bx == bl and nx == nl
85
+ pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten())
86
+ pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1)
87
+ pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2)
88
+ return pos
89
+
90
+ @torch.no_grad()
91
+ def forward(self, x):
92
+ cache_key = None
93
+ cache_key = (x.shape[-2], x.shape[-1])
94
+ if cache_key in self.cache:
95
+ return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1)
96
+ y_embed = (
97
+ torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device)
98
+ .view(1, -1, 1)
99
+ .repeat(x.shape[0], 1, x.shape[-1])
100
+ )
101
+ x_embed = (
102
+ torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device)
103
+ .view(1, 1, -1)
104
+ .repeat(x.shape[0], x.shape[-2], 1)
105
+ )
106
+
107
+ if self.normalize:
108
+ eps = 1e-6
109
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
110
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
111
+
112
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
113
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
114
+
115
+ pos_x = x_embed[:, :, :, None] / dim_t
116
+ pos_y = y_embed[:, :, :, None] / dim_t
117
+ pos_x = torch.stack(
118
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
119
+ ).flatten(3)
120
+ pos_y = torch.stack(
121
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
122
+ ).flatten(3)
123
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
124
+ if cache_key is not None:
125
+ self.cache[cache_key] = pos[0]
126
+ return pos
third_party/GraspGen/sam3/sam3/model/sam1_task_predictor.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+ # All rights reserved.
3
+
4
+ # pyre-unsafe
5
+
6
+ # This source code is licensed under the license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import logging
10
+ from typing import List, Optional, Tuple, Union
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ from PIL.Image import Image
16
+ from sam3.model.sam3_tracker_base import Sam3TrackerBase
17
+ from sam3.model.utils.sam1_utils import SAM2Transforms
18
+
19
+
20
+ # Adapted from https://github.com/facebookresearch/sam2/blob/main/sam2/sam2_image_predictor.py
21
+ class SAM3InteractiveImagePredictor(nn.Module):
22
+ def __init__(
23
+ self,
24
+ sam_model: Sam3TrackerBase,
25
+ mask_threshold=0.0,
26
+ max_hole_area=256.0,
27
+ max_sprinkle_area=0.0,
28
+ **kwargs,
29
+ ) -> None:
30
+ """
31
+ Uses SAM-3 to calculate the image embedding for an image, and then
32
+ allow repeated, efficient mask prediction given prompts.
33
+
34
+ Arguments:
35
+ sam_model : The model to use for mask prediction.
36
+ mask_threshold (float): The threshold to use when converting mask logits
37
+ to binary masks. Masks are thresholded at 0 by default.
38
+ max_hole_area (int): If max_hole_area > 0, we fill small holes in up to
39
+ the maximum area of max_hole_area in low_res_masks.
40
+ max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to
41
+ the maximum area of max_sprinkle_area in low_res_masks.
42
+ """
43
+ super().__init__()
44
+ self.model = sam_model
45
+ self._transforms = SAM2Transforms(
46
+ resolution=self.model.image_size,
47
+ mask_threshold=mask_threshold,
48
+ max_hole_area=max_hole_area,
49
+ max_sprinkle_area=max_sprinkle_area,
50
+ )
51
+
52
+ # Predictor state
53
+ self._is_image_set = False
54
+ self._features = None
55
+ self._orig_hw = None
56
+ # Whether the predictor is set for single image or a batch of images
57
+ self._is_batch = False
58
+
59
+ # Predictor config
60
+ self.mask_threshold = mask_threshold
61
+
62
+ # Spatial dim for backbone feature maps
63
+ self._bb_feat_sizes = [
64
+ (288, 288),
65
+ (144, 144),
66
+ (72, 72),
67
+ ]
68
+
69
+ @torch.no_grad()
70
+ def set_image(
71
+ self,
72
+ image: Union[np.ndarray, Image],
73
+ ) -> None:
74
+ """
75
+ Calculates the image embeddings for the provided image, allowing
76
+ masks to be predicted with the 'predict' method.
77
+
78
+ Arguments:
79
+ image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image
80
+ with pixel values in [0, 255].
81
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
82
+ """
83
+ self.reset_predictor()
84
+ # Transform the image to the form expected by the model
85
+ if isinstance(image, np.ndarray):
86
+ logging.info("For numpy array image, we assume (HxWxC) format")
87
+ self._orig_hw = [image.shape[:2]]
88
+ elif isinstance(image, Image):
89
+ w, h = image.size
90
+ self._orig_hw = [(h, w)]
91
+ else:
92
+ raise NotImplementedError("Image format not supported")
93
+
94
+ input_image = self._transforms(image)
95
+ input_image = input_image[None, ...].to(self.device)
96
+
97
+ assert len(input_image.shape) == 4 and input_image.shape[1] == 3, (
98
+ f"input_image must be of size 1x3xHxW, got {input_image.shape}"
99
+ )
100
+ logging.info("Computing image embeddings for the provided image...")
101
+ backbone_out = self.model.forward_image(input_image)
102
+ (
103
+ _,
104
+ vision_feats,
105
+ _,
106
+ _,
107
+ ) = self.model._prepare_backbone_features(backbone_out)
108
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
109
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
110
+
111
+ feats = [
112
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
113
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
114
+ ][::-1]
115
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
116
+ self._is_image_set = True
117
+ logging.info("Image embeddings computed.")
118
+
119
+ @torch.no_grad()
120
+ def set_image_batch(
121
+ self,
122
+ image_list: List[Union[np.ndarray]],
123
+ ) -> None:
124
+ """
125
+ Calculates the image embeddings for the provided image batch, allowing
126
+ masks to be predicted with the 'predict_batch' method.
127
+
128
+ Arguments:
129
+ image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
130
+ with pixel values in [0, 255].
131
+ """
132
+ self.reset_predictor()
133
+ assert isinstance(image_list, list)
134
+ self._orig_hw = []
135
+ for image in image_list:
136
+ assert isinstance(image, np.ndarray), (
137
+ "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
138
+ )
139
+ self._orig_hw.append(image.shape[:2])
140
+ # Transform the image to the form expected by the model
141
+ img_batch = self._transforms.forward_batch(image_list)
142
+ img_batch = img_batch.to(self.device)
143
+ batch_size = img_batch.shape[0]
144
+ assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, (
145
+ f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
146
+ )
147
+ logging.info("Computing image embeddings for the provided images...")
148
+ backbone_out = self.model.forward_image(img_batch)
149
+ (
150
+ _,
151
+ vision_feats,
152
+ _,
153
+ _,
154
+ ) = self.model._prepare_backbone_features(backbone_out)
155
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
156
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
157
+
158
+ feats = [
159
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
160
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
161
+ ][::-1]
162
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
163
+ self._is_image_set = True
164
+ self._is_batch = True
165
+ logging.info("Image embeddings computed.")
166
+
167
+ def predict_batch(
168
+ self,
169
+ point_coords_batch: List[np.ndarray] = None,
170
+ point_labels_batch: List[np.ndarray] = None,
171
+ box_batch: List[np.ndarray] = None,
172
+ mask_input_batch: List[np.ndarray] = None,
173
+ multimask_output: bool = True,
174
+ return_logits: bool = False,
175
+ normalize_coords=True,
176
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
177
+ """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images.
178
+ It returns a tuple of lists of masks, ious, and low_res_masks_logits.
179
+ """
180
+ assert self._is_batch, "This function should only be used when in batched mode"
181
+ if not self._is_image_set:
182
+ raise RuntimeError(
183
+ "An image must be set with .set_image_batch(...) before mask prediction."
184
+ )
185
+ num_images = len(self._features["image_embed"])
186
+ all_masks = []
187
+ all_ious = []
188
+ all_low_res_masks = []
189
+ for img_idx in range(num_images):
190
+ # Transform input prompts
191
+ point_coords = (
192
+ point_coords_batch[img_idx] if point_coords_batch is not None else None
193
+ )
194
+ point_labels = (
195
+ point_labels_batch[img_idx] if point_labels_batch is not None else None
196
+ )
197
+ box = box_batch[img_idx] if box_batch is not None else None
198
+ mask_input = (
199
+ mask_input_batch[img_idx] if mask_input_batch is not None else None
200
+ )
201
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
202
+ point_coords,
203
+ point_labels,
204
+ box,
205
+ mask_input,
206
+ normalize_coords,
207
+ img_idx=img_idx,
208
+ )
209
+ masks, iou_predictions, low_res_masks = self._predict(
210
+ unnorm_coords,
211
+ labels,
212
+ unnorm_box,
213
+ mask_input,
214
+ multimask_output,
215
+ return_logits=return_logits,
216
+ img_idx=img_idx,
217
+ )
218
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
219
+ iou_predictions_np = (
220
+ iou_predictions.squeeze(0).float().detach().cpu().numpy()
221
+ )
222
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
223
+ all_masks.append(masks_np)
224
+ all_ious.append(iou_predictions_np)
225
+ all_low_res_masks.append(low_res_masks_np)
226
+
227
+ return all_masks, all_ious, all_low_res_masks
228
+
229
+ def predict(
230
+ self,
231
+ point_coords: Optional[np.ndarray] = None,
232
+ point_labels: Optional[np.ndarray] = None,
233
+ box: Optional[np.ndarray] = None,
234
+ mask_input: Optional[np.ndarray] = None,
235
+ multimask_output: bool = True,
236
+ return_logits: bool = False,
237
+ normalize_coords=True,
238
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
239
+ """
240
+ Predict masks for the given input prompts, using the currently set image.
241
+
242
+ Arguments:
243
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
244
+ model. Each point is in (X,Y) in pixels.
245
+ point_labels (np.ndarray or None): A length N array of labels for the
246
+ point prompts. 1 indicates a foreground point and 0 indicates a
247
+ background point.
248
+ box (np.ndarray or None): A length 4 array given a box prompt to the
249
+ model, in XYXY format.
250
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
251
+ coming from a previous prediction iteration. Has form 1xHxW, where
252
+ for SAM, H=W=256.
253
+ multimask_output (bool): If true, the model will return three masks.
254
+ For ambiguous input prompts (such as a single click), this will often
255
+ produce better masks than a single prediction. If only a single
256
+ mask is needed, the model's predicted quality score can be used
257
+ to select the best mask. For non-ambiguous prompts, such as multiple
258
+ input prompts, multimask_output=False can give better results.
259
+ return_logits (bool): If true, returns un-thresholded masks logits
260
+ instead of a binary mask.
261
+ normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions.
262
+
263
+ Returns:
264
+ (np.ndarray): The output masks in CxHxW format, where C is the
265
+ number of masks, and (H, W) is the original image size.
266
+ (np.ndarray): An array of length C containing the model's
267
+ predictions for the quality of each mask.
268
+ (np.ndarray): An array of shape CxHxW, where C is the number
269
+ of masks and H=W=256. These low resolution logits can be passed to
270
+ a subsequent iteration as mask input.
271
+ """
272
+ if not self._is_image_set:
273
+ raise RuntimeError(
274
+ "An image must be set with .set_image(...) before mask prediction."
275
+ )
276
+
277
+ # Transform input prompts
278
+
279
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
280
+ point_coords, point_labels, box, mask_input, normalize_coords
281
+ )
282
+
283
+ masks, iou_predictions, low_res_masks = self._predict(
284
+ unnorm_coords,
285
+ labels,
286
+ unnorm_box,
287
+ mask_input,
288
+ multimask_output,
289
+ return_logits=return_logits,
290
+ )
291
+
292
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
293
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
294
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
295
+ return masks_np, iou_predictions_np, low_res_masks_np
296
+
297
+ def _prep_prompts(
298
+ self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1
299
+ ):
300
+ unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
301
+ if point_coords is not None:
302
+ assert point_labels is not None, (
303
+ "point_labels must be supplied if point_coords is supplied."
304
+ )
305
+ point_coords = torch.as_tensor(
306
+ point_coords, dtype=torch.float, device=self.device
307
+ )
308
+ unnorm_coords = self._transforms.transform_coords(
309
+ point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
310
+ )
311
+ labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
312
+ if len(unnorm_coords.shape) == 2:
313
+ unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...]
314
+ if box is not None:
315
+ box = torch.as_tensor(box, dtype=torch.float, device=self.device)
316
+ unnorm_box = self._transforms.transform_boxes(
317
+ box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
318
+ ) # Bx2x2
319
+ if mask_logits is not None:
320
+ mask_input = torch.as_tensor(
321
+ mask_logits, dtype=torch.float, device=self.device
322
+ )
323
+ if len(mask_input.shape) == 3:
324
+ mask_input = mask_input[None, :, :, :]
325
+ return mask_input, unnorm_coords, labels, unnorm_box
326
+
327
+ @torch.no_grad()
328
+ def _predict(
329
+ self,
330
+ point_coords: Optional[torch.Tensor],
331
+ point_labels: Optional[torch.Tensor],
332
+ boxes: Optional[torch.Tensor] = None,
333
+ mask_input: Optional[torch.Tensor] = None,
334
+ multimask_output: bool = True,
335
+ return_logits: bool = False,
336
+ img_idx: int = -1,
337
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
338
+ """
339
+ Predict masks for the given input prompts, using the currently set image.
340
+ Input prompts are batched torch tensors and are expected to already be
341
+ transformed to the input frame using SAM2Transforms.
342
+
343
+ Arguments:
344
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
345
+ model. Each point is in (X,Y) in pixels.
346
+ point_labels (torch.Tensor or None): A BxN array of labels for the
347
+ point prompts. 1 indicates a foreground point and 0 indicates a
348
+ background point.
349
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
350
+ model, in XYXY format.
351
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
352
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
353
+ for SAM, H=W=256. Masks returned by a previous iteration of the
354
+ predict method do not need further transformation.
355
+ multimask_output (bool): If true, the model will return three masks.
356
+ For ambiguous input prompts (such as a single click), this will often
357
+ produce better masks than a single prediction. If only a single
358
+ mask is needed, the model's predicted quality score can be used
359
+ to select the best mask. For non-ambiguous prompts, such as multiple
360
+ input prompts, multimask_output=False can give better results.
361
+ return_logits (bool): If true, returns un-thresholded masks logits
362
+ instead of a binary mask.
363
+
364
+ Returns:
365
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
366
+ number of masks, and (H, W) is the original image size.
367
+ (torch.Tensor): An array of shape BxC containing the model's
368
+ predictions for the quality of each mask.
369
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
370
+ of masks and H=W=256. These low res logits can be passed to
371
+ a subsequent iteration as mask input.
372
+ """
373
+ if not self._is_image_set:
374
+ raise RuntimeError(
375
+ "An image must be set with .set_image(...) before mask prediction."
376
+ )
377
+
378
+ if point_coords is not None:
379
+ concat_points = (point_coords, point_labels)
380
+ else:
381
+ concat_points = None
382
+
383
+ # Embed prompts
384
+ if boxes is not None:
385
+ box_coords = boxes.reshape(-1, 2, 2)
386
+ box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device)
387
+ box_labels = box_labels.repeat(boxes.size(0), 1)
388
+ # we merge "boxes" and "points" into a single "concat_points" input (where
389
+ # boxes are added at the beginning) to sam_prompt_encoder
390
+ if concat_points is not None:
391
+ concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
392
+ concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
393
+ concat_points = (concat_coords, concat_labels)
394
+ else:
395
+ concat_points = (box_coords, box_labels)
396
+
397
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
398
+ points=concat_points,
399
+ boxes=None,
400
+ masks=mask_input,
401
+ )
402
+
403
+ # Predict masks
404
+ batched_mode = (
405
+ concat_points is not None and concat_points[0].shape[0] > 1
406
+ ) # multi object prediction
407
+ high_res_features = [
408
+ feat_level[img_idx].unsqueeze(0)
409
+ for feat_level in self._features["high_res_feats"]
410
+ ]
411
+ low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
412
+ image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
413
+ image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
414
+ sparse_prompt_embeddings=sparse_embeddings,
415
+ dense_prompt_embeddings=dense_embeddings,
416
+ multimask_output=multimask_output,
417
+ repeat_image=batched_mode,
418
+ high_res_features=high_res_features,
419
+ )
420
+
421
+ # Upscale the masks to the original image resolution
422
+ masks = self._transforms.postprocess_masks(
423
+ low_res_masks, self._orig_hw[img_idx]
424
+ )
425
+ low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
426
+ if not return_logits:
427
+ masks = masks > self.mask_threshold
428
+
429
+ return masks, iou_predictions, low_res_masks
430
+
431
+ def get_image_embedding(self) -> torch.Tensor:
432
+ """
433
+ Returns the image embeddings for the currently set image, with
434
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
435
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
436
+ """
437
+ if not self._is_image_set:
438
+ raise RuntimeError(
439
+ "An image must be set with .set_image(...) to generate an embedding."
440
+ )
441
+ assert self._features is not None, (
442
+ "Features must exist if an image has been set."
443
+ )
444
+ return self._features["image_embed"]
445
+
446
+ @property
447
+ def device(self) -> torch.device:
448
+ return self.model.device
449
+
450
+ def reset_predictor(self) -> None:
451
+ """
452
+ Resets the image embeddings and other state variables.
453
+ """
454
+ self._is_image_set = False
455
+ self._features = None
456
+ self._orig_hw = None
457
+ self._is_batch = False
third_party/GraspGen/sam3/sam3/model/sam3_image.py ADDED
@@ -0,0 +1,880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import os
6
+ from copy import deepcopy
7
+ from typing import Dict, List, Optional, Tuple
8
+
9
+ import numpy as np
10
+ import torch
11
+ from sam3.model.model_misc import SAM3Output
12
+ from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
13
+ from sam3.model.vl_combiner import SAM3VLBackbone
14
+ from sam3.perflib.nms import nms_masks
15
+ from sam3.train.data.collator import BatchedDatapoint
16
+
17
+ from .act_ckpt_utils import activation_ckpt_wrapper
18
+ from .box_ops import box_cxcywh_to_xyxy
19
+ from .geometry_encoders import Prompt
20
+ from .model_misc import inverse_sigmoid
21
+
22
+
23
+ def _update_out(out, out_name, out_value, auxiliary=True, update_aux=True):
24
+ out[out_name] = out_value[-1] if auxiliary else out_value
25
+ if auxiliary and update_aux:
26
+ if "aux_outputs" not in out:
27
+ out["aux_outputs"] = [{} for _ in range(len(out_value) - 1)]
28
+ assert len(out["aux_outputs"]) == len(out_value) - 1
29
+ for aux_output, aux_value in zip(out["aux_outputs"], out_value[:-1]):
30
+ aux_output[out_name] = aux_value
31
+
32
+
33
+ class Sam3Image(torch.nn.Module):
34
+ TEXT_ID_FOR_TEXT = 0
35
+ TEXT_ID_FOR_VISUAL = 1
36
+ TEXT_ID_FOR_GEOMETRIC = 2
37
+
38
+ def __init__(
39
+ self,
40
+ backbone: SAM3VLBackbone,
41
+ transformer,
42
+ input_geometry_encoder,
43
+ segmentation_head=None,
44
+ num_feature_levels=1,
45
+ o2m_mask_predict=True,
46
+ dot_prod_scoring=None,
47
+ use_instance_query: bool = True,
48
+ multimask_output: bool = True,
49
+ use_act_checkpoint_seg_head: bool = True,
50
+ interactivity_in_encoder: bool = True,
51
+ matcher=None,
52
+ use_dot_prod_scoring=True,
53
+ supervise_joint_box_scores: bool = False, # only relevant if using presence token/score
54
+ detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score
55
+ separate_scorer_for_instance: bool = False,
56
+ num_interactive_steps_val: int = 0,
57
+ inst_interactive_predictor: SAM3InteractiveImagePredictor = None,
58
+ **kwargs,
59
+ ):
60
+ super().__init__()
61
+ self.backbone = backbone
62
+ self.geometry_encoder = input_geometry_encoder
63
+ self.transformer = transformer
64
+ self.hidden_dim = transformer.d_model
65
+ self.num_feature_levels = num_feature_levels
66
+ self.segmentation_head = segmentation_head
67
+
68
+ self.o2m_mask_predict = o2m_mask_predict
69
+
70
+ self.dot_prod_scoring = dot_prod_scoring
71
+ self.use_act_checkpoint_seg_head = use_act_checkpoint_seg_head
72
+ self.interactivity_in_encoder = interactivity_in_encoder
73
+ self.matcher = matcher
74
+
75
+ self.num_interactive_steps_val = num_interactive_steps_val
76
+ self.use_dot_prod_scoring = use_dot_prod_scoring
77
+
78
+ if self.use_dot_prod_scoring:
79
+ assert dot_prod_scoring is not None
80
+ self.dot_prod_scoring = dot_prod_scoring
81
+ self.instance_dot_prod_scoring = None
82
+ if separate_scorer_for_instance:
83
+ self.instance_dot_prod_scoring = deepcopy(dot_prod_scoring)
84
+ else:
85
+ self.class_embed = torch.nn.Linear(self.hidden_dim, 1)
86
+ self.instance_class_embed = None
87
+ if separate_scorer_for_instance:
88
+ self.instance_class_embed = deepcopy(self.class_embed)
89
+
90
+ self.supervise_joint_box_scores = supervise_joint_box_scores
91
+ self.detach_presence_in_joint_score = detach_presence_in_joint_score
92
+
93
+ # verify the number of queries for O2O and O2M
94
+ num_o2o_static = self.transformer.decoder.num_queries
95
+ num_o2m_static = self.transformer.decoder.num_o2m_queries
96
+ assert num_o2m_static == (num_o2o_static if self.transformer.decoder.dac else 0)
97
+ self.dac = self.transformer.decoder.dac
98
+
99
+ self.use_instance_query = use_instance_query
100
+ self.multimask_output = multimask_output
101
+
102
+ self.inst_interactive_predictor = inst_interactive_predictor
103
+
104
+ @property
105
+ def device(self):
106
+ self._device = getattr(self, "_device", None) or next(self.parameters()).device
107
+ return self._device
108
+
109
+ def to(self, *args, **kwargs):
110
+ # clear cached _device in case the model is moved to a different device
111
+ self._device = None
112
+ return super().to(*args, **kwargs)
113
+
114
+ def _get_img_feats(self, backbone_out, img_ids):
115
+ """Retrieve correct image features from backbone output."""
116
+ if "backbone_fpn" in backbone_out:
117
+ if "id_mapping" in backbone_out and backbone_out["id_mapping"] is not None:
118
+ img_ids = backbone_out["id_mapping"][img_ids]
119
+ # If this assert fails, it likely means we're requesting different img_ids (perhaps a different frame?)
120
+ # We currently don't expect this to happen. We could technically trigger a recompute here,
121
+ # but likely at the cost of a cpu<->gpu sync point, which would deteriorate perf
122
+ torch._assert_async((img_ids >= 0).all())
123
+
124
+ vis_feats = backbone_out["backbone_fpn"][-self.num_feature_levels :]
125
+ vis_pos_enc = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
126
+ vis_feat_sizes = [x.shape[-2:] for x in vis_pos_enc] # (H, W) shapes
127
+ # index and flatten visual features NxCxHxW => HWxNxC (batch-first => seq-first)
128
+ img_feats = [x[img_ids].flatten(2).permute(2, 0, 1) for x in vis_feats]
129
+ img_pos_embeds = [
130
+ x[img_ids].flatten(2).permute(2, 0, 1) for x in vis_pos_enc
131
+ ]
132
+ return backbone_out, img_feats, img_pos_embeds, vis_feat_sizes
133
+
134
+ # Image features not available in backbone output, so we compute them on the fly
135
+ # This case likely occurs for video. In that case, we want to forward only the current frame
136
+ img_batch = backbone_out["img_batch_all_stages"]
137
+ if img_ids.numel() > 1:
138
+ # Only forward backbone on unique image ids to avoid repetitive computation
139
+ unique_ids, _ = torch.unique(img_ids, return_inverse=True)
140
+ else:
141
+ unique_ids, _ = img_ids, slice(None)
142
+ # Compute the image features on those unique image ids
143
+ # note: we allow using a list (or other indexable types) of tensors as img_batch
144
+ # (e.g. for async frame loading in demo). In this case we index img_batch.tensors directly
145
+ if isinstance(img_batch, torch.Tensor):
146
+ image = img_batch[unique_ids]
147
+ elif unique_ids.numel() == 1:
148
+ image = img_batch[unique_ids.item()].unsqueeze(0)
149
+ else:
150
+ image = torch.stack([img_batch[i] for i in unique_ids.tolist()])
151
+ # `img_batch` might be fp16 and offloaded to CPU
152
+ image = image.to(dtype=torch.float32, device=self.device)
153
+ # Next time we call this function, we want to remember which indices we computed
154
+ id_mapping = torch.full(
155
+ (len(img_batch),), -1, dtype=torch.long, device=self.device
156
+ )
157
+ id_mapping[unique_ids] = torch.arange(len(unique_ids), device=self.device)
158
+ backbone_out = {
159
+ **backbone_out,
160
+ **self.backbone.forward_image(image),
161
+ "id_mapping": id_mapping,
162
+ }
163
+ assert "backbone_fpn" in backbone_out
164
+ return self._get_img_feats(backbone_out, img_ids=img_ids)
165
+
166
+ def _encode_prompt(
167
+ self,
168
+ backbone_out,
169
+ find_input,
170
+ geometric_prompt,
171
+ visual_prompt_embed=None,
172
+ visual_prompt_mask=None,
173
+ encode_text=True,
174
+ prev_mask_pred=None,
175
+ ):
176
+ # index text features (note that regardless of early or late fusion, the batch size of
177
+ # `txt_feats` is always the number of *prompts* in the encoder)
178
+ txt_ids = find_input.text_ids
179
+ txt_feats = backbone_out["language_features"][:, txt_ids]
180
+ txt_masks = backbone_out["language_mask"][txt_ids]
181
+
182
+ feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids)
183
+ backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple
184
+
185
+ if prev_mask_pred is not None:
186
+ img_feats = [img_feats[-1] + prev_mask_pred]
187
+ # Encode geometry
188
+ geo_feats, geo_masks = self.geometry_encoder(
189
+ geo_prompt=geometric_prompt,
190
+ img_feats=img_feats,
191
+ img_sizes=vis_feat_sizes,
192
+ img_pos_embeds=img_pos_embeds,
193
+ )
194
+ if visual_prompt_embed is None:
195
+ visual_prompt_embed = torch.zeros(
196
+ (0, *geo_feats.shape[1:]), device=geo_feats.device
197
+ )
198
+ visual_prompt_mask = torch.zeros(
199
+ (*geo_masks.shape[:-1], 0),
200
+ device=geo_masks.device,
201
+ dtype=geo_masks.dtype,
202
+ )
203
+ if encode_text:
204
+ prompt = torch.cat([txt_feats, geo_feats, visual_prompt_embed], dim=0)
205
+ prompt_mask = torch.cat([txt_masks, geo_masks, visual_prompt_mask], dim=1)
206
+ else:
207
+ prompt = torch.cat([geo_feats, visual_prompt_embed], dim=0)
208
+ prompt_mask = torch.cat([geo_masks, visual_prompt_mask], dim=1)
209
+ return prompt, prompt_mask, backbone_out
210
+
211
+ def _run_encoder(
212
+ self,
213
+ backbone_out,
214
+ find_input,
215
+ prompt,
216
+ prompt_mask,
217
+ encoder_extra_kwargs: Optional[Dict] = None,
218
+ ):
219
+ feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids)
220
+ backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple
221
+
222
+ # Run the encoder
223
+ prompt_pos_embed = torch.zeros_like(prompt)
224
+ # make a copy of the image feature lists since the encoder may modify these lists in-place
225
+ memory = self.transformer.encoder(
226
+ src=img_feats.copy(),
227
+ src_key_padding_mask=None,
228
+ src_pos=img_pos_embeds.copy(),
229
+ prompt=prompt,
230
+ prompt_pos=prompt_pos_embed,
231
+ prompt_key_padding_mask=prompt_mask,
232
+ feat_sizes=vis_feat_sizes,
233
+ encoder_extra_kwargs=encoder_extra_kwargs,
234
+ )
235
+ encoder_out = {
236
+ # encoded image features
237
+ "encoder_hidden_states": memory["memory"],
238
+ "pos_embed": memory["pos_embed"],
239
+ "padding_mask": memory["padding_mask"],
240
+ "level_start_index": memory["level_start_index"],
241
+ "spatial_shapes": memory["spatial_shapes"],
242
+ "valid_ratios": memory["valid_ratios"],
243
+ "vis_feat_sizes": vis_feat_sizes,
244
+ # encoded text features (or other prompts)
245
+ "prompt_before_enc": prompt,
246
+ "prompt_after_enc": memory.get("memory_text", prompt),
247
+ "prompt_mask": prompt_mask,
248
+ }
249
+ return backbone_out, encoder_out, feat_tuple
250
+
251
+ def _run_decoder(
252
+ self,
253
+ pos_embed,
254
+ memory,
255
+ src_mask,
256
+ out,
257
+ prompt,
258
+ prompt_mask,
259
+ encoder_out,
260
+ ):
261
+ bs = memory.shape[1]
262
+ query_embed = self.transformer.decoder.query_embed.weight
263
+ tgt = query_embed.unsqueeze(1).repeat(1, bs, 1)
264
+
265
+ apply_dac = self.transformer.decoder.dac and self.training
266
+ hs, reference_boxes, dec_presence_out, dec_presence_feats = (
267
+ self.transformer.decoder(
268
+ tgt=tgt,
269
+ memory=memory,
270
+ memory_key_padding_mask=src_mask,
271
+ pos=pos_embed,
272
+ reference_boxes=None,
273
+ level_start_index=encoder_out["level_start_index"],
274
+ spatial_shapes=encoder_out["spatial_shapes"],
275
+ valid_ratios=encoder_out["valid_ratios"],
276
+ tgt_mask=None,
277
+ memory_text=prompt,
278
+ text_attention_mask=prompt_mask,
279
+ apply_dac=apply_dac,
280
+ )
281
+ )
282
+ hs = hs.transpose(1, 2) # seq-first to batch-first
283
+ reference_boxes = reference_boxes.transpose(1, 2) # seq-first to batch-first
284
+ if dec_presence_out is not None:
285
+ # seq-first to batch-first
286
+ dec_presence_out = dec_presence_out.transpose(1, 2)
287
+
288
+ out["presence_feats"] = dec_presence_feats
289
+ self._update_scores_and_boxes(
290
+ out,
291
+ hs,
292
+ reference_boxes,
293
+ prompt,
294
+ prompt_mask,
295
+ dec_presence_out=dec_presence_out,
296
+ )
297
+ return out, hs
298
+
299
+ def _update_scores_and_boxes(
300
+ self,
301
+ out,
302
+ hs,
303
+ reference_boxes,
304
+ prompt,
305
+ prompt_mask,
306
+ dec_presence_out=None,
307
+ is_instance_prompt=False,
308
+ ):
309
+ apply_dac = self.transformer.decoder.dac and self.training
310
+ num_o2o = (hs.size(2) // 2) if apply_dac else hs.size(2)
311
+ num_o2m = hs.size(2) - num_o2o
312
+ assert num_o2m == (num_o2o if apply_dac else 0)
313
+ out["queries"] = hs[-1][:, :num_o2o] # remove o2m queries if there are any
314
+ # score prediction
315
+ if self.use_dot_prod_scoring:
316
+ dot_prod_scoring_head = self.dot_prod_scoring
317
+ if is_instance_prompt and self.instance_dot_prod_scoring is not None:
318
+ dot_prod_scoring_head = self.instance_dot_prod_scoring
319
+ outputs_class = dot_prod_scoring_head(hs, prompt, prompt_mask)
320
+ else:
321
+ class_embed_head = self.class_embed
322
+ if is_instance_prompt and self.instance_class_embed is not None:
323
+ class_embed_head = self.instance_class_embed
324
+ outputs_class = class_embed_head(hs)
325
+
326
+ # box prediction
327
+ box_head = self.transformer.decoder.bbox_embed
328
+ if (
329
+ is_instance_prompt
330
+ and self.transformer.decoder.instance_bbox_embed is not None
331
+ ):
332
+ box_head = self.transformer.decoder.instance_bbox_embed
333
+ anchor_box_offsets = box_head(hs)
334
+ reference_boxes_inv_sig = inverse_sigmoid(reference_boxes)
335
+ outputs_coord = (reference_boxes_inv_sig + anchor_box_offsets).sigmoid()
336
+ outputs_boxes_xyxy = box_cxcywh_to_xyxy(outputs_coord)
337
+
338
+ if dec_presence_out is not None:
339
+ _update_out(
340
+ out, "presence_logit_dec", dec_presence_out, update_aux=self.training
341
+ )
342
+
343
+ if self.supervise_joint_box_scores:
344
+ assert dec_presence_out is not None
345
+ prob_dec_presence_out = dec_presence_out.clone().sigmoid()
346
+ if self.detach_presence_in_joint_score:
347
+ prob_dec_presence_out = prob_dec_presence_out.detach()
348
+
349
+ outputs_class = inverse_sigmoid(
350
+ outputs_class.sigmoid() * prob_dec_presence_out.unsqueeze(2)
351
+ ).clamp(min=-10.0, max=10.0)
352
+
353
+ _update_out(
354
+ out, "pred_logits", outputs_class[:, :, :num_o2o], update_aux=self.training
355
+ )
356
+ _update_out(
357
+ out, "pred_boxes", outputs_coord[:, :, :num_o2o], update_aux=self.training
358
+ )
359
+ _update_out(
360
+ out,
361
+ "pred_boxes_xyxy",
362
+ outputs_boxes_xyxy[:, :, :num_o2o],
363
+ update_aux=self.training,
364
+ )
365
+ if num_o2m > 0 and self.training:
366
+ _update_out(
367
+ out,
368
+ "pred_logits_o2m",
369
+ outputs_class[:, :, num_o2o:],
370
+ update_aux=self.training,
371
+ )
372
+ _update_out(
373
+ out,
374
+ "pred_boxes_o2m",
375
+ outputs_coord[:, :, num_o2o:],
376
+ update_aux=self.training,
377
+ )
378
+ _update_out(
379
+ out,
380
+ "pred_boxes_xyxy_o2m",
381
+ outputs_boxes_xyxy[:, :, num_o2o:],
382
+ update_aux=self.training,
383
+ )
384
+
385
+ def _run_segmentation_heads(
386
+ self,
387
+ out,
388
+ backbone_out,
389
+ img_ids,
390
+ vis_feat_sizes,
391
+ encoder_hidden_states,
392
+ prompt,
393
+ prompt_mask,
394
+ hs,
395
+ ):
396
+ apply_dac = self.transformer.decoder.dac and self.training
397
+ if self.segmentation_head is not None:
398
+ num_o2o = (hs.size(2) // 2) if apply_dac else hs.size(2)
399
+ num_o2m = hs.size(2) - num_o2o
400
+ obj_queries = hs if self.o2m_mask_predict else hs[:, :, :num_o2o]
401
+ seg_head_outputs = activation_ckpt_wrapper(self.segmentation_head)(
402
+ backbone_feats=backbone_out["backbone_fpn"],
403
+ obj_queries=obj_queries,
404
+ image_ids=img_ids,
405
+ encoder_hidden_states=encoder_hidden_states,
406
+ act_ckpt_enable=self.training and self.use_act_checkpoint_seg_head,
407
+ prompt=prompt,
408
+ prompt_mask=prompt_mask,
409
+ )
410
+ aux_masks = False # self.aux_loss and self.segmentation_head.aux_masks
411
+ for k, v in seg_head_outputs.items():
412
+ if k in self.segmentation_head.instance_keys:
413
+ _update_out(out, k, v[:, :num_o2o], auxiliary=aux_masks)
414
+ if (
415
+ self.o2m_mask_predict and num_o2m > 0
416
+ ): # handle o2m mask prediction
417
+ _update_out(
418
+ out, f"{k}_o2m", v[:, num_o2o:], auxiliary=aux_masks
419
+ )
420
+ else:
421
+ out[k] = v
422
+ else:
423
+ backbone_out.pop("backbone_fpn", None)
424
+
425
+ def _get_best_mask(self, out):
426
+ prev_mask_idx = out["pred_logits"].argmax(dim=1).squeeze(1)
427
+ batch_idx = torch.arange(
428
+ out["pred_logits"].shape[0], device=prev_mask_idx.device
429
+ )
430
+ prev_mask_pred = out["pred_masks"][batch_idx, prev_mask_idx][:, None]
431
+ # Downsample mask to match image resolution.
432
+ prev_mask_pred = self.geometry_encoder.mask_encoder.mask_downsampler(
433
+ prev_mask_pred
434
+ )
435
+ prev_mask_pred = prev_mask_pred.flatten(-2).permute(2, 0, 1)
436
+
437
+ return prev_mask_pred
438
+
439
+ def forward_grounding(
440
+ self,
441
+ backbone_out,
442
+ find_input,
443
+ find_target,
444
+ geometric_prompt: Prompt,
445
+ ):
446
+ with torch.profiler.record_function("SAM3Image._encode_prompt"):
447
+ prompt, prompt_mask, backbone_out = self._encode_prompt(
448
+ backbone_out, find_input, geometric_prompt
449
+ )
450
+ # Run the encoder
451
+ with torch.profiler.record_function("SAM3Image._run_encoder"):
452
+ backbone_out, encoder_out, _ = self._run_encoder(
453
+ backbone_out, find_input, prompt, prompt_mask
454
+ )
455
+ out = {
456
+ "encoder_hidden_states": encoder_out["encoder_hidden_states"],
457
+ "prev_encoder_out": {
458
+ "encoder_out": encoder_out,
459
+ "backbone_out": backbone_out,
460
+ },
461
+ }
462
+
463
+ # Run the decoder
464
+ with torch.profiler.record_function("SAM3Image._run_decoder"):
465
+ out, hs = self._run_decoder(
466
+ memory=out["encoder_hidden_states"],
467
+ pos_embed=encoder_out["pos_embed"],
468
+ src_mask=encoder_out["padding_mask"],
469
+ out=out,
470
+ prompt=prompt,
471
+ prompt_mask=prompt_mask,
472
+ encoder_out=encoder_out,
473
+ )
474
+
475
+ # Run segmentation heads
476
+ with torch.profiler.record_function("SAM3Image._run_segmentation_heads"):
477
+ self._run_segmentation_heads(
478
+ out=out,
479
+ backbone_out=backbone_out,
480
+ img_ids=find_input.img_ids,
481
+ vis_feat_sizes=encoder_out["vis_feat_sizes"],
482
+ encoder_hidden_states=out["encoder_hidden_states"],
483
+ prompt=prompt,
484
+ prompt_mask=prompt_mask,
485
+ hs=hs,
486
+ )
487
+
488
+ if self.training or self.num_interactive_steps_val > 0:
489
+ self._compute_matching(out, self.back_convert(find_target))
490
+ return out
491
+
492
+ def _postprocess_out(self, out: Dict, multimask_output: bool = False):
493
+ # For multimask output, during eval we return the single best mask with the dict keys expected by the evaluators, but also return the multimasks output with new keys.
494
+ num_mask_boxes = out["pred_boxes"].size(1)
495
+ if not self.training and multimask_output and num_mask_boxes > 1:
496
+ out["multi_pred_logits"] = out["pred_logits"]
497
+ if "pred_masks" in out:
498
+ out["multi_pred_masks"] = out["pred_masks"]
499
+ out["multi_pred_boxes"] = out["pred_boxes"]
500
+ out["multi_pred_boxes_xyxy"] = out["pred_boxes_xyxy"]
501
+
502
+ best_mask_idx = out["pred_logits"].argmax(1).squeeze(1)
503
+ batch_idx = torch.arange(len(best_mask_idx), device=best_mask_idx.device)
504
+
505
+ out["pred_logits"] = out["pred_logits"][batch_idx, best_mask_idx].unsqueeze(
506
+ 1
507
+ )
508
+ if "pred_masks" in out:
509
+ out["pred_masks"] = out["pred_masks"][
510
+ batch_idx, best_mask_idx
511
+ ].unsqueeze(1)
512
+ out["pred_boxes"] = out["pred_boxes"][batch_idx, best_mask_idx].unsqueeze(1)
513
+ out["pred_boxes_xyxy"] = out["pred_boxes_xyxy"][
514
+ batch_idx, best_mask_idx
515
+ ].unsqueeze(1)
516
+
517
+ return out
518
+
519
+ def _get_dummy_prompt(self, num_prompts=1):
520
+ device = self.device
521
+ geometric_prompt = Prompt(
522
+ box_embeddings=torch.zeros(0, num_prompts, 4, device=device),
523
+ box_mask=torch.zeros(num_prompts, 0, device=device, dtype=torch.bool),
524
+ )
525
+ return geometric_prompt
526
+
527
+ def forward(self, input: BatchedDatapoint):
528
+ device = self.device
529
+ backbone_out = {"img_batch_all_stages": input.img_batch}
530
+ backbone_out.update(self.backbone.forward_image(input.img_batch))
531
+ num_frames = len(input.find_inputs)
532
+ assert num_frames == 1
533
+
534
+ text_outputs = self.backbone.forward_text(input.find_text_batch, device=device)
535
+ backbone_out.update(text_outputs)
536
+
537
+ previous_stages_out = SAM3Output(
538
+ iter_mode=SAM3Output.IterMode.LAST_STEP_PER_STAGE
539
+ )
540
+
541
+ find_input = input.find_inputs[0]
542
+ find_target = input.find_targets[0]
543
+
544
+ if find_input.input_points is not None and find_input.input_points.numel() > 0:
545
+ print("Warning: Point prompts are ignored in PCS.")
546
+
547
+ num_interactive_steps = 0 if self.training else self.num_interactive_steps_val
548
+ geometric_prompt = Prompt(
549
+ box_embeddings=find_input.input_boxes,
550
+ box_mask=find_input.input_boxes_mask,
551
+ box_labels=find_input.input_boxes_label,
552
+ )
553
+
554
+ # Init vars that are shared across the loop.
555
+ stage_outs = []
556
+ for cur_step in range(num_interactive_steps + 1):
557
+ if cur_step > 0:
558
+ # We sample interactive geometric prompts (boxes, points)
559
+ geometric_prompt, _ = self.interactive_prompt_sampler.sample(
560
+ geo_prompt=geometric_prompt,
561
+ find_target=find_target,
562
+ previous_out=stage_outs[-1],
563
+ )
564
+ out = self.forward_grounding(
565
+ backbone_out=backbone_out,
566
+ find_input=find_input,
567
+ find_target=find_target,
568
+ geometric_prompt=geometric_prompt.clone(),
569
+ )
570
+ stage_outs.append(out)
571
+
572
+ previous_stages_out.append(stage_outs)
573
+ return previous_stages_out
574
+
575
+ def _compute_matching(self, out, targets):
576
+ out["indices"] = self.matcher(out, targets)
577
+ for aux_out in out.get("aux_outputs", []):
578
+ aux_out["indices"] = self.matcher(aux_out, targets)
579
+
580
+ def back_convert(self, targets):
581
+ batched_targets = {
582
+ "boxes": targets.boxes.view(-1, 4),
583
+ "boxes_xyxy": box_cxcywh_to_xyxy(targets.boxes.view(-1, 4)),
584
+ "boxes_padded": targets.boxes_padded,
585
+ "positive_map": targets.boxes.new_ones(len(targets.boxes), 1),
586
+ "num_boxes": targets.num_boxes,
587
+ "masks": targets.segments,
588
+ "semantic_masks": targets.semantic_segments,
589
+ "is_valid_mask": targets.is_valid_segment,
590
+ "is_exhaustive": targets.is_exhaustive,
591
+ "object_ids_packed": targets.object_ids,
592
+ "object_ids_padded": targets.object_ids_padded,
593
+ }
594
+ return batched_targets
595
+
596
+ def predict_inst(
597
+ self,
598
+ inference_state,
599
+ **kwargs,
600
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
601
+ orig_h, orig_w = (
602
+ inference_state["original_height"],
603
+ inference_state["original_width"],
604
+ )
605
+ backbone_out = inference_state["backbone_out"]["sam2_backbone_out"]
606
+ (
607
+ _,
608
+ vision_feats,
609
+ _,
610
+ _,
611
+ ) = self.inst_interactive_predictor.model._prepare_backbone_features(
612
+ backbone_out
613
+ )
614
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
615
+ vision_feats[-1] = (
616
+ vision_feats[-1] + self.inst_interactive_predictor.model.no_mem_embed
617
+ )
618
+ feats = [
619
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
620
+ for feat, feat_size in zip(
621
+ vision_feats[::-1], self.inst_interactive_predictor._bb_feat_sizes[::-1]
622
+ )
623
+ ][::-1]
624
+ self.inst_interactive_predictor._features = {
625
+ "image_embed": feats[-1],
626
+ "high_res_feats": feats[:-1],
627
+ }
628
+ self.inst_interactive_predictor._is_image_set = True
629
+ self.inst_interactive_predictor._orig_hw = [(orig_h, orig_w)]
630
+ res = self.inst_interactive_predictor.predict(**kwargs)
631
+ self.inst_interactive_predictor._features = None
632
+ self.inst_interactive_predictor._is_image_set = False
633
+ return res
634
+
635
+ def predict_inst_batch(
636
+ self,
637
+ inference_state,
638
+ *args,
639
+ **kwargs,
640
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
641
+ backbone_out = inference_state["backbone_out"]["sam2_backbone_out"]
642
+ (
643
+ _,
644
+ vision_feats,
645
+ _,
646
+ _,
647
+ ) = self.inst_interactive_predictor.model._prepare_backbone_features(
648
+ backbone_out
649
+ )
650
+ # Add no_mem_embed, which is added to the lowest res feat. map during training on videos
651
+ vision_feats[-1] = (
652
+ vision_feats[-1] + self.inst_interactive_predictor.model.no_mem_embed
653
+ )
654
+ batch_size = vision_feats[-1].shape[1]
655
+ orig_heights, orig_widths = (
656
+ inference_state["original_heights"],
657
+ inference_state["original_widths"],
658
+ )
659
+ assert batch_size == len(orig_heights) == len(orig_widths), (
660
+ f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
661
+ )
662
+ feats = [
663
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
664
+ for feat, feat_size in zip(
665
+ vision_feats[::-1], self.inst_interactive_predictor._bb_feat_sizes[::-1]
666
+ )
667
+ ][::-1]
668
+ self.inst_interactive_predictor._features = {
669
+ "image_embed": feats[-1],
670
+ "high_res_feats": feats[:-1],
671
+ }
672
+ self.inst_interactive_predictor._is_image_set = True
673
+ self.inst_interactive_predictor._is_batch = True
674
+ self.inst_interactive_predictor._orig_hw = [
675
+ (orig_h, orig_w) for orig_h, orig_w in zip(orig_heights, orig_widths)
676
+ ]
677
+ res = self.inst_interactive_predictor.predict_batch(*args, **kwargs)
678
+ self.inst_interactive_predictor._features = None
679
+ self.inst_interactive_predictor._is_image_set = False
680
+ self.inst_interactive_predictor._is_batch = False
681
+ return res
682
+
683
+
684
+ class Sam3ImageOnVideoMultiGPU(Sam3Image):
685
+ def __init__(
686
+ self, *args, async_all_gather=True, gather_backbone_out=None, **kwargs
687
+ ):
688
+ super().__init__(*args, **kwargs)
689
+ self.rank = int(os.getenv("RANK", "0"))
690
+ self.world_size = int(os.getenv("WORLD_SIZE", "1"))
691
+ self.async_all_gather = async_all_gather
692
+
693
+ # if gather_backbone is not set, default to gathering only for `SAM3VLBackbone`
694
+ if gather_backbone_out is None:
695
+ gather_backbone_out = isinstance(self.backbone, SAM3VLBackbone)
696
+ self.gather_backbone_out = gather_backbone_out
697
+
698
+ def forward_video_grounding_multigpu(
699
+ self,
700
+ backbone_out,
701
+ find_inputs,
702
+ geometric_prompt: Prompt,
703
+ frame_idx,
704
+ num_frames,
705
+ # `multigpu_buffer` is a dict to cache detector's outputs in a chunk between different calls
706
+ multigpu_buffer,
707
+ track_in_reverse=False,
708
+ # whether to also return the SAM2 backbone features
709
+ return_sam2_backbone_feats=False,
710
+ # whether to perform NMS and suppress the scores of those detections removed by NMS
711
+ run_nms=False,
712
+ nms_prob_thresh=None,
713
+ nms_iou_thresh=None,
714
+ **kwargs,
715
+ ):
716
+ """
717
+ Compute the detector's detection outputs in a distributed manner, where all GPUs process
718
+ a chunk of frames (equal to the number of GPUs) at once and store them in cache.
719
+ """
720
+ # Step 1: fetch the detector outputs in the current chunk from buffer
721
+ frame_idx_curr_b = frame_idx - frame_idx % self.world_size
722
+ frame_idx_curr_e = min(frame_idx_curr_b + self.world_size, num_frames)
723
+ # in case the current frame's detection results are not in the buffer yet, build the current chunk
724
+ # (this should only happen on the first chunk, since we are also building the next chunk below)
725
+ if frame_idx not in multigpu_buffer:
726
+ with torch.profiler.record_function("build_multigpu_buffer_next_chunk1"):
727
+ self._build_multigpu_buffer_next_chunk(
728
+ backbone_out=backbone_out,
729
+ find_inputs=find_inputs,
730
+ geometric_prompt=geometric_prompt,
731
+ frame_idx_begin=frame_idx_curr_b,
732
+ frame_idx_end=frame_idx_curr_e,
733
+ num_frames=num_frames,
734
+ multigpu_buffer=multigpu_buffer,
735
+ run_nms=run_nms,
736
+ nms_prob_thresh=nms_prob_thresh,
737
+ nms_iou_thresh=nms_iou_thresh,
738
+ )
739
+
740
+ # read out the current frame's results from `multigpu_buffer`
741
+ out = {}
742
+ for k, (v, handle) in multigpu_buffer[frame_idx].items():
743
+ if k.startswith("sam2_backbone_") and not return_sam2_backbone_feats:
744
+ continue
745
+ if handle is not None:
746
+ handle.wait() # wait for async all-gather to finish
747
+ out[k] = v
748
+
749
+ # Step 2: remove detection outputs of the previous chunk from cache to save GPU memory
750
+ if not track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
751
+ frame_idx_prev_e = frame_idx_curr_b
752
+ frame_idx_prev_b = frame_idx_curr_b - self.world_size
753
+ elif track_in_reverse and frame_idx_curr_e < num_frames:
754
+ frame_idx_prev_b = frame_idx_curr_e
755
+ frame_idx_prev_e = min(frame_idx_prev_b + self.world_size, num_frames)
756
+ else:
757
+ frame_idx_prev_b = frame_idx_prev_e = None
758
+ if frame_idx_prev_b is not None:
759
+ for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
760
+ multigpu_buffer.pop(frame_idx_rm, None)
761
+
762
+ # Step 3: compute and cache detection outputs of the next chunk ahead of time
763
+ # (so that we can overlap computation with all-gather transfer)
764
+ if not track_in_reverse and frame_idx_curr_e < num_frames:
765
+ frame_idx_next_b = frame_idx_curr_e
766
+ frame_idx_next_e = min(frame_idx_next_b + self.world_size, num_frames)
767
+ elif track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
768
+ frame_idx_next_e = frame_idx_curr_b
769
+ frame_idx_next_b = frame_idx_curr_b - self.world_size
770
+ else:
771
+ frame_idx_next_b = frame_idx_next_e = None
772
+ if frame_idx_next_b is not None and frame_idx_next_b not in multigpu_buffer:
773
+ with torch.profiler.record_function("build_multigpu_buffer_next_chunk2"):
774
+ self._build_multigpu_buffer_next_chunk(
775
+ backbone_out=backbone_out,
776
+ find_inputs=find_inputs,
777
+ geometric_prompt=geometric_prompt,
778
+ frame_idx_begin=frame_idx_next_b,
779
+ frame_idx_end=frame_idx_next_e,
780
+ num_frames=num_frames,
781
+ multigpu_buffer=multigpu_buffer,
782
+ run_nms=run_nms,
783
+ nms_prob_thresh=nms_prob_thresh,
784
+ nms_iou_thresh=nms_iou_thresh,
785
+ )
786
+
787
+ return out, backbone_out
788
+
789
+ def _build_multigpu_buffer_next_chunk(
790
+ self,
791
+ backbone_out,
792
+ find_inputs,
793
+ geometric_prompt: Prompt,
794
+ frame_idx_begin,
795
+ frame_idx_end,
796
+ num_frames,
797
+ multigpu_buffer,
798
+ run_nms=False,
799
+ nms_prob_thresh=None,
800
+ nms_iou_thresh=None,
801
+ ):
802
+ """Compute detection outputs on a chunk of frames and store their results in multigpu_buffer."""
803
+ # each GPU computes detections on one frame in the chunk (in a round-robin manner)
804
+ frame_idx_local_gpu = min(frame_idx_begin + self.rank, frame_idx_end - 1)
805
+ # `forward_grounding` (from base class `Sam3ImageOnVideo`) runs the detector on a single frame
806
+ with torch.profiler.record_function("forward_grounding"):
807
+ out_local = self.forward_grounding(
808
+ backbone_out=backbone_out,
809
+ find_input=find_inputs[frame_idx_local_gpu],
810
+ find_target=None,
811
+ geometric_prompt=geometric_prompt,
812
+ )
813
+ if run_nms:
814
+ with torch.profiler.record_function("nms_masks"):
815
+ # run NMS as a post-processing step on top of the detection outputs
816
+ assert nms_prob_thresh is not None and nms_iou_thresh is not None
817
+ pred_probs = out_local["pred_logits"].squeeze(-1).sigmoid()
818
+ pred_masks = out_local["pred_masks"]
819
+ # loop over text prompts (not an overhead for demo where there's only 1 prompt)
820
+ for prompt_idx in range(pred_probs.size(0)):
821
+ keep = nms_masks(
822
+ pred_probs=pred_probs[prompt_idx],
823
+ pred_masks=pred_masks[prompt_idx],
824
+ prob_threshold=nms_prob_thresh,
825
+ iou_threshold=nms_iou_thresh,
826
+ )
827
+ # set a very low threshold for those detections removed by NMS
828
+ out_local["pred_logits"][prompt_idx, :, 0] -= 1e4 * (~keep).float()
829
+
830
+ if self.gather_backbone_out:
831
+ # gather the SAM 2 backbone features across GPUs
832
+ feats = out_local["prev_encoder_out"]["backbone_out"]["sam2_backbone_out"]
833
+ assert len(feats["backbone_fpn"]) == 3 # SAM2 backbone always have 3 levels
834
+ # cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
835
+ # a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
836
+ backbone_fpn_bf16 = [x.to(torch.bfloat16) for x in feats["backbone_fpn"]]
837
+ fpn0, fpn_handle0 = self._gather_tensor(backbone_fpn_bf16[0])
838
+ fpn1, fpn_handle1 = self._gather_tensor(backbone_fpn_bf16[1])
839
+ fpn2, fpn_handle2 = self._gather_tensor(backbone_fpn_bf16[2])
840
+ # vision_pos_enc is the same on all frames, so no need to all-gather them
841
+ vision_pos_enc = feats["vision_pos_enc"]
842
+
843
+ # trim the detector output to only include the necessary keys
844
+ out_local = {
845
+ "pred_logits": out_local["pred_logits"],
846
+ "pred_boxes": out_local["pred_boxes"],
847
+ "pred_boxes_xyxy": out_local["pred_boxes_xyxy"],
848
+ "pred_masks": out_local["pred_masks"],
849
+ }
850
+
851
+ # gather the results: after this step, each GPU will receive detector outputs on
852
+ # all frames in the chunk and store them in `multigpu_buffer`
853
+ out_gathered = {k: self._gather_tensor(v) for k, v in out_local.items()}
854
+ for rank in range(self.world_size):
855
+ frame_idx_to_save = frame_idx_begin + rank
856
+ if frame_idx_to_save >= num_frames:
857
+ continue
858
+ frame_buffer = {
859
+ k: (v[rank], handle) for k, (v, handle) in out_gathered.items()
860
+ }
861
+ if self.gather_backbone_out:
862
+ # also add gathered SAM 2 backbone features to frame_buffer
863
+ frame_buffer["tracker_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
864
+ frame_buffer["tracker_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
865
+ frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
866
+ frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None)
867
+
868
+ multigpu_buffer[frame_idx_to_save] = frame_buffer
869
+
870
+ def _gather_tensor(self, x):
871
+ if self.world_size == 1:
872
+ return [x], None
873
+
874
+ async_op = self.async_all_gather
875
+ # here `.contiguous()` is required -- otherwise NCCL all_gather
876
+ # sometimes gives wrong results
877
+ x = x.contiguous() # ensure contiguous memory for NCCL
878
+ output_list = [torch.empty_like(x) for _ in range(self.world_size)]
879
+ handle = torch.distributed.all_gather(output_list, x, async_op=async_op)
880
+ return output_list, handle
third_party/GraspGen/sam3/sam3/model/sam3_image_processor.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ from typing import Dict, List
5
+
6
+ import numpy as np
7
+ import PIL
8
+ import torch
9
+ from sam3.model import box_ops
10
+ from sam3.model.data_misc import FindStage, interpolate
11
+ from torchvision.transforms import v2
12
+
13
+
14
+ class Sam3Processor:
15
+ """ """
16
+
17
+ def __init__(self, model, resolution=1008, device="cuda", confidence_threshold=0.5):
18
+ self.model = model
19
+ self.resolution = resolution
20
+ self.device = device
21
+ self.transform = v2.Compose(
22
+ [
23
+ v2.ToDtype(torch.uint8, scale=True),
24
+ v2.Resize(size=(resolution, resolution)),
25
+ v2.ToDtype(torch.float32, scale=True),
26
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
27
+ ]
28
+ )
29
+ self.confidence_threshold = confidence_threshold
30
+
31
+ self.find_stage = FindStage(
32
+ img_ids=torch.tensor([0], device=device, dtype=torch.long),
33
+ text_ids=torch.tensor([0], device=device, dtype=torch.long),
34
+ input_boxes=None,
35
+ input_boxes_mask=None,
36
+ input_boxes_label=None,
37
+ input_points=None,
38
+ input_points_mask=None,
39
+ )
40
+
41
+ @torch.inference_mode()
42
+ def set_image(self, image, state=None):
43
+ """Sets the image on which we want to do predictions."""
44
+ if state is None:
45
+ state = {}
46
+
47
+ if isinstance(image, PIL.Image.Image):
48
+ width, height = image.size
49
+ elif isinstance(image, (torch.Tensor, np.ndarray)):
50
+ height, width = image.shape[-2:]
51
+ else:
52
+ raise ValueError("Image must be a PIL image or a tensor")
53
+
54
+ image = v2.functional.to_image(image).to(self.device)
55
+ image = self.transform(image).unsqueeze(0)
56
+
57
+ state["original_height"] = height
58
+ state["original_width"] = width
59
+ state["backbone_out"] = self.model.backbone.forward_image(image)
60
+ inst_interactivity_en = self.model.inst_interactive_predictor is not None
61
+ if inst_interactivity_en and "sam2_backbone_out" in state["backbone_out"]:
62
+ sam2_backbone_out = state["backbone_out"]["sam2_backbone_out"]
63
+ sam2_backbone_out["backbone_fpn"][0] = (
64
+ self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s0(
65
+ sam2_backbone_out["backbone_fpn"][0]
66
+ )
67
+ )
68
+ sam2_backbone_out["backbone_fpn"][1] = (
69
+ self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s1(
70
+ sam2_backbone_out["backbone_fpn"][1]
71
+ )
72
+ )
73
+ return state
74
+
75
+ @torch.inference_mode()
76
+ def set_image_batch(self, images: List[np.ndarray], state=None):
77
+ """Sets the image batch on which we want to do predictions."""
78
+ if state is None:
79
+ state = {}
80
+
81
+ if not isinstance(images, list):
82
+ raise ValueError("Images must be a list of PIL images or tensors")
83
+ assert len(images) > 0, "Images list must not be empty"
84
+ assert isinstance(images[0], PIL.Image.Image), (
85
+ "Images must be a list of PIL images"
86
+ )
87
+
88
+ state["original_heights"] = [image.height for image in images]
89
+ state["original_widths"] = [image.width for image in images]
90
+
91
+ images = [
92
+ self.transform(v2.functional.to_image(image).to(self.device))
93
+ for image in images
94
+ ]
95
+ images = torch.stack(images, dim=0)
96
+ state["backbone_out"] = self.model.backbone.forward_image(images)
97
+ inst_interactivity_en = self.model.inst_interactive_predictor is not None
98
+ if inst_interactivity_en and "sam2_backbone_out" in state["backbone_out"]:
99
+ sam2_backbone_out = state["backbone_out"]["sam2_backbone_out"]
100
+ sam2_backbone_out["backbone_fpn"][0] = (
101
+ self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s0(
102
+ sam2_backbone_out["backbone_fpn"][0]
103
+ )
104
+ )
105
+ sam2_backbone_out["backbone_fpn"][1] = (
106
+ self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s1(
107
+ sam2_backbone_out["backbone_fpn"][1]
108
+ )
109
+ )
110
+ return state
111
+
112
+ @torch.inference_mode()
113
+ def set_text_prompt(self, prompt: str, state: Dict):
114
+ """Sets the text prompt and run the inference"""
115
+
116
+ if "backbone_out" not in state:
117
+ raise ValueError("You must call set_image before set_text_prompt")
118
+
119
+ text_outputs = self.model.backbone.forward_text([prompt], device=self.device)
120
+ # will erase the previous text prompt if any
121
+ state["backbone_out"].update(text_outputs)
122
+ if "geometric_prompt" not in state:
123
+ state["geometric_prompt"] = self.model._get_dummy_prompt()
124
+
125
+ return self._forward_grounding(state)
126
+
127
+ @torch.inference_mode()
128
+ def add_geometric_prompt(self, box: List, label: bool, state: Dict):
129
+ """Adds a box prompt and run the inference.
130
+ The image needs to be set, but not necessarily the text prompt.
131
+ The box is assumed to be in [center_x, center_y, width, height] format and normalized in [0, 1] range.
132
+ The label is True for a positive box, False for a negative box.
133
+ """
134
+ if "backbone_out" not in state:
135
+ raise ValueError("You must call set_image before set_text_prompt")
136
+
137
+ if "language_features" not in state["backbone_out"]:
138
+ # Looks like we don't have a text prompt yet. This is allowed, but we need to set the text prompt to "visual" for the model to rely only on the geometric prompt
139
+ dummy_text_outputs = self.model.backbone.forward_text(
140
+ ["visual"], device=self.device
141
+ )
142
+ state["backbone_out"].update(dummy_text_outputs)
143
+
144
+ if "geometric_prompt" not in state:
145
+ state["geometric_prompt"] = self.model._get_dummy_prompt()
146
+
147
+ # adding a batch and sequence dimension
148
+ boxes = torch.tensor(box, device=self.device, dtype=torch.float32).view(1, 1, 4)
149
+ labels = torch.tensor([label], device=self.device, dtype=torch.bool).view(1, 1)
150
+ state["geometric_prompt"].append_boxes(boxes, labels)
151
+
152
+ return self._forward_grounding(state)
153
+
154
+ def reset_all_prompts(self, state: Dict):
155
+ """Removes all the prompts and results"""
156
+ if "backbone_out" in state:
157
+ backbone_keys_to_del = [
158
+ "language_features",
159
+ "language_mask",
160
+ "language_embeds",
161
+ ]
162
+ for key in backbone_keys_to_del:
163
+ if key in state["backbone_out"]:
164
+ del state["backbone_out"][key]
165
+
166
+ keys_to_del = ["geometric_prompt", "boxes", "masks", "masks_logits", "scores"]
167
+ for key in keys_to_del:
168
+ if key in state:
169
+ del state[key]
170
+
171
+ @torch.inference_mode()
172
+ def set_confidence_threshold(self, threshold: float, state=None):
173
+ """Sets the confidence threshold for the masks"""
174
+ self.confidence_threshold = threshold
175
+ if state is not None and "boxes" in state:
176
+ # we need to filter the boxes again
177
+ # In principle we could do this more efficiently since we would only need
178
+ # to rerun the heads. But this is simpler and not too inefficient
179
+ return self._forward_grounding(state)
180
+ return state
181
+
182
+ @torch.inference_mode()
183
+ def _forward_grounding(self, state: Dict):
184
+ outputs = self.model.forward_grounding(
185
+ backbone_out=state["backbone_out"],
186
+ find_input=self.find_stage,
187
+ geometric_prompt=state["geometric_prompt"],
188
+ find_target=None,
189
+ )
190
+
191
+ out_bbox = outputs["pred_boxes"]
192
+ out_logits = outputs["pred_logits"]
193
+ out_masks = outputs["pred_masks"]
194
+ out_probs = out_logits.sigmoid()
195
+ presence_score = outputs["presence_logit_dec"].sigmoid().unsqueeze(1)
196
+ out_probs = (out_probs * presence_score).squeeze(-1)
197
+
198
+ keep = out_probs > self.confidence_threshold
199
+ out_probs = out_probs[keep]
200
+ out_masks = out_masks[keep]
201
+ out_bbox = out_bbox[keep]
202
+
203
+ # convert to [x0, y0, x1, y1] format
204
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
205
+
206
+ img_h = state["original_height"]
207
+ img_w = state["original_width"]
208
+ scale_fct = torch.tensor([img_w, img_h, img_w, img_h]).to(self.device)
209
+ boxes = boxes * scale_fct[None, :]
210
+
211
+ out_masks = interpolate(
212
+ out_masks.unsqueeze(1),
213
+ (img_h, img_w),
214
+ mode="bilinear",
215
+ align_corners=False,
216
+ ).sigmoid()
217
+
218
+ state["masks_logits"] = out_masks
219
+ state["masks"] = out_masks > 0.5
220
+ state["boxes"] = boxes
221
+ state["scores"] = out_probs
222
+ return state
third_party/GraspGen/sam3/sam3/model/sam3_tracker_base.py ADDED
@@ -0,0 +1,1185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from sam3.model.memory import SimpleMaskEncoder
10
+ from sam3.model.sam3_tracker_utils import get_1d_sine_pe, select_closest_cond_frames
11
+ from sam3.sam.mask_decoder import MaskDecoder, MLP
12
+ from sam3.sam.prompt_encoder import PromptEncoder
13
+ from sam3.sam.transformer import TwoWayTransformer
14
+ from sam3.train.data.collator import BatchedDatapoint
15
+
16
+ try:
17
+ from timm.layers import trunc_normal_
18
+ except ModuleNotFoundError:
19
+ # compatibility for older timm versions
20
+ from timm.models.layers import trunc_normal_
21
+
22
+ # a large negative value as a placeholder score for missing objects
23
+ NO_OBJ_SCORE = -1024.0
24
+
25
+
26
+ class Sam3TrackerBase(torch.nn.Module):
27
+ def __init__(
28
+ self,
29
+ backbone,
30
+ transformer,
31
+ maskmem_backbone,
32
+ num_maskmem=7, # default 1 input frame + 6 previous frames as in CAE
33
+ image_size=1008,
34
+ backbone_stride=14, # stride of the image backbone output
35
+ # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit,
36
+ # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model
37
+ # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM.
38
+ max_cond_frames_in_attn=-1,
39
+ # Whether to always keep the first conditioning frame in case we exceed the maximum number of conditioning frames allowed
40
+ keep_first_cond_frame=False,
41
+ # whether to output multiple (3) masks for the first click on initial conditioning frames
42
+ multimask_output_in_sam=False,
43
+ # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`;
44
+ # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points)
45
+ multimask_min_pt_num=1,
46
+ multimask_max_pt_num=1,
47
+ # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`)
48
+ multimask_output_for_tracking=False,
49
+ # whether to forward image features per frame (as it's being tracked) during evaluation, instead of forwarding image features
50
+ # of all frames at once. This avoids backbone OOM errors on very long videos in evaluation, but could be slightly slower.
51
+ forward_backbone_per_frame_for_eval=False,
52
+ # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5).
53
+ # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of
54
+ # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame.
55
+ memory_temporal_stride_for_eval=1,
56
+ # whether to offload outputs to CPU memory during evaluation, to avoid GPU OOM on very long videos or very large resolutions or too many objects
57
+ # (it's recommended to use `forward_backbone_per_frame_for_eval=True` first before setting this option to True)
58
+ offload_output_to_cpu_for_eval=False,
59
+ # whether to trim the output of past non-conditioning frames (num_maskmem frames before the current frame) during evaluation
60
+ # (this helps save GPU or CPU memory on very long videos for semi-supervised VOS eval, where only the first frame receives prompts)
61
+ trim_past_non_cond_mem_for_eval=False,
62
+ # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks)
63
+ non_overlap_masks_for_mem_enc=False,
64
+ # the maximum number of object pointers from other frames in encoder cross attention
65
+ max_obj_ptrs_in_encoder=16,
66
+ # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class.
67
+ sam_mask_decoder_extra_args=None,
68
+ # whether to compile all the model compoents
69
+ compile_all_components=False,
70
+ # select the frame with object existence
71
+ use_memory_selection=False,
72
+ # when using memory selection, the threshold to determine if the frame is good
73
+ mf_threshold=0.01,
74
+ ):
75
+ super().__init__()
76
+
77
+ # Part 1: the image backbone
78
+ self.backbone = backbone
79
+ self.num_feature_levels = 3
80
+ self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
81
+ # A conv layer to downsample the GT mask prompt to stride 4 (the same stride as
82
+ # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
83
+ # so that it can be fed into the SAM mask decoder to generate a pointer.
84
+ self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
85
+
86
+ # Part 2: encoder-only transformer to fuse current frame's visual features
87
+ # with memories from past frames
88
+ assert transformer.decoder is None, "transformer should be encoder-only"
89
+ self.transformer = transformer
90
+ self.hidden_dim = transformer.d_model
91
+
92
+ # Part 3: memory encoder for the previous frame's outputs
93
+ self.maskmem_backbone = maskmem_backbone
94
+ self.mem_dim = self.hidden_dim
95
+ if hasattr(self.maskmem_backbone, "out_proj") and hasattr(
96
+ self.maskmem_backbone.out_proj, "weight"
97
+ ):
98
+ # if there is compression of memories along channel dim
99
+ self.mem_dim = self.maskmem_backbone.out_proj.weight.shape[0]
100
+ self.num_maskmem = num_maskmem # Number of memories accessible
101
+
102
+ # Temporal encoding of the memories
103
+ self.maskmem_tpos_enc = torch.nn.Parameter(
104
+ torch.zeros(num_maskmem, 1, 1, self.mem_dim)
105
+ )
106
+ trunc_normal_(self.maskmem_tpos_enc, std=0.02)
107
+
108
+ # a single token to indicate no memory embedding from previous frames
109
+ self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
110
+ self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
111
+ trunc_normal_(self.no_mem_embed, std=0.02)
112
+ trunc_normal_(self.no_mem_pos_enc, std=0.02)
113
+ # Apply sigmoid to the output raw mask logits (to turn them from
114
+ # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
115
+ self.sigmoid_scale_for_mem_enc = 20.0
116
+ self.sigmoid_bias_for_mem_enc = -10.0
117
+ self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
118
+ self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
119
+ # On frames with mask input, whether to directly output the input mask without
120
+ # using a SAM prompt encoder + mask decoder
121
+ self.multimask_output_in_sam = multimask_output_in_sam
122
+ self.multimask_min_pt_num = multimask_min_pt_num
123
+ self.multimask_max_pt_num = multimask_max_pt_num
124
+ self.multimask_output_for_tracking = multimask_output_for_tracking
125
+
126
+ # Part 4: SAM-style prompt encoder (for both mask and point inputs)
127
+ # and SAM-style mask decoder for the final mask output
128
+ self.image_size = image_size
129
+ self.backbone_stride = backbone_stride
130
+ self.low_res_mask_size = self.image_size // self.backbone_stride * 4
131
+ # we resize the mask if it doesn't match `self.input_mask_size` (which is always 4x
132
+ # the low-res mask size, regardless of the actual input image size); this is because
133
+ # `_use_mask_as_output` always downsamples the input masks by 4x
134
+ self.input_mask_size = self.low_res_mask_size * 4
135
+ self.forward_backbone_per_frame_for_eval = forward_backbone_per_frame_for_eval
136
+ self.offload_output_to_cpu_for_eval = offload_output_to_cpu_for_eval
137
+ self.trim_past_non_cond_mem_for_eval = trim_past_non_cond_mem_for_eval
138
+ self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
139
+ self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
140
+ trunc_normal_(self.no_obj_ptr, std=0.02)
141
+ self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
142
+ trunc_normal_(self.no_obj_embed_spatial, std=0.02)
143
+
144
+ self._build_sam_heads()
145
+ self.max_cond_frames_in_attn = max_cond_frames_in_attn
146
+ self.keep_first_cond_frame = keep_first_cond_frame
147
+
148
+ # Use frame filtering according to SAM2Long
149
+ self.use_memory_selection = use_memory_selection
150
+ self.mf_threshold = mf_threshold
151
+
152
+ # Compile all components of the model
153
+ self.compile_all_components = compile_all_components
154
+ if self.compile_all_components:
155
+ self._compile_all_components()
156
+
157
+ @property
158
+ def device(self):
159
+ return next(self.parameters()).device
160
+
161
+ def _get_tpos_enc(self, rel_pos_list, device, max_abs_pos=None, dummy=False):
162
+ if dummy:
163
+ return torch.zeros(len(rel_pos_list), self.mem_dim, device=device)
164
+
165
+ t_diff_max = max_abs_pos - 1 if max_abs_pos is not None else 1
166
+ pos_enc = (
167
+ torch.tensor(rel_pos_list).pin_memory().to(device=device, non_blocking=True)
168
+ / t_diff_max
169
+ )
170
+ tpos_dim = self.hidden_dim
171
+ pos_enc = get_1d_sine_pe(pos_enc, dim=tpos_dim)
172
+ pos_enc = self.obj_ptr_tpos_proj(pos_enc)
173
+
174
+ return pos_enc
175
+
176
+ def _build_sam_heads(self):
177
+ """Build SAM-style prompt encoder and mask decoder."""
178
+ self.sam_prompt_embed_dim = self.hidden_dim
179
+ self.sam_image_embedding_size = self.image_size // self.backbone_stride
180
+
181
+ # build PromptEncoder and MaskDecoder from SAM
182
+ # (their hyperparameters like `mask_in_chans=16` are from SAM code)
183
+ self.sam_prompt_encoder = PromptEncoder(
184
+ embed_dim=self.sam_prompt_embed_dim,
185
+ image_embedding_size=(
186
+ self.sam_image_embedding_size,
187
+ self.sam_image_embedding_size,
188
+ ),
189
+ input_image_size=(self.image_size, self.image_size),
190
+ mask_in_chans=16,
191
+ )
192
+ self.sam_mask_decoder = MaskDecoder(
193
+ num_multimask_outputs=3,
194
+ transformer=TwoWayTransformer(
195
+ depth=2,
196
+ embedding_dim=self.sam_prompt_embed_dim,
197
+ mlp_dim=2048,
198
+ num_heads=8,
199
+ ),
200
+ transformer_dim=self.sam_prompt_embed_dim,
201
+ iou_head_depth=3,
202
+ iou_head_hidden_dim=256,
203
+ use_high_res_features=True,
204
+ iou_prediction_use_sigmoid=True,
205
+ pred_obj_scores=True,
206
+ pred_obj_scores_mlp=True,
207
+ use_multimask_token_for_obj_ptr=True,
208
+ **(self.sam_mask_decoder_extra_args or {}),
209
+ )
210
+ # a linear projection on SAM output tokens to turn them into object pointers
211
+ self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
212
+ self.obj_ptr_proj = MLP(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3)
213
+ # a linear projection on temporal positional encoding in object pointers to
214
+ # avoid potential interference with spatial positional encoding
215
+ self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
216
+
217
+ def _forward_sam_heads(
218
+ self,
219
+ backbone_features,
220
+ point_inputs=None,
221
+ mask_inputs=None,
222
+ high_res_features=None,
223
+ multimask_output=False,
224
+ gt_masks=None,
225
+ ):
226
+ """
227
+ Forward SAM prompt encoders and mask heads.
228
+
229
+ Inputs:
230
+ - backbone_features: image features of [B, C, H, W] shape
231
+ - point_inputs: a dictionary with "point_coords" and "point_labels", where
232
+ 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
233
+ absolute pixel-unit coordinate in (x, y) format of the P input points
234
+ 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means
235
+ positive clicks, 0 means negative clicks, and -1 means padding
236
+ - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the
237
+ same spatial size as the image.
238
+ - high_res_features: either 1) None or 2) or a list of length 2 containing
239
+ two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively,
240
+ which will be used as high-resolution feature maps for SAM decoder.
241
+ - multimask_output: if it's True, we output 3 candidate masks and their 3
242
+ corresponding IoU estimates, and if it's False, we output only 1 mask and
243
+ its corresponding IoU estimate.
244
+
245
+ Outputs:
246
+ - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if
247
+ `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM
248
+ output mask logits (before sigmoid) for the low-resolution masks, with 4x
249
+ the resolution (1/4 stride) of the input backbone_features.
250
+ - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3
251
+ if `multimask_output=True` and M = 1 if `multimask_output=False`),
252
+ upsampled from the low-resolution masks, with shape size as the image
253
+ (stride is 1 pixel).
254
+ - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1
255
+ if `multimask_output=False`), the estimated IoU of each output mask.
256
+ - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`.
257
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
258
+ If `multimask_output=False`, it's the same as `low_res_multimasks`.
259
+ - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`.
260
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
261
+ If `multimask_output=False`, it's the same as `high_res_multimasks`.
262
+ - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted
263
+ based on the output token from the SAM mask decoder.
264
+ """
265
+ B = backbone_features.size(0)
266
+ device = backbone_features.device
267
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
268
+ assert backbone_features.size(2) == self.sam_image_embedding_size
269
+ assert backbone_features.size(3) == self.sam_image_embedding_size
270
+
271
+ # a) Handle point prompts
272
+ if point_inputs is not None:
273
+ sam_point_coords = point_inputs["point_coords"]
274
+ sam_point_labels = point_inputs["point_labels"]
275
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
276
+ else:
277
+ # If no points are provide, pad with an empty point (with label -1)
278
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
279
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
280
+
281
+ # b) Handle mask prompts
282
+ if mask_inputs is not None:
283
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
284
+ # and feed it as a dense mask prompt into the SAM mask encoder
285
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
286
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
287
+ sam_mask_prompt = F.interpolate(
288
+ mask_inputs.float(),
289
+ size=self.sam_prompt_encoder.mask_input_size,
290
+ align_corners=False,
291
+ mode="bilinear",
292
+ antialias=True, # use antialias for downsampling
293
+ )
294
+ else:
295
+ sam_mask_prompt = mask_inputs
296
+ else:
297
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
298
+ # a learned `no_mask_embed` to indicate no mask input in this case).
299
+ sam_mask_prompt = None
300
+
301
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
302
+ points=(sam_point_coords, sam_point_labels),
303
+ boxes=None,
304
+ masks=sam_mask_prompt,
305
+ )
306
+ # Clone image_pe and the outputs of sam_prompt_encoder
307
+ # to enable compilation
308
+ sparse_embeddings = self._maybe_clone(sparse_embeddings)
309
+ dense_embeddings = self._maybe_clone(dense_embeddings)
310
+ image_pe = self._maybe_clone(self.sam_prompt_encoder.get_dense_pe())
311
+ with torch.profiler.record_function("sam_mask_decoder"):
312
+ (
313
+ low_res_multimasks,
314
+ ious,
315
+ sam_output_tokens,
316
+ object_score_logits,
317
+ ) = self.sam_mask_decoder(
318
+ image_embeddings=backbone_features,
319
+ image_pe=image_pe,
320
+ sparse_prompt_embeddings=sparse_embeddings,
321
+ dense_prompt_embeddings=dense_embeddings,
322
+ multimask_output=multimask_output,
323
+ repeat_image=False, # the image is already batched
324
+ high_res_features=high_res_features,
325
+ )
326
+ # Clone the output of sam_mask_decoder
327
+ # to enable compilation
328
+ low_res_multimasks = self._maybe_clone(low_res_multimasks)
329
+ ious = self._maybe_clone(ious)
330
+ sam_output_tokens = self._maybe_clone(sam_output_tokens)
331
+ object_score_logits = self._maybe_clone(object_score_logits)
332
+
333
+ if self.training and self.teacher_force_obj_scores_for_mem:
334
+ # we use gt to detect if there is an object or not to
335
+ # select no obj ptr and use an empty mask for spatial memory
336
+ is_obj_appearing = torch.any(gt_masks.float().flatten(1) > 0, dim=1)
337
+ is_obj_appearing = is_obj_appearing[..., None]
338
+ else:
339
+ is_obj_appearing = object_score_logits > 0
340
+
341
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
342
+ # consistent with the actual mask prediction
343
+ low_res_multimasks = torch.where(
344
+ is_obj_appearing[:, None, None],
345
+ low_res_multimasks,
346
+ NO_OBJ_SCORE,
347
+ )
348
+
349
+ # convert masks from possibly bfloat16 (or float16) to float32
350
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
351
+ low_res_multimasks = low_res_multimasks.float()
352
+ high_res_multimasks = F.interpolate(
353
+ low_res_multimasks,
354
+ size=(self.image_size, self.image_size),
355
+ mode="bilinear",
356
+ align_corners=False,
357
+ )
358
+
359
+ sam_output_token = sam_output_tokens[:, 0]
360
+ if multimask_output:
361
+ # take the best mask prediction (with the highest IoU estimation)
362
+ best_iou_inds = torch.argmax(ious, dim=-1)
363
+ batch_inds = torch.arange(B, device=device)
364
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
365
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
366
+ if sam_output_tokens.size(1) > 1:
367
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
368
+ else:
369
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
370
+
371
+ # Extract object pointer from the SAM output token (with occlusion handling)
372
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
373
+ lambda_is_obj_appearing = is_obj_appearing.float()
374
+
375
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
376
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
377
+
378
+ return (
379
+ low_res_multimasks,
380
+ high_res_multimasks,
381
+ ious,
382
+ low_res_masks,
383
+ high_res_masks,
384
+ obj_ptr,
385
+ object_score_logits,
386
+ )
387
+
388
+ def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
389
+ """
390
+ Directly turn binary `mask_inputs` into a output mask logits without using SAM.
391
+ (same input and output shapes as in _forward_sam_heads above).
392
+ """
393
+ # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
394
+ out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
395
+ mask_inputs_float = mask_inputs.float()
396
+ high_res_masks = mask_inputs_float * out_scale + out_bias
397
+ low_res_masks = F.interpolate(
398
+ high_res_masks,
399
+ size=(
400
+ high_res_masks.size(-2) // self.backbone_stride * 4,
401
+ high_res_masks.size(-1) // self.backbone_stride * 4,
402
+ ),
403
+ align_corners=False,
404
+ mode="bilinear",
405
+ antialias=True, # use antialias for downsampling
406
+ )
407
+ # a dummy IoU prediction of all 1's under mask input
408
+ ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
409
+ # produce an object pointer using the SAM decoder from the mask input
410
+ _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
411
+ backbone_features=backbone_features,
412
+ mask_inputs=self.mask_downsample(mask_inputs_float),
413
+ high_res_features=high_res_features,
414
+ gt_masks=mask_inputs,
415
+ )
416
+ # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
417
+ # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
418
+ # on the object_scores from the SAM decoder.
419
+ is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
420
+ is_obj_appearing = is_obj_appearing[..., None]
421
+ lambda_is_obj_appearing = is_obj_appearing.float()
422
+ object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
423
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
424
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
425
+
426
+ return (
427
+ low_res_masks,
428
+ high_res_masks,
429
+ ious,
430
+ low_res_masks,
431
+ high_res_masks,
432
+ obj_ptr,
433
+ object_score_logits,
434
+ )
435
+
436
+ def forward(self, input: BatchedDatapoint, is_inference=False):
437
+ raise NotImplementedError(
438
+ "Please use the corresponding methods in SAM3VideoPredictor for inference."
439
+ "See examples/sam3_dense_video_tracking.ipynb for an inference example."
440
+ )
441
+
442
+ def forward_image(self, img_batch):
443
+ """Get the image feature on the input batch."""
444
+ # This line is the only change from the parent class
445
+ # to use the SAM3 backbone instead of the SAM2 backbone.
446
+ backbone_out = self.backbone.forward_image(img_batch)["sam2_backbone_out"]
447
+ # precompute projected level 0 and level 1 features in SAM decoder
448
+ # to avoid running it again on every SAM click
449
+ backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(
450
+ backbone_out["backbone_fpn"][0]
451
+ )
452
+ backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(
453
+ backbone_out["backbone_fpn"][1]
454
+ )
455
+ # Clone to help torch.compile
456
+ for i in range(len(backbone_out["backbone_fpn"])):
457
+ backbone_out["backbone_fpn"][i] = self._maybe_clone(
458
+ backbone_out["backbone_fpn"][i]
459
+ )
460
+ backbone_out["vision_pos_enc"][i] = self._maybe_clone(
461
+ backbone_out["vision_pos_enc"][i]
462
+ )
463
+ return backbone_out
464
+
465
+ def _prepare_backbone_features(self, backbone_out):
466
+ """Prepare and flatten visual features (same as in MDETR_API model)."""
467
+ backbone_out = backbone_out.copy()
468
+ assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
469
+ assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
470
+
471
+ feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
472
+ vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
473
+
474
+ feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
475
+ # flatten NxCxHxW to HWxNxC
476
+ vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
477
+ vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
478
+
479
+ return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
480
+
481
+ def _prepare_backbone_features_per_frame(self, img_batch, img_ids):
482
+ """Compute the image backbone features on the fly for the given img_ids."""
483
+ # Only forward backbone on unique image ids to avoid repeatitive computation
484
+ # (if `img_ids` has only one element, it's already unique so we skip this step).
485
+ if img_ids.numel() > 1:
486
+ unique_img_ids, inv_ids = torch.unique(img_ids, return_inverse=True)
487
+ else:
488
+ unique_img_ids, inv_ids = img_ids, None
489
+
490
+ # Compute the image features on those unique image ids
491
+ image = img_batch[unique_img_ids]
492
+ backbone_out = self.forward_image(image)
493
+ (
494
+ _,
495
+ vision_feats,
496
+ vision_pos_embeds,
497
+ feat_sizes,
498
+ ) = self._prepare_backbone_features(backbone_out)
499
+ # Inverse-map image features for `unique_img_ids` to the final image features
500
+ # for the original input `img_ids`.
501
+ if inv_ids is not None:
502
+ image = image[inv_ids]
503
+ vision_feats = [x[:, inv_ids] for x in vision_feats]
504
+ vision_pos_embeds = [x[:, inv_ids] for x in vision_pos_embeds]
505
+
506
+ return image, vision_feats, vision_pos_embeds, feat_sizes
507
+
508
+ def cal_mem_score(self, object_score_logits, iou_score):
509
+ object_score_norm = torch.where(
510
+ object_score_logits > 0,
511
+ object_score_logits.sigmoid() * 2 - 1, ## rescale to [0, 1]
512
+ torch.zeros_like(object_score_logits),
513
+ )
514
+ score_per_frame = (object_score_norm * iou_score).mean()
515
+ return score_per_frame
516
+
517
+ def frame_filter(self, output_dict, track_in_reverse, frame_idx, num_frames, r):
518
+ if (frame_idx == 0 and not track_in_reverse) or (
519
+ frame_idx == num_frames - 1 and track_in_reverse
520
+ ):
521
+ return []
522
+
523
+ max_num = min(
524
+ num_frames, self.max_obj_ptrs_in_encoder
525
+ ) ## maximum number of pointer memory frames to consider
526
+
527
+ if not track_in_reverse:
528
+ start = frame_idx - 1
529
+ end = 0
530
+ step = -r
531
+ must_include = frame_idx - 1
532
+ else:
533
+ start = frame_idx + 1
534
+ end = num_frames
535
+ step = r
536
+ must_include = frame_idx + 1
537
+
538
+ valid_indices = []
539
+ for i in range(start, end, step):
540
+ if (
541
+ i not in output_dict["non_cond_frame_outputs"]
542
+ or "eff_iou_score" not in output_dict["non_cond_frame_outputs"][i]
543
+ ):
544
+ continue
545
+
546
+ score_per_frame = output_dict["non_cond_frame_outputs"][i]["eff_iou_score"]
547
+
548
+ if score_per_frame > self.mf_threshold: # threshold
549
+ valid_indices.insert(0, i)
550
+
551
+ if len(valid_indices) >= max_num - 1:
552
+ break
553
+
554
+ if must_include not in valid_indices:
555
+ valid_indices.append(must_include)
556
+
557
+ return valid_indices
558
+
559
+ def _prepare_memory_conditioned_features(
560
+ self,
561
+ frame_idx,
562
+ is_init_cond_frame,
563
+ current_vision_feats,
564
+ current_vision_pos_embeds,
565
+ feat_sizes,
566
+ output_dict,
567
+ num_frames,
568
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
569
+ use_prev_mem_frame=True,
570
+ ):
571
+ """Fuse the current frame's visual feature map with previous memory."""
572
+ B = current_vision_feats[-1].size(1) # batch size on this frame
573
+ C = self.hidden_dim
574
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
575
+ device = current_vision_feats[-1].device
576
+ # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
577
+ # In this case, we skip the fusion with any memory.
578
+ if self.num_maskmem == 0: # Disable memory and skip fusion
579
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
580
+ return pix_feat
581
+
582
+ num_obj_ptr_tokens = 0
583
+ tpos_sign_mul = -1 if track_in_reverse else 1
584
+ # Step 1: condition the visual features of the current frame on previous memories
585
+ if not is_init_cond_frame and use_prev_mem_frame:
586
+ # Retrieve the memories encoded with the maskmem backbone
587
+ to_cat_prompt, to_cat_prompt_mask, to_cat_prompt_pos_embed = [], [], []
588
+ # Add conditioning frames's output first (all cond frames have t_pos=0 for
589
+ # when getting temporal positional embedding below)
590
+ assert len(output_dict["cond_frame_outputs"]) > 0
591
+ # Select a maximum number of temporally closest cond frames for cross attention
592
+ cond_outputs = output_dict["cond_frame_outputs"]
593
+ selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
594
+ frame_idx,
595
+ cond_outputs,
596
+ self.max_cond_frames_in_attn,
597
+ keep_first_cond_frame=self.keep_first_cond_frame,
598
+ )
599
+ t_pos_and_prevs = [
600
+ ((frame_idx - t) * tpos_sign_mul, out, True)
601
+ for t, out in selected_cond_outputs.items()
602
+ ]
603
+ # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
604
+ # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
605
+ # We also allow taking the memory frame non-consecutively (with r>1), in which case
606
+ # we take (self.num_maskmem - 2) frames among every r-th frames plus the last frame.
607
+ r = 1 if self.training else self.memory_temporal_stride_for_eval
608
+
609
+ if self.use_memory_selection:
610
+ valid_indices = self.frame_filter(
611
+ output_dict, track_in_reverse, frame_idx, num_frames, r
612
+ )
613
+
614
+ for t_pos in range(1, self.num_maskmem):
615
+ t_rel = self.num_maskmem - t_pos # how many frames before current frame
616
+ if self.use_memory_selection:
617
+ if t_rel > len(valid_indices):
618
+ continue
619
+ prev_frame_idx = valid_indices[-t_rel]
620
+ else:
621
+ if t_rel == 1:
622
+ # for t_rel == 1, we take the last frame (regardless of r)
623
+ if not track_in_reverse:
624
+ # the frame immediately before this frame (i.e. frame_idx - 1)
625
+ prev_frame_idx = frame_idx - t_rel
626
+ else:
627
+ # the frame immediately after this frame (i.e. frame_idx + 1)
628
+ prev_frame_idx = frame_idx + t_rel
629
+ else:
630
+ # for t_rel >= 2, we take the memory frame from every r-th frames
631
+ if not track_in_reverse:
632
+ # first find the nearest frame among every r-th frames before this frame
633
+ # for r=1, this would be (frame_idx - 2)
634
+ prev_frame_idx = ((frame_idx - 2) // r) * r
635
+ # then seek further among every r-th frames
636
+ prev_frame_idx = prev_frame_idx - (t_rel - 2) * r
637
+ else:
638
+ # first find the nearest frame among every r-th frames after this frame
639
+ # for r=1, this would be (frame_idx + 2)
640
+ prev_frame_idx = -(-(frame_idx + 2) // r) * r
641
+ # then seek further among every r-th frames
642
+ prev_frame_idx = prev_frame_idx + (t_rel - 2) * r
643
+
644
+ out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
645
+ if out is None:
646
+ # If an unselected conditioning frame is among the last (self.num_maskmem - 1)
647
+ # frames, we still attend to it as if it's a non-conditioning frame.
648
+ out = unselected_cond_outputs.get(prev_frame_idx, None)
649
+ t_pos_and_prevs.append((t_pos, out, False))
650
+
651
+ for t_pos, prev, is_selected_cond_frame in t_pos_and_prevs:
652
+ if prev is None:
653
+ continue # skip padding frames
654
+ # "maskmem_features" might have been offloaded to CPU in demo use cases,
655
+ # so we load it back to GPU (it's a no-op if it's already on GPU).
656
+ feats = prev["maskmem_features"].cuda(non_blocking=True)
657
+ seq_len = feats.shape[-2] * feats.shape[-1]
658
+ to_cat_prompt.append(feats.flatten(2).permute(2, 0, 1))
659
+ to_cat_prompt_mask.append(
660
+ torch.zeros(B, seq_len, device=device, dtype=bool)
661
+ )
662
+ # Spatial positional encoding (it might have been offloaded to CPU in eval)
663
+ maskmem_enc = prev["maskmem_pos_enc"][-1].cuda()
664
+ maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
665
+
666
+ if (
667
+ is_selected_cond_frame
668
+ and getattr(self, "cond_frame_spatial_embedding", None) is not None
669
+ ):
670
+ # add a spatial embedding for the conditioning frame
671
+ maskmem_enc = maskmem_enc + self.cond_frame_spatial_embedding
672
+
673
+ # Temporal positional encoding
674
+ t = t_pos if not is_selected_cond_frame else 0
675
+ maskmem_enc = (
676
+ maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t - 1]
677
+ )
678
+ to_cat_prompt_pos_embed.append(maskmem_enc)
679
+
680
+ # Construct the list of past object pointers
681
+ # Optionally, select only a subset of spatial memory frames during trainining
682
+ if (
683
+ self.training
684
+ and self.prob_to_dropout_spatial_mem > 0
685
+ and self.rng.random() < self.prob_to_dropout_spatial_mem
686
+ ):
687
+ num_spatial_mem_keep = self.rng.integers(len(to_cat_prompt) + 1)
688
+ keep = self.rng.choice(
689
+ range(len(to_cat_prompt)), num_spatial_mem_keep, replace=False
690
+ ).tolist()
691
+ to_cat_prompt = [to_cat_prompt[i] for i in keep]
692
+ to_cat_prompt_mask = [to_cat_prompt_mask[i] for i in keep]
693
+ to_cat_prompt_pos_embed = [to_cat_prompt_pos_embed[i] for i in keep]
694
+
695
+ max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
696
+ # First add those object pointers from selected conditioning frames
697
+ # (optionally, only include object pointers in the past during evaluation)
698
+ if not self.training:
699
+ ptr_cond_outputs = {
700
+ t: out
701
+ for t, out in selected_cond_outputs.items()
702
+ if (t >= frame_idx if track_in_reverse else t <= frame_idx)
703
+ }
704
+ else:
705
+ ptr_cond_outputs = selected_cond_outputs
706
+ pos_and_ptrs = [
707
+ # Temporal pos encoding contains how far away each pointer is from current frame
708
+ (
709
+ (frame_idx - t) * tpos_sign_mul,
710
+ out["obj_ptr"],
711
+ True, # is_selected_cond_frame
712
+ )
713
+ for t, out in ptr_cond_outputs.items()
714
+ ]
715
+
716
+ # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
717
+ for t_diff in range(1, max_obj_ptrs_in_encoder):
718
+ if not self.use_memory_selection:
719
+ t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
720
+ if t < 0 or (num_frames is not None and t >= num_frames):
721
+ break
722
+ else:
723
+ if -t_diff <= -len(valid_indices):
724
+ break
725
+ t = valid_indices[-t_diff]
726
+
727
+ out = output_dict["non_cond_frame_outputs"].get(
728
+ t, unselected_cond_outputs.get(t, None)
729
+ )
730
+ if out is not None:
731
+ pos_and_ptrs.append((t_diff, out["obj_ptr"], False))
732
+
733
+ # If we have at least one object pointer, add them to the across attention
734
+ if len(pos_and_ptrs) > 0:
735
+ pos_list, ptrs_list, is_selected_cond_frame_list = zip(*pos_and_ptrs)
736
+ # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
737
+ obj_ptrs = torch.stack(ptrs_list, dim=0)
738
+ if getattr(self, "cond_frame_obj_ptr_embedding", None) is not None:
739
+ obj_ptrs = (
740
+ obj_ptrs
741
+ + self.cond_frame_obj_ptr_embedding
742
+ * torch.tensor(is_selected_cond_frame_list, device=device)[
743
+ ..., None, None
744
+ ].float()
745
+ )
746
+ # a temporal positional embedding based on how far each object pointer is from
747
+ # the current frame (sine embedding normalized by the max pointer num).
748
+ obj_pos = self._get_tpos_enc(
749
+ pos_list,
750
+ max_abs_pos=max_obj_ptrs_in_encoder,
751
+ device=device,
752
+ )
753
+ # expand to batch size
754
+ obj_pos = obj_pos.unsqueeze(1).expand(-1, B, -1)
755
+
756
+ if self.mem_dim < C:
757
+ # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
758
+ obj_ptrs = obj_ptrs.reshape(-1, B, C // self.mem_dim, self.mem_dim)
759
+ obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
760
+ obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
761
+ to_cat_prompt.append(obj_ptrs)
762
+ to_cat_prompt_mask.append(None) # "to_cat_prompt_mask" is not used
763
+ to_cat_prompt_pos_embed.append(obj_pos)
764
+ num_obj_ptr_tokens = obj_ptrs.shape[0]
765
+ else:
766
+ num_obj_ptr_tokens = 0
767
+ else:
768
+ # directly add no-mem embedding (instead of using the transformer encoder)
769
+ pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
770
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
771
+ return pix_feat_with_mem
772
+
773
+ # Use a dummy token on the first grame (to avoid emtpy memory input to tranformer encoder)
774
+ to_cat_prompt = [self.no_mem_embed.expand(1, B, self.mem_dim)]
775
+ to_cat_prompt_mask = [torch.zeros(B, 1, device=device, dtype=bool)]
776
+ to_cat_prompt_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
777
+
778
+ # Step 2: Concatenate the memories and forward through the transformer encoder
779
+ prompt = torch.cat(to_cat_prompt, dim=0)
780
+ prompt_mask = None # For now, we always masks are zeros anyways
781
+ prompt_pos_embed = torch.cat(to_cat_prompt_pos_embed, dim=0)
782
+ encoder_out = self.transformer.encoder(
783
+ src=current_vision_feats,
784
+ src_key_padding_mask=[None],
785
+ src_pos=current_vision_pos_embeds,
786
+ prompt=prompt,
787
+ prompt_pos=prompt_pos_embed,
788
+ prompt_key_padding_mask=prompt_mask,
789
+ feat_sizes=feat_sizes,
790
+ num_obj_ptr_tokens=num_obj_ptr_tokens,
791
+ )
792
+ # reshape the output (HW)BC => BCHW
793
+ pix_feat_with_mem = encoder_out["memory"].permute(1, 2, 0).view(B, C, H, W)
794
+ return pix_feat_with_mem
795
+
796
+ def _encode_new_memory(
797
+ self,
798
+ image,
799
+ current_vision_feats,
800
+ feat_sizes,
801
+ pred_masks_high_res,
802
+ object_score_logits,
803
+ is_mask_from_pts,
804
+ output_dict=None,
805
+ is_init_cond_frame=False,
806
+ ):
807
+ """Encode the current image and its prediction into a memory feature."""
808
+ B = current_vision_feats[-1].size(1) # batch size on this frame
809
+ C = self.hidden_dim
810
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
811
+ # top-level feature, (HW)BC => BCHW
812
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
813
+ if self.non_overlap_masks_for_mem_enc and not self.training:
814
+ # optionally, apply non-overlapping constraints to the masks (it's applied
815
+ # in the batch dimension and should only be used during eval, where all
816
+ # the objects come from the same video under batch size 1).
817
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
818
+ pred_masks_high_res
819
+ )
820
+ # scale the raw mask logits with a temperature before applying sigmoid
821
+ if is_mask_from_pts and not self.training:
822
+ mask_for_mem = (pred_masks_high_res > 0).float()
823
+ else:
824
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
825
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
826
+ # apply scale and bias terms to the sigmoid probabilities
827
+ if self.sigmoid_scale_for_mem_enc != 1.0:
828
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
829
+ if self.sigmoid_bias_for_mem_enc != 0.0:
830
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
831
+
832
+ if isinstance(self.maskmem_backbone, SimpleMaskEncoder):
833
+ pix_feat = pix_feat.view_as(pix_feat)
834
+ maskmem_out = self.maskmem_backbone(
835
+ pix_feat, mask_for_mem, skip_mask_sigmoid=True
836
+ )
837
+ else:
838
+ maskmem_out = self.maskmem_backbone(image, pix_feat, mask_for_mem)
839
+ # Clone the feats and pos_enc to enable compilation
840
+ maskmem_features = self._maybe_clone(maskmem_out["vision_features"])
841
+ maskmem_pos_enc = [self._maybe_clone(m) for m in maskmem_out["vision_pos_enc"]]
842
+ # add a no-object embedding to the spatial memory to indicate that the frame
843
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
844
+ is_obj_appearing = (object_score_logits > 0).float()
845
+ maskmem_features += (
846
+ 1 - is_obj_appearing[..., None, None]
847
+ ) * self.no_obj_embed_spatial[..., None, None].expand(*maskmem_features.shape)
848
+
849
+ return maskmem_features, maskmem_pos_enc
850
+
851
+ def forward_tracking(self, backbone_out, input, return_dict=False):
852
+ """Forward video tracking on each frame (and sample correction clicks)."""
853
+ img_feats_already_computed = backbone_out["backbone_fpn"] is not None
854
+ if img_feats_already_computed:
855
+ # Prepare the backbone features
856
+ # - vision_feats and vision_pos_embeds are in (HW)BC format
857
+ (
858
+ _,
859
+ vision_feats,
860
+ vision_pos_embeds,
861
+ feat_sizes,
862
+ ) = self._prepare_backbone_features(backbone_out)
863
+
864
+ # Starting the stage loop
865
+ num_frames = backbone_out["num_frames"]
866
+ init_cond_frames = backbone_out["init_cond_frames"]
867
+ frames_to_add_correction_pt = backbone_out["frames_to_add_correction_pt"]
868
+ # first process all the initial conditioning frames to encode them as memory,
869
+ # and then conditioning on them to track the remaining frames
870
+ processing_order = init_cond_frames + backbone_out["frames_not_in_init_cond"]
871
+ output_dict = {
872
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
873
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
874
+ }
875
+ for stage_id in processing_order:
876
+ # Get the image features for the current frames
877
+ img_ids = input.find_inputs[stage_id].img_ids
878
+ if img_feats_already_computed:
879
+ # Retrieve image features according to img_ids (if they are already computed).
880
+ current_image = input.img_batch[img_ids]
881
+ current_vision_feats = [x[:, img_ids] for x in vision_feats]
882
+ current_vision_pos_embeds = [x[:, img_ids] for x in vision_pos_embeds]
883
+ else:
884
+ # Otherwise, compute the image features on the fly for the given img_ids
885
+ # (this might be used for evaluation on long videos to avoid backbone OOM).
886
+ (
887
+ current_image,
888
+ current_vision_feats,
889
+ current_vision_pos_embeds,
890
+ feat_sizes,
891
+ ) = self._prepare_backbone_features_per_frame(input.img_batch, img_ids)
892
+ # Get output masks based on this frame's prompts and previous memory
893
+ current_out = self.track_step(
894
+ frame_idx=stage_id,
895
+ is_init_cond_frame=stage_id in init_cond_frames,
896
+ current_vision_feats=current_vision_feats,
897
+ current_vision_pos_embeds=current_vision_pos_embeds,
898
+ feat_sizes=feat_sizes,
899
+ image=current_image,
900
+ point_inputs=backbone_out["point_inputs_per_frame"].get(stage_id, None),
901
+ mask_inputs=backbone_out["mask_inputs_per_frame"].get(stage_id, None),
902
+ output_dict=output_dict,
903
+ num_frames=num_frames,
904
+ )
905
+ # Append the output, depending on whether it's a conditioning frame
906
+ add_output_as_cond_frame = stage_id in init_cond_frames or (
907
+ self.add_all_frames_to_correct_as_cond
908
+ and stage_id in frames_to_add_correction_pt
909
+ )
910
+ if add_output_as_cond_frame:
911
+ output_dict["cond_frame_outputs"][stage_id] = current_out
912
+ else:
913
+ output_dict["non_cond_frame_outputs"][stage_id] = current_out
914
+
915
+ if return_dict:
916
+ return output_dict
917
+ # turn `output_dict` into a list for loss function
918
+ all_frame_outputs = {}
919
+ all_frame_outputs.update(output_dict["cond_frame_outputs"])
920
+ all_frame_outputs.update(output_dict["non_cond_frame_outputs"])
921
+ all_frame_outputs = [all_frame_outputs[t] for t in range(num_frames)]
922
+ # Make DDP happy with activation checkpointing by removing unused keys
923
+ all_frame_outputs = [
924
+ {k: v for k, v in d.items() if k != "obj_ptr"} for d in all_frame_outputs
925
+ ]
926
+
927
+ return all_frame_outputs
928
+
929
+ def track_step(
930
+ self,
931
+ frame_idx,
932
+ is_init_cond_frame,
933
+ current_vision_feats,
934
+ current_vision_pos_embeds,
935
+ feat_sizes,
936
+ image,
937
+ point_inputs,
938
+ mask_inputs,
939
+ output_dict,
940
+ num_frames,
941
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
942
+ # Whether to run the memory encoder on the predicted masks. Sometimes we might want
943
+ # to skip the memory encoder with `run_mem_encoder=False`. For example,
944
+ # in demo we might call `track_step` multiple times for each user click,
945
+ # and only encode the memory when the user finalizes their clicks. And in ablation
946
+ # settings like SAM training on static images, we don't need the memory encoder.
947
+ run_mem_encoder=True,
948
+ # The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
949
+ prev_sam_mask_logits=None,
950
+ use_prev_mem_frame=True,
951
+ ):
952
+ current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
953
+ # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
954
+ if len(current_vision_feats) > 1:
955
+ high_res_features = [
956
+ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
957
+ for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
958
+ ]
959
+ else:
960
+ high_res_features = None
961
+ if mask_inputs is not None:
962
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
963
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0)
964
+ pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
965
+ sam_outputs = self._use_mask_as_output(
966
+ pix_feat, high_res_features, mask_inputs
967
+ )
968
+ else:
969
+ # fused the visual feature with previous memory features in the memory bank
970
+ pix_feat_with_mem = self._prepare_memory_conditioned_features(
971
+ frame_idx=frame_idx,
972
+ is_init_cond_frame=is_init_cond_frame,
973
+ current_vision_feats=current_vision_feats[-1:],
974
+ current_vision_pos_embeds=current_vision_pos_embeds[-1:],
975
+ feat_sizes=feat_sizes[-1:],
976
+ output_dict=output_dict,
977
+ num_frames=num_frames,
978
+ track_in_reverse=track_in_reverse,
979
+ use_prev_mem_frame=use_prev_mem_frame,
980
+ )
981
+ # apply SAM-style segmentation head
982
+ # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
983
+ # e.g. in demo where such logits come from earlier interaction instead of correction sampling
984
+ # (in this case, the SAM mask decoder should have `self.iter_use_prev_mask_pred=True`, and
985
+ # any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
986
+ if prev_sam_mask_logits is not None:
987
+ assert self.iter_use_prev_mask_pred
988
+ assert point_inputs is not None and mask_inputs is None
989
+ mask_inputs = prev_sam_mask_logits
990
+ multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
991
+ sam_outputs = self._forward_sam_heads(
992
+ backbone_features=pix_feat_with_mem,
993
+ point_inputs=point_inputs,
994
+ mask_inputs=mask_inputs,
995
+ high_res_features=high_res_features,
996
+ multimask_output=multimask_output,
997
+ )
998
+ (
999
+ _,
1000
+ high_res_multimasks,
1001
+ ious,
1002
+ low_res_masks,
1003
+ high_res_masks,
1004
+ obj_ptr,
1005
+ object_score_logits,
1006
+ ) = sam_outputs
1007
+ # Use the final prediction (after all correction steps for output and eval)
1008
+ current_out["pred_masks"] = low_res_masks
1009
+ current_out["pred_masks_high_res"] = high_res_masks
1010
+ current_out["obj_ptr"] = obj_ptr
1011
+ if self.use_memory_selection:
1012
+ current_out["object_score_logits"] = object_score_logits
1013
+ iou_score = ious.max(-1)[0]
1014
+ current_out["iou_score"] = iou_score
1015
+ current_out["eff_iou_score"] = self.cal_mem_score(
1016
+ object_score_logits, iou_score
1017
+ )
1018
+ if not self.training:
1019
+ # Only add this in inference (to avoid unused param in activation checkpointing;
1020
+ # it's mainly used in the demo to encode spatial memories w/ consolidated masks)
1021
+ current_out["object_score_logits"] = object_score_logits
1022
+
1023
+ # Finally run the memory encoder on the predicted mask to encode
1024
+ # it into a new memory feature (that can be used in future frames)
1025
+ # (note that `self.num_maskmem == 0` is primarily used for reproducing SAM on
1026
+ # images, in which case we'll just skip memory encoder to save compute).
1027
+ if run_mem_encoder and self.num_maskmem > 0:
1028
+ high_res_masks_for_mem_enc = high_res_masks
1029
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
1030
+ image=image,
1031
+ current_vision_feats=current_vision_feats,
1032
+ feat_sizes=feat_sizes,
1033
+ pred_masks_high_res=high_res_masks_for_mem_enc,
1034
+ object_score_logits=object_score_logits,
1035
+ is_mask_from_pts=(point_inputs is not None),
1036
+ output_dict=output_dict,
1037
+ is_init_cond_frame=is_init_cond_frame,
1038
+ )
1039
+ current_out["maskmem_features"] = maskmem_features
1040
+ current_out["maskmem_pos_enc"] = maskmem_pos_enc
1041
+ else:
1042
+ current_out["maskmem_features"] = None
1043
+ current_out["maskmem_pos_enc"] = None
1044
+
1045
+ # Optionally, offload the outputs to CPU memory during evaluation to avoid
1046
+ # GPU OOM on very long videos or very large resolution or too many objects
1047
+ if self.offload_output_to_cpu_for_eval and not self.training:
1048
+ # Here we only keep those keys needed for evaluation to get a compact output
1049
+ trimmed_out = {
1050
+ "pred_masks": current_out["pred_masks"].cpu(),
1051
+ "pred_masks_high_res": current_out["pred_masks_high_res"].cpu(),
1052
+ # other items for evaluation (these are small tensors so we keep them on GPU)
1053
+ "obj_ptr": current_out["obj_ptr"],
1054
+ "object_score_logits": current_out["object_score_logits"],
1055
+ }
1056
+ if run_mem_encoder and self.num_maskmem > 0:
1057
+ trimmed_out["maskmem_features"] = maskmem_features.cpu()
1058
+ trimmed_out["maskmem_pos_enc"] = [x.cpu() for x in maskmem_pos_enc]
1059
+ if self.use_memory_selection:
1060
+ trimmed_out["iou_score"] = current_out["iou_score"].cpu()
1061
+ trimmed_out["eff_iou_score"] = current_out["eff_iou_score"].cpu()
1062
+ current_out = trimmed_out
1063
+
1064
+ # Optionally, trim the output of past non-conditioning frame (r * num_maskmem frames
1065
+ # before the current frame) during evaluation. This is intended to save GPU or CPU
1066
+ # memory for semi-supervised VOS eval, where only the first frame receives prompts.
1067
+ def _trim_past_out(past_out, current_out):
1068
+ if past_out is None:
1069
+ return None
1070
+ return {
1071
+ "pred_masks": past_out["pred_masks"],
1072
+ "obj_ptr": past_out["obj_ptr"],
1073
+ "object_score_logits": past_out["object_score_logits"],
1074
+ }
1075
+
1076
+ if self.trim_past_non_cond_mem_for_eval and not self.training:
1077
+ r = self.memory_temporal_stride_for_eval
1078
+ past_frame_idx = frame_idx - r * self.num_maskmem
1079
+ past_out = output_dict["non_cond_frame_outputs"].get(past_frame_idx, None)
1080
+
1081
+ if past_out is not None:
1082
+ print(past_out.get("eff_iou_score", 0))
1083
+ if (
1084
+ self.use_memory_selection
1085
+ and past_out.get("eff_iou_score", 0) < self.mf_threshold
1086
+ ) or not self.use_memory_selection:
1087
+ output_dict["non_cond_frame_outputs"][past_frame_idx] = (
1088
+ _trim_past_out(past_out, current_out)
1089
+ )
1090
+
1091
+ if (
1092
+ self.use_memory_selection and not self.offload_output_to_cpu_for_eval
1093
+ ): ## design for memory selection, trim too old frames to save memory
1094
+ far_old_frame_idx = frame_idx - 20 * self.max_obj_ptrs_in_encoder
1095
+ past_out = output_dict["non_cond_frame_outputs"].get(
1096
+ far_old_frame_idx, None
1097
+ )
1098
+ if past_out is not None:
1099
+ output_dict["non_cond_frame_outputs"][far_old_frame_idx] = (
1100
+ _trim_past_out(past_out, current_out)
1101
+ )
1102
+
1103
+ return current_out
1104
+
1105
+ def _use_multimask(self, is_init_cond_frame, point_inputs):
1106
+ """Whether to use multimask output in the SAM head."""
1107
+ num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
1108
+ multimask_output = (
1109
+ self.multimask_output_in_sam
1110
+ and (is_init_cond_frame or self.multimask_output_for_tracking)
1111
+ and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
1112
+ )
1113
+ return multimask_output
1114
+
1115
+ def _apply_non_overlapping_constraints(self, pred_masks):
1116
+ """
1117
+ Apply non-overlapping constraints to the object scores in pred_masks. Here we
1118
+ keep only the highest scoring object at each spatial location in pred_masks.
1119
+ """
1120
+ batch_size = pred_masks.size(0)
1121
+ if batch_size == 1:
1122
+ return pred_masks
1123
+
1124
+ device = pred_masks.device
1125
+ # "max_obj_inds": object index of the object with the highest score at each location
1126
+ max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
1127
+ # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
1128
+ batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
1129
+ keep = max_obj_inds == batch_obj_inds
1130
+ # suppress overlapping regions' scores below -10.0 so that the foreground regions
1131
+ # don't overlap (here sigmoid(-10.0)=4.5398e-05)
1132
+ pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
1133
+ return pred_masks
1134
+
1135
+ def _compile_all_components(self):
1136
+ """Compile all model components for faster inference."""
1137
+ # a larger cache size to hold varying number of shapes for torch.compile
1138
+ # see https://github.com/pytorch/pytorch/blob/v2.5.1/torch/_dynamo/config.py#L42-L49
1139
+ torch._dynamo.config.cache_size_limit = 64
1140
+ torch._dynamo.config.accumulated_cache_size_limit = 2048
1141
+ from sam3.perflib.compile import compile_wrapper
1142
+
1143
+ logging.info("Compiling all components. First time may be very slow.")
1144
+
1145
+ self.maskmem_backbone.forward = compile_wrapper(
1146
+ self.maskmem_backbone.forward,
1147
+ mode="max-autotune",
1148
+ fullgraph=True,
1149
+ dynamic=False,
1150
+ )
1151
+ self.transformer.encoder.forward = compile_wrapper(
1152
+ self.transformer.encoder.forward,
1153
+ mode="max-autotune",
1154
+ fullgraph=True,
1155
+ dynamic=True, # Num. of memories varies
1156
+ )
1157
+ # We disable compilation of sam_prompt_encoder as it sometimes gives a large accuracy regression,
1158
+ # especially when sam_mask_prompt (previous mask logits) is not None
1159
+ # self.sam_prompt_encoder.forward = torch.compile(
1160
+ # self.sam_prompt_encoder.forward,
1161
+ # mode="max-autotune",
1162
+ # fullgraph=True,
1163
+ # dynamic=False, # Accuracy regression on True
1164
+ # )
1165
+ self.sam_mask_decoder.forward = compile_wrapper(
1166
+ self.sam_mask_decoder.forward,
1167
+ mode="max-autotune",
1168
+ fullgraph=True,
1169
+ dynamic=False, # Accuracy regression on True
1170
+ )
1171
+
1172
+ def _maybe_clone(self, x):
1173
+ """Clone a tensor if and only if `self.compile_all_components` is True."""
1174
+ return x.clone() if self.compile_all_components else x
1175
+
1176
+
1177
+ def concat_points(old_point_inputs, new_points, new_labels):
1178
+ """Add new points and labels to previous point inputs (add at the end)."""
1179
+ if old_point_inputs is None:
1180
+ points, labels = new_points, new_labels
1181
+ else:
1182
+ points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1)
1183
+ labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1)
1184
+
1185
+ return {"point_coords": points, "point_labels": labels}
third_party/GraspGen/sam3/sam3/model/sam3_tracker_utils.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from numpy.typing import NDArray
9
+ from sam3.model.edt import edt_triton
10
+
11
+
12
+ def sample_box_points(
13
+ masks: torch.Tensor,
14
+ noise: float = 0.1, # SAM default
15
+ noise_bound: int = 20, # SAM default
16
+ top_left_label: int = 2,
17
+ bottom_right_label: int = 3,
18
+ ) -> tuple[NDArray, NDArray]:
19
+ """
20
+ Sample a noised version of the top left and bottom right corners of a given `bbox`
21
+
22
+ Inputs:
23
+ - masks: [B, 1, H, W] tensor
24
+ - noise: noise as a fraction of box width and height, dtype=float
25
+ - noise_bound: maximum amount of noise (in pure pixels), dtype=int
26
+
27
+ Returns:
28
+ - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float
29
+ - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32
30
+ """
31
+ device = masks.device
32
+ box_coords = mask_to_box(masks)
33
+ B, _, H, W = masks.shape
34
+ box_labels = torch.tensor(
35
+ [top_left_label, bottom_right_label], dtype=torch.int, device=device
36
+ ).repeat(B)
37
+ if noise > 0.0:
38
+ if not isinstance(noise_bound, torch.Tensor):
39
+ noise_bound = torch.tensor(noise_bound, device=device)
40
+ bbox_w = box_coords[..., 2] - box_coords[..., 0]
41
+ bbox_h = box_coords[..., 3] - box_coords[..., 1]
42
+ max_dx = torch.min(bbox_w * noise, noise_bound)
43
+ max_dy = torch.min(bbox_h * noise, noise_bound)
44
+ box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1
45
+ box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
46
+
47
+ box_coords = box_coords + box_noise
48
+ img_bounds = (
49
+ torch.tensor([W, H, W, H], device=device) - 1
50
+ ) # uncentered pixel coords
51
+ box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
52
+
53
+ box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
54
+ box_labels = box_labels.reshape(-1, 2)
55
+ return box_coords, box_labels
56
+
57
+
58
+ def mask_to_box(masks: torch.Tensor):
59
+ """
60
+ compute bounding box given an input mask
61
+
62
+ Inputs:
63
+ - masks: [B, 1, H, W] tensor
64
+
65
+ Returns:
66
+ - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
67
+ """
68
+ B, _, h, w = masks.shape
69
+ device = masks.device
70
+ mask_area = masks.sum(dim=(-1, -2))
71
+ xs = torch.arange(w, device=device, dtype=torch.int32)
72
+ ys = torch.arange(h, device=device, dtype=torch.int32)
73
+ grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy")
74
+ grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w)
75
+ grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w)
76
+ min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1)
77
+ max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1)
78
+ min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1)
79
+ max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1)
80
+ bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1)
81
+ bbox_coords = torch.where(
82
+ mask_area[..., None] > 0, bbox_coords, torch.zeros_like(bbox_coords)
83
+ )
84
+ return bbox_coords
85
+
86
+
87
+ def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):
88
+ """
89
+ Sample `num_pt` random points (along with their labels) independently from the error regions.
90
+
91
+ Inputs:
92
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
93
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
94
+ - num_pt: int, number of points to sample independently for each of the B error maps
95
+
96
+ Outputs:
97
+ - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
98
+ - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means
99
+ negative clicks
100
+ """
101
+ if pred_masks is None: # if pred_masks is not provided, treat it as empty
102
+ pred_masks = torch.zeros_like(gt_masks)
103
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
104
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
105
+ assert num_pt >= 0
106
+
107
+ B, _, H_im, W_im = gt_masks.shape
108
+ device = gt_masks.device
109
+
110
+ # false positive region, a new point sampled in this region should have
111
+ # negative label to correct the FP error
112
+ fp_masks = ~gt_masks & pred_masks
113
+ # false negative region, a new point sampled in this region should have
114
+ # positive label to correct the FN error
115
+ fn_masks = gt_masks & ~pred_masks
116
+ # whether the prediction completely match the ground-truth on each mask
117
+ all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2)
118
+ all_correct = all_correct[..., None, None]
119
+
120
+ # channel 0 is FP map, while channel 1 is FN map
121
+ pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device)
122
+ # sample a negative new click from FP region or a positive new click
123
+ # from FN region, depend on where the maximum falls,
124
+ # and in case the predictions are all correct (no FP or FN), we just
125
+ # sample a negative click from the background region
126
+ pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks)
127
+ pts_noise[..., 1] *= fn_masks
128
+ pts_idx = pts_noise.flatten(2).argmax(dim=2)
129
+ labels = (pts_idx % 2).to(torch.int32)
130
+ pts_idx = pts_idx // 2
131
+ pts_x = pts_idx % W_im
132
+ pts_y = pts_idx // W_im
133
+ points = torch.stack([pts_x, pts_y], dim=2).to(torch.float)
134
+ return points, labels
135
+
136
+
137
+ def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):
138
+ """
139
+ Sample 1 random point (along with its label) from the center of each error region,
140
+ that is, the point with the largest distance to the boundary of each error region.
141
+ This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
142
+
143
+ Inputs:
144
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
145
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
146
+ - padding: if True, pad with boundary of 1 px for distance transform
147
+
148
+ Outputs:
149
+ - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
150
+ - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
151
+ """
152
+ if pred_masks is None:
153
+ pred_masks = torch.zeros_like(gt_masks)
154
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
155
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
156
+
157
+ B, _, H, W = gt_masks.shape
158
+
159
+ # false positive region, a new point sampled in this region should have
160
+ # negative label to correct the FP error
161
+ fp_masks = (~gt_masks & pred_masks).squeeze(1)
162
+ # false negative region, a new point sampled in this region should have
163
+ # positive label to correct the FN error
164
+ fn_masks = (gt_masks & ~pred_masks).squeeze(1)
165
+
166
+ if padding:
167
+ padded_fp_masks = torch.zeros(
168
+ B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device
169
+ )
170
+ padded_fp_masks[:, 1 : H + 1, 1 : W + 1] = fp_masks
171
+ padded_fn_masks = torch.zeros(
172
+ B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device
173
+ )
174
+ padded_fn_masks[:, 1 : H + 1, 1 : W + 1] = fn_masks
175
+ else:
176
+ padded_fp_masks = fp_masks
177
+ padded_fn_masks = fn_masks
178
+
179
+ fn_mask_dt = edt_triton(padded_fn_masks)
180
+ fp_mask_dt = edt_triton(padded_fp_masks)
181
+ if padding:
182
+ fn_mask_dt = fn_mask_dt[:, 1:-1, 1:-1]
183
+ fp_mask_dt = fp_mask_dt[:, 1:-1, 1:-1]
184
+
185
+ fn_max, fn_argmax = fn_mask_dt.reshape(B, -1).max(dim=-1)
186
+ fp_max, fp_argmax = fp_mask_dt.reshape(B, -1).max(dim=-1)
187
+ is_positive = fn_max > fp_max
188
+ chosen = torch.where(is_positive, fn_argmax, fp_argmax)
189
+ points_x = chosen % W
190
+ points_y = chosen // W
191
+
192
+ labels = is_positive.long()
193
+ points = torch.stack([points_x, points_y], -1)
194
+ return points.unsqueeze(1), labels.unsqueeze(1)
195
+
196
+
197
+ def sample_one_point_from_error_center_slow(gt_masks, pred_masks, padding=True):
198
+ """
199
+ Sample 1 random point (along with its label) from the center of each error region,
200
+ that is, the point with the largest distance to the boundary of each error region.
201
+ This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
202
+
203
+ Inputs:
204
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
205
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
206
+ - padding: if True, pad with boundary of 1 px for distance transform
207
+
208
+ Outputs:
209
+ - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
210
+ - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
211
+ """
212
+ import cv2 # delay OpenCV import to avoid unnecessary dependency
213
+
214
+ if pred_masks is None:
215
+ pred_masks = torch.zeros_like(gt_masks)
216
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
217
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
218
+
219
+ B, _, _, W_im = gt_masks.shape
220
+ device = gt_masks.device
221
+
222
+ # false positive region, a new point sampled in this region should have
223
+ # negative label to correct the FP error
224
+ fp_masks = ~gt_masks & pred_masks
225
+ # false negative region, a new point sampled in this region should have
226
+ # positive label to correct the FN error
227
+ fn_masks = gt_masks & ~pred_masks
228
+
229
+ fp_masks = fp_masks.cpu().numpy()
230
+ fn_masks = fn_masks.cpu().numpy()
231
+ points = torch.zeros(B, 1, 2, dtype=torch.float)
232
+ labels = torch.ones(B, 1, dtype=torch.int32)
233
+ for b in range(B):
234
+ fn_mask = fn_masks[b, 0]
235
+ fp_mask = fp_masks[b, 0]
236
+ if padding:
237
+ fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant")
238
+ fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant")
239
+ # compute the distance of each point in FN/FP region to its boundary
240
+ fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0)
241
+ fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0)
242
+ if padding:
243
+ fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
244
+ fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
245
+
246
+ # take the point in FN/FP region with the largest distance to its boundary
247
+ fn_mask_dt_flat = fn_mask_dt.reshape(-1)
248
+ fp_mask_dt_flat = fp_mask_dt.reshape(-1)
249
+ fn_argmax = np.argmax(fn_mask_dt_flat)
250
+ fp_argmax = np.argmax(fp_mask_dt_flat)
251
+ is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax]
252
+ pt_idx = fn_argmax if is_positive else fp_argmax
253
+ points[b, 0, 0] = pt_idx % W_im # x
254
+ points[b, 0, 1] = pt_idx // W_im # y
255
+ labels[b, 0] = int(is_positive)
256
+
257
+ points = points.to(device)
258
+ labels = labels.to(device)
259
+ return points, labels
260
+
261
+
262
+ def get_next_point(gt_masks, pred_masks, method):
263
+ if method == "uniform":
264
+ return sample_random_points_from_errors(gt_masks, pred_masks)
265
+ elif method == "center":
266
+ return sample_one_point_from_error_center(gt_masks, pred_masks)
267
+ else:
268
+ raise ValueError(f"unknown sampling method {method}")
269
+
270
+
271
+ def select_closest_cond_frames(
272
+ frame_idx, cond_frame_outputs, max_cond_frame_num, keep_first_cond_frame=False
273
+ ):
274
+ """
275
+ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
276
+ that are temporally closest to the current frame at `frame_idx`. Here, we take
277
+ - a) the closest conditioning frame before `frame_idx` (if any);
278
+ - b) the closest conditioning frame after `frame_idx` (if any);
279
+ - c) any other temporally closest conditioning frames until reaching a total
280
+ of `max_cond_frame_num` conditioning frames.
281
+
282
+ Outputs:
283
+ - selected_outputs: selected items (keys & values) from `cond_frame_outputs`.
284
+ - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`.
285
+ """
286
+ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
287
+ selected_outputs = cond_frame_outputs
288
+ unselected_outputs = {}
289
+ else:
290
+ assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
291
+ selected_outputs = {}
292
+ if keep_first_cond_frame:
293
+ idx_first = min(
294
+ (t for t in cond_frame_outputs if t < frame_idx), default=None
295
+ )
296
+ if idx_first is None:
297
+ # Maybe we are tracking in reverse
298
+ idx_first = max(
299
+ (t for t in cond_frame_outputs if t > frame_idx), default=None
300
+ )
301
+ if idx_first is not None:
302
+ selected_outputs[idx_first] = cond_frame_outputs[idx_first]
303
+ # the closest conditioning frame before `frame_idx` (if any)
304
+ idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
305
+ if idx_before is not None:
306
+ selected_outputs[idx_before] = cond_frame_outputs[idx_before]
307
+
308
+ # the closest conditioning frame after `frame_idx` (if any)
309
+ idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
310
+ if idx_after is not None:
311
+ selected_outputs[idx_after] = cond_frame_outputs[idx_after]
312
+
313
+ # add other temporally closest conditioning frames until reaching a total
314
+ # of `max_cond_frame_num` conditioning frames.
315
+ num_remain = max_cond_frame_num - len(selected_outputs)
316
+ inds_remain = sorted(
317
+ (t for t in cond_frame_outputs if t not in selected_outputs),
318
+ key=lambda x: abs(x - frame_idx),
319
+ )[:num_remain]
320
+ selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
321
+ unselected_outputs = {
322
+ t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs
323
+ }
324
+
325
+ return selected_outputs, unselected_outputs
326
+
327
+
328
+ def get_1d_sine_pe(pos_inds, dim, temperature=10000):
329
+ """
330
+ Get 1D sine positional embedding as in the original Transformer paper.
331
+ """
332
+ pe_dim = dim // 2
333
+ dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
334
+ dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
335
+
336
+ pos_embed = pos_inds.unsqueeze(-1) / dim_t
337
+ pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
338
+ return pos_embed
339
+
340
+
341
+ def get_best_gt_match_from_multimasks(pred_multimasks, gt_masks, pred_scores=None):
342
+ """
343
+ Get the mask with the best match to GT masks (based on IoU) from pred_multimasks.
344
+ Optionally, use `pred_scores` to break ties in case all IoUs are zeros.
345
+ """
346
+ assert pred_multimasks.ndim == 4 and gt_masks.ndim == 4
347
+ if pred_multimasks.size(1) == 1:
348
+ return pred_multimasks # only a single mask channel, nothing to select
349
+
350
+ pred_multimasks_binary = pred_multimasks > 0
351
+ area_i = torch.sum(pred_multimasks_binary & gt_masks, dim=(2, 3)).float()
352
+ area_u = torch.sum(pred_multimasks_binary | gt_masks, dim=(2, 3)).float()
353
+ ious = area_i / torch.clamp(area_u, min=1.0)
354
+
355
+ # In case all IoUs are zeros (e.g. because the GT mask is empty), use pred_scores
356
+ # to break ties and select the best mask
357
+ if pred_scores is not None:
358
+ has_nonzero_ious = torch.any(ious > 0).expand_as(ious)
359
+ scores = torch.where(has_nonzero_ious, ious, pred_scores)
360
+ else:
361
+ scores = ious
362
+
363
+ # Finally, take the best mask prediction (with the highest score)
364
+ best_scores_inds = torch.argmax(scores, dim=-1)
365
+ batch_inds = torch.arange(scores.size(0), device=scores.device)
366
+ best_pred_mask = pred_multimasks[batch_inds, best_scores_inds].unsqueeze(1)
367
+ return best_pred_mask
368
+
369
+
370
+ def fill_holes_in_mask_scores(mask, max_area, fill_holes=True, remove_sprinkles=True):
371
+ """
372
+ A post processor to fill small holes in mask scores with area under `max_area`.
373
+ Holes are those small connected components in either background or foreground.
374
+
375
+ Note that it relies on the "cc_torch" package to find connected components fast. You can
376
+ install it via the following command (`TORCH_CUDA_ARCH_LIST=8.0` is for A100 GPUs):
377
+ ```
378
+ pip uninstall -y cc_torch; TORCH_CUDA_ARCH_LIST=8.0 9.0 pip install git+https://github.com/ronghanghu/cc_torch
379
+ ```
380
+ Otherwise, it will fallback to a slightly slower triton implementation, or skimage if the tensor is on cpu
381
+ """
382
+
383
+ if max_area <= 0:
384
+ return mask # nothing to fill in this case
385
+
386
+ if fill_holes:
387
+ # We remove small connected components in background by changing them to foreground
388
+ # with a small positive mask score (0.1).
389
+ mask_bg = mask <= 0
390
+ bg_area_thresh = max_area
391
+ _, areas_bg = _get_connected_components_with_padding(mask_bg)
392
+ small_components_bg = mask_bg & (areas_bg <= bg_area_thresh)
393
+ mask = torch.where(small_components_bg, 0.1, mask)
394
+
395
+ if remove_sprinkles:
396
+ # We remove small connected components in foreground by changing them to background
397
+ # with a small negative mask score (-0.1). Here we only remove connected components
398
+ # whose areas are under both `max_area` and half of the entire mask's area. This
399
+ # removes sprinkles while avoids filtering out tiny objects that we want to track.
400
+ mask_fg = mask > 0
401
+ fg_area_thresh = torch.sum(mask_fg, dim=(2, 3), keepdim=True, dtype=torch.int32)
402
+ fg_area_thresh.floor_divide_(2).clamp_(max=max_area)
403
+ _, areas_fg = _get_connected_components_with_padding(mask_fg)
404
+ small_components_fg = mask_fg & (areas_fg <= fg_area_thresh)
405
+ mask = torch.where(small_components_fg, -0.1, mask)
406
+ return mask
407
+
408
+
409
+ def _get_connected_components_with_padding(mask):
410
+ """Get connected components from masks (possibly padding them to an even size)."""
411
+ from sam3.perflib.connected_components import connected_components
412
+
413
+ mask = mask.to(torch.uint8)
414
+ _, _, H, W = mask.shape
415
+ # make sure both height and width are even (to be compatible with cc_torch)
416
+ pad_h = H % 2
417
+ pad_w = W % 2
418
+ if pad_h == 0 and pad_w == 0:
419
+ labels, counts = connected_components(mask)
420
+ else:
421
+ # pad the mask to make its height and width even
422
+ # padding format is (padding_left,padding_right,padding_top,padding_bottom)
423
+ mask_pad = F.pad(mask, (0, pad_w, 0, pad_h), mode="constant", value=0)
424
+ labels, counts = connected_components(mask_pad)
425
+ labels = labels[:, :, :H, :W]
426
+ counts = counts[:, :, :H, :W]
427
+
428
+ return labels, counts
third_party/GraspGen/sam3/sam3/model/sam3_tracking_predictor.py ADDED
@@ -0,0 +1,1369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+ from collections import OrderedDict
7
+
8
+ import torch
9
+ from sam3.model.sam3_tracker_base import concat_points, NO_OBJ_SCORE, Sam3TrackerBase
10
+ from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores
11
+ from sam3.model.utils.sam2_utils import load_video_frames
12
+ from tqdm.auto import tqdm
13
+
14
+
15
+ class Sam3TrackerPredictor(Sam3TrackerBase):
16
+ """
17
+ The demo class that extends the `Sam3TrackerBase` to handle user interactions
18
+ and manage inference states, with support for multi-object tracking.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
24
+ # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
25
+ clear_non_cond_mem_around_input=False,
26
+ # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True).
27
+ clear_non_cond_mem_for_multi_obj=False,
28
+ # if fill_hole_area > 0, we fill small holes in the final masks up to this area (after resizing them to the original video resolution)
29
+ fill_hole_area=0,
30
+ # if always_start_from_first_ann_frame is True, we always start tracking from the frame where we receive the first annotation (clicks or mask)
31
+ # and ignore the `start_frame_idx` passed to `propagate_in_video`
32
+ always_start_from_first_ann_frame=False,
33
+ # the maximum number of points to be used in the prompt encoder, which reduce the domain gap between training (that only has 8 points)
34
+ # - if it's set to a positive integer, we only take the `max_point_num_in_prompt_enc//2` points and
35
+ # the last `(max_point_num_in_prompt_enc - max_point_num_in_prompt_enc//2)` points in the prompt encoder
36
+ # - if it's set to 0 or negative, this option is turned off and we use all points in the prompt encoder
37
+ max_point_num_in_prompt_enc=16,
38
+ non_overlap_masks_for_output=True,
39
+ # checkpoint_file=None,
40
+ **kwargs,
41
+ ):
42
+ super().__init__(**kwargs)
43
+ self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
44
+ self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj
45
+ self.fill_hole_area = fill_hole_area
46
+ self.always_start_from_first_ann_frame = always_start_from_first_ann_frame
47
+ self.max_point_num_in_prompt_enc = max_point_num_in_prompt_enc
48
+ self.non_overlap_masks_for_output = non_overlap_masks_for_output
49
+
50
+ self.bf16_context = torch.autocast(device_type="cuda", dtype=torch.bfloat16)
51
+ self.bf16_context.__enter__() # keep using for the entire model process
52
+
53
+ self.iter_use_prev_mask_pred = True
54
+ self.add_all_frames_to_correct_as_cond = True
55
+
56
+ @torch.inference_mode()
57
+ def init_state(
58
+ self,
59
+ video_height=None,
60
+ video_width=None,
61
+ num_frames=None,
62
+ video_path=None,
63
+ cached_features=None,
64
+ offload_video_to_cpu=False,
65
+ offload_state_to_cpu=False,
66
+ async_loading_frames=False,
67
+ ):
68
+ """Initialize a inference state."""
69
+ inference_state = {}
70
+ # whether to offload the video frames to CPU memory
71
+ # turning on this option saves the GPU memory with only a very small overhead
72
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
73
+ # whether to offload the inference state to CPU memory
74
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
75
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
76
+ # and from 24 to 21 when tracking two objects)
77
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
78
+ inference_state["device"] = self.device
79
+ if offload_state_to_cpu:
80
+ inference_state["storage_device"] = torch.device("cpu")
81
+ else:
82
+ inference_state["storage_device"] = torch.device("cuda")
83
+
84
+ if video_path is not None:
85
+ images, video_height, video_width = load_video_frames(
86
+ video_path=video_path,
87
+ image_size=self.image_size,
88
+ offload_video_to_cpu=offload_video_to_cpu,
89
+ async_loading_frames=async_loading_frames,
90
+ compute_device=inference_state["storage_device"],
91
+ )
92
+ inference_state["images"] = images
93
+ inference_state["num_frames"] = len(images)
94
+ inference_state["video_height"] = video_height
95
+ inference_state["video_width"] = video_width
96
+ else:
97
+ # the original video height and width, used for resizing final output scores
98
+ inference_state["video_height"] = video_height
99
+ inference_state["video_width"] = video_width
100
+ inference_state["num_frames"] = num_frames
101
+ # inputs on each frame
102
+ inference_state["point_inputs_per_obj"] = {}
103
+ inference_state["mask_inputs_per_obj"] = {}
104
+ # visual features on a small number of recently visited frames for quick interactions
105
+ inference_state["cached_features"] = (
106
+ {} if cached_features is None else cached_features
107
+ )
108
+ # values that don't change across frames (so we only need to hold one copy of them)
109
+ inference_state["constants"] = {}
110
+ # mapping between client-side object id and model-side object index
111
+ inference_state["obj_id_to_idx"] = OrderedDict()
112
+ inference_state["obj_idx_to_id"] = OrderedDict()
113
+ inference_state["obj_ids"] = []
114
+ # A storage to hold the model's tracking results and states on each frame
115
+ inference_state["output_dict"] = {
116
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
117
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
118
+ }
119
+ # The index of the frame that received the first annotation
120
+ inference_state["first_ann_frame_idx"] = None
121
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
122
+ inference_state["output_dict_per_obj"] = {}
123
+ # A temporary storage to hold new outputs when user interact with a frame
124
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
125
+ inference_state["temp_output_dict_per_obj"] = {}
126
+ # Frames that already holds consolidated outputs from click or mask inputs
127
+ # (we directly use their consolidated outputs during tracking)
128
+ inference_state["consolidated_frame_inds"] = {
129
+ "cond_frame_outputs": set(), # set containing frame indices
130
+ "non_cond_frame_outputs": set(), # set containing frame indices
131
+ }
132
+ # metadata for each tracking frame (e.g. which direction it's tracked)
133
+ inference_state["tracking_has_started"] = False
134
+ inference_state["frames_already_tracked"] = {}
135
+ self.clear_all_points_in_video(inference_state)
136
+ return inference_state
137
+
138
+ def _obj_id_to_idx(self, inference_state, obj_id):
139
+ """Map client-side object id to model-side object index."""
140
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
141
+ if obj_idx is not None:
142
+ return obj_idx
143
+
144
+ # This is a new object id not sent to the server before. We only allow adding
145
+ # new objects *before* the tracking starts.
146
+ allow_new_object = not inference_state["tracking_has_started"]
147
+ if allow_new_object:
148
+ # get the next object slot
149
+ obj_idx = len(inference_state["obj_id_to_idx"])
150
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
151
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
152
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
153
+ # set up input and output structures for this object
154
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
155
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
156
+ inference_state["output_dict_per_obj"][obj_idx] = {
157
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
158
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
159
+ }
160
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
161
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
162
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
163
+ }
164
+ return obj_idx
165
+ else:
166
+ raise RuntimeError(
167
+ f"Cannot add new object id {obj_id} after tracking starts. "
168
+ f"All existing object ids: {inference_state['obj_ids']}."
169
+ )
170
+
171
+ def _obj_idx_to_id(self, inference_state, obj_idx):
172
+ """Map model-side object index to client-side object id."""
173
+ return inference_state["obj_idx_to_id"][obj_idx]
174
+
175
+ def _get_obj_num(self, inference_state):
176
+ """Get the total number of unique object ids received so far in this session."""
177
+ return len(inference_state["obj_idx_to_id"])
178
+
179
+ @torch.inference_mode()
180
+ def add_new_points_or_box(
181
+ self,
182
+ inference_state,
183
+ frame_idx,
184
+ obj_id,
185
+ points=None,
186
+ labels=None,
187
+ clear_old_points=True,
188
+ rel_coordinates=True,
189
+ use_prev_mem_frame=False,
190
+ normalize_coords=True,
191
+ box=None,
192
+ ):
193
+ """Add new points to a frame."""
194
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
195
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
196
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
197
+
198
+ if (points is not None) != (labels is not None):
199
+ raise ValueError("points and labels must be provided together")
200
+ if points is None and box is None:
201
+ raise ValueError("at least one of points or box must be provided as input")
202
+
203
+ if points is None:
204
+ points = torch.zeros(0, 2, dtype=torch.float32)
205
+ elif not isinstance(points, torch.Tensor):
206
+ points = torch.tensor(points, dtype=torch.float32)
207
+ if labels is None:
208
+ labels = torch.zeros(0, dtype=torch.int32)
209
+ elif not isinstance(labels, torch.Tensor):
210
+ labels = torch.tensor(labels, dtype=torch.int32)
211
+ if points.dim() == 2:
212
+ points = points.unsqueeze(0) # add batch dimension
213
+ if labels.dim() == 1:
214
+ labels = labels.unsqueeze(0) # add batch dimension
215
+
216
+ if rel_coordinates:
217
+ # convert the points from relative coordinates to absolute coordinates
218
+ if points is not None:
219
+ points = points * self.image_size
220
+ if box is not None:
221
+ box = box * self.image_size
222
+
223
+ # If `box` is provided, we add it as the first two points with labels 2 and 3
224
+ # along with the user-provided points (consistent with how SAM 2 is trained).
225
+ if box is not None:
226
+ if not clear_old_points:
227
+ raise ValueError(
228
+ "cannot add box without clearing old points, since "
229
+ "box prompt must be provided before any point prompt "
230
+ "(please use clear_old_points=True instead)"
231
+ )
232
+ if not isinstance(box, torch.Tensor):
233
+ box = torch.tensor(box, dtype=torch.float32, device=points.device)
234
+ box_coords = box.reshape(1, 2, 2)
235
+ box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
236
+ box_labels = box_labels.reshape(1, 2)
237
+ points = torch.cat([box_coords, points], dim=1)
238
+ labels = torch.cat([box_labels, labels], dim=1)
239
+
240
+ points = points.to(inference_state["device"])
241
+ labels = labels.to(inference_state["device"])
242
+
243
+ if not clear_old_points:
244
+ point_inputs = point_inputs_per_frame.get(frame_idx, None)
245
+ else:
246
+ point_inputs = None
247
+ point_inputs = concat_points(point_inputs, points, labels)
248
+
249
+ point_inputs_per_frame[frame_idx] = point_inputs
250
+ mask_inputs_per_frame.pop(frame_idx, None)
251
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
252
+ # frame, meaning that the inputs points are to generate segments on this frame without
253
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
254
+ # the input points will be used to correct the already tracked masks.
255
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
256
+ # whether to track in reverse time order
257
+ if is_init_cond_frame:
258
+ reverse = False
259
+ else:
260
+ reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
261
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
262
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
263
+ # Add a frame to conditioning output if it's an initial conditioning frame or
264
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
265
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
266
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
267
+
268
+ # Limit to a maximum number of input points to the prompt encoder (to reduce domain gap)
269
+ num_points = point_inputs["point_coords"].size(1)
270
+ if num_points > self.max_point_num_in_prompt_enc > 0:
271
+ num_first = self.max_point_num_in_prompt_enc // 2
272
+ num_last = self.max_point_num_in_prompt_enc - num_first
273
+ point_inputs["point_coords"] = torch.cat(
274
+ [
275
+ point_inputs["point_coords"][:, :num_first],
276
+ point_inputs["point_coords"][:, -num_last:],
277
+ ],
278
+ dim=1,
279
+ )
280
+ point_inputs["point_labels"] = torch.cat(
281
+ [
282
+ point_inputs["point_labels"][:, :num_first],
283
+ point_inputs["point_labels"][:, -num_last:],
284
+ ],
285
+ dim=1,
286
+ )
287
+ logging.warning(
288
+ f"Too many points ({num_points}) are provided on frame {frame_idx}. Only "
289
+ f"the first {num_first} points and the last {num_last} points will be used."
290
+ )
291
+ # Get any previously predicted mask logits on this object and feed it along with
292
+ # the new clicks into the SAM mask decoder when `self.iter_use_prev_mask_pred=True`.
293
+ prev_sam_mask_logits = None
294
+ if self.iter_use_prev_mask_pred:
295
+ # lookup temporary output dict first, which contains the most recent output
296
+ # (if not found, then lookup conditioning and non-conditioning frame output)
297
+ prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
298
+ if prev_out is None:
299
+ prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
300
+ if prev_out is None:
301
+ prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
302
+
303
+ if prev_out is not None and prev_out["pred_masks"] is not None:
304
+ prev_sam_mask_logits = prev_out["pred_masks"].cuda(non_blocking=True)
305
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
306
+ prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
307
+ current_out, _ = self._run_single_frame_inference(
308
+ inference_state=inference_state,
309
+ output_dict=obj_output_dict, # run on the slice of a single object
310
+ frame_idx=frame_idx,
311
+ batch_size=1, # run on the slice of a single object
312
+ is_init_cond_frame=is_init_cond_frame,
313
+ point_inputs=point_inputs,
314
+ mask_inputs=None,
315
+ reverse=reverse,
316
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
317
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
318
+ # allows us to enforce non-overlapping constraints on all objects before encoding
319
+ # them into memory.
320
+ run_mem_encoder=False,
321
+ prev_sam_mask_logits=prev_sam_mask_logits,
322
+ use_prev_mem_frame=use_prev_mem_frame,
323
+ )
324
+ # Add the output to the output dict (to be used as future memory)
325
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
326
+
327
+ # Resize the output mask to the original video resolution
328
+ obj_ids = inference_state["obj_ids"]
329
+ consolidated_out = self._consolidate_temp_output_across_obj(
330
+ inference_state,
331
+ frame_idx,
332
+ is_cond=is_cond,
333
+ run_mem_encoder=False,
334
+ consolidate_at_video_res=True,
335
+ )
336
+ _, video_res_masks = self._get_orig_video_res_output(
337
+ inference_state, consolidated_out["pred_masks_video_res"]
338
+ )
339
+ low_res_masks = None # not needed by the demo
340
+ return frame_idx, obj_ids, low_res_masks, video_res_masks
341
+
342
+ @torch.inference_mode()
343
+ def add_new_mask(
344
+ self,
345
+ inference_state,
346
+ frame_idx,
347
+ obj_id,
348
+ mask,
349
+ add_mask_to_memory=False,
350
+ ):
351
+ """Add new mask to a frame."""
352
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
353
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
354
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
355
+
356
+ assert mask.dim() == 2
357
+ mask_H, mask_W = mask.shape
358
+ mask_inputs_orig = mask[None, None] # add batch and channel dimension
359
+ mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
360
+
361
+ # resize the mask if it doesn't match the model's input mask size
362
+ if mask_H != self.input_mask_size or mask_W != self.input_mask_size:
363
+ mask_inputs = torch.nn.functional.interpolate(
364
+ mask_inputs_orig,
365
+ size=(self.input_mask_size, self.input_mask_size),
366
+ align_corners=False,
367
+ mode="bilinear",
368
+ antialias=True, # use antialias for downsampling
369
+ )
370
+ else:
371
+ mask_inputs = mask_inputs_orig
372
+
373
+ # also get the mask at the original video resolution (for outputting)
374
+ video_H = inference_state["video_height"]
375
+ video_W = inference_state["video_width"]
376
+ if mask_H != video_H or mask_W != video_W:
377
+ mask_inputs_video_res = torch.nn.functional.interpolate(
378
+ mask_inputs_orig,
379
+ size=(video_H, video_W),
380
+ align_corners=False,
381
+ mode="bilinear",
382
+ antialias=True, # use antialias for potential downsampling
383
+ )
384
+ else:
385
+ mask_inputs_video_res = mask_inputs_orig
386
+ # convert mask_inputs_video_res to binary (threshold at 0.5 as it is in range 0~1)
387
+ mask_inputs_video_res = mask_inputs_video_res > 0.5
388
+
389
+ mask_inputs_per_frame[frame_idx] = mask_inputs_video_res
390
+ point_inputs_per_frame.pop(frame_idx, None)
391
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
392
+ # frame, meaning that the inputs points are to generate segments on this frame without
393
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
394
+ # the input points will be used to correct the already tracked masks.
395
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
396
+ # whether to track in reverse time order
397
+ if is_init_cond_frame:
398
+ reverse = False
399
+ else:
400
+ reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
401
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
402
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
403
+ # Add a frame to conditioning output if it's an initial conditioning frame or
404
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
405
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
406
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
407
+
408
+ current_out, _ = self._run_single_frame_inference(
409
+ inference_state=inference_state,
410
+ output_dict=obj_output_dict, # run on the slice of a single object
411
+ frame_idx=frame_idx,
412
+ batch_size=1, # run on the slice of a single object
413
+ is_init_cond_frame=is_init_cond_frame,
414
+ point_inputs=None,
415
+ mask_inputs=mask_inputs,
416
+ reverse=reverse,
417
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
418
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
419
+ # allows us to enforce non-overlapping constraints on all objects before encoding
420
+ # them into memory.
421
+ run_mem_encoder=False,
422
+ )
423
+ # We directly use the input mask at video resolution as the output mask for a better
424
+ # video editing experience (so that the masks don't change after each brushing).
425
+ # Here NO_OBJ_SCORE is a large negative value to represent the background and
426
+ # similarly -NO_OBJ_SCORE is a large positive value to represent the foreground.
427
+ current_out["pred_masks"] = None
428
+ current_out["pred_masks_video_res"] = torch.where(
429
+ mask_inputs_video_res, -NO_OBJ_SCORE, NO_OBJ_SCORE
430
+ )
431
+ # Add the output to the output dict (to be used as future memory)
432
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
433
+ # Remove the overlapping proportion of other objects' input masks on this frame
434
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
435
+ for obj_idx2, obj_temp_output_dict2 in temp_output_dict_per_obj.items():
436
+ if obj_idx2 == obj_idx:
437
+ continue
438
+ current_out2 = obj_temp_output_dict2[storage_key].get(frame_idx, None)
439
+ if current_out2 is not None and "pred_masks_video_res" in current_out2:
440
+ current_out2["pred_masks_video_res"] = torch.where(
441
+ mask_inputs_video_res,
442
+ NO_OBJ_SCORE,
443
+ current_out2["pred_masks_video_res"],
444
+ )
445
+
446
+ # Resize the output mask to the original video resolution
447
+ obj_ids = inference_state["obj_ids"]
448
+ consolidated_out = self._consolidate_temp_output_across_obj(
449
+ inference_state,
450
+ frame_idx,
451
+ is_cond=is_cond,
452
+ run_mem_encoder=False,
453
+ consolidate_at_video_res=True,
454
+ )
455
+ _, video_res_masks = self._get_orig_video_res_output(
456
+ inference_state, consolidated_out["pred_masks_video_res"]
457
+ )
458
+ low_res_masks = None # not needed by the demo
459
+ return frame_idx, obj_ids, low_res_masks, video_res_masks
460
+
461
+ def add_new_points(self, *args, **kwargs):
462
+ """Deprecated method. Please use `add_new_points_or_box` instead."""
463
+ return self.add_new_points_or_box(*args, **kwargs)
464
+
465
+ def _get_orig_video_res_output(self, inference_state, any_res_masks):
466
+ """
467
+ Resize the object scores to the original video resolution (video_res_masks)
468
+ and apply non-overlapping constraints for final output.
469
+ """
470
+ device = inference_state["device"]
471
+ video_H = inference_state["video_height"]
472
+ video_W = inference_state["video_width"]
473
+ any_res_masks = any_res_masks.to(device, non_blocking=True)
474
+ if any_res_masks.shape[-2:] == (video_H, video_W):
475
+ video_res_masks = any_res_masks
476
+ else:
477
+ video_res_masks = torch.nn.functional.interpolate(
478
+ any_res_masks,
479
+ size=(video_H, video_W),
480
+ mode="bilinear",
481
+ align_corners=False,
482
+ )
483
+ if self.non_overlap_masks_for_output:
484
+ video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
485
+ # potentially fill holes in the predicted masks
486
+ if self.fill_hole_area > 0:
487
+ video_res_masks = fill_holes_in_mask_scores(
488
+ video_res_masks, self.fill_hole_area
489
+ )
490
+ return any_res_masks, video_res_masks
491
+
492
+ def _consolidate_temp_output_across_obj(
493
+ self,
494
+ inference_state,
495
+ frame_idx,
496
+ is_cond,
497
+ run_mem_encoder,
498
+ consolidate_at_video_res=False,
499
+ ):
500
+ """
501
+ Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
502
+ a frame into a single output for all objects, including
503
+ 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
504
+ `output_dict_per_obj` for this frame) or leave them as placeholder values
505
+ (if they don't exist in `output_dict_per_obj` for this frame);
506
+ 2) if specified, rerun memory encoder after apply non-overlapping constraints
507
+ on the object scores.
508
+ """
509
+ batch_size = self._get_obj_num(inference_state)
510
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
511
+ # Optionally, we allow consolidating the temporary outputs at the original
512
+ # video resolution (to provide a better editing experience for mask prompts).
513
+ if consolidate_at_video_res:
514
+ assert not run_mem_encoder, "memory encoder cannot run at video resolution"
515
+ consolidated_H = inference_state["video_height"]
516
+ consolidated_W = inference_state["video_width"]
517
+ consolidated_mask_key = "pred_masks_video_res"
518
+ else:
519
+ consolidated_H = consolidated_W = self.low_res_mask_size
520
+ consolidated_mask_key = "pred_masks"
521
+
522
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
523
+ # will be added when rerunning the memory encoder after applying non-overlapping
524
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
525
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
526
+ consolidated_out = {
527
+ "maskmem_features": None,
528
+ "maskmem_pos_enc": None,
529
+ consolidated_mask_key: torch.full(
530
+ size=(batch_size, 1, consolidated_H, consolidated_W),
531
+ fill_value=NO_OBJ_SCORE,
532
+ dtype=torch.float32,
533
+ device=inference_state["storage_device"],
534
+ ),
535
+ "obj_ptr": torch.full(
536
+ size=(batch_size, self.hidden_dim),
537
+ fill_value=NO_OBJ_SCORE,
538
+ dtype=torch.float32,
539
+ device=inference_state["device"],
540
+ ),
541
+ "object_score_logits": torch.full(
542
+ size=(batch_size, 1),
543
+ # default to 10.0 for object_score_logits, i.e. assuming the object is
544
+ # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
545
+ fill_value=10.0,
546
+ dtype=torch.float32,
547
+ device=inference_state["device"],
548
+ ),
549
+ }
550
+ if self.use_memory_selection:
551
+ consolidated_out["iou_score"] = torch.full(
552
+ size=(batch_size, 1),
553
+ fill_value=0.0,
554
+ dtype=torch.float32,
555
+ device=inference_state["device"],
556
+ )
557
+ empty_mask_ptr = None
558
+ for obj_idx in range(batch_size):
559
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
560
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
561
+ out = obj_temp_output_dict[storage_key].get(frame_idx, None)
562
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
563
+ # we fall back and look up its previous output in "output_dict_per_obj".
564
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
565
+ # "output_dict_per_obj" to find a previous output for this object.
566
+ if out is None:
567
+ out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
568
+ if out is None:
569
+ out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
570
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
571
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
572
+ # placeholder above) and set its object pointer to be a dummy pointer.
573
+ if out is None:
574
+ # Fill in dummy object pointers for those objects without any inputs or
575
+ # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
576
+ # i.e. when we need to build the memory for tracking).
577
+ if run_mem_encoder:
578
+ if empty_mask_ptr is None:
579
+ empty_mask_ptr = self._get_empty_mask_ptr(
580
+ inference_state, frame_idx
581
+ )
582
+ # fill object pointer with a dummy pointer (based on an empty mask)
583
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr
584
+ continue
585
+ # Add the temporary object output mask to consolidated output mask
586
+ # (use "pred_masks_video_res" if it's available)
587
+ obj_mask = out.get("pred_masks_video_res", out["pred_masks"])
588
+ consolidated_pred_masks = consolidated_out[consolidated_mask_key]
589
+ if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
590
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
591
+ else:
592
+ # Resize first if temporary object mask has a different resolution
593
+ is_downsampling = "pred_masks_video_res" in out
594
+ resized_obj_mask = torch.nn.functional.interpolate(
595
+ obj_mask,
596
+ size=consolidated_pred_masks.shape[-2:],
597
+ mode="bilinear",
598
+ align_corners=False,
599
+ antialias=is_downsampling, # use antialias for downsampling
600
+ )
601
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
602
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
603
+ consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[
604
+ "object_score_logits"
605
+ ]
606
+ if self.use_memory_selection:
607
+ consolidated_out["iou_score"][obj_idx : obj_idx + 1] = out["iou_score"]
608
+ # Optionally, apply non-overlapping constraints on the consolidated scores
609
+ # and rerun the memory encoder
610
+ if run_mem_encoder:
611
+ device = inference_state["device"]
612
+ high_res_masks = torch.nn.functional.interpolate(
613
+ consolidated_out["pred_masks"].to(device, non_blocking=True),
614
+ size=(self.image_size, self.image_size),
615
+ mode="bilinear",
616
+ align_corners=False,
617
+ )
618
+ high_res_masks = self._apply_non_overlapping_constraints(high_res_masks)
619
+ maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
620
+ inference_state=inference_state,
621
+ frame_idx=frame_idx,
622
+ batch_size=batch_size,
623
+ high_res_masks=high_res_masks,
624
+ object_score_logits=consolidated_out["object_score_logits"],
625
+ is_mask_from_pts=True, # these frames are what the user interacted with
626
+ )
627
+ consolidated_out["maskmem_features"] = maskmem_features
628
+ consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
629
+
630
+ return consolidated_out
631
+
632
+ def _get_empty_mask_ptr(self, inference_state, frame_idx):
633
+ """Get a dummy object pointer based on an empty mask on the current frame."""
634
+ # A dummy (empty) mask with a single object
635
+ batch_size = 1
636
+ mask_inputs = torch.zeros(
637
+ (batch_size, 1, self.image_size, self.image_size),
638
+ dtype=torch.float32,
639
+ device=inference_state["device"],
640
+ )
641
+
642
+ # Retrieve correct image features
643
+ (
644
+ image,
645
+ _,
646
+ current_vision_feats,
647
+ current_vision_pos_embeds,
648
+ feat_sizes,
649
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
650
+
651
+ # Feed the empty mask and image feature above to get a dummy object pointer
652
+ current_out = self.track_step(
653
+ frame_idx=frame_idx,
654
+ is_init_cond_frame=True,
655
+ current_vision_feats=current_vision_feats,
656
+ current_vision_pos_embeds=current_vision_pos_embeds,
657
+ feat_sizes=feat_sizes,
658
+ image=image,
659
+ point_inputs=None,
660
+ mask_inputs=mask_inputs,
661
+ output_dict={
662
+ "cond_frame_outputs": {},
663
+ "non_cond_frame_outputs": {},
664
+ },
665
+ num_frames=inference_state["num_frames"],
666
+ track_in_reverse=False,
667
+ run_mem_encoder=False,
668
+ prev_sam_mask_logits=None,
669
+ )
670
+ return current_out["obj_ptr"]
671
+
672
+ @torch.inference_mode()
673
+ def propagate_in_video_preflight(self, inference_state, run_mem_encoder=True):
674
+ """Prepare inference_state and consolidate temporary outputs before tracking."""
675
+ # Tracking has started and we don't allow adding new objects until session is reset.
676
+ inference_state["tracking_has_started"] = True
677
+ batch_size = self._get_obj_num(inference_state)
678
+
679
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
680
+ # add them into "output_dict".
681
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
682
+ output_dict = inference_state["output_dict"]
683
+ # "consolidated_frame_inds" contains indices of those frames where consolidated
684
+ # temporary outputs have been added (either in this call or any previous calls
685
+ # to `propagate_in_video_preflight`).
686
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
687
+ for is_cond in [False, True]:
688
+ # Separately consolidate conditioning and non-conditioning temp outptus
689
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
690
+ # Find all the frames that contain temporary outputs for any objects
691
+ # (these should be the frames that have just received clicks for mask inputs
692
+ # via `add_new_points` or `add_new_mask`)
693
+ temp_frame_inds = set()
694
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
695
+ temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
696
+ consolidated_frame_inds[storage_key].update(temp_frame_inds)
697
+ # consolidate the temprary output across all objects on this frame
698
+ for frame_idx in temp_frame_inds:
699
+ consolidated_out = self._consolidate_temp_output_across_obj(
700
+ inference_state,
701
+ frame_idx,
702
+ is_cond=is_cond,
703
+ run_mem_encoder=run_mem_encoder,
704
+ )
705
+ # merge them into "output_dict" and also create per-object slices
706
+ output_dict[storage_key][frame_idx] = consolidated_out
707
+ self._add_output_per_object(
708
+ inference_state, frame_idx, consolidated_out, storage_key
709
+ )
710
+ clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
711
+ self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
712
+ )
713
+ if clear_non_cond_mem:
714
+ # clear non-conditioning memory of the surrounding frames
715
+ self._clear_non_cond_mem_around_input(inference_state, frame_idx)
716
+
717
+ # clear temporary outputs in `temp_output_dict_per_obj`
718
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
719
+ obj_temp_output_dict[storage_key].clear()
720
+
721
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
722
+ # output on the same frame in "non_cond_frame_outputs"
723
+ for frame_idx in output_dict["cond_frame_outputs"]:
724
+ output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
725
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
726
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
727
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
728
+ for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
729
+ assert frame_idx in output_dict["cond_frame_outputs"]
730
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
731
+
732
+ # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
733
+ # with either points or mask inputs (which should be true under a correct demo workflow).
734
+ all_consolidated_frame_inds = (
735
+ consolidated_frame_inds["cond_frame_outputs"]
736
+ | consolidated_frame_inds["non_cond_frame_outputs"]
737
+ )
738
+ input_frames_inds = set()
739
+ for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
740
+ input_frames_inds.update(point_inputs_per_frame.keys())
741
+ for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
742
+ input_frames_inds.update(mask_inputs_per_frame.keys())
743
+ assert all_consolidated_frame_inds == input_frames_inds
744
+ # Record the first interacted frame index (for tracking start)
745
+ if inference_state["first_ann_frame_idx"] is None:
746
+ inference_state["first_ann_frame_idx"] = min(
747
+ input_frames_inds, default=None
748
+ )
749
+ # In case `first_ann_frame_idx` is not in the conditioning frames (e.g. because
750
+ # we cleared the input points on that frame), pick the first conditioning frame
751
+ if (
752
+ inference_state["first_ann_frame_idx"]
753
+ not in output_dict["cond_frame_outputs"]
754
+ ):
755
+ inference_state["first_ann_frame_idx"] = min(
756
+ output_dict["cond_frame_outputs"], default=None
757
+ )
758
+
759
+ def _get_processing_order(
760
+ self, inference_state, start_frame_idx, max_frame_num_to_track, reverse
761
+ ):
762
+ num_frames = inference_state["num_frames"]
763
+ # set start index, end index, and processing order
764
+ if self.always_start_from_first_ann_frame:
765
+ # in this case, we always start tracking from the frame where we receive
766
+ # the initial annotation and ignore the provided start_frame_idx
767
+ start_frame_idx = inference_state["first_ann_frame_idx"]
768
+ if start_frame_idx is None:
769
+ # default: start from the earliest frame with input points
770
+ start_frame_idx = min(inference_state["output_dict"]["cond_frame_outputs"])
771
+ if max_frame_num_to_track is None:
772
+ # default: track all the frames in the video
773
+ max_frame_num_to_track = num_frames
774
+ if reverse:
775
+ end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
776
+ if start_frame_idx > 0:
777
+ processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
778
+ else:
779
+ # this is the edge case where we start from frame 0 and track in reverse order;
780
+ # in this case, we track a single frame (frame 0)
781
+ processing_order = [0]
782
+ else:
783
+ end_frame_idx = min(
784
+ start_frame_idx + max_frame_num_to_track, num_frames - 1
785
+ )
786
+ processing_order = range(start_frame_idx, end_frame_idx + 1)
787
+ return processing_order
788
+
789
+ @torch.inference_mode()
790
+ def propagate_in_video(
791
+ self,
792
+ inference_state,
793
+ start_frame_idx,
794
+ max_frame_num_to_track,
795
+ reverse,
796
+ tqdm_disable=False,
797
+ obj_ids=None,
798
+ run_mem_encoder=True,
799
+ propagate_preflight=False,
800
+ ):
801
+ """Propagate the input points across frames to track in the entire video."""
802
+ if propagate_preflight:
803
+ self.propagate_in_video_preflight(inference_state)
804
+ # NOTE: This is a copy from the parent class, except that we return object scores as well.
805
+ output_dict = inference_state["output_dict"]
806
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
807
+ if obj_ids is not None:
808
+ raise NotImplementedError(
809
+ "Per-object tracking yet for batched inference if not implemented."
810
+ )
811
+ obj_ids = inference_state["obj_ids"]
812
+ batch_size = self._get_obj_num(inference_state)
813
+ if len(output_dict["cond_frame_outputs"]) == 0:
814
+ raise RuntimeError("No points are provided; please add points first")
815
+ clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
816
+ self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
817
+ )
818
+
819
+ processing_order = self._get_processing_order(
820
+ inference_state,
821
+ start_frame_idx,
822
+ max_frame_num_to_track,
823
+ reverse,
824
+ )
825
+
826
+ for frame_idx in tqdm(
827
+ processing_order, desc="propagate in video", disable=tqdm_disable
828
+ ):
829
+ # We skip those frames already in consolidated outputs (these are frames
830
+ # that received input clicks or mask). Note that we cannot directly run
831
+ # batched forward on them via `_run_single_frame_inference` because the
832
+ # number of clicks on each object might be different.
833
+ if frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
834
+ storage_key = "cond_frame_outputs"
835
+ current_out = output_dict[storage_key][frame_idx]
836
+ pred_masks = current_out["pred_masks"]
837
+ obj_scores = current_out["object_score_logits"]
838
+ if clear_non_cond_mem:
839
+ # clear non-conditioning memory of the surrounding frames
840
+ self._clear_non_cond_mem_around_input(inference_state, frame_idx)
841
+ elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]:
842
+ storage_key = "non_cond_frame_outputs"
843
+ current_out = output_dict[storage_key][frame_idx]
844
+ pred_masks = current_out["pred_masks"]
845
+ obj_scores = current_out["object_score_logits"]
846
+ else:
847
+ storage_key = "non_cond_frame_outputs"
848
+ current_out, pred_masks = self._run_single_frame_inference(
849
+ inference_state=inference_state,
850
+ output_dict=output_dict,
851
+ frame_idx=frame_idx,
852
+ batch_size=batch_size,
853
+ is_init_cond_frame=False,
854
+ point_inputs=None,
855
+ mask_inputs=None,
856
+ reverse=reverse,
857
+ run_mem_encoder=run_mem_encoder,
858
+ )
859
+ obj_scores = current_out["object_score_logits"]
860
+ output_dict[storage_key][frame_idx] = current_out
861
+ # Create slices of per-object outputs for subsequent interaction with each
862
+ # individual object after tracking.
863
+ self._add_output_per_object(
864
+ inference_state, frame_idx, current_out, storage_key
865
+ )
866
+ inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse}
867
+
868
+ # Resize the output mask to the original video resolution (we directly use
869
+ # the mask scores on GPU for output to avoid any CPU conversion in between)
870
+ low_res_masks, video_res_masks = self._get_orig_video_res_output(
871
+ inference_state, pred_masks
872
+ )
873
+ yield frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores
874
+
875
+ def _add_output_per_object(
876
+ self, inference_state, frame_idx, current_out, storage_key
877
+ ):
878
+ """
879
+ Split a multi-object output into per-object output slices and add them into
880
+ `output_dict_per_obj`. The resulting slices share the same tensor storage.
881
+ """
882
+ maskmem_features = current_out["maskmem_features"]
883
+ assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
884
+
885
+ maskmem_pos_enc = current_out["maskmem_pos_enc"]
886
+ assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
887
+
888
+ output_dict_per_obj = inference_state["output_dict_per_obj"]
889
+ for obj_idx, obj_output_dict in output_dict_per_obj.items():
890
+ obj_slice = slice(obj_idx, obj_idx + 1)
891
+ obj_out = {
892
+ "maskmem_features": None,
893
+ "maskmem_pos_enc": None,
894
+ "pred_masks": current_out["pred_masks"][obj_slice],
895
+ "obj_ptr": current_out["obj_ptr"][obj_slice],
896
+ "object_score_logits": current_out["object_score_logits"][obj_slice],
897
+ }
898
+ if self.use_memory_selection:
899
+ obj_out["iou_score"] = current_out["iou_score"][obj_slice]
900
+ if maskmem_features is not None:
901
+ obj_out["maskmem_features"] = maskmem_features[obj_slice]
902
+ if maskmem_pos_enc is not None:
903
+ obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
904
+ obj_output_dict[storage_key][frame_idx] = obj_out
905
+
906
+ @torch.inference_mode()
907
+ def clear_all_points_in_frame(
908
+ self, inference_state, frame_idx, obj_id, need_output=True
909
+ ):
910
+ """Remove all input points or mask in a specific frame for a given object."""
911
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
912
+
913
+ # Clear the conditioning information on the given frame
914
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
915
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
916
+
917
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
918
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
919
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
920
+
921
+ # Check and see if there are still any inputs left on this frame
922
+ batch_size = self._get_obj_num(inference_state)
923
+ frame_has_input = False
924
+ for obj_idx2 in range(batch_size):
925
+ if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]:
926
+ frame_has_input = True
927
+ break
928
+ if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]:
929
+ frame_has_input = True
930
+ break
931
+
932
+ # If this frame has no remaining inputs for any objects, we further clear its
933
+ # conditioning frame status
934
+ if not frame_has_input:
935
+ output_dict = inference_state["output_dict"]
936
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
937
+ consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx)
938
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
939
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
940
+ out = output_dict["cond_frame_outputs"].pop(frame_idx, None)
941
+ if out is not None:
942
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
943
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
944
+ output_dict["non_cond_frame_outputs"][frame_idx] = out
945
+ inference_state["frames_already_tracked"].pop(frame_idx, None)
946
+ # Similarly, do it for the sliced output on each object.
947
+ for obj_idx2 in range(batch_size):
948
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2]
949
+ obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
950
+ if obj_out is not None:
951
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
952
+
953
+ # If all the conditioning frames have been removed, we also clear the tracking outputs
954
+ if len(output_dict["cond_frame_outputs"]) == 0:
955
+ self._reset_tracking_results(inference_state)
956
+
957
+ if not need_output:
958
+ return
959
+ # Finally, output updated masks per object (after removing the inputs above)
960
+ obj_ids = inference_state["obj_ids"]
961
+ is_cond = any(
962
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
963
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
964
+ )
965
+ consolidated_out = self._consolidate_temp_output_across_obj(
966
+ inference_state,
967
+ frame_idx,
968
+ is_cond=is_cond,
969
+ run_mem_encoder=False,
970
+ consolidate_at_video_res=True,
971
+ )
972
+ _, video_res_masks = self._get_orig_video_res_output(
973
+ inference_state, consolidated_out["pred_masks_video_res"]
974
+ )
975
+ low_res_masks = None # not needed by the demo
976
+ return frame_idx, obj_ids, low_res_masks, video_res_masks
977
+
978
+ @torch.inference_mode()
979
+ def clear_all_points_in_video(self, inference_state):
980
+ """Remove all input points or mask in all frames throughout the video."""
981
+ self._reset_tracking_results(inference_state)
982
+ # Remove all object ids
983
+ inference_state["obj_id_to_idx"].clear()
984
+ inference_state["obj_idx_to_id"].clear()
985
+ inference_state["obj_ids"].clear()
986
+ inference_state["point_inputs_per_obj"].clear()
987
+ inference_state["mask_inputs_per_obj"].clear()
988
+ inference_state["output_dict_per_obj"].clear()
989
+ inference_state["temp_output_dict_per_obj"].clear()
990
+
991
+ def _reset_tracking_results(self, inference_state):
992
+ """Reset all tracking inputs and results across the videos."""
993
+ for v in inference_state["point_inputs_per_obj"].values():
994
+ v.clear()
995
+ for v in inference_state["mask_inputs_per_obj"].values():
996
+ v.clear()
997
+ for v in inference_state["output_dict_per_obj"].values():
998
+ v["cond_frame_outputs"].clear()
999
+ v["non_cond_frame_outputs"].clear()
1000
+ for v in inference_state["temp_output_dict_per_obj"].values():
1001
+ v["cond_frame_outputs"].clear()
1002
+ v["non_cond_frame_outputs"].clear()
1003
+ inference_state["output_dict"]["cond_frame_outputs"].clear()
1004
+ inference_state["output_dict"]["non_cond_frame_outputs"].clear()
1005
+ inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
1006
+ inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
1007
+ inference_state["tracking_has_started"] = False
1008
+ inference_state["frames_already_tracked"].clear()
1009
+ inference_state["first_ann_frame_idx"] = None
1010
+
1011
+ def _get_image_feature(self, inference_state, frame_idx, batch_size):
1012
+ """Compute the image features on a given frame."""
1013
+ # Look up in the cache
1014
+ image, backbone_out = inference_state["cached_features"].get(
1015
+ frame_idx, (None, None)
1016
+ )
1017
+ if backbone_out is None:
1018
+ if self.backbone is None:
1019
+ raise RuntimeError(
1020
+ f"Image features for frame {frame_idx} are not cached. "
1021
+ "Please run inference on this frame first."
1022
+ )
1023
+ else:
1024
+ # Cache miss -- we will run inference on a single image
1025
+ image = inference_state["images"][frame_idx].cuda().float().unsqueeze(0)
1026
+ backbone_out = self.forward_image(image)
1027
+ # Cache the most recent frame's feature (for repeated interactions with
1028
+ # a frame; we can use an LRU cache for more frames in the future).
1029
+ inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
1030
+ if "tracker_backbone_out" in backbone_out:
1031
+ backbone_out = backbone_out["tracker_backbone_out"] # get backbone output
1032
+
1033
+ # expand the features to have the same dimension as the number of objects
1034
+ expanded_image = image.expand(batch_size, -1, -1, -1)
1035
+ expanded_backbone_out = {
1036
+ "backbone_fpn": backbone_out["backbone_fpn"].copy(),
1037
+ "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
1038
+ }
1039
+ for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
1040
+ feat = feat.expand(batch_size, -1, -1, -1)
1041
+ expanded_backbone_out["backbone_fpn"][i] = feat
1042
+ for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
1043
+ pos = pos.expand(batch_size, -1, -1, -1)
1044
+ expanded_backbone_out["vision_pos_enc"][i] = pos
1045
+
1046
+ features = self._prepare_backbone_features(expanded_backbone_out)
1047
+ features = (expanded_image,) + features
1048
+ return features
1049
+
1050
+ def _run_single_frame_inference(
1051
+ self,
1052
+ inference_state,
1053
+ output_dict,
1054
+ frame_idx,
1055
+ batch_size,
1056
+ is_init_cond_frame,
1057
+ point_inputs,
1058
+ mask_inputs,
1059
+ reverse,
1060
+ run_mem_encoder,
1061
+ prev_sam_mask_logits=None,
1062
+ use_prev_mem_frame=True,
1063
+ ):
1064
+ """Run tracking on a single frame based on current inputs and previous memory."""
1065
+ # Retrieve correct image features
1066
+ (
1067
+ image,
1068
+ _,
1069
+ current_vision_feats,
1070
+ current_vision_pos_embeds,
1071
+ feat_sizes,
1072
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
1073
+
1074
+ # point and mask should not appear as input simultaneously on the same frame
1075
+ assert point_inputs is None or mask_inputs is None
1076
+ current_out = self.track_step(
1077
+ frame_idx=frame_idx,
1078
+ is_init_cond_frame=is_init_cond_frame,
1079
+ current_vision_feats=current_vision_feats,
1080
+ current_vision_pos_embeds=current_vision_pos_embeds,
1081
+ feat_sizes=feat_sizes,
1082
+ image=image,
1083
+ point_inputs=point_inputs,
1084
+ mask_inputs=mask_inputs,
1085
+ output_dict=output_dict,
1086
+ num_frames=inference_state["num_frames"],
1087
+ track_in_reverse=reverse,
1088
+ run_mem_encoder=run_mem_encoder,
1089
+ prev_sam_mask_logits=prev_sam_mask_logits,
1090
+ use_prev_mem_frame=use_prev_mem_frame,
1091
+ )
1092
+
1093
+ # optionally offload the output to CPU memory to save GPU space
1094
+ storage_device = inference_state["storage_device"]
1095
+ maskmem_features = current_out["maskmem_features"]
1096
+ if maskmem_features is not None:
1097
+ maskmem_features = maskmem_features.to(torch.bfloat16)
1098
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
1099
+ pred_masks_gpu = current_out["pred_masks"]
1100
+ pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
1101
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1102
+ maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
1103
+ # object pointer is a small tensor, so we always keep it on GPU memory for fast access
1104
+ obj_ptr = current_out["obj_ptr"]
1105
+ object_score_logits = current_out["object_score_logits"]
1106
+ # make a compact version of this frame's output to reduce the state size
1107
+ compact_current_out = {
1108
+ "maskmem_features": maskmem_features,
1109
+ "maskmem_pos_enc": maskmem_pos_enc,
1110
+ "pred_masks": pred_masks,
1111
+ "obj_ptr": obj_ptr,
1112
+ "object_score_logits": object_score_logits,
1113
+ }
1114
+ if self.use_memory_selection:
1115
+ compact_current_out["iou_score"] = current_out["iou_score"]
1116
+ compact_current_out["eff_iou_score"] = current_out["eff_iou_score"]
1117
+ return compact_current_out, pred_masks_gpu
1118
+
1119
+ def _run_memory_encoder(
1120
+ self,
1121
+ inference_state,
1122
+ frame_idx,
1123
+ batch_size,
1124
+ high_res_masks,
1125
+ object_score_logits,
1126
+ is_mask_from_pts,
1127
+ ):
1128
+ """
1129
+ Run the memory encoder on `high_res_masks`. This is usually after applying
1130
+ non-overlapping constraints to object scores. Since their scores changed, their
1131
+ memory also need to be computed again with the memory encoder.
1132
+ """
1133
+ # Retrieve correct image features
1134
+ image, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
1135
+ inference_state, frame_idx, batch_size
1136
+ )
1137
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
1138
+ image=image,
1139
+ current_vision_feats=current_vision_feats,
1140
+ feat_sizes=feat_sizes,
1141
+ pred_masks_high_res=high_res_masks,
1142
+ object_score_logits=object_score_logits,
1143
+ is_mask_from_pts=is_mask_from_pts,
1144
+ )
1145
+
1146
+ # optionally offload the output to CPU memory to save GPU space
1147
+ storage_device = inference_state["storage_device"]
1148
+ maskmem_features = maskmem_features.to(torch.bfloat16)
1149
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
1150
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1151
+ maskmem_pos_enc = self._get_maskmem_pos_enc(
1152
+ inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
1153
+ )
1154
+ return maskmem_features, maskmem_pos_enc
1155
+
1156
+ def _get_maskmem_pos_enc(self, inference_state, current_out):
1157
+ """
1158
+ `maskmem_pos_enc` is the same across frames and objects, so we cache it as
1159
+ a constant in the inference session to reduce session storage size.
1160
+ """
1161
+ model_constants = inference_state["constants"]
1162
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
1163
+ out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
1164
+ if out_maskmem_pos_enc is not None:
1165
+ if "maskmem_pos_enc" not in model_constants:
1166
+ assert isinstance(out_maskmem_pos_enc, list)
1167
+ # only take the slice for one object, since it's same across objects
1168
+ maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
1169
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
1170
+ else:
1171
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
1172
+ # expand the cached maskmem_pos_enc to the actual batch size
1173
+ batch_size = out_maskmem_pos_enc[0].size(0)
1174
+ expanded_maskmem_pos_enc = [
1175
+ x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
1176
+ ]
1177
+ else:
1178
+ expanded_maskmem_pos_enc = None
1179
+ return expanded_maskmem_pos_enc
1180
+
1181
+ @torch.inference_mode()
1182
+ def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
1183
+ """
1184
+ Remove an object id from the tracking state. If strict is True, we check whether
1185
+ the object id actually exists and raise an error if it doesn't exist.
1186
+ """
1187
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
1188
+ updated_frames = []
1189
+ # Check whether this object_id to remove actually exists and possibly raise an error.
1190
+ if old_obj_idx_to_rm is None:
1191
+ if not strict:
1192
+ return inference_state["obj_ids"], updated_frames
1193
+ raise RuntimeError(
1194
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
1195
+ f"All existing object ids: {inference_state['obj_ids']}."
1196
+ )
1197
+
1198
+ # If this is the only remaining object id, we simply reset the state.
1199
+ if len(inference_state["obj_id_to_idx"]) == 1:
1200
+ self.clear_all_points_in_video(inference_state)
1201
+ return inference_state["obj_ids"], updated_frames
1202
+
1203
+ # There are still remaining objects after removing this object id. In this case,
1204
+ # we need to delete the object storage from inference state tensors.
1205
+ # Step 0: clear the input on those frames where this object id has point or mask input
1206
+ # (note that this step is required as it might downgrade conditioning frames to
1207
+ # non-conditioning ones)
1208
+ obj_input_frames_inds = set()
1209
+ obj_input_frames_inds.update(
1210
+ inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
1211
+ )
1212
+ obj_input_frames_inds.update(
1213
+ inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
1214
+ )
1215
+ for frame_idx in obj_input_frames_inds:
1216
+ self.clear_all_points_in_frame(
1217
+ inference_state, frame_idx, obj_id, need_output=False
1218
+ )
1219
+
1220
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
1221
+ # since Step 0 still requires the old object id mappings in inference_state)
1222
+ old_obj_ids = inference_state["obj_ids"]
1223
+ old_obj_inds = list(range(len(old_obj_ids)))
1224
+ remain_old_obj_inds = old_obj_inds.copy()
1225
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
1226
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
1227
+ new_obj_inds = list(range(len(new_obj_ids)))
1228
+ # build new mappings
1229
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
1230
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
1231
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
1232
+ inference_state["obj_ids"] = new_obj_ids
1233
+
1234
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
1235
+ # (note that "consolidated_frame_inds" doesn't need to be updated in this step as
1236
+ # it's already handled in Step 0)
1237
+ def _map_keys(container):
1238
+ new_kvs = []
1239
+ for k in old_obj_inds:
1240
+ v = container.pop(k)
1241
+ if k in old_idx_to_new_idx:
1242
+ new_kvs.append((old_idx_to_new_idx[k], v))
1243
+ container.update(new_kvs)
1244
+
1245
+ _map_keys(inference_state["point_inputs_per_obj"])
1246
+ _map_keys(inference_state["mask_inputs_per_obj"])
1247
+ _map_keys(inference_state["output_dict_per_obj"])
1248
+ _map_keys(inference_state["temp_output_dict_per_obj"])
1249
+
1250
+ # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices.
1251
+ def _slice_state(output_dict, storage_key):
1252
+ for frame_idx, out in output_dict[storage_key].items():
1253
+ out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds]
1254
+ out["maskmem_pos_enc"] = [
1255
+ x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]
1256
+ ]
1257
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1258
+ out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out)
1259
+ out["pred_masks"] = out["pred_masks"][remain_old_obj_inds]
1260
+ out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds]
1261
+ out["object_score_logits"] = out["object_score_logits"][
1262
+ remain_old_obj_inds
1263
+ ]
1264
+ if self.use_memory_selection:
1265
+ out["iou_score"] = out["iou_score"][remain_old_obj_inds]
1266
+ out["eff_iou_score"] = self.cal_mem_score(
1267
+ out["object_score_logits"], out["iou_score"]
1268
+ ) # recalculate the memory frame score
1269
+ # also update the per-object slices
1270
+ self._add_output_per_object(
1271
+ inference_state, frame_idx, out, storage_key
1272
+ )
1273
+
1274
+ _slice_state(inference_state["output_dict"], "cond_frame_outputs")
1275
+ _slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
1276
+
1277
+ # Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which
1278
+ # could show an updated mask for objects previously occluded by the object being removed
1279
+ if need_output:
1280
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1281
+ for frame_idx in obj_input_frames_inds:
1282
+ is_cond = any(
1283
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
1284
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
1285
+ )
1286
+ consolidated_out = self._consolidate_temp_output_across_obj(
1287
+ inference_state,
1288
+ frame_idx,
1289
+ is_cond=is_cond,
1290
+ run_mem_encoder=False,
1291
+ consolidate_at_video_res=True,
1292
+ )
1293
+ _, video_res_masks = self._get_orig_video_res_output(
1294
+ inference_state, consolidated_out["pred_masks_video_res"]
1295
+ )
1296
+ updated_frames.append((frame_idx, video_res_masks))
1297
+
1298
+ return inference_state["obj_ids"], updated_frames
1299
+
1300
+ def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
1301
+ """
1302
+ Remove the non-conditioning memory around the input frame. When users provide
1303
+ correction clicks, the surrounding frames' non-conditioning memories can still
1304
+ contain outdated object appearance information and could confuse the model.
1305
+
1306
+ This method clears those non-conditioning memories surrounding the interacted
1307
+ frame to avoid giving the model both old and new information about the object.
1308
+ """
1309
+ r = self.memory_temporal_stride_for_eval
1310
+ frame_idx_begin = frame_idx - r * self.num_maskmem
1311
+ frame_idx_end = frame_idx + r * self.num_maskmem
1312
+ batch_size = self._get_obj_num(inference_state)
1313
+ for obj_idx in range(batch_size):
1314
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
1315
+ non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"]
1316
+ for t in range(frame_idx_begin, frame_idx_end + 1):
1317
+ non_cond_frame_outputs.pop(t, None)
1318
+
1319
+ def _suppress_shrinked_masks(
1320
+ self, pred_masks, new_pred_masks, shrink_threshold=0.3
1321
+ ):
1322
+ area_before = (pred_masks > 0).sum(dim=(-1, -2))
1323
+ area_after = (new_pred_masks > 0).sum(dim=(-1, -2))
1324
+ area_before = torch.clamp(area_before, min=1.0)
1325
+ area_ratio = area_after / area_before
1326
+ keep = area_ratio >= shrink_threshold
1327
+ keep_mask = keep[..., None, None].expand_as(pred_masks)
1328
+ pred_masks_after = torch.where(
1329
+ keep_mask, pred_masks, torch.clamp(pred_masks, max=-10.0)
1330
+ )
1331
+ return pred_masks_after
1332
+
1333
+ def _suppress_object_pw_area_shrinkage(self, pred_masks):
1334
+ """
1335
+ This function suppresses masks that shrink in area after applying pixelwise non-overlapping constriants.
1336
+ Note that the final output can still be overlapping.
1337
+ """
1338
+ # Apply pixel-wise non-overlapping constraint based on mask scores
1339
+ pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints(
1340
+ pred_masks
1341
+ )
1342
+ # Fully suppress masks with high shrinkage (probably noisy) based on the pixel wise non-overlapping constraints
1343
+ # NOTE: The output of this function can be a no op if none of the masks shrinked by a large factor.
1344
+ pred_masks = self._suppress_shrinked_masks(
1345
+ pred_masks, pixel_level_non_overlapping_masks
1346
+ )
1347
+ return pred_masks
1348
+
1349
+ def _apply_object_wise_non_overlapping_constraints(
1350
+ self, pred_masks, obj_scores, background_value=-10.0
1351
+ ):
1352
+ """
1353
+ Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region)
1354
+ """
1355
+ # Replace pixel scores with object scores
1356
+ pred_masks_single_score = torch.where(
1357
+ pred_masks > 0, obj_scores[..., None, None], background_value
1358
+ )
1359
+ # Apply pixel-wise non-overlapping constraint based on mask scores
1360
+ pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints(
1361
+ pred_masks_single_score
1362
+ )
1363
+ # Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region
1364
+ pred_masks = torch.where(
1365
+ pixel_level_non_overlapping_masks > 0,
1366
+ pred_masks,
1367
+ torch.clamp(pred_masks, max=background_value),
1368
+ )
1369
+ return pred_masks
third_party/GraspGen/sam3/sam3/model/sam3_video_base.py ADDED
@@ -0,0 +1,1768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import datetime
6
+ import logging
7
+ import math
8
+ import os
9
+ from collections import defaultdict
10
+ from copy import deepcopy
11
+ from enum import Enum
12
+ from typing import Any, Dict, List, Set
13
+
14
+ import numpy as np
15
+ import numpy.typing as npt
16
+ import torch
17
+ import torch.distributed as dist
18
+ import torch.nn.functional as F
19
+ from sam3 import perflib
20
+ from sam3.logger import get_logger
21
+ from sam3.model.box_ops import fast_diag_box_iou
22
+ from sam3.model.data_misc import BatchedDatapoint
23
+ from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores, mask_to_box
24
+ from sam3.perflib.masks_ops import mask_iou
25
+ from sam3.train.masks_ops import rle_encode
26
+ from torch import nn, Tensor
27
+
28
+ logger = get_logger(__name__)
29
+
30
+
31
+ class MaskletConfirmationStatus(Enum):
32
+ UNCONFIRMED = 1 # newly added masklet, not confirmed by any detection yet
33
+ CONFIRMED = 2 # confirmed by at least one detection
34
+
35
+
36
+ class Sam3VideoBase(nn.Module):
37
+ def __init__(
38
+ self,
39
+ detector: nn.Module,
40
+ tracker: nn.Module,
41
+ # prob threshold for detection outputs -- only keep detections above this threshold
42
+ # enters NMS and det-to-track matching
43
+ score_threshold_detection=0.5,
44
+ # IoU threshold for detection NMS
45
+ det_nms_thresh=0.0,
46
+ # IoU threshold for det-to-track matching -- a detection is considered "matched" to a tracklet it
47
+ # overlaps with a tracklet above this threshold -- it is often a loose threshold like 0.1
48
+ assoc_iou_thresh=0.5,
49
+ # IoU threshold for det-to-track matching, which is used to determine whether a masklet is "unmatched"
50
+ # by any detections -- it is often a stricter threshold like 0.5
51
+ trk_assoc_iou_thresh=0.5,
52
+ # prob threshold for a detection to be added as a new object
53
+ new_det_thresh=0.0,
54
+ # hotstart parameters: we hold off the outputs for `hotstart_delay` frames and
55
+ # 1) remove those tracklets unmatched by any detections based on `hotstart_unmatch_thresh`
56
+ # 2) remove those tracklets overlapping with one another based on `hotstart_dup_thresh`
57
+ hotstart_delay=0,
58
+ hotstart_unmatch_thresh=3,
59
+ hotstart_dup_thresh=3,
60
+ # Whether to suppress masks only within hotstart. If False, we can suppress masks even if they start before hotstart period.
61
+ suppress_unmatched_only_within_hotstart=True,
62
+ init_trk_keep_alive=0,
63
+ max_trk_keep_alive=8,
64
+ min_trk_keep_alive=-4,
65
+ # Threshold for suppressing overlapping objects based on recent occlusion
66
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.0,
67
+ decrease_trk_keep_alive_for_empty_masklets=False,
68
+ o2o_matching_masklets_enable=False, # Enable hungarian matching to match existing masklets
69
+ suppress_det_close_to_boundary=False,
70
+ fill_hole_area=16,
71
+ # The maximum number of objects (masklets) to track across all GPUs (for no limit, set it to -1)
72
+ max_num_objects=-1,
73
+ recondition_every_nth_frame=-1,
74
+ # masket confirmation status (to suppress unconfirmed masklets)
75
+ masklet_confirmation_enable=False,
76
+ # a masklet is confirmed after being consecutively detected and matched for
77
+ # `masklet_confirmation_consecutive_det_thresh`
78
+ masklet_confirmation_consecutive_det_thresh=3,
79
+ # bbox heuristic parameters
80
+ reconstruction_bbox_iou_thresh=0.0,
81
+ reconstruction_bbox_det_score=0.0,
82
+ ):
83
+ super().__init__()
84
+ self.detector = detector
85
+ self.tracker = tracker
86
+ self.score_threshold_detection = score_threshold_detection
87
+ self.det_nms_thresh = det_nms_thresh
88
+ self.assoc_iou_thresh = assoc_iou_thresh
89
+ self.trk_assoc_iou_thresh = trk_assoc_iou_thresh
90
+ self.new_det_thresh = new_det_thresh
91
+
92
+ # hotstart parameters
93
+ if hotstart_delay > 0:
94
+ assert hotstart_unmatch_thresh <= hotstart_delay
95
+ assert hotstart_dup_thresh <= hotstart_delay
96
+ self.hotstart_delay = hotstart_delay
97
+ self.hotstart_unmatch_thresh = hotstart_unmatch_thresh
98
+ self.hotstart_dup_thresh = hotstart_dup_thresh
99
+ self.suppress_unmatched_only_within_hotstart = (
100
+ suppress_unmatched_only_within_hotstart
101
+ )
102
+ self.init_trk_keep_alive = init_trk_keep_alive
103
+ self.max_trk_keep_alive = max_trk_keep_alive
104
+ self.min_trk_keep_alive = min_trk_keep_alive
105
+ self.suppress_overlapping_based_on_recent_occlusion_threshold = (
106
+ suppress_overlapping_based_on_recent_occlusion_threshold
107
+ )
108
+ self.suppress_det_close_to_boundary = suppress_det_close_to_boundary
109
+ self.decrease_trk_keep_alive_for_empty_masklets = (
110
+ decrease_trk_keep_alive_for_empty_masklets
111
+ )
112
+ self.o2o_matching_masklets_enable = o2o_matching_masklets_enable
113
+ self.fill_hole_area = fill_hole_area
114
+ self.eval()
115
+ self.rank = int(os.getenv("RANK", "0"))
116
+ self.world_size = int(os.getenv("WORLD_SIZE", "1"))
117
+ self._dist_pg_cpu = None # CPU process group (lazy-initialized on first use)
118
+
119
+ # the maximum object number
120
+ if max_num_objects > 0:
121
+ num_obj_for_compile = math.ceil(max_num_objects / self.world_size)
122
+ else:
123
+ max_num_objects = 10000 # no limit
124
+ num_obj_for_compile = 16
125
+ logger.info(f"setting {max_num_objects=} and {num_obj_for_compile=}")
126
+ self.max_num_objects = max_num_objects
127
+ self.num_obj_for_compile = num_obj_for_compile
128
+ self.recondition_every_nth_frame = recondition_every_nth_frame
129
+ self.masklet_confirmation_enable = masklet_confirmation_enable
130
+ self.masklet_confirmation_consecutive_det_thresh = (
131
+ masklet_confirmation_consecutive_det_thresh
132
+ )
133
+ self.reconstruction_bbox_iou_thresh = reconstruction_bbox_iou_thresh
134
+ self.reconstruction_bbox_det_score = reconstruction_bbox_det_score
135
+
136
+ @property
137
+ def device(self):
138
+ self._device = getattr(self, "_device", None) or next(self.parameters()).device
139
+ return self._device
140
+
141
+ def _init_dist_pg_cpu(self):
142
+ # a short 3-min timeout to quickly detect any synchronization failures
143
+ timeout_sec = int(os.getenv("SAM3_COLLECTIVE_OP_TIMEOUT_SEC", "180"))
144
+ timeout = datetime.timedelta(seconds=timeout_sec)
145
+ self._dist_pg_cpu = dist.new_group(backend="gloo", timeout=timeout)
146
+
147
+ def broadcast_python_obj_cpu(self, python_obj_list, src):
148
+ if self._dist_pg_cpu is None:
149
+ self._init_dist_pg_cpu()
150
+ dist.broadcast_object_list(python_obj_list, src=src, group=self._dist_pg_cpu)
151
+
152
+ def _det_track_one_frame(
153
+ self,
154
+ frame_idx: int,
155
+ num_frames: int,
156
+ reverse: bool,
157
+ input_batch: BatchedDatapoint,
158
+ geometric_prompt: Any,
159
+ tracker_states_local: List[Any],
160
+ tracker_metadata_prev: Dict[str, Any],
161
+ feature_cache: Dict,
162
+ orig_vid_height: int,
163
+ orig_vid_width: int,
164
+ is_image_only: bool = False,
165
+ allow_new_detections: bool = True,
166
+ ):
167
+ """
168
+ This function handles one-step inference for the DenseTracking model in an SPMD manner.
169
+ At a high-level, all GPUs execute the same function calls as if it's done on a single GPU,
170
+ while under the hood, some function calls involve distributed computation based on sharded
171
+ SAM2 states.
172
+
173
+ - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
174
+ - `tracker_states_local` holds the local masklet information in this GPU shard
175
+ - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
176
+ it contains both global and local masklet information
177
+ """
178
+
179
+ # Step 1: run backbone and detector in a distributed manner -- this is done via Sam3ImageOnVideoMultiGPU,
180
+ # a MultiGPU model (assigned to `self.detector`) that shards frames in a round-robin manner.
181
+ # It returns a "det_out" dict for `frame_idx` and fills SAM2 backbone features for `frame_idx`
182
+ # into `feature_cache`. Despite its distributed inference under the hood, the results would be
183
+ # the same as if it is running backbone and detector for every frame on a single GPU.
184
+ det_out = self.run_backbone_and_detection(
185
+ frame_idx=frame_idx,
186
+ num_frames=num_frames,
187
+ reverse=reverse,
188
+ input_batch=input_batch,
189
+ geometric_prompt=geometric_prompt,
190
+ feature_cache=feature_cache,
191
+ allow_new_detections=allow_new_detections,
192
+ )
193
+
194
+ # Step 2: each GPU propagates its local SAM2 states to get the SAM2 prediction masks.
195
+ # the returned `tracker_low_res_masks_global` contains the concatenated masklet predictions
196
+ # gathered from all GPUs (as if they are propagated on a single GPU). Note that this step only
197
+ # runs the SAM2 propagation step, but doesn't encode new memory for the predicted masks;
198
+ # we defer memory encoding to `run_tracker_update_execution_phase` after resolving all heuristics.
199
+ if tracker_metadata_prev == {}:
200
+ # initialize masklet metadata if it's uninitialized (empty dict)
201
+ tracker_metadata_prev.update(self._initialize_metadata())
202
+ tracker_low_res_masks_global, tracker_obj_scores_global = (
203
+ self.run_tracker_propagation(
204
+ frame_idx=frame_idx,
205
+ num_frames=num_frames,
206
+ reverse=reverse,
207
+ tracker_states_local=tracker_states_local,
208
+ tracker_metadata_prev=tracker_metadata_prev,
209
+ )
210
+ )
211
+
212
+ # Step 3: based on detection outputs and the propagated SAM2 prediction masks, we make plans
213
+ # for SAM2 masklet updates (i.e. which objects to add and remove, how to load-balance them, etc).
214
+ # We also run SAM2 memory encoder globally in this step to resolve non-overlapping constraints.
215
+ # **This step should involve all the heuristics needed for any updates.** Most of the update
216
+ # planning will be done on the master rank (GPU 0) and the resulting plan `tracker_update_plan` is
217
+ # broadcasted to other GPUs (to be executed in a distributed manner). This step also generates the
218
+ # new masklet metadata `tracker_metadata_new` (based on its previous version `tracker_metadata_prev`).
219
+ tracker_update_plan, tracker_metadata_new = (
220
+ self.run_tracker_update_planning_phase(
221
+ frame_idx=frame_idx,
222
+ num_frames=num_frames,
223
+ reverse=reverse,
224
+ det_out=det_out,
225
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
226
+ tracker_obj_scores_global=tracker_obj_scores_global,
227
+ tracker_metadata_prev=tracker_metadata_prev,
228
+ tracker_states_local=tracker_states_local,
229
+ is_image_only=is_image_only,
230
+ )
231
+ )
232
+
233
+ # Get reconditioning info from the update plan
234
+ reconditioned_obj_ids = tracker_update_plan.get("reconditioned_obj_ids", set())
235
+ det_to_matched_trk_obj_ids = tracker_update_plan.get(
236
+ "det_to_matched_trk_obj_ids", {}
237
+ )
238
+
239
+ # Step 4: based on `tracker_update_plan`, each GPU executes the update w.r.t. its local SAM2 inference states
240
+ tracker_states_local_new = self.run_tracker_update_execution_phase(
241
+ frame_idx=frame_idx,
242
+ num_frames=num_frames,
243
+ reverse=reverse,
244
+ det_out=det_out,
245
+ tracker_states_local=tracker_states_local,
246
+ tracker_update_plan=tracker_update_plan,
247
+ orig_vid_height=orig_vid_height,
248
+ orig_vid_width=orig_vid_width,
249
+ feature_cache=feature_cache,
250
+ )
251
+
252
+ # Step 5: finally, build the outputs for this frame (it only needs to be done on GPU 0 since
253
+ # only GPU 0 will send outputs to the server).
254
+ if self.rank == 0:
255
+ obj_id_to_mask = self.build_outputs(
256
+ frame_idx=frame_idx,
257
+ num_frames=num_frames,
258
+ reverse=reverse,
259
+ det_out=det_out,
260
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
261
+ tracker_obj_scores_global=tracker_obj_scores_global,
262
+ tracker_metadata_prev=tracker_metadata_prev,
263
+ tracker_update_plan=tracker_update_plan,
264
+ orig_vid_height=orig_vid_height,
265
+ orig_vid_width=orig_vid_width,
266
+ reconditioned_obj_ids=reconditioned_obj_ids,
267
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
268
+ )
269
+ obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
270
+ else:
271
+ obj_id_to_mask, obj_id_to_score = {}, {} # dummy outputs on other GPUs
272
+ # a few statistics for the current frame as a part of the output
273
+ frame_stats = {
274
+ "num_obj_tracked": np.sum(tracker_metadata_new["num_obj_per_gpu"]),
275
+ "num_obj_dropped": tracker_update_plan["num_obj_dropped_due_to_limit"],
276
+ }
277
+ # add tracker scores to metadata, it should be fired for frames except the first frame
278
+ if tracker_obj_scores_global.shape[0] > 0:
279
+ # Convert tracker_obj_scores_global to sigmoid scores before updating
280
+ tracker_obj_scores_global = tracker_obj_scores_global.sigmoid().tolist()
281
+ tracker_obj_ids = tracker_metadata_prev["obj_ids_all_gpu"]
282
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
283
+ frame_idx
284
+ ].update(dict(zip(tracker_obj_ids, tracker_obj_scores_global)))
285
+ return (
286
+ obj_id_to_mask, # a dict: obj_id --> output mask
287
+ obj_id_to_score, # a dict: obj_id --> output score (prob)
288
+ tracker_states_local_new,
289
+ tracker_metadata_new,
290
+ frame_stats,
291
+ tracker_obj_scores_global, # a dict: obj_id --> tracker frame-level scores
292
+ )
293
+
294
+ def _suppress_detections_close_to_boundary(self, boxes, margin=0.025):
295
+ """
296
+ Suppress detections too close to image edges (for normalized boxes).
297
+
298
+ boxes: (N, 4) in xyxy format, normalized [0,1]
299
+ margin: fraction of image
300
+ """
301
+ x_min, y_min, x_max, y_max = boxes.unbind(-1)
302
+ x_c = (x_min + x_max) / 2
303
+ y_c = (y_min + y_max) / 2
304
+ keep = (
305
+ (x_c > margin)
306
+ & (x_c < 1.0 - margin)
307
+ & (y_c > margin)
308
+ & (y_c < 1.0 - margin)
309
+ )
310
+
311
+ return keep
312
+
313
+ def run_backbone_and_detection(
314
+ self,
315
+ frame_idx: int,
316
+ num_frames: int,
317
+ input_batch: BatchedDatapoint,
318
+ geometric_prompt: Any,
319
+ feature_cache: Dict,
320
+ reverse: bool,
321
+ allow_new_detections: bool,
322
+ ):
323
+ # Step 1: if text feature is not cached in `feature_cache`, compute and cache it
324
+ text_batch_key = tuple(input_batch.find_text_batch)
325
+ if "text" not in feature_cache or text_batch_key not in feature_cache["text"]:
326
+ text_outputs = self.detector.backbone.forward_text(
327
+ input_batch.find_text_batch, device=self.device
328
+ )
329
+ # note: we only cache the text feature of the most recent prompt
330
+ feature_cache["text"] = {text_batch_key: text_outputs}
331
+ else:
332
+ text_outputs = feature_cache["text"][text_batch_key]
333
+
334
+ # Step 2: run backbone, detector, and post-processing with NMS
335
+ if "multigpu_buffer" not in feature_cache:
336
+ # "multigpu_buffer" is a buffer cache used by `self.detector` and it needs
337
+ # to be passed to `forward_video_grounding_multigpu` for every call
338
+ feature_cache["multigpu_buffer"] = {}
339
+
340
+ # Extract max_frame_num_to_track from feature_cache if available
341
+ tracking_bounds = feature_cache.get("tracking_bounds", {})
342
+ max_frame_num_to_track = tracking_bounds.get("max_frame_num_to_track")
343
+ start_frame_idx = tracking_bounds.get("propagate_in_video_start_frame_idx")
344
+
345
+ sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
346
+ backbone_out={
347
+ "img_batch_all_stages": input_batch.img_batch,
348
+ **text_outputs,
349
+ },
350
+ find_inputs=input_batch.find_inputs,
351
+ geometric_prompt=geometric_prompt,
352
+ frame_idx=frame_idx,
353
+ num_frames=num_frames,
354
+ multigpu_buffer=feature_cache["multigpu_buffer"],
355
+ track_in_reverse=reverse,
356
+ # also get the SAM2 backbone features
357
+ return_tracker_backbone_feats=True,
358
+ # run NMS as a part of distributed computation
359
+ run_nms=self.det_nms_thresh > 0.0,
360
+ nms_prob_thresh=self.score_threshold_detection,
361
+ nms_iou_thresh=self.det_nms_thresh,
362
+ # pass max_frame_num_to_track to respect tracking limits
363
+ max_frame_num_to_track=max_frame_num_to_track,
364
+ propagate_in_video_start_frame_idx=start_frame_idx,
365
+ )
366
+ # note: detections in `sam3_image_out` has already gone through NMS
367
+ pred_probs = sam3_image_out["pred_logits"].squeeze(-1).sigmoid()
368
+ if not allow_new_detections:
369
+ pred_probs = pred_probs - 1e8 # make sure no detections are kept
370
+ pred_boxes_xyxy = sam3_image_out["pred_boxes_xyxy"]
371
+ pred_masks = sam3_image_out["pred_masks"]
372
+ # get the positive detection outputs above threshold
373
+ pos_pred_idx = torch.where(pred_probs > self.score_threshold_detection)
374
+ det_out = {
375
+ "bbox": pred_boxes_xyxy[pos_pred_idx[0], pos_pred_idx[1]],
376
+ "mask": pred_masks[pos_pred_idx[0], pos_pred_idx[1]],
377
+ "scores": pred_probs[pos_pred_idx[0], pos_pred_idx[1]],
378
+ }
379
+
380
+ # Step 3: build SAM2 backbone features and store them in `feature_cache`
381
+ backbone_cache = {}
382
+ sam_mask_decoder = self.tracker.sam_mask_decoder
383
+ tracker_backbone_fpn = [
384
+ sam_mask_decoder.conv_s0(sam3_image_out["tracker_backbone_fpn_0"]),
385
+ sam_mask_decoder.conv_s1(sam3_image_out["tracker_backbone_fpn_1"]),
386
+ sam3_image_out["tracker_backbone_fpn_2"], # fpn_2 doesn't need conv
387
+ ]
388
+ tracker_backbone_out = {
389
+ "vision_features": tracker_backbone_fpn[-1], # top-level feature
390
+ "vision_pos_enc": sam3_image_out["tracker_backbone_pos_enc"],
391
+ "backbone_fpn": tracker_backbone_fpn,
392
+ }
393
+ backbone_cache["tracker_backbone_out"] = tracker_backbone_out
394
+ feature_cache[frame_idx] = (
395
+ input_batch.img_batch[frame_idx],
396
+ backbone_cache,
397
+ )
398
+ # remove from `feature_cache` old features to save GPU memory
399
+ feature_cache.pop(frame_idx - 1 if not reverse else frame_idx + 1, None)
400
+ return det_out
401
+
402
+ def run_tracker_propagation(
403
+ self,
404
+ frame_idx: int,
405
+ num_frames: int,
406
+ reverse: bool,
407
+ tracker_states_local: List[Any],
408
+ tracker_metadata_prev: Dict[str, npt.NDArray],
409
+ ):
410
+ # Step 1: propagate the local SAM2 states to get the current frame's prediction
411
+ # `low_res_masks_local` of the existing masklets on this GPU
412
+ # - obj_ids_local: List[int] -- list of object IDs
413
+ # - low_res_masks_local: Tensor -- (num_local_obj, H_mask, W_mask)
414
+ obj_ids_local, low_res_masks_local, obj_scores_local = (
415
+ self._propogate_tracker_one_frame_local_gpu(
416
+ tracker_states_local, frame_idx=frame_idx, reverse=reverse
417
+ )
418
+ )
419
+
420
+ assert np.all(
421
+ obj_ids_local == tracker_metadata_prev["obj_ids_per_gpu"][self.rank]
422
+ ), "{} != {}".format(
423
+ obj_ids_local, tracker_metadata_prev["obj_ids_per_gpu"][self.rank]
424
+ )
425
+
426
+ # Step 2: all-gather `low_res_masks_local` into `low_res_masks_global`
427
+ # - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask)
428
+ _, H_mask, W_mask = low_res_masks_local.shape
429
+ if self.world_size > 1:
430
+ # `low_res_masks_local` and `obj_scores_local` need to be contiguous and float32
431
+ # (they could be non-contiguous due to slicing and/or bfloat16 due to autocast)
432
+ low_res_masks_local = low_res_masks_local.float().contiguous()
433
+ obj_scores_local = obj_scores_local.float().contiguous()
434
+ num_obj_this_gpu = tracker_metadata_prev["num_obj_per_gpu"][self.rank]
435
+ assert low_res_masks_local.size(0) == num_obj_this_gpu
436
+ assert obj_scores_local.size(0) == num_obj_this_gpu
437
+ low_res_masks_peers = [
438
+ low_res_masks_local.new_empty(num_obj, H_mask, W_mask)
439
+ for num_obj in tracker_metadata_prev["num_obj_per_gpu"]
440
+ ]
441
+ obj_scores_peers = [
442
+ obj_scores_local.new_empty(num_obj)
443
+ for num_obj in tracker_metadata_prev["num_obj_per_gpu"]
444
+ ]
445
+ dist.all_gather(low_res_masks_peers, low_res_masks_local)
446
+ dist.all_gather(obj_scores_peers, obj_scores_local)
447
+ low_res_masks_global = torch.cat(low_res_masks_peers, dim=0)
448
+ obj_scores_global = torch.cat(obj_scores_peers, dim=0)
449
+ else:
450
+ low_res_masks_global = low_res_masks_local
451
+ obj_scores_global = obj_scores_local
452
+ return low_res_masks_global, obj_scores_global
453
+
454
+ def _recondition_masklets(
455
+ self,
456
+ frame_idx,
457
+ det_out: Dict[str, Tensor],
458
+ trk_id_to_max_iou_high_conf_det: List[int],
459
+ tracker_states_local: List[Any],
460
+ tracker_metadata: Dict[str, npt.NDArray],
461
+ tracker_obj_scores_global: Tensor,
462
+ ):
463
+ # Recondition the masklets based on the new detections
464
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
465
+ new_mask = det_out["mask"][det_idx : det_idx + 1]
466
+ input_mask_res = self.tracker.input_mask_size
467
+ new_mask_binary = (
468
+ F.interpolate(
469
+ new_mask.unsqueeze(1),
470
+ size=(input_mask_res, input_mask_res),
471
+ mode="bilinear",
472
+ align_corners=False,
473
+ ).squeeze(1)[0]
474
+ > 0
475
+ )
476
+ HIGH_CONF_THRESH = 0.8
477
+ reconditioned_states_idx = set()
478
+ obj_idx = np.where(tracker_metadata["obj_ids_all_gpu"] == trk_obj_id)[
479
+ 0
480
+ ].item()
481
+ obj_score = tracker_obj_scores_global[obj_idx]
482
+ for state_idx, inference_state in enumerate(tracker_states_local):
483
+ if (
484
+ trk_obj_id in inference_state["obj_ids"]
485
+ # NOTE: Goal of this condition is to avoid reconditioning masks that are occluded/low qualiy.
486
+ # Unfortunately, these can get reconditioned anyway due to batching. We should consider removing these heuristics.
487
+ and obj_score > HIGH_CONF_THRESH
488
+ ):
489
+ logger.debug(
490
+ f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
491
+ )
492
+ self.tracker.add_new_mask(
493
+ inference_state=inference_state,
494
+ frame_idx=frame_idx,
495
+ obj_id=trk_obj_id,
496
+ mask=new_mask_binary,
497
+ )
498
+ reconditioned_states_idx.add(state_idx)
499
+
500
+ for idx in reconditioned_states_idx:
501
+ self.tracker.propagate_in_video_preflight(
502
+ tracker_states_local[idx], run_mem_encoder=True
503
+ )
504
+ return tracker_states_local
505
+
506
+ def run_tracker_update_planning_phase(
507
+ self,
508
+ frame_idx: int,
509
+ num_frames: int,
510
+ reverse: bool,
511
+ det_out: Dict[str, Tensor],
512
+ tracker_low_res_masks_global: Tensor,
513
+ tracker_obj_scores_global: Tensor,
514
+ tracker_metadata_prev: Dict[str, npt.NDArray],
515
+ tracker_states_local: List[Any],
516
+ is_image_only: bool = False,
517
+ ):
518
+ # initialize new metadata from previous metadata (its values will be updated later)
519
+ tracker_metadata_new = {
520
+ "obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
521
+ "obj_ids_all_gpu": None, # will be filled later
522
+ "num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
523
+ "obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
524
+ "obj_id_to_tracker_score_frame_wise": deepcopy(
525
+ tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]
526
+ ),
527
+ "obj_id_to_last_occluded": {}, # will be filled later
528
+ "max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
529
+ }
530
+
531
+ # Initialize reconditioned_obj_ids early to avoid UnboundLocalError
532
+ reconditioned_obj_ids = set()
533
+
534
+ # Step 1: make the update plan and resolve heuristics on GPU 0
535
+ det_mask_preds: Tensor = det_out["mask"] # low-res mask logits
536
+ det_scores_np: npt.NDArray = det_out["scores"].float().cpu().numpy()
537
+ det_bbox_xyxy: Tensor = det_out["bbox"]
538
+ if self.rank == 0:
539
+ # a) match detector and tracker masks and find new objects
540
+ (
541
+ new_det_fa_inds,
542
+ unmatched_trk_obj_ids,
543
+ det_to_matched_trk_obj_ids,
544
+ trk_id_to_max_iou_high_conf_det,
545
+ empty_trk_obj_ids,
546
+ ) = self._associate_det_trk(
547
+ det_masks=det_mask_preds,
548
+ det_scores_np=det_scores_np,
549
+ trk_masks=tracker_low_res_masks_global,
550
+ trk_obj_ids=tracker_metadata_prev["obj_ids_all_gpu"],
551
+ )
552
+ if self.suppress_det_close_to_boundary:
553
+ keep = self._suppress_detections_close_to_boundary(
554
+ det_bbox_xyxy[new_det_fa_inds]
555
+ )
556
+ new_det_fa_inds = new_det_fa_inds[keep.cpu().numpy()]
557
+
558
+ # check whether we've hit the maximum number of objects we can track (and if so, drop some detections)
559
+ prev_obj_num = np.sum(tracker_metadata_prev["num_obj_per_gpu"])
560
+ new_det_num = len(new_det_fa_inds)
561
+ num_obj_dropped_due_to_limit = 0
562
+ if not is_image_only and prev_obj_num + new_det_num > self.max_num_objects:
563
+ logger.warning(
564
+ f"hitting {self.max_num_objects=} with {new_det_num=} and {prev_obj_num=}"
565
+ )
566
+ new_det_num_to_keep = self.max_num_objects - prev_obj_num
567
+ num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
568
+ new_det_fa_inds = self._drop_new_det_with_obj_limit(
569
+ new_det_fa_inds, det_scores_np, new_det_num_to_keep
570
+ )
571
+ assert len(new_det_fa_inds) == new_det_num_to_keep
572
+ new_det_num = len(new_det_fa_inds)
573
+
574
+ # assign object IDs to new detections and decide which GPU to place them
575
+ new_det_start_obj_id = tracker_metadata_prev["max_obj_id"] + 1
576
+ new_det_obj_ids = new_det_start_obj_id + np.arange(new_det_num)
577
+ prev_workload_per_gpu = tracker_metadata_prev["num_obj_per_gpu"]
578
+ new_det_gpu_ids = self._assign_new_det_to_gpus(
579
+ new_det_num=new_det_num,
580
+ prev_workload_per_gpu=prev_workload_per_gpu,
581
+ )
582
+
583
+ # b) handle hotstart heuristics to remove objects
584
+ # here `rank0_metadata` contains metadata stored on (and only accessible to) GPU 0;
585
+ # we avoid broadcasting them to other GPUs to save communication cost, assuming
586
+ # that `rank0_metadata` is not needed by other GPUs
587
+ rank0_metadata_new = deepcopy(tracker_metadata_prev["rank0_metadata"])
588
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
589
+ obj_ids_newly_removed, rank0_metadata_new = self._process_hotstart(
590
+ frame_idx=frame_idx,
591
+ num_frames=num_frames,
592
+ reverse=reverse,
593
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
594
+ new_det_obj_ids=new_det_obj_ids,
595
+ empty_trk_obj_ids=empty_trk_obj_ids,
596
+ unmatched_trk_obj_ids=unmatched_trk_obj_ids,
597
+ rank0_metadata=rank0_metadata_new,
598
+ tracker_metadata=tracker_metadata_prev,
599
+ )
600
+ else:
601
+ # if warm-up is not complete, we don't remove any objects
602
+ obj_ids_newly_removed = set()
603
+ tracker_metadata_new["rank0_metadata"] = rank0_metadata_new
604
+
605
+ # Step 2: broadcast the update plan to other GPUs
606
+ NUM_BROADCAST_ITEMS = 9
607
+ if self.rank == 0 and self.world_size > 1:
608
+ # `num_obj_per_gpu_on_rank0` is used for metadata consistency check on other GPUs
609
+ # (it's a small array with length==self.world_size, so broadcasting it is cheap)
610
+ num_obj_per_gpu_on_rank0 = tracker_metadata_prev["num_obj_per_gpu"]
611
+ update_plan = [
612
+ new_det_fa_inds,
613
+ new_det_obj_ids,
614
+ new_det_gpu_ids,
615
+ num_obj_per_gpu_on_rank0,
616
+ unmatched_trk_obj_ids,
617
+ det_to_matched_trk_obj_ids,
618
+ obj_ids_newly_removed,
619
+ num_obj_dropped_due_to_limit,
620
+ trk_id_to_max_iou_high_conf_det,
621
+ ]
622
+ assert len(update_plan) == NUM_BROADCAST_ITEMS, (
623
+ f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
624
+ )
625
+ self.broadcast_python_obj_cpu(update_plan, src=0)
626
+ elif self.rank > 0 and self.world_size > 1:
627
+ update_plan = [
628
+ None
629
+ ] * NUM_BROADCAST_ITEMS # other ranks receive the plan from rank 0
630
+ self.broadcast_python_obj_cpu(update_plan, src=0)
631
+ (
632
+ new_det_fa_inds,
633
+ new_det_obj_ids,
634
+ new_det_gpu_ids,
635
+ num_obj_per_gpu_on_rank0,
636
+ unmatched_trk_obj_ids,
637
+ det_to_matched_trk_obj_ids,
638
+ obj_ids_newly_removed,
639
+ num_obj_dropped_due_to_limit,
640
+ trk_id_to_max_iou_high_conf_det,
641
+ ) = update_plan
642
+ # metadata consistency check: verify that the received `num_obj_per_gpu_on_rank0` is consistent with the local metadata
643
+ # it's critical that all GPUs agree on the previous number of objects (otherwise the inference might hang or fail silently)
644
+ if not np.all(
645
+ num_obj_per_gpu_on_rank0 == tracker_metadata_prev["num_obj_per_gpu"]
646
+ ):
647
+ raise RuntimeError(
648
+ f"{self.rank=} received {num_obj_per_gpu_on_rank0=}, which is inconsistent with local record "
649
+ f"{tracker_metadata_prev['num_obj_per_gpu']=}. There's likely a bug in update planning or execution."
650
+ )
651
+
652
+ # `tracker_update_plan` should be identical on all GPUs after broadcasting
653
+ tracker_update_plan = {
654
+ "new_det_fa_inds": new_det_fa_inds, # npt.NDArray
655
+ "new_det_obj_ids": new_det_obj_ids, # npt.NDArray
656
+ "new_det_gpu_ids": new_det_gpu_ids, # npt.NDArray
657
+ "unmatched_trk_obj_ids": unmatched_trk_obj_ids, # npt.NDArray
658
+ "det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
659
+ "obj_ids_newly_removed": obj_ids_newly_removed, # set
660
+ "num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
661
+ "trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
662
+ "reconditioned_obj_ids": reconditioned_obj_ids, # set
663
+ }
664
+
665
+ # Step 3 (optional): recondition masklets based on high-confidence detections before memory encoding
666
+ # NOTE: Running this in execution phase (after memory encoding) can lead to suboptimal results
667
+ should_recondition_iou = False
668
+
669
+ # Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
670
+ if (
671
+ self.reconstruction_bbox_iou_thresh > 0
672
+ and len(trk_id_to_max_iou_high_conf_det) > 0
673
+ ):
674
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
675
+ det_box = det_out["bbox"][det_idx]
676
+ det_score = det_out["scores"][det_idx]
677
+
678
+ try:
679
+ trk_idx = list(tracker_metadata_prev["obj_ids_all_gpu"]).index(
680
+ trk_obj_id
681
+ )
682
+ except ValueError:
683
+ continue # Skip if tracklet not found
684
+
685
+ tracker_mask = tracker_low_res_masks_global[trk_idx]
686
+ mask_binary = tracker_mask > 0
687
+ mask_area = mask_binary.sum().item()
688
+
689
+ if mask_area == 0:
690
+ continue # Skip tracklets with zero mask area
691
+
692
+ # Get bounding box from SAM2 mask and convert to normalized coordinates
693
+ tracker_box_pixels = (
694
+ mask_to_box(mask_binary.unsqueeze(0).unsqueeze(0))
695
+ .squeeze(0)
696
+ .squeeze(0)
697
+ )
698
+ mask_height, mask_width = tracker_mask.shape[-2:]
699
+ tracker_box_normalized = torch.tensor(
700
+ [
701
+ tracker_box_pixels[0] / mask_width,
702
+ tracker_box_pixels[1] / mask_height,
703
+ tracker_box_pixels[2] / mask_width,
704
+ tracker_box_pixels[3] / mask_height,
705
+ ],
706
+ device=tracker_box_pixels.device,
707
+ )
708
+
709
+ # Compute IoU between detection and SAM2 tracklet bounding boxes
710
+ det_box_batch = det_box.unsqueeze(0)
711
+ tracker_box_batch = tracker_box_normalized.unsqueeze(0)
712
+ iou = fast_diag_box_iou(det_box_batch, tracker_box_batch)[0]
713
+
714
+ if (
715
+ iou < self.reconstruction_bbox_iou_thresh
716
+ and det_score >= self.reconstruction_bbox_det_score
717
+ ):
718
+ should_recondition_iou = True
719
+ reconditioned_obj_ids.add(trk_obj_id)
720
+
721
+ should_recondition_periodic = (
722
+ self.recondition_every_nth_frame > 0
723
+ and frame_idx % self.recondition_every_nth_frame == 0
724
+ and len(trk_id_to_max_iou_high_conf_det) > 0
725
+ )
726
+
727
+ # Recondition if periodic or IoU condition met
728
+ if should_recondition_periodic or should_recondition_iou:
729
+ self._recondition_masklets(
730
+ frame_idx,
731
+ det_out,
732
+ trk_id_to_max_iou_high_conf_det,
733
+ tracker_states_local,
734
+ tracker_metadata_prev,
735
+ tracker_obj_scores_global,
736
+ )
737
+
738
+ # Step 4: Run SAM2 memory encoder on the current frame's prediction masks
739
+ # This is done on all GPUs
740
+ batch_size = tracker_low_res_masks_global.size(0)
741
+ if batch_size > 0:
742
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
743
+ if self.suppress_overlapping_based_on_recent_occlusion_threshold > 0.0:
744
+ # NOTE: tracker_low_res_masks_global is updated in-place then returned
745
+ tracker_low_res_masks_global = (
746
+ self._suppress_overlapping_based_on_recent_occlusion(
747
+ frame_idx,
748
+ tracker_low_res_masks_global,
749
+ tracker_metadata_prev,
750
+ tracker_metadata_new,
751
+ obj_ids_newly_removed,
752
+ reverse,
753
+ )
754
+ )
755
+
756
+ self._tracker_update_memories(
757
+ tracker_states_local,
758
+ frame_idx,
759
+ tracker_metadata=tracker_metadata_prev,
760
+ low_res_masks=tracker_low_res_masks_global,
761
+ )
762
+
763
+ # Step 4: update the SAM2 metadata based on the update plan
764
+ # note: except for "rank0_metadata" (that is only available on GPU 0),
765
+ # the updated `tracker_metadata_new` should be identical on all GPUs
766
+ for rank in range(self.world_size):
767
+ new_det_obj_ids_this_gpu = new_det_obj_ids[new_det_gpu_ids == rank]
768
+ updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids_per_gpu"][rank]
769
+ if len(new_det_obj_ids_this_gpu) > 0:
770
+ updated_obj_ids_this_gpu = np.concatenate(
771
+ [updated_obj_ids_this_gpu, new_det_obj_ids_this_gpu]
772
+ )
773
+ if len(obj_ids_newly_removed) > 0:
774
+ is_removed = np.isin(
775
+ updated_obj_ids_this_gpu, list(obj_ids_newly_removed)
776
+ )
777
+ updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
778
+ tracker_metadata_new["obj_ids_per_gpu"][rank] = updated_obj_ids_this_gpu
779
+ tracker_metadata_new["num_obj_per_gpu"][rank] = len(
780
+ updated_obj_ids_this_gpu
781
+ )
782
+ tracker_metadata_new["obj_ids_all_gpu"] = np.concatenate(
783
+ tracker_metadata_new["obj_ids_per_gpu"]
784
+ )
785
+ # update object scores and the maximum object ID assigned so far
786
+ if len(new_det_obj_ids) > 0:
787
+ tracker_metadata_new["obj_id_to_score"].update(
788
+ zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
789
+ )
790
+ # tracker scores are not available for new objects, use det score instead.
791
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
792
+ frame_idx
793
+ ].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
794
+ tracker_metadata_new["max_obj_id"] = max(
795
+ tracker_metadata_new["max_obj_id"],
796
+ np.max(new_det_obj_ids),
797
+ )
798
+ # for removed objects, we set their scores to a very low value (-1e4) but still
799
+ # keep them in "obj_id_to_score" (it's easier to handle outputs this way)
800
+ for obj_id in obj_ids_newly_removed:
801
+ tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
802
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][
803
+ obj_id
804
+ ] = -1e4
805
+ tracker_metadata_new["obj_id_to_last_occluded"].pop(obj_id, None)
806
+ # check that "rank0_metadata" is in tracker_metadata_new if and only if it's GPU 0
807
+ assert ("rank0_metadata" in tracker_metadata_new) == (self.rank == 0)
808
+ if self.rank == 0 and self.masklet_confirmation_enable:
809
+ rank0_metadata = self.update_masklet_confirmation_status(
810
+ rank0_metadata=tracker_metadata_new["rank0_metadata"],
811
+ obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids_all_gpu"],
812
+ obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids_all_gpu"],
813
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
814
+ new_det_obj_ids=new_det_obj_ids,
815
+ )
816
+ tracker_metadata_new["rank0_metadata"] = rank0_metadata
817
+
818
+ return tracker_update_plan, tracker_metadata_new
819
+
820
+ def _suppress_overlapping_based_on_recent_occlusion(
821
+ self,
822
+ frame_idx: int,
823
+ tracker_low_res_masks_global: Tensor,
824
+ tracker_metadata_prev: Dict[str, Any],
825
+ tracker_metadata_new: Dict[str, Any],
826
+ obj_ids_newly_removed: Set[int],
827
+ reverse: bool = False,
828
+ ):
829
+ """
830
+ Suppress overlapping masks based on the most recent occlusion information. If an object is removed by hotstart, we always suppress it if it overlaps with any other object.
831
+ Args:
832
+ frame_idx (int): The current frame index.
833
+ tracker_low_res_masks_global (Tensor): The low-resolution masks for the current frame.
834
+ tracker_metadata_prev (Dict[str, Any]): The metadata from the previous frame.
835
+ tracker_metadata_new (Dict[str, Any]): The metadata for the current frame.
836
+ obj_ids_newly_removed (Set[int]): The object IDs that have been removed.
837
+ Return:
838
+ Tensor: The updated low-resolution masks with some objects suppressed.
839
+ """
840
+ obj_ids_global = tracker_metadata_prev["obj_ids_all_gpu"]
841
+ binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
842
+ batch_size = tracker_low_res_masks_global.size(0)
843
+ if batch_size > 0:
844
+ assert len(obj_ids_global) == batch_size, (
845
+ f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
846
+ )
847
+ NEVER_OCCLUDED = -1
848
+ ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
849
+ last_occluded_prev = torch.cat(
850
+ [
851
+ tracker_metadata_prev["obj_id_to_last_occluded"].get(
852
+ obj_id,
853
+ torch.full(
854
+ (1,),
855
+ fill_value=(
856
+ NEVER_OCCLUDED
857
+ if obj_id not in obj_ids_newly_removed
858
+ else ALWAYS_OCCLUDED
859
+ ),
860
+ device=binary_tracker_low_res_masks_global.device,
861
+ dtype=torch.long,
862
+ ),
863
+ )
864
+ for obj_id in obj_ids_global
865
+ ],
866
+ dim=0,
867
+ )
868
+ to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
869
+ binary_tracker_low_res_masks_global,
870
+ last_occluded_prev,
871
+ obj_ids_global,
872
+ frame_idx,
873
+ reverse,
874
+ )
875
+
876
+ # Update metadata with occlusion information
877
+ is_obj_occluded = ~(binary_tracker_low_res_masks_global.any(dim=(-1, -2)))
878
+ is_obj_occluded_or_suppressed = is_obj_occluded | to_suppress
879
+ last_occluded_new = last_occluded_prev.clone()
880
+ last_occluded_new[is_obj_occluded_or_suppressed] = frame_idx
881
+ # Slice out the last occluded frame for each object
882
+ tracker_metadata_new["obj_id_to_last_occluded"] = {
883
+ obj_id: last_occluded_new[obj_idx : obj_idx + 1]
884
+ for obj_idx, obj_id in enumerate(obj_ids_global)
885
+ }
886
+
887
+ # Zero out suppressed masks before memory encoding
888
+ NO_OBJ_LOGIT = -10
889
+ tracker_low_res_masks_global[to_suppress] = NO_OBJ_LOGIT
890
+
891
+ return tracker_low_res_masks_global
892
+
893
+ def run_tracker_update_execution_phase(
894
+ self,
895
+ frame_idx: int,
896
+ num_frames: int,
897
+ reverse: bool,
898
+ det_out: Dict[str, Tensor],
899
+ tracker_states_local: List[Any],
900
+ tracker_update_plan: Dict[str, npt.NDArray],
901
+ orig_vid_height: int,
902
+ orig_vid_width: int,
903
+ feature_cache: Dict,
904
+ ):
905
+ # initialize tracking scores with detection scores
906
+ new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
907
+ new_det_obj_ids: npt.NDArray = tracker_update_plan["new_det_obj_ids"]
908
+ new_det_gpu_ids: npt.NDArray = tracker_update_plan["new_det_gpu_ids"]
909
+ is_on_this_gpu: npt.NDArray = new_det_gpu_ids == self.rank
910
+ new_det_obj_ids_local: npt.NDArray = new_det_obj_ids[is_on_this_gpu]
911
+ new_det_fa_inds_local: npt.NDArray = new_det_fa_inds[is_on_this_gpu]
912
+ obj_ids_newly_removed: Set[int] = tracker_update_plan["obj_ids_newly_removed"]
913
+
914
+ # Step 1: add new objects from the detector to SAM2 inference states
915
+ if len(new_det_fa_inds_local) > 0:
916
+ new_det_fa_inds_local_t = torch.from_numpy(new_det_fa_inds_local)
917
+ new_det_masks: Tensor = det_out["mask"][new_det_fa_inds_local_t]
918
+ # initialize SAM2 with new object masks
919
+ tracker_states_local = self._tracker_add_new_objects(
920
+ frame_idx=frame_idx,
921
+ num_frames=num_frames,
922
+ new_obj_ids=new_det_obj_ids_local,
923
+ new_obj_masks=new_det_masks,
924
+ tracker_states_local=tracker_states_local,
925
+ orig_vid_height=orig_vid_height,
926
+ orig_vid_width=orig_vid_width,
927
+ feature_cache=feature_cache,
928
+ )
929
+
930
+ # Step 2: remove from SAM2 inference states those objects removed by heuristics
931
+ if len(obj_ids_newly_removed) > 0:
932
+ self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
933
+
934
+ return tracker_states_local
935
+
936
+ def build_outputs(
937
+ self,
938
+ frame_idx: int,
939
+ num_frames: int,
940
+ reverse: bool,
941
+ det_out: Dict[str, Tensor],
942
+ tracker_low_res_masks_global: Tensor,
943
+ tracker_obj_scores_global: Tensor,
944
+ tracker_metadata_prev: Dict[str, npt.NDArray],
945
+ tracker_update_plan: Dict[str, npt.NDArray],
946
+ orig_vid_height: int,
947
+ orig_vid_width: int,
948
+ reconditioned_obj_ids: set = None,
949
+ det_to_matched_trk_obj_ids: dict = None,
950
+ ):
951
+ new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
952
+ new_det_obj_ids: npt.NDArray = tracker_update_plan["new_det_obj_ids"]
953
+ obj_id_to_mask = {} # obj_id --> output mask tensor
954
+
955
+ # Part 1: masks from previous SAM2 propagation
956
+ existing_masklet_obj_ids = tracker_metadata_prev["obj_ids_all_gpu"]
957
+ existing_masklet_video_res_masks = F.interpolate(
958
+ tracker_low_res_masks_global.unsqueeze(1),
959
+ size=(orig_vid_height, orig_vid_width),
960
+ mode="bilinear",
961
+ align_corners=False,
962
+ ) # (num_obj, 1, H_video, W_video)
963
+ existing_masklet_binary = existing_masklet_video_res_masks > 0
964
+ assert len(existing_masklet_obj_ids) == len(existing_masklet_binary)
965
+ for obj_id, mask in zip(existing_masklet_obj_ids, existing_masklet_binary):
966
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
967
+
968
+ # Part 2: masks from new detections
969
+ new_det_fa_inds_t = torch.from_numpy(new_det_fa_inds)
970
+ new_det_low_res_masks = det_out["mask"][new_det_fa_inds_t].unsqueeze(1)
971
+ new_det_low_res_masks = fill_holes_in_mask_scores(
972
+ new_det_low_res_masks,
973
+ max_area=self.fill_hole_area,
974
+ fill_holes=True,
975
+ remove_sprinkles=True,
976
+ )
977
+ new_masklet_video_res_masks = F.interpolate(
978
+ new_det_low_res_masks,
979
+ size=(orig_vid_height, orig_vid_width),
980
+ mode="bilinear",
981
+ align_corners=False,
982
+ ) # (num_obj, 1, H_video, W_video)
983
+
984
+ new_masklet_binary = new_masklet_video_res_masks > 0
985
+ assert len(new_det_obj_ids) == len(new_masklet_video_res_masks)
986
+ for obj_id, mask in zip(new_det_obj_ids, new_masklet_binary):
987
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
988
+
989
+ # Part 3: Override masks for reconditioned objects using detection masks
990
+ if reconditioned_obj_ids is not None and len(reconditioned_obj_ids) > 0:
991
+ trk_id_to_max_iou_high_conf_det = tracker_update_plan.get(
992
+ "trk_id_to_max_iou_high_conf_det", {}
993
+ )
994
+
995
+ for obj_id in reconditioned_obj_ids:
996
+ det_idx = trk_id_to_max_iou_high_conf_det.get(obj_id)
997
+
998
+ if det_idx is not None:
999
+ det_mask = det_out["mask"][det_idx]
1000
+ det_mask = det_mask.unsqueeze(0).unsqueeze(0)
1001
+ det_mask_resized = (
1002
+ F.interpolate(
1003
+ det_mask.float(),
1004
+ size=(orig_vid_height, orig_vid_width),
1005
+ mode="bilinear",
1006
+ align_corners=False,
1007
+ )
1008
+ > 0
1009
+ )
1010
+
1011
+ det_mask_final = det_mask_resized.squeeze(0)
1012
+ obj_id_to_mask[obj_id] = det_mask_final
1013
+
1014
+ return obj_id_to_mask
1015
+
1016
+ def _get_objects_to_suppress_based_on_most_recently_occluded(
1017
+ self,
1018
+ binary_low_res_masks: Tensor,
1019
+ last_occluded: List[int],
1020
+ obj_ids: List[int],
1021
+ frame_idx: int = None,
1022
+ reverse: bool = False,
1023
+ ):
1024
+ # Suppress overlapping masks for objects that were most recently occluded
1025
+ assert binary_low_res_masks.dtype == torch.bool, (
1026
+ f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
1027
+ )
1028
+ to_suppress = torch.zeros(
1029
+ binary_low_res_masks.size(0),
1030
+ device=binary_low_res_masks.device,
1031
+ dtype=torch.bool,
1032
+ )
1033
+ if len(obj_ids) <= 1:
1034
+ return to_suppress
1035
+
1036
+ iou = mask_iou(binary_low_res_masks, binary_low_res_masks) # [N,N]
1037
+
1038
+ # Create masks for upper triangular matrix (i < j) and IoU threshold
1039
+ mask_iou_thresh = (
1040
+ iou >= self.suppress_overlapping_based_on_recent_occlusion_threshold
1041
+ )
1042
+ overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
1043
+
1044
+ last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
1045
+ last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
1046
+ # Suppress most recently occluded
1047
+ cmp_op = torch.gt if not reverse else torch.lt
1048
+ suppress_i_mask = (
1049
+ overlapping_pairs
1050
+ & cmp_op(
1051
+ last_occ_expanded_i, last_occ_expanded_j
1052
+ ) # (last_occ_expanded_i > last_occ_expanded_j)
1053
+ & (
1054
+ last_occ_expanded_j > -1
1055
+ ) # j can suppress i only if i was previously occluded
1056
+ )
1057
+ suppress_j_mask = (
1058
+ overlapping_pairs
1059
+ & cmp_op(last_occ_expanded_j, last_occ_expanded_i)
1060
+ & (
1061
+ last_occ_expanded_i > -1
1062
+ ) # i can suppress j only if j was previously occluded
1063
+ )
1064
+ # Apply suppression
1065
+ to_suppress = suppress_i_mask.any(dim=1) | suppress_j_mask.any(dim=0)
1066
+
1067
+ # Log for debugging
1068
+ if (
1069
+ self.rank == 0
1070
+ and logger.isEnabledFor(logging.DEBUG)
1071
+ and frame_idx is not None
1072
+ ):
1073
+ suppress_i_mask = suppress_i_mask.cpu().numpy()
1074
+ suppress_j_mask = suppress_j_mask.cpu().numpy()
1075
+ last_occluded = last_occluded.cpu().numpy()
1076
+
1077
+ # Find all suppression pairs without using torch.where
1078
+ batch_size = suppress_i_mask.shape[0]
1079
+
1080
+ # Log i-suppression cases (where i gets suppressed in favor of j)
1081
+ for i in range(batch_size):
1082
+ for j in range(batch_size):
1083
+ if suppress_i_mask[i, j]:
1084
+ logger.debug(
1085
+ f"{frame_idx=}: Suppressing obj {obj_ids[i]} last occluded {last_occluded[i]} in favor of {obj_ids[j]} last occluded {last_occluded[j]}"
1086
+ )
1087
+
1088
+ # Log j-suppression cases (where j gets suppressed in favor of i)
1089
+ for i in range(batch_size):
1090
+ for j in range(batch_size):
1091
+ if suppress_j_mask[i, j]:
1092
+ logger.debug(
1093
+ f"{frame_idx=}: Suppressing obj {obj_ids[j]} last occluded {last_occluded[j]} in favor of {obj_ids[i]} last occluded {last_occluded[i]}"
1094
+ )
1095
+
1096
+ return to_suppress
1097
+
1098
+ def _propogate_tracker_one_frame_local_gpu(
1099
+ self,
1100
+ inference_states: List[Any],
1101
+ frame_idx: int,
1102
+ reverse: bool,
1103
+ # by default, we disable memory encoding until we gather all outputs
1104
+ run_mem_encoder: bool = False,
1105
+ ):
1106
+ """
1107
+ inference_states: List of inference states, each state corresponds to a different set of objects.
1108
+ """
1109
+ obj_ids_local = []
1110
+ low_res_masks_list = []
1111
+ obj_scores_list = []
1112
+ for inference_state in inference_states:
1113
+ if len(inference_state["obj_ids"]) == 0:
1114
+ continue # skip propagation on empty inference states
1115
+
1116
+ # propagate one frame
1117
+ num_frames_propagated = 0
1118
+ for out in self.tracker.propagate_in_video(
1119
+ inference_state,
1120
+ start_frame_idx=frame_idx,
1121
+ # end_frame_idx = start_frame_idx + max_frame_num_to_track
1122
+ # (i.e. propagating 1 frame since end_frame_idx is inclusive)
1123
+ max_frame_num_to_track=0,
1124
+ reverse=reverse,
1125
+ tqdm_disable=True,
1126
+ run_mem_encoder=run_mem_encoder,
1127
+ ):
1128
+ out_frame_idx, out_obj_ids, out_low_res_masks, _, out_obj_scores = out
1129
+ num_frames_propagated += 1
1130
+
1131
+ # only 1 frames should be propagated
1132
+ assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
1133
+ f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
1134
+ )
1135
+ assert isinstance(out_obj_ids, list)
1136
+ obj_ids_local.extend(out_obj_ids)
1137
+ low_res_masks_list.append(out_low_res_masks.squeeze(1))
1138
+ obj_scores_list.append(out_obj_scores.squeeze(1))
1139
+
1140
+ # concatenate the output masklets from all local inference states
1141
+ H_mask = W_mask = self.tracker.low_res_mask_size
1142
+ if len(low_res_masks_list) > 0:
1143
+ low_res_masks_local = torch.cat(low_res_masks_list, dim=0)
1144
+ obj_scores_local = torch.cat(obj_scores_list, dim=0)
1145
+ assert low_res_masks_local.shape[1:] == (H_mask, W_mask)
1146
+
1147
+ # Apply hole filling to the masks
1148
+ low_res_masks_local = fill_holes_in_mask_scores(
1149
+ low_res_masks_local.unsqueeze(1),
1150
+ max_area=self.fill_hole_area,
1151
+ fill_holes=True,
1152
+ remove_sprinkles=True,
1153
+ )
1154
+ low_res_masks_local = low_res_masks_local.squeeze(1)
1155
+ else:
1156
+ low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
1157
+ obj_scores_local = torch.zeros(0, device=self.device)
1158
+
1159
+ return obj_ids_local, low_res_masks_local, obj_scores_local
1160
+
1161
+ def _associate_det_trk(
1162
+ self,
1163
+ det_masks: Tensor,
1164
+ det_scores_np: npt.NDArray,
1165
+ trk_masks: Tensor,
1166
+ trk_obj_ids: npt.NDArray,
1167
+ ):
1168
+ """
1169
+ Match detections on the current frame with the existing masklets.
1170
+
1171
+ Args:
1172
+ - det_masks: (N, H, W) tensor of predicted masks
1173
+ - det_scores_np: (N,) array of detection scores
1174
+ - trk_masks: (M, H, W) tensor of track masks
1175
+ - trk_obj_ids: (M,) array of object IDs corresponding to trk_masks
1176
+
1177
+ Returns:
1178
+ - new_det_fa_inds: array of new object indices.
1179
+ - unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched
1180
+ to any detections on this frame (for unmatched, we only count masklets with >0 area)
1181
+ - det_to_matched_trk_obj_ids: dict[int, npt.NDArray]: mapping from detector's detection indices
1182
+ to the list of matched tracklet object IDs
1183
+ - empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
1184
+ """
1185
+ iou_threshold = self.assoc_iou_thresh
1186
+ iou_threshold_trk = self.trk_assoc_iou_thresh
1187
+ new_det_thresh = self.new_det_thresh
1188
+
1189
+ assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
1190
+ assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
1191
+ assert trk_masks.size(0) == len(trk_obj_ids), (
1192
+ f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
1193
+ )
1194
+ if trk_masks.size(0) == 0:
1195
+ # all detections are new
1196
+ new_det_fa_inds = np.arange(det_masks.size(0))
1197
+ unmatched_trk_obj_ids = np.array([], np.int64)
1198
+ empty_trk_obj_ids = np.array([], np.int64)
1199
+ det_to_matched_trk_obj_ids = {}
1200
+ trk_id_to_max_iou_high_conf_det = {}
1201
+ return (
1202
+ new_det_fa_inds,
1203
+ unmatched_trk_obj_ids,
1204
+ det_to_matched_trk_obj_ids,
1205
+ trk_id_to_max_iou_high_conf_det,
1206
+ empty_trk_obj_ids,
1207
+ )
1208
+ elif det_masks.size(0) == 0:
1209
+ # all previous tracklets are unmatched if they have a non-zero area
1210
+ new_det_fa_inds = np.array([], np.int64)
1211
+ trk_is_nonempty = (trk_masks > 0).any(dim=(1, 2)).cpu().numpy()
1212
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_nonempty]
1213
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
1214
+ det_to_matched_trk_obj_ids = {}
1215
+ trk_id_to_max_iou_high_conf_det = {}
1216
+ return (
1217
+ new_det_fa_inds,
1218
+ unmatched_trk_obj_ids,
1219
+ det_to_matched_trk_obj_ids,
1220
+ trk_id_to_max_iou_high_conf_det,
1221
+ empty_trk_obj_ids,
1222
+ )
1223
+
1224
+ if det_masks.shape[-2:] != trk_masks.shape[-2:]:
1225
+ # resize to the smaller size to save GPU memory
1226
+ if np.prod(det_masks.shape[-2:]) < np.prod(trk_masks.shape[-2:]):
1227
+ trk_masks = F.interpolate(
1228
+ trk_masks.unsqueeze(1),
1229
+ size=det_masks.shape[-2:],
1230
+ mode="bilinear",
1231
+ align_corners=False,
1232
+ ).squeeze(1)
1233
+ else:
1234
+ # resize detections to track size
1235
+ det_masks = F.interpolate(
1236
+ det_masks.unsqueeze(1),
1237
+ size=trk_masks.shape[-2:],
1238
+ mode="bilinear",
1239
+ align_corners=False,
1240
+ ).squeeze(1)
1241
+
1242
+ det_masks_binary = det_masks > 0
1243
+ trk_masks_binary = trk_masks > 0
1244
+ ious = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
1245
+
1246
+ ious_np = ious.cpu().numpy()
1247
+ if self.o2o_matching_masklets_enable:
1248
+ from scipy.optimize import linear_sum_assignment
1249
+
1250
+ # Hungarian matching for tracks (one-to-one: each track matches at most one detection)
1251
+ cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
1252
+ row_ind, col_ind = linear_sum_assignment(cost_matrix)
1253
+ trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
1254
+ for d, t in zip(row_ind, col_ind):
1255
+ if ious_np[d, t] >= iou_threshold_trk:
1256
+ trk_is_matched[t] = True
1257
+ else:
1258
+ trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
1259
+ # Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
1260
+ trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
1261
+ trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
1262
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
1263
+ # also record masklets that have zero area in SAM 2 prediction
1264
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
1265
+
1266
+ # For detections: allow many tracks to match to the same detection (many-to-one)
1267
+ # So, a detection is 'new' if it does not match any track above threshold
1268
+ is_new_det = np.logical_and(
1269
+ det_scores_np >= new_det_thresh,
1270
+ np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
1271
+ )
1272
+ new_det_fa_inds = np.nonzero(is_new_det)[0]
1273
+
1274
+ # for each detection, which tracks it matched to (above threshold)
1275
+ det_to_matched_trk_obj_ids = {}
1276
+ trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
1277
+ HIGH_CONF_THRESH = 0.8
1278
+ HIGH_IOU_THRESH = 0.8
1279
+ det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
1280
+ det_is_high_conf = (det_scores_np >= HIGH_CONF_THRESH) & ~is_new_det
1281
+ det_is_high_iou = np.max(ious_np, axis=1) >= HIGH_IOU_THRESH
1282
+ det_is_high_conf_and_iou = set(
1283
+ np.nonzero(det_is_high_conf & det_is_high_iou)[0]
1284
+ )
1285
+ for d in range(det_masks.size(0)):
1286
+ det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
1287
+ if d in det_is_high_conf_and_iou:
1288
+ trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
1289
+ trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
1290
+
1291
+ return (
1292
+ new_det_fa_inds,
1293
+ unmatched_trk_obj_ids,
1294
+ det_to_matched_trk_obj_ids,
1295
+ trk_id_to_max_iou_high_conf_det,
1296
+ empty_trk_obj_ids,
1297
+ )
1298
+
1299
+ def _assign_new_det_to_gpus(self, new_det_num, prev_workload_per_gpu):
1300
+ """Distribute the new objects to the GPUs with the least workload."""
1301
+ workload_per_gpu: npt.NDArray = prev_workload_per_gpu.copy()
1302
+ new_det_gpu_ids = np.zeros(new_det_num, np.int64)
1303
+
1304
+ # assign the objects one by one
1305
+ for i in range(len(new_det_gpu_ids)):
1306
+ # find the GPU with the least workload
1307
+ min_gpu = np.argmin(workload_per_gpu)
1308
+ new_det_gpu_ids[i] = min_gpu
1309
+ workload_per_gpu[min_gpu] += 1
1310
+ return new_det_gpu_ids
1311
+
1312
+ def _process_hotstart(
1313
+ self,
1314
+ frame_idx: int,
1315
+ num_frames: int,
1316
+ reverse: bool,
1317
+ det_to_matched_trk_obj_ids: Dict[int, npt.NDArray],
1318
+ new_det_obj_ids: npt.NDArray,
1319
+ empty_trk_obj_ids: npt.NDArray,
1320
+ unmatched_trk_obj_ids: npt.NDArray,
1321
+ rank0_metadata: Dict[str, Any],
1322
+ tracker_metadata: Dict[str, Any],
1323
+ ):
1324
+ """Handle hotstart heuristics to remove unmatched or duplicated objects."""
1325
+ # obj_id --> first frame index where the object was detected
1326
+ obj_first_frame_idx = rank0_metadata["obj_first_frame_idx"]
1327
+ # obj_id --> [mismatched frame indices]
1328
+ unmatched_frame_inds = rank0_metadata["unmatched_frame_inds"]
1329
+ trk_keep_alive = rank0_metadata["trk_keep_alive"]
1330
+ # (first_appear_obj_id, obj_id) --> [overlap frame indices]
1331
+ overlap_pair_to_frame_inds = rank0_metadata["overlap_pair_to_frame_inds"]
1332
+ # removed_obj_ids: object IDs that are suppressed via hot-start
1333
+ removed_obj_ids = rank0_metadata["removed_obj_ids"]
1334
+ suppressed_obj_ids = rank0_metadata["suppressed_obj_ids"][frame_idx]
1335
+
1336
+ obj_ids_newly_removed = set() # object IDs to be newly removed on this frame
1337
+ hotstart_diff = (
1338
+ frame_idx - self.hotstart_delay
1339
+ if not reverse
1340
+ else frame_idx + self.hotstart_delay
1341
+ )
1342
+
1343
+ # Step 1: log the frame index where each object ID first appears
1344
+ for obj_id in new_det_obj_ids:
1345
+ if obj_id not in obj_first_frame_idx:
1346
+ obj_first_frame_idx[obj_id] = frame_idx
1347
+ assert obj_id not in trk_keep_alive
1348
+ trk_keep_alive[obj_id] = self.init_trk_keep_alive
1349
+
1350
+ matched_trks = set()
1351
+ # We use the det-->tracks list to check for matched objects. Otherwise, we need to compute areas to decide whether they're occluded
1352
+ for matched_trks_per_det in det_to_matched_trk_obj_ids.values():
1353
+ matched_trks.update(matched_trks_per_det)
1354
+ for obj_id in matched_trks:
1355
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the max value of trk_keep_alive
1356
+ trk_keep_alive[obj_id] = min(
1357
+ self.max_trk_keep_alive, trk_keep_alive[obj_id] + 1
1358
+ )
1359
+ for obj_id in unmatched_trk_obj_ids:
1360
+ unmatched_frame_inds[obj_id].append(frame_idx)
1361
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
1362
+ # The max keep alive is 2x the min, means the model prefers to keep the prediction rather than suppress it if it was matched long enough.
1363
+ trk_keep_alive[obj_id] = max(
1364
+ self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1
1365
+ )
1366
+ if self.decrease_trk_keep_alive_for_empty_masklets:
1367
+ for obj_id in empty_trk_obj_ids:
1368
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
1369
+ trk_keep_alive[obj_id] = max(
1370
+ self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1
1371
+ )
1372
+
1373
+ # Step 2: removed tracks that has not matched with detections for `hotstart_unmatch_thresh` frames with hotstart period
1374
+ # a) add unmatched frame indices for each existing object ID
1375
+ # note that `unmatched_trk_obj_ids` contains those frames where the SAM2 output mask
1376
+ # doesn't match any detection; it excludes those frames where SAM2 gives an empty mask
1377
+ # b) remove a masklet if it first appears after `hotstart_diff` and is unmatched for more
1378
+ # than `self.hotstart_unmatch_thresh` frames
1379
+ for obj_id, frame_indices in unmatched_frame_inds.items():
1380
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
1381
+ continue # skip if the object is already removed
1382
+ if len(frame_indices) >= self.hotstart_unmatch_thresh:
1383
+ is_within_hotstart = (
1384
+ obj_first_frame_idx[obj_id] > hotstart_diff and not reverse
1385
+ ) or (obj_first_frame_idx[obj_id] < hotstart_diff and reverse)
1386
+ if is_within_hotstart:
1387
+ obj_ids_newly_removed.add(obj_id)
1388
+ logger.debug(
1389
+ f"Removing object {obj_id} at frame {frame_idx} "
1390
+ f"since it is unmatched for frames: {frame_indices}"
1391
+ )
1392
+ if (
1393
+ trk_keep_alive[obj_id] <= 0 # Object has not been matched for too long
1394
+ and not self.suppress_unmatched_only_within_hotstart
1395
+ and obj_id not in removed_obj_ids
1396
+ and obj_id not in obj_ids_newly_removed
1397
+ ):
1398
+ logger.debug(
1399
+ f"Suppressing object {obj_id} at frame {frame_idx}, due to being unmatched"
1400
+ )
1401
+ suppressed_obj_ids.add(obj_id)
1402
+
1403
+ # Step 3: removed tracks that overlaps with another track for `hotstart_dup_thresh` frames
1404
+ # a) find overlaps tracks -- we consider overlap if they match to the same detection
1405
+ for _, matched_trk_obj_ids in det_to_matched_trk_obj_ids.items():
1406
+ if len(matched_trk_obj_ids) < 2:
1407
+ continue # only count detections that are matched to multiple (>=2) masklets
1408
+ # if there are multiple matched track ids, we need to find the one that appeared first;
1409
+ # these later appearing ids may be removed since they may be considered as duplicates
1410
+ first_appear_obj_id = (
1411
+ min(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
1412
+ if not reverse
1413
+ else max(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
1414
+ )
1415
+ for obj_id in matched_trk_obj_ids:
1416
+ if obj_id != first_appear_obj_id:
1417
+ key = (first_appear_obj_id, obj_id)
1418
+ overlap_pair_to_frame_inds[key].append(frame_idx)
1419
+
1420
+ # b) remove a masklet if it first appears after `hotstart_diff` and it overlaps with another
1421
+ # masklet (that appears earlier) for more than `self.hotstart_dup_thresh` frames
1422
+ for (first_obj_id, obj_id), frame_indices in overlap_pair_to_frame_inds.items():
1423
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
1424
+ continue # skip if the object is already removed
1425
+ if (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
1426
+ obj_first_frame_idx[obj_id] < hotstart_diff and reverse
1427
+ ):
1428
+ if len(frame_indices) >= self.hotstart_dup_thresh:
1429
+ obj_ids_newly_removed.add(obj_id)
1430
+ logger.debug(
1431
+ f"Removing object {obj_id} at frame {frame_idx} "
1432
+ f"since it overlaps with another track {first_obj_id} at frames: {frame_indices}"
1433
+ )
1434
+
1435
+ removed_obj_ids.update(obj_ids_newly_removed)
1436
+ return obj_ids_newly_removed, rank0_metadata
1437
+
1438
+ def _tracker_update_memories(
1439
+ self,
1440
+ tracker_inference_states: List[Any],
1441
+ frame_idx: int,
1442
+ tracker_metadata: Dict[str, Any],
1443
+ low_res_masks: Tensor,
1444
+ ):
1445
+ """
1446
+ Run Sam2 memory encoder, enforcing non-overlapping constraints globally.
1447
+ """
1448
+ if len(tracker_inference_states) == 0:
1449
+ return
1450
+ # Avoid an extra interpolation step by directly interpolating to `interpol_size`
1451
+ high_res_H, high_res_W = (
1452
+ self.tracker.maskmem_backbone.mask_downsampler.interpol_size
1453
+ )
1454
+ # NOTE: inspect this part if we observe OOMs in the demo
1455
+ high_res_masks = F.interpolate(
1456
+ low_res_masks.unsqueeze(1),
1457
+ size=(high_res_H, high_res_W),
1458
+ mode="bilinear",
1459
+ align_corners=False,
1460
+ )
1461
+ # We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
1462
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
1463
+ high_res_masks = self.tracker._suppress_object_pw_area_shrinkage(
1464
+ high_res_masks
1465
+ )
1466
+ # Instead of gathering the predicted object scores, we use mask areas as a proxy.
1467
+ object_score_logits = torch.where(
1468
+ (high_res_masks > 0).any(dim=(-1, -2)), 10.0, -10.0
1469
+ )
1470
+
1471
+ # Run the memory encoder on local slices for each GPU
1472
+ start_idx_gpu = sum(tracker_metadata["num_obj_per_gpu"][: self.rank])
1473
+ start_idx_state = start_idx_gpu
1474
+ for tracker_state in tracker_inference_states:
1475
+ num_obj_per_state = len(tracker_state["obj_ids"])
1476
+ if num_obj_per_state == 0:
1477
+ continue
1478
+ # Get the local high-res masks and object score logits for this inference state
1479
+ end_idx_state = start_idx_state + num_obj_per_state
1480
+ local_high_res_masks = high_res_masks[start_idx_state:end_idx_state]
1481
+ local_object_score_logits = object_score_logits[
1482
+ start_idx_state:end_idx_state
1483
+ ]
1484
+ local_batch_size = local_high_res_masks.size(0)
1485
+ # Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
1486
+
1487
+ encoded_mem = self.tracker._run_memory_encoder(
1488
+ tracker_state,
1489
+ frame_idx,
1490
+ local_batch_size,
1491
+ local_high_res_masks,
1492
+ local_object_score_logits,
1493
+ is_mask_from_pts=False,
1494
+ )
1495
+ local_maskmem_features, local_maskmem_pos_enc = encoded_mem
1496
+ # Store encoded memories in the local inference state
1497
+ output_dict = tracker_state["output_dict"]
1498
+ for storage_key in ["cond_frame_outputs", "non_cond_frame_outputs"]:
1499
+ if frame_idx not in output_dict[storage_key]:
1500
+ continue
1501
+ output_dict[storage_key][frame_idx]["maskmem_features"] = (
1502
+ local_maskmem_features
1503
+ )
1504
+ output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = [
1505
+ pos for pos in local_maskmem_pos_enc
1506
+ ]
1507
+ # for batched inference state, we also need to add per-object
1508
+ # memory slides to support instance interactivity
1509
+ self.tracker._add_output_per_object(
1510
+ inference_state=tracker_state,
1511
+ frame_idx=frame_idx,
1512
+ current_out=output_dict[storage_key][frame_idx],
1513
+ storage_key=storage_key,
1514
+ )
1515
+ start_idx_state += num_obj_per_state
1516
+
1517
+ def _tracker_add_new_objects(
1518
+ self,
1519
+ frame_idx: int,
1520
+ num_frames: int,
1521
+ new_obj_ids: List[int],
1522
+ new_obj_masks: Tensor,
1523
+ tracker_states_local: List[Any],
1524
+ orig_vid_height: int,
1525
+ orig_vid_width: int,
1526
+ feature_cache: Dict,
1527
+ ):
1528
+ """Add a new object to SAM2 inference states."""
1529
+ prev_tracker_state = (
1530
+ tracker_states_local[0] if len(tracker_states_local) > 0 else None
1531
+ )
1532
+
1533
+ # prepare inference_state
1534
+ # batch objects that first appear on the same frame together
1535
+ # Clear inference state. Keep the cached image features if available.
1536
+ new_tracker_state = self.tracker.init_state(
1537
+ cached_features=feature_cache,
1538
+ video_height=orig_vid_height,
1539
+ video_width=orig_vid_width,
1540
+ num_frames=num_frames,
1541
+ )
1542
+ new_tracker_state["backbone_out"] = (
1543
+ prev_tracker_state.get("backbone_out", None)
1544
+ if prev_tracker_state is not None
1545
+ else None
1546
+ )
1547
+
1548
+ assert len(new_obj_ids) == new_obj_masks.size(0)
1549
+ assert new_obj_masks.is_floating_point()
1550
+ input_mask_res = self.tracker.input_mask_size
1551
+ new_obj_masks = F.interpolate(
1552
+ new_obj_masks.unsqueeze(1),
1553
+ size=(input_mask_res, input_mask_res),
1554
+ mode="bilinear",
1555
+ align_corners=False,
1556
+ ).squeeze(1)
1557
+ new_obj_masks = new_obj_masks > 0
1558
+
1559
+ # add object one by one
1560
+ for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
1561
+ self.tracker.add_new_mask(
1562
+ inference_state=new_tracker_state,
1563
+ frame_idx=frame_idx,
1564
+ obj_id=new_obj_id,
1565
+ mask=new_mask,
1566
+ add_mask_to_memory=True,
1567
+ )
1568
+ # NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
1569
+ self.tracker.propagate_in_video_preflight(
1570
+ new_tracker_state, run_mem_encoder=True
1571
+ )
1572
+ tracker_states_local.append(new_tracker_state)
1573
+ return tracker_states_local
1574
+
1575
+ def _tracker_remove_object(self, tracker_states_local: List[Any], obj_id: int):
1576
+ """
1577
+ Remove an object from SAM2 inference states. This would remove the object from
1578
+ all frames in the video.
1579
+ """
1580
+ tracker_states_local_before_removal = tracker_states_local.copy()
1581
+ tracker_states_local.clear()
1582
+ for tracker_inference_state in tracker_states_local_before_removal:
1583
+ # we try to remove `obj_id` on every inference state with `strict=False`
1584
+ # it will not do anything if an inference state doesn't contain `obj_id`
1585
+ new_obj_ids, _ = self.tracker.remove_object(
1586
+ tracker_inference_state, obj_id, strict=False, need_output=False
1587
+ )
1588
+ # only keep an inference state if it's non-empty after object removal
1589
+ if len(new_obj_ids) > 0:
1590
+ tracker_states_local.append(tracker_inference_state)
1591
+
1592
+ def _tracker_remove_objects(
1593
+ self, tracker_states_local: List[Any], obj_ids: list[int]
1594
+ ):
1595
+ """
1596
+ Remove an object from SAM2 inference states. This would remove the object from
1597
+ all frames in the video.
1598
+ """
1599
+ for obj_id in obj_ids:
1600
+ self._tracker_remove_object(tracker_states_local, obj_id)
1601
+
1602
+ def _initialize_metadata(self):
1603
+ """Initialize metadata for the masklets."""
1604
+ tracker_metadata = {
1605
+ "obj_ids_per_gpu": [np.array([], np.int64) for _ in range(self.world_size)],
1606
+ "obj_ids_all_gpu": np.array([], np.int64),
1607
+ "num_obj_per_gpu": np.zeros(self.world_size, np.int64),
1608
+ "max_obj_id": -1,
1609
+ "obj_id_to_score": {},
1610
+ "obj_id_to_tracker_score_frame_wise": defaultdict(dict),
1611
+ "obj_id_to_last_occluded": {},
1612
+ }
1613
+ if self.rank == 0:
1614
+ # "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
1615
+ # - obj_first_frame_idx: obj_id --> first frame index where the object was detected
1616
+ # - unmatched_frame_inds: obj_id --> [mismatched frame indices]
1617
+ # - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
1618
+ # - removed_obj_ids: object IDs that are suppressed via hot-start
1619
+ rank0_metadata = {
1620
+ "obj_first_frame_idx": {},
1621
+ "unmatched_frame_inds": defaultdict(list),
1622
+ "trk_keep_alive": defaultdict(
1623
+ int
1624
+ ), # This is used only for object suppression not for removal
1625
+ "overlap_pair_to_frame_inds": defaultdict(list),
1626
+ "removed_obj_ids": set(),
1627
+ "suppressed_obj_ids": defaultdict(
1628
+ set
1629
+ ), # frame_idx --> set of objects with suppressed outputs, but still continue to be tracked
1630
+ }
1631
+ if self.masklet_confirmation_enable:
1632
+ # all the following are npt.NDArray with the same shape as `obj_ids_all_gpu`
1633
+ rank0_metadata["masklet_confirmation"] = {
1634
+ # "status" is the confirmation status of each masklet (in `MaskletConfirmationStatus`)
1635
+ "status": np.array([], np.int64),
1636
+ # "consecutive_det_num" is the number of consecutive frames where the masklet is
1637
+ # detected by the detector (with a matched detection)
1638
+ "consecutive_det_num": np.array([], np.int64),
1639
+ }
1640
+ tracker_metadata["rank0_metadata"] = rank0_metadata
1641
+
1642
+ return tracker_metadata
1643
+
1644
+ def update_masklet_confirmation_status(
1645
+ self,
1646
+ rank0_metadata: Dict[str, Any],
1647
+ obj_ids_all_gpu_prev: npt.NDArray,
1648
+ obj_ids_all_gpu_updated: npt.NDArray,
1649
+ det_to_matched_trk_obj_ids: Dict[int, npt.NDArray],
1650
+ new_det_obj_ids: npt.NDArray,
1651
+ ):
1652
+ confirmation_data = rank0_metadata["masklet_confirmation"]
1653
+
1654
+ # a) first, expand "confirmation_data" to include new masklets added in this frame
1655
+ status_prev = confirmation_data["status"]
1656
+ consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
1657
+ assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
1658
+ f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
1659
+ )
1660
+
1661
+ obj_id_to_updated_idx = {
1662
+ obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
1663
+ }
1664
+ prev_elem_is_in_updated = np.isin(obj_ids_all_gpu_prev, obj_ids_all_gpu_updated)
1665
+ prev_elem_obj_ids_in_updated = obj_ids_all_gpu_prev[prev_elem_is_in_updated]
1666
+ prev_elem_inds_in_updated = np.array(
1667
+ [obj_id_to_updated_idx[obj_id] for obj_id in prev_elem_obj_ids_in_updated],
1668
+ dtype=np.int64,
1669
+ )
1670
+ # newly added masklets are initialized to "UNCONFIRMED" status
1671
+ unconfirmed_val = MaskletConfirmationStatus.UNCONFIRMED.value
1672
+ status = np.full_like(obj_ids_all_gpu_updated, fill_value=unconfirmed_val)
1673
+ status[prev_elem_inds_in_updated] = status_prev[prev_elem_is_in_updated]
1674
+ consecutive_det_num = np.zeros_like(obj_ids_all_gpu_updated)
1675
+ consecutive_det_num[prev_elem_inds_in_updated] = consecutive_det_num_prev[
1676
+ prev_elem_is_in_updated
1677
+ ]
1678
+
1679
+ # b) update the confirmation status of all masklets based on the current frame
1680
+ # b.1) update "consecutive_det_num"
1681
+ # "is_matched": whether a masklet is matched to a detection on this frame
1682
+ is_matched = np.isin(obj_ids_all_gpu_updated, new_det_obj_ids)
1683
+ for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values():
1684
+ is_matched |= np.isin(obj_ids_all_gpu_updated, matched_trk_obj_ids)
1685
+ consecutive_det_num = np.where(is_matched, consecutive_det_num + 1, 0)
1686
+
1687
+ # b.2) update "status"
1688
+ change_to_confirmed = (
1689
+ consecutive_det_num >= self.masklet_confirmation_consecutive_det_thresh
1690
+ )
1691
+ status[change_to_confirmed] = MaskletConfirmationStatus.CONFIRMED.value
1692
+
1693
+ confirmation_data["status"] = status
1694
+ confirmation_data["consecutive_det_num"] = consecutive_det_num
1695
+ return rank0_metadata
1696
+
1697
+ def forward(self, input: BatchedDatapoint, is_inference: bool = False):
1698
+ raise NotImplementedError("Evaluation outside demo is not implemented yet")
1699
+
1700
+ def _load_checkpoint(self, ckpt_path: str, strict: bool = True):
1701
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
1702
+ missing_keys, unexpected_keys = self.load_state_dict(sd, strict=strict)
1703
+ if len(missing_keys) > 0 or len(unexpected_keys) > 0:
1704
+ logger.warning(f"Loaded ckpt with {missing_keys=}, {unexpected_keys=}")
1705
+ else:
1706
+ logger.info("Loaded ckpt successfully without missing or unexpected keys")
1707
+
1708
+ def prep_for_evaluator(self, video_frames, tracking_res, scores_labels):
1709
+ """This method is only used for benchmark eval (not used in the demo)."""
1710
+ num_frames = len(video_frames)
1711
+ w, h = video_frames[0].size
1712
+ zero_mask = torch.zeros((1, h, w), dtype=torch.bool)
1713
+ object_ids = list(scores_labels.keys())
1714
+ preds = {"scores": [], "labels": [], "boxes": [], "masks_rle": []}
1715
+ for oid in object_ids:
1716
+ o_masks = []
1717
+ o_score = scores_labels[oid][0].item()
1718
+ o_label = scores_labels[oid][1]
1719
+ for frame_idx in range(num_frames):
1720
+ if frame_idx not in tracking_res:
1721
+ o_masks.append(zero_mask)
1722
+ else:
1723
+ o_masks.append(tracking_res[frame_idx].get(oid, zero_mask))
1724
+
1725
+ o_masks = torch.cat(o_masks, dim=0) # (n_frames, H, W)
1726
+ preds["scores"].append(o_score)
1727
+ preds["labels"].append(o_label)
1728
+ preds["boxes"].append(mask_to_box(o_masks.unsqueeze(1)).squeeze())
1729
+ preds["masks_rle"].append(rle_encode(o_masks, return_areas=True))
1730
+
1731
+ preds["boxes"] = (
1732
+ torch.stack(preds["boxes"], dim=0)
1733
+ if len(preds["boxes"]) > 0
1734
+ else torch.empty(
1735
+ (0, num_frames, 4), dtype=torch.float32, device=self.device
1736
+ )
1737
+ )
1738
+ preds["scores"] = (
1739
+ torch.tensor(preds["scores"], device=self.device)
1740
+ if len(preds["scores"]) > 0
1741
+ else torch.empty((0,), device=self.device)
1742
+ )
1743
+ preds["per_frame_scores"] = preds["scores"]
1744
+ preds["labels"] = (
1745
+ torch.tensor(preds["labels"], device=self.device)
1746
+ if len(preds["labels"]) > 0
1747
+ else torch.empty((0,), device=self.device)
1748
+ )
1749
+ return preds
1750
+
1751
+ def _encode_prompt(self, **kwargs):
1752
+ return self.detector._encode_prompt(**kwargs)
1753
+
1754
+ def _drop_new_det_with_obj_limit(self, new_det_fa_inds, det_scores_np, num_to_keep):
1755
+ """
1756
+ Drop a few new detections based on the maximum number of objects. We drop new objects based
1757
+ on their detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
1758
+ """
1759
+ assert 0 <= num_to_keep <= len(new_det_fa_inds)
1760
+ if num_to_keep == 0:
1761
+ return np.array([], np.int64) # keep none
1762
+ if num_to_keep == len(new_det_fa_inds):
1763
+ return new_det_fa_inds # keep all
1764
+
1765
+ # keep the top-scoring detections
1766
+ score_order = np.argsort(det_scores_np[new_det_fa_inds])[::-1]
1767
+ new_det_fa_inds = new_det_fa_inds[score_order[:num_to_keep]]
1768
+ return new_det_fa_inds